content
stringlengths
0
13M
path
stringlengths
4
263
contentHash
stringlengths
1
10
/* * Copyright (c) 2019 toastkidjp. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompany this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html. */ package jp.toastkid.yobidashi.search.url import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import androidx.cardview.widget.CardView import androidx.core.view.isVisible import androidx.databinding.DataBindingUtil import jp.toastkid.lib.color.IconColorFinder import jp.toastkid.lib.intent.UrlShareIntentFactory import jp.toastkid.lib.preference.PreferenceApplier import jp.toastkid.yobidashi.R import jp.toastkid.yobidashi.databinding.ViewSearchCardUrlBinding import jp.toastkid.yobidashi.libs.Toaster import jp.toastkid.yobidashi.libs.clip.Clipboard /** * @author toastkidjp */ class UrlCardView @JvmOverloads constructor( context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 ) : CardView(context, attrs, defStyleAttr) { private val preferenceApplier = PreferenceApplier(context) private var binding: ViewSearchCardUrlBinding? = null private var insertAction: ((String) -> Unit)? = null init { val inflater = LayoutInflater.from(context) binding = DataBindingUtil.inflate(inflater, R.layout.view_search_card_url, this, true) binding?.module = this } /** * This function is called from data-binding. * * @param view [View] */ fun clipUrl(view: View) { val text = getCurrentText() val context = view.context Clipboard.clip(context, text) Toaster.snackShort( view, context.getString(R.string.message_clip_to, text), preferenceApplier.colorPair() ) } fun setInsertAction(action: (String) -> Unit) { insertAction = action } fun edit() { insertAction?.invoke(binding?.text?.text.toString()) } /** * This function is called from data-binding. * * @param view [View] */ fun shareUrl(view: View) { view.context.startActivity(UrlShareIntentFactory()(getCurrentText())) } /** * Switch visibility and content. * * @param title site's title * @param url URL */ fun switch(title: String?, url: String?) = if (url.isNullOrBlank() || !isEnabled) { clearContent() hide() } else { setTitle(title) setLink(url) show() } /** * Show this module. */ private fun show() { if (this.visibility == View.GONE && isEnabled) { runOnMainThread { this.visibility = View.VISIBLE } } } /** * Hide this module. */ fun hide() { if (isVisible) { runOnMainThread { this.visibility = View.GONE } } } fun onResume() { val color = IconColorFinder.from(this).invoke() binding?.clip?.setColorFilter(color) binding?.share?.setColorFilter(color) binding?.edit?.setColorFilter(color) } fun dispose() { binding = null } private fun getCurrentText() = binding?.text?.text.toString() private fun setTitle(title: String?) { binding?.title?.text = title } /** * Set open link and icon. * * @param link Link URL(string) */ private fun setLink(link: String) { binding?.text?.text = link } private fun clearContent() { binding?.title?.text = "" binding?.text?.text = "" } private fun runOnMainThread(action: () -> Unit) = post { action() } }
app/src/main/java/jp/toastkid/yobidashi/search/url/UrlCardView.kt
656380310
package info.papdt.express.helper.ui import android.app.Activity import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.LinearLayout import androidx.recyclerview.widget.RecyclerView import info.papdt.express.helper.R import info.papdt.express.helper.dao.PackageDatabase import info.papdt.express.helper.dao.SRDatabase import info.papdt.express.helper.event.EventCallbacks import info.papdt.express.helper.event.EventIntents import info.papdt.express.helper.ui.adapter.CategoriesListAdapter import info.papdt.express.helper.ui.common.AbsActivity import info.papdt.express.helper.ui.dialog.EditCategoryDialog import info.papdt.express.helper.ui.items.CategoryItemViewBinder import moe.feng.kotlinyan.common.* class ManageCategoriesActivity : AbsActivity() { companion object { fun launch(activity: Activity, requestCode: Int) { val intent = Intent(activity, ManageCategoriesActivity::class.java) intent.addFlags(Intent.FLAG_ACTIVITY_MULTIPLE_TASK) activity.startActivityForResult(intent, requestCode) } } private val listView: RecyclerView by lazyFindNonNullView(android.R.id.list) private val emptyView: LinearLayout by lazyFindNonNullView(R.id.empty_view) private val adapter: CategoriesListAdapter = CategoriesListAdapter() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_manage_categories) } override fun setUpViews() { listView.adapter = adapter adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() { override fun onChanged() { emptyView.visibility = if (adapter.itemCount > 0) View.GONE else View.VISIBLE } override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) { onChanged() } override fun onItemRangeInserted(positionStart: Int, itemCount: Int) { onChanged() } }) ui { adapter.setCategories(asyncIO { SRDatabase.categoryDao.getAll() }.await()) } } override fun onStart() { super.onStart() registerLocalBroadcastReceiver(EventCallbacks.onItemClick(CategoryItemViewBinder::class) { if (it != null) { EditCategoryDialog.newEditDialog(it).show(supportFragmentManager, "edit_dialog") } }, action = EventIntents.getItemOnClickActionName(CategoryItemViewBinder::class)) registerLocalBroadcastReceiver(EventCallbacks.onSaveNewCategory { ui { val newList = asyncIO { SRDatabase.categoryDao.add(it) SRDatabase.categoryDao.getAll() }.await() adapter.setCategories(newList) setResult(RESULT_OK) } }, action = EventIntents.ACTION_SAVE_NEW_CATEGORY) registerLocalBroadcastReceiver(EventCallbacks.onSaveEditCategory { oldData, data -> ui { if (oldData.title == data.title) { // Its title hasn't been changed. Just update val newList = asyncIO { SRDatabase.categoryDao.update(data) SRDatabase.categoryDao.getAll() }.await() adapter.setCategories(newList) setResult(RESULT_OK) } else { // Title has been changed. Need update package list val newList = asyncIO { val packDatabase = PackageDatabase.getInstance(this) for (pack in packDatabase.data) { if (pack.categoryTitle == oldData.title) { pack.categoryTitle = data.title } } packDatabase.save() SRDatabase.categoryDao.delete(oldData) SRDatabase.categoryDao.add(data) SRDatabase.categoryDao.getAll() }.await() adapter.setCategories(newList) setResult(RESULT_OK) } } }, action = EventIntents.ACTION_SAVE_EDIT_CATEGORY) registerLocalBroadcastReceiver(EventCallbacks.onDeleteCategory { buildAlertDialog { titleRes = R.string.delete_category_dialog_title messageRes = R.string.delete_category_dialog_message okButton { _, _ -> ui { val newList = asyncIO { SRDatabase.categoryDao.deleteWithUpdatingPackages(this, it) SRDatabase.categoryDao.getAll() }.await() adapter.setCategories(newList) setResult(RESULT_OK) } } cancelButton() }.show() }, action = EventIntents.ACTION_REQUEST_DELETE_CATEGORY) } override fun onStop() { super.onStop() unregisterAllLocalBroadcastReceiver() } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_manage_categories, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.action_new_category -> { EditCategoryDialog.newCreateDialog().show(supportFragmentManager, "create_dialog") true } R.id.action_reset_category -> { buildAlertDialog { titleRes = R.string.reset_default_category_dialog_title messageRes = R.string.reset_default_category_dialog_message okButton { _, _ -> ui { val newList = asyncIO { SRDatabase.categoryDao.clearWithUpdatingPackages(this) SRDatabase.categoryDao.addDefaultCategories(this) SRDatabase.categoryDao.getAll() }.await() adapter.setCategories(newList) setResult(RESULT_OK) } } cancelButton() }.show() true } else -> super.onOptionsItemSelected(item) } }
mobile/src/main/kotlin/info/papdt/express/helper/ui/ManageCategoriesActivity.kt
4280015951
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:OptIn(ExperimentalHorologistMediaUiApi::class) package com.google.android.horologist.media.ui.components import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsEnabled import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.junit4.createComposeRule import androidx.compose.ui.test.onNodeWithContentDescription import androidx.compose.ui.test.performClick import androidx.test.filters.FlakyTest import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi import com.google.android.horologist.media.ui.components.controls.SeekButtonIncrement import com.google.android.horologist.test.toolbox.matchers.hasProgressBar import org.junit.Rule import org.junit.Test @FlakyTest(detail = "https://github.com/google/horologist/issues/407") class PodcastControlButtonsTest { @get:Rule val composeTestRule = createComposeRule() @Test fun givenIsPlaying_thenPauseButtonIsDisplayed() { // given val playing = true composeTestRule.setContent { PodcastControlButtons( onPlayButtonClick = {}, onPauseButtonClick = {}, playPauseButtonEnabled = true, playing = playing, onSeekBackButtonClick = {}, seekBackButtonEnabled = true, onSeekForwardButtonClick = {}, seekForwardButtonEnabled = true ) } // then composeTestRule.onNodeWithContentDescription("Pause") .assertIsDisplayed() composeTestRule.onNodeWithContentDescription("Play") .assertDoesNotExist() } @Test fun givenIsPlaying_whenPauseIsClicked_thenCorrectEventIsTriggered() { // given val playing = true var clicked = false composeTestRule.setContent { PodcastControlButtons( onPlayButtonClick = {}, onPauseButtonClick = { clicked = true }, playPauseButtonEnabled = true, playing = playing, onSeekBackButtonClick = {}, seekBackButtonEnabled = true, onSeekForwardButtonClick = {}, seekForwardButtonEnabled = true ) } // when composeTestRule.onNodeWithContentDescription("Pause") .performClick() // then // assert that the click event was assigned to the correct button composeTestRule.waitUntil(timeoutMillis = 1_000) { clicked } } @Test fun givenIsNOTPlaying_thenPlayButtonIsDisplayed() { // given val playing = false composeTestRule.setContent { PodcastControlButtons( onPlayButtonClick = {}, onPauseButtonClick = {}, playPauseButtonEnabled = true, playing = playing, onSeekBackButtonClick = {}, seekBackButtonEnabled = true, onSeekForwardButtonClick = {}, seekForwardButtonEnabled = true ) } // then composeTestRule.onNodeWithContentDescription("Play") .assertIsDisplayed() composeTestRule.onNodeWithContentDescription("Pause") .assertDoesNotExist() } @Test fun givenIsNOTPlaying_whenPlayIsClicked_thenCorrectEventIsTriggered() { // given val playing = false var clicked = false composeTestRule.setContent { PodcastControlButtons( onPlayButtonClick = { clicked = true }, onPauseButtonClick = {}, playPauseButtonEnabled = true, playing = playing, onSeekBackButtonClick = {}, seekBackButtonEnabled = true, onSeekForwardButtonClick = {}, seekForwardButtonEnabled = true ) } // when composeTestRule.onNodeWithContentDescription("Play") .performClick() // then // assert that the click event was assigned to the correct button composeTestRule.waitUntil(timeoutMillis = 1_000) { clicked } } @Test fun whenSeekBackIsClicked_thenCorrectEventIsTriggered() { // given var clicked = false composeTestRule.setContent { PodcastControlButtons( onPlayButtonClick = {}, onPauseButtonClick = {}, playPauseButtonEnabled = true, playing = false, onSeekBackButtonClick = { clicked = true }, seekBackButtonEnabled = true, onSeekForwardButtonClick = {}, seekForwardButtonEnabled = true ) } // when composeTestRule.onNodeWithContentDescription("Rewind") .performClick() // then // assert that the click event was assigned to the correct button composeTestRule.waitUntil(timeoutMillis = 1_000) { clicked } } @Test fun whenSeekForwardIsClicked_thenCorrectEventIsTriggered() { // given var clicked = false composeTestRule.setContent { PodcastControlButtons( onPlayButtonClick = {}, onPauseButtonClick = {}, playPauseButtonEnabled = true, playing = false, onSeekBackButtonClick = {}, seekBackButtonEnabled = true, onSeekForwardButtonClick = { clicked = true }, seekForwardButtonEnabled = true ) } // when composeTestRule.onNodeWithContentDescription("Forward") .performClick() // then // assert that the click event was assigned to the correct button composeTestRule.waitUntil(timeoutMillis = 1_000) { clicked } } @Test fun givenNoPercentParam_thenNOProgressBarIsDisplayed() { // given composeTestRule.setContent { PodcastControlButtons( onPlayButtonClick = {}, onPauseButtonClick = {}, playPauseButtonEnabled = true, playing = false, onSeekBackButtonClick = {}, seekBackButtonEnabled = true, onSeekForwardButtonClick = {}, seekForwardButtonEnabled = true ) } // then composeTestRule.onNode(hasProgressBar()) .assertDoesNotExist() } @Test fun givenIsPlayingAndPlayPauseEnabledIsTrue_thenPauseButtonIsEnabled() { // given val playing = true val playPauseButtonEnabled = true composeTestRule.setContent { PodcastControlButtons( onPlayButtonClick = {}, onPauseButtonClick = {}, playPauseButtonEnabled = playPauseButtonEnabled, playing = playing, onSeekBackButtonClick = {}, seekBackButtonEnabled = false, onSeekForwardButtonClick = {}, seekForwardButtonEnabled = false ) } // then composeTestRule.onNodeWithContentDescription("Pause") .assertIsEnabled() composeTestRule.onNodeWithContentDescription("Rewind") .assertIsNotEnabled() composeTestRule.onNodeWithContentDescription("Forward") .assertIsNotEnabled() } @Test fun givenIsNOTPlayingAndPlayPauseEnabledIsTrue_thenPlayButtonIsEnabled() { // given val playing = false val playPauseButtonEnabled = true composeTestRule.setContent { PodcastControlButtons( onPlayButtonClick = {}, onPauseButtonClick = {}, playPauseButtonEnabled = playPauseButtonEnabled, playing = playing, onSeekBackButtonClick = {}, seekBackButtonEnabled = false, onSeekForwardButtonClick = {}, seekForwardButtonEnabled = false ) } // then composeTestRule.onNodeWithContentDescription("Play") .assertIsEnabled() composeTestRule.onNodeWithContentDescription("Rewind") .assertIsNotEnabled() composeTestRule.onNodeWithContentDescription("Forward") .assertIsNotEnabled() } @Test fun givenSeekBackButtonEnabledIsTrue_thenSeekBackButtonIsEnabled() { // given val seekBackButtonEnabled = true composeTestRule.setContent { PodcastControlButtons( onPlayButtonClick = {}, onPauseButtonClick = {}, playPauseButtonEnabled = false, playing = false, onSeekBackButtonClick = {}, seekBackButtonEnabled = seekBackButtonEnabled, onSeekForwardButtonClick = {}, seekForwardButtonEnabled = false ) } // then composeTestRule.onNodeWithContentDescription("Rewind") .assertIsEnabled() composeTestRule.onNodeWithContentDescription("Play") .assertIsNotEnabled() composeTestRule.onNodeWithContentDescription("Forward") .assertIsNotEnabled() } @Test fun givenSeekForwardButtonEnabledIsTrue_thenSeekForwardButtonIsEnabled() { // given val seekForwardButtonEnabled = true composeTestRule.setContent { PodcastControlButtons( onPlayButtonClick = {}, onPauseButtonClick = {}, playPauseButtonEnabled = false, playing = false, onSeekBackButtonClick = {}, seekBackButtonEnabled = false, onSeekForwardButtonClick = {}, seekForwardButtonEnabled = seekForwardButtonEnabled ) } // then composeTestRule.onNodeWithContentDescription("Forward") .assertIsEnabled() composeTestRule.onNodeWithContentDescription("Play") .assertIsNotEnabled() composeTestRule.onNodeWithContentDescription("Rewind") .assertIsNotEnabled() } @Test fun givenSeekBackIncrementIsFive_thenSeekBackDescriptionIsFive() { // given val seekBackButtonIncrement = SeekButtonIncrement.Five composeTestRule.setContent { PodcastControlButtons( onPlayButtonClick = {}, onPauseButtonClick = {}, playPauseButtonEnabled = false, playing = false, onSeekBackButtonClick = {}, seekBackButtonEnabled = false, onSeekForwardButtonClick = {}, seekForwardButtonEnabled = false, seekBackButtonIncrement = seekBackButtonIncrement ) } // then composeTestRule.onNodeWithContentDescription("Rewind 5 seconds") .assertExists() composeTestRule.onNodeWithContentDescription("Forward") .assertExists() } @Test fun givenSeekForwardIncrementIsFive_thenSeekForwardDescriptionIsFive() { // given val seekForwardButtonIncrement = SeekButtonIncrement.Five composeTestRule.setContent { PodcastControlButtons( onPlayButtonClick = {}, onPauseButtonClick = {}, playPauseButtonEnabled = false, playing = false, onSeekBackButtonClick = {}, seekBackButtonEnabled = false, onSeekForwardButtonClick = {}, seekForwardButtonEnabled = false, seekForwardButtonIncrement = seekForwardButtonIncrement ) } // then composeTestRule.onNodeWithContentDescription("Forward 5 seconds") .assertExists() composeTestRule.onNodeWithContentDescription("Rewind") .assertExists() } }
media-ui/src/androidTest/java/com/google/android/horologist/media/ui/components/PodcastControlButtonsTest.kt
436154310
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.progress import com.intellij.openapi.project.Project import org.jetbrains.annotations.Nls inline fun runModalTask(@Nls(capitalization = Nls.Capitalization.Title) title: String, project: Project? = null, cancellable: Boolean = true, crossinline task: (indicator: ProgressIndicator) -> Unit) { ProgressManager.getInstance().run(object : Task.Modal(project, title, cancellable) { override fun run(indicator: ProgressIndicator) { task(indicator) } }) } inline fun runBackgroundableTask(@Nls(capitalization = Nls.Capitalization.Title) title: String, project: Project? = null, cancellable: Boolean = true, crossinline task: (indicator: ProgressIndicator) -> Unit) { ProgressManager.getInstance().run(object : Task.Backgroundable(project, title, cancellable) { override fun run(indicator: ProgressIndicator) { task(indicator) } }) }
platform/platform-impl/src/com/intellij/openapi/progress/progress.kt
2611946848
/* * Copyright 2017-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.koin.dsl import org.koin.core.definition.BeanDefinition import org.koin.core.definition.Callbacks import org.koin.core.definition.OnCloseCallback import kotlin.reflect.KClass /** * BeanDefinition DSL specific functions * * @author Arnaud Giuliani */ /** * Add a compatible type to match for definition * @param clazz */ infix fun <T> BeanDefinition<T>.bind(clazz: KClass<*>): BeanDefinition<T> { secondaryTypes = secondaryTypes + clazz return this } /** * Add a compatible type to match for definition */ inline fun <reified T> BeanDefinition<*>.bind(): BeanDefinition<*> { return bind(T::class) } /** * Add compatible types to match for definition * @param classes */ infix fun BeanDefinition<*>.binds(classes: Array<KClass<*>>): BeanDefinition<*> { secondaryTypes = secondaryTypes + classes return this } /** * Callback when closing instance */ infix fun <T> BeanDefinition<T>.onClose(onClose: OnCloseCallback<T>): BeanDefinition<T> { callbacks = Callbacks(onClose) return this }
koin-projects/koin-core/src/main/kotlin/org/koin/dsl/DefinitionBinding.kt
689311741
/* * Copyright 2019 Andrey Tolpeev * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.vase4kin.teamcityapp.snapshot_dependencies.model import com.github.vase4kin.teamcityapp.account.create.data.OnLoadingListener import com.github.vase4kin.teamcityapp.api.Repository import com.github.vase4kin.teamcityapp.buildlist.data.BuildListDataManager import com.github.vase4kin.teamcityapp.buildlist.data.BuildListDataManagerImpl import com.github.vase4kin.teamcityapp.overview.data.BuildDetails import com.github.vase4kin.teamcityapp.storage.SharedUserStorage /** * Snapshot dependencies build list interactor */ class SnapshotDependenciesInteractorImpl( repository: Repository, storage: SharedUserStorage ) : BuildListDataManagerImpl(repository, storage), SnapshotDependenciesInteractor { /** * {@inheritDoc} */ override fun load(id: String, loadingListener: OnLoadingListener<List<BuildDetails>>, update: Boolean) { loadNotSortedBuilds(repository.listSnapshotBuilds(id, update), loadingListener) } } interface SnapshotDependenciesInteractor : BuildListDataManager
app/src/main/java/com/github/vase4kin/teamcityapp/snapshot_dependencies/model/SnapshotDependenciesInteractorImpl.kt
1137243867
package org.jetbrains.dokka.base.transformers.pages.sourcelinks import com.intellij.psi.PsiDocumentManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiIdentifier import org.jetbrains.dokka.DokkaConfiguration import org.jetbrains.dokka.DokkaConfiguration.DokkaSourceSet import org.jetbrains.dokka.analysis.DescriptorDocumentableSource import org.jetbrains.dokka.analysis.PsiDocumentableSource import org.jetbrains.dokka.base.DokkaBase import org.jetbrains.dokka.base.translators.documentables.PageContentBuilder import org.jetbrains.dokka.links.DRI import org.jetbrains.dokka.model.* import org.jetbrains.dokka.pages.* import org.jetbrains.dokka.plugability.DokkaContext import org.jetbrains.dokka.plugability.plugin import org.jetbrains.dokka.plugability.querySingle import org.jetbrains.dokka.transformers.pages.PageTransformer import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithSource import org.jetbrains.kotlin.lexer.KtTokens import org.jetbrains.kotlin.psi.psiUtil.getChildOfType import org.jetbrains.kotlin.resolve.source.getPsi import org.jetbrains.kotlin.utils.addToStdlib.cast import java.io.File class SourceLinksTransformer(val context: DokkaContext) : PageTransformer { private val builder : PageContentBuilder = PageContentBuilder( context.plugin<DokkaBase>().querySingle { commentsToContentConverter }, context.plugin<DokkaBase>().querySingle { signatureProvider }, context.logger ) override fun invoke(input: RootPageNode): RootPageNode { val sourceLinks = getSourceLinksFromConfiguration() if (sourceLinks.isEmpty()) { return input } return input.transformContentPagesTree { node -> when (node) { is WithDocumentables -> { val sources = node.documentables .filterIsInstance<WithSources>() .fold(mutableMapOf<DRI, List<Pair<DokkaSourceSet, String>>>()) { acc, documentable -> val dri = (documentable as Documentable).dri acc.compute(dri) { _, v -> val sources = resolveSources(sourceLinks, documentable) v?.plus(sources) ?: sources } acc } if (sources.isNotEmpty()) node.modified(content = transformContent(node.content, sources)) else node } else -> node } } } private fun getSourceLinksFromConfiguration(): List<SourceLink> { return context.configuration.sourceSets .flatMap { it.sourceLinks.map { sl -> SourceLink(sl, it) } } } private fun resolveSources( sourceLinks: List<SourceLink>, documentable: WithSources ): List<Pair<DokkaSourceSet, String>> { return documentable.sources.mapNotNull { (sourceSet, documentableSource) -> val sourceLink = sourceLinks.find { sourceLink -> File(documentableSource.path).startsWith(sourceLink.path) && sourceLink.sourceSetData == sourceSet } ?: return@mapNotNull null sourceSet to documentableSource.toLink(sourceLink) } } private fun DocumentableSource.toLink(sourceLink: SourceLink): String { val sourcePath = File(this.path).invariantSeparatorsPath val sourceLinkPath = File(sourceLink.path).invariantSeparatorsPath val lineNumber = when (this) { is DescriptorDocumentableSource -> this.descriptor .cast<DeclarationDescriptorWithSource>() .source.getPsi() ?.lineNumber() is PsiDocumentableSource -> this.psi.lineNumber() else -> null } return sourceLink.url + sourcePath.split(sourceLinkPath)[1] + sourceLink.lineSuffix + "${lineNumber ?: 1}" } private fun PsiElement.lineNumber(): Int? { val ktIdentifierTextRange = this.node?.findChildByType(KtTokens.IDENTIFIER)?.textRange val javaIdentifierTextRange = this.getChildOfType<PsiIdentifier>()?.textRange // synthetic and some light methods might return null val textRange = ktIdentifierTextRange ?: javaIdentifierTextRange ?: textRange ?: return null val doc = PsiDocumentManager.getInstance(project).getDocument(containingFile) // IJ uses 0-based line-numbers; external source browsers use 1-based return doc?.getLineNumber(textRange.startOffset)?.plus(1) } private fun ContentNode.signatureGroupOrNull() = (this as? ContentGroup)?.takeIf { it.dci.kind == ContentKind.Symbol } private fun transformContent( contentNode: ContentNode, sources: Map<DRI, List<Pair<DokkaSourceSet, String>>> ): ContentNode = contentNode.signatureGroupOrNull()?.let { sg -> sources[sg.dci.dri.singleOrNull()]?.let { sourceLinks -> sourceLinks .filter { it.first.sourceSetID in sg.sourceSets.sourceSetIDs } .takeIf { it.isNotEmpty() } ?.let { filteredSourcesLinks -> sg.copy(children = sg.children + filteredSourcesLinks.map { buildContentLink( sg.dci.dri.first(), it.first, it.second ) }) } } } ?: when (contentNode) { is ContentComposite -> contentNode.transformChildren { transformContent(it, sources) } else -> contentNode } private fun buildContentLink(dri: DRI, sourceSet: DokkaSourceSet, link: String) = builder.contentFor( dri, setOf(sourceSet), ContentKind.Source, setOf(TextStyle.FloatingRight) ) { text("(") link("source", link) text(")") } } data class SourceLink(val path: String, val url: String, val lineSuffix: String?, val sourceSetData: DokkaSourceSet) { constructor(sourceLinkDefinition: DokkaConfiguration.SourceLinkDefinition, sourceSetData: DokkaSourceSet) : this( sourceLinkDefinition.localDirectory, sourceLinkDefinition.remoteUrl.toExternalForm(), sourceLinkDefinition.remoteLineSuffix, sourceSetData ) }
plugins/base/src/main/kotlin/transformers/pages/sourcelinks/SourceLinksTransformer.kt
1958292956
package com.wnc_21.kandroidextensions.view import android.content.Context import android.support.test.InstrumentationRegistry import android.support.test.runner.AndroidJUnit4 import android.view.View import org.junit.Assert.* import org.junit.Before import org.junit.Test import org.junit.runner.RunWith @RunWith(AndroidJUnit4::class) class TestViewVisibility { private lateinit var context: Context @Before fun runBeforeEachTest() { context = InstrumentationRegistry.getContext() } @Test fun setGone_Should_set_GONE_Visibility_flag() { val view: View = View(context) assertEquals(View.VISIBLE, view.visibility) view.setGone(true) assertEquals(View.GONE, view.visibility) view.setGone(false) assertEquals(View.VISIBLE, view.visibility) } @Test fun setInvisible_Should_set_INVISIBLE_Visibility_flag() { val view: View = View(context) assertEquals(View.VISIBLE, view.visibility) view.setVisible(false) assertEquals(View.INVISIBLE, view.visibility) view.setVisible(true) assertEquals(View.VISIBLE, view.visibility) } @Test fun isVisible_Should_return_visible_state_bool() { val view: View = View(context) assertTrue(view.isVisible()) view.setVisible(false) assertFalse(view.isVisible()) view.setVisible(true) assertTrue(view.isVisible()) view.setGone(true) assertFalse(view.isVisible()) view.setGone(false) assertTrue(view.isVisible()) } }
lib/src/androidTest/kotlin/com/wnc_21/kandroidextensions/view/TestViewVisibility.kt
2109914341
package i_introduction._3_Default_Arguments import util.TODO import util.doc2 fun todoTask3(): Nothing = TODO( """ Task 3. Several overloaded 'foo' functions in the class 'JavaCode3' can be replaced with one function in Kotlin. Change the declaration of the function 'foo' in a way that makes the code using 'foo' compile. You have to add 'foo' parameters and implement its body. Uncomment the commented code and make it compile. """, documentation = doc2(), references = { name: String -> JavaCode3().foo(name); foo(name) }) fun foo(name: String, number: Int = 42, toUpperCase: Boolean = false): String = (if (toUpperCase) name.toUpperCase() else name) + number fun task3(): String { // todoTask3() return (foo("a") + foo("b", number = 1) + foo("c", toUpperCase = true) + foo(name = "d", number = 2, toUpperCase = true)) }
src/i_introduction/_3_Default_Arguments/n03DefaultArguments.kt
684071575
package com.yy.codex.uikit import com.yy.codex.foundation.NSLog import com.yy.codex.foundation.lets import java.util.* /** * Created by cuiminghui on 2017/2/27. */ internal fun UITableView._updateCellsFrame() { subviews.forEach { (it as? UITableViewCell)?.let { it.frame = it.frame.setWidth(frame.width) } } } internal fun UITableView._reloadData() { _lastVisibleHash = "" _reloadSectionHeaderFooterView() _reloadCellCaches() _reloadContentSize() _markCellReusable(listOf()) _updateCells() _updateTableHeaderFooterViewFrame() _updateSectionHeaderFooterFrame() } internal fun UITableView._requestCell(indexPath: NSIndexPath): UITableViewCell? { _cellInstances.toList().forEach { it.second.toList().forEach { if (it.cell._indexPath == indexPath) { return it.cell } } } return null } internal fun UITableView._allCells(): List<UITableViewCell> { var cells: MutableList<UITableViewCell> = mutableListOf() _cellInstances.toList().forEach { it.second.toList().forEach { cells.add(it.cell) } } return cells.toList() } internal fun UITableView._updateCells() { val dataSource = dataSource ?: return val visiblePositions = _requestVisiblePositions() val currentVisibleHash = _computeVisibleHash(visiblePositions) if (_lastVisibleHash == currentVisibleHash) { return } _lastVisibleHash = currentVisibleHash _markCellReusable(visiblePositions).forEach { val visiblePosition = it val cell = dataSource.cellForRowAtIndexPath(this, it.indexPath) cell._indexPath = it.indexPath cell.frame = CGRect(0.0, it.value, frame.width, it.height) cell.setSelected(_isCellSelected(cell), false) _enqueueCell(cell, it) if (cell.superview !== this) { cell.removeFromSuperview() insertSubview(cell, 0) } cell._updateAppearance() delegate()?.let { it.willDisplayCell(this, cell, visiblePosition.indexPath) } } } internal fun UITableView._isCellSelected(cell: UITableViewCell): Boolean { indexPathsForSelectedRows.forEach { if (it == cell._indexPath) { return true } } return false } internal fun UITableView._dequeueCell(reuseIdentifier: String): UITableViewCell? { var cell: UITableViewCell? = null _cellInstances[reuseIdentifier]?.let { it.toList().forEach { if (cell != null) { return@forEach } if (!it.isBusy) { cell = it.cell } } } cell?.prepareForReuse() return cell } internal fun UITableView._requestPreviousPointCell(cell: UITableViewCell): UITableViewCell? { (this._requestCell(this._requestCellPositionWithPoint(cell.frame.y - 1.0).indexPath))?.let { if (it != cell && it.frame.y + it.frame.height >= cell.frame.y - 1.0) { return it } } return null } internal fun UITableView._requestNextPointCell(cell: UITableViewCell): UITableViewCell? { (this._requestCell(this._requestCellPositionWithPoint(cell.frame.y + cell.frame.height + 1.0).indexPath))?.let { if (it != cell && it.frame.y <= cell.frame.y + cell.frame.height + 1.0) { return it } } return null } private fun UITableView._enqueueCell(cell: UITableViewCell, cellPosition: UITableViewCellPosition) { val reuseIdentifier = cell.reuseIdentifier ?: return if (_cellInstances[reuseIdentifier] == null) { _cellInstances[reuseIdentifier] = mutableListOf() } _cellInstances[reuseIdentifier]?.let { var found = false it.toList().forEach { if (it.cell === cell) { it.cellPosition = cellPosition it.isBusy = true found = true } } if (!found) { it.add(UITableViewReusableCell(cell, cellPosition, true)) } } } private fun UITableView._markCellReusable(visiblePositions: List<UITableViewCellPosition>): List<UITableViewCellPosition> { val trimmedPositions: MutableList<UITableViewCellPosition> = visiblePositions.toMutableList() val visibleMapping: HashMap<UITableViewCellPosition, Boolean> = hashMapOf() visiblePositions.forEach { visibleMapping[it] = true } _cellInstances.toList().forEach { it.second.toList().forEach { it.isBusy = it.cellPosition != null && visibleMapping[it.cellPosition!!] == true if (it.isBusy) { trimmedPositions.remove(it.cellPosition) } else { it.cellPosition = null lets(it.cell, it.cell._indexPath) { cell, indexPath -> delegate()?.let { it.didEndDisplayingCell(this, cell, indexPath) } } } } } return trimmedPositions.toList() } internal class UITableViewReusableCell(val cell: UITableViewCell, var cellPosition: UITableViewCellPosition?, var isBusy: Boolean)
library/src/main/java/com/yy/codex/uikit/UITableView_CellProcesser.kt
880930239
package org.roylance.yaorm.services.sqlite import org.roylance.common.service.IBuilder import org.roylance.yaorm.services.EntityService import org.roylance.yaorm.services.IEntityService import org.roylance.yaorm.services.jdbc.JDBCGranularDatabaseService import org.roylance.yaorm.utilities.ICommonTest import java.io.File open class SQLiteBase: ICommonTest { override fun buildEntityService(schema: String?): IEntityService { val sourceConnection = SQLiteConnectionSourceFactory(schema!!) val granularDatabaseService = JDBCGranularDatabaseService( sourceConnection, false, true) val sqliteGeneratorService = SQLiteGeneratorService() val entityService = EntityService(granularDatabaseService, sqliteGeneratorService) return entityService } override fun cleanup(schema: String?): IBuilder<Boolean> { return object : IBuilder<Boolean> { override fun build(): Boolean { File(schema).deleteOnExit() return true } } } }
yaorm/src/test/java/org/roylance/yaorm/services/sqlite/SQLiteBase.kt
2674552365
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.slicesbasiccodelab import android.app.PendingIntent import android.content.ContentResolver import android.content.Context import android.content.Intent import android.net.Uri import android.util.Log import androidx.core.content.ContextCompat import androidx.core.graphics.drawable.IconCompat import androidx.slice.Slice import androidx.slice.SliceProvider import androidx.slice.builders.ListBuilder import androidx.slice.builders.SliceAction import androidx.slice.builders.header import androidx.slice.builders.list import com.example.android.slicesbasiccodelab.MainActivity.Companion.getTemperature import com.example.android.slicesbasiccodelab.MainActivity.Companion.getTemperatureString import com.example.android.slicesbasiccodelab.TemperatureBroadcastReceiver.Companion.ACTION_CHANGE_TEMPERATURE import com.example.android.slicesbasiccodelab.TemperatureBroadcastReceiver.Companion.EXTRA_TEMPERATURE_VALUE /** * Creates a temperature control Slice that mirrors the main activity. The slice displays the * current temperature and allows the user to adjust the temperature up and down from the Slice * without launching the activity. * * NOTE: The main action still allows the user to launch the main activity if they choose. */ class TemperatureSliceProvider : SliceProvider() { private lateinit var contextNonNull: Context override fun onCreateSliceProvider(): Boolean { // TODO: Step 2.3, Review non-nullable Context variable. contextNonNull = context ?: return false return true } /* * Each Slice has an associated URI. The standard format is package name + path for each Slice. * In our case, we only have one slice mapped to the 'temperature' path * ('com.example.android.slicesbasiccodelab/temperature'). * * When a surface wants to display a Slice, it sends a binding request to your app with this * URI via this method and you build out the slice to return. The surface can then display the * Slice when appropriate. * * Note: You can make your slices interactive by adding actions. (We do this for our * temperature up/down buttons.) */ override fun onBindSlice(sliceUri: Uri): Slice? { Log.d(TAG, "onBindSlice(): $sliceUri") // TODO: Step 2.4, Define a slice path. when (sliceUri.path) { "/temperature" -> return createTemperatureSlice(sliceUri) } return null } // Creates the actual Slice used in onBindSlice(). private fun createTemperatureSlice(sliceUri: Uri): Slice { Log.d(TAG, "createTemperatureSlice(): $sliceUri") /* Slices are constructed by using a ListBuilder (it is the main building block of Slices). * ListBuilder allows you to add different types of rows that are displayed in a list. * Because we are using the Slice KTX library, we can use the DSL version of ListBuilder, * so we just need to use list() and include some general arguments before defining the * structure of the Slice. */ // TODO: Step 3.1, Review Slice's ListBuilder. return list(contextNonNull, sliceUri, ListBuilder.INFINITY) { setAccentColor(ContextCompat.getColor(contextNonNull, R.color.slice_accent_color)) /* The first row of your slice should be a header. The header supports a title, * subtitle, and a tappable action (usually used to launch an Activity). A header * can also have a summary of the contents of the slice which can be shown when * the Slice may be too large to be displayed. In our case, we are also attaching * multiple actions to the header row (temp up/down). * * If we wanted to add additional rows, you can use the RowBuilder or the GridBuilder. * */ // TODO: Step 3.2, Create a Slice Header (title and primary action). header { title = getTemperatureString(contextNonNull) // Launches the main Activity associated with the Slice. primaryAction = SliceAction.create( PendingIntent.getActivity( contextNonNull, sliceUri.hashCode(), Intent(contextNonNull, MainActivity::class.java), 0 ), IconCompat.createWithResource(contextNonNull, R.drawable.ic_home), ListBuilder.ICON_IMAGE, contextNonNull.getString(R.string.slice_action_primary_title) ) } // TODO: Step 3.3, Add Temperature Up Slice Action. addAction( SliceAction.create( createTemperatureChangePendingIntent(getTemperature() + 1), IconCompat.createWithResource(contextNonNull, R.drawable.ic_temp_up), ListBuilder.ICON_IMAGE, contextNonNull.getString(R.string.increase_temperature) ) ) // TODO: Step 3.4, Add Temperature Down Slice Action. addAction( SliceAction.create( createTemperatureChangePendingIntent(getTemperature() - 1), IconCompat.createWithResource(contextNonNull, R.drawable.ic_temp_down), ListBuilder.ICON_IMAGE, contextNonNull.getString(R.string.decrease_temperature) ) ) } } // TODO: Step 3.4, Review Pending Intent Creation. // PendingIntent that triggers an increase/decrease in temperature. private fun createTemperatureChangePendingIntent(value: Int): PendingIntent { val intent = Intent(ACTION_CHANGE_TEMPERATURE) .setClass(contextNonNull, TemperatureBroadcastReceiver::class.java) .putExtra(EXTRA_TEMPERATURE_VALUE, value) return PendingIntent.getBroadcast( contextNonNull, requestCode++, intent, PendingIntent.FLAG_UPDATE_CURRENT ) } companion object { private const val TAG = "TempSliceProvider" private var requestCode = 0 fun getUri(context: Context, path: String): Uri { return Uri.Builder() .scheme(ContentResolver.SCHEME_CONTENT) .authority(context.packageName) .appendPath(path) .build() } } }
complete/src/main/java/com/example/android/slicesbasiccodelab/TemperatureSliceProvider.kt
2828152746
package com.apkupdater.receiver import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import com.apkupdater.util.app.AlarmUtil import org.koin.core.KoinComponent import org.koin.core.inject class BootReceiver : BroadcastReceiver(), KoinComponent { private val alarmUtil: AlarmUtil by inject() override fun onReceive(context: Context, intent: Intent) { if (intent.action == "android.intent.action.BOOT_COMPLETED") { alarmUtil.setupAlarm(context) } } }
app/src/main/java/com/apkupdater/receiver/BootReceiver.kt
2504938908
/* AndroidSwissKnife Copyright (C) 2016 macleod2486 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see [http://www.gnu.org/licenses/]. */ package com.macleod2486.androidswissknife import android.content.pm.PackageManager import android.os.Bundle import androidx.core.view.GravityCompat import androidx.drawerlayout.widget.DrawerLayout import androidx.appcompat.app.AppCompatActivity import android.util.Log import android.view.MenuItem import android.view.View import android.widget.AdapterView.OnItemClickListener import android.widget.ArrayAdapter import android.widget.ListView import android.widget.Toast import androidx.appcompat.app.ActionBarDrawerToggle import com.macleod2486.androidswissknife.views.NFC import com.macleod2486.androidswissknife.views.Toggles class MainActivity : AppCompatActivity() { var index = 0 //Request codes val CAMERA_CODE = 0 lateinit private var drawer: DrawerLayout lateinit private var drawerToggle: ActionBarDrawerToggle //Different fragments var toggleFrag = Toggles() var nfcFrag = NFC() //Manages what the back button does override fun onBackPressed() { if (drawer.isDrawerOpen(GravityCompat.START)) { Log.i("Main", "Drawer closed") drawer.closeDrawers() } if (index == 0 && !toggleFrag.isAdded) { supportFragmentManager.beginTransaction().replace(R.id.container, toggleFrag, "main").commit() } else { super.onBackPressed() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //Configures the drawer drawer = findViewById<View>(R.id.drawer) as DrawerLayout drawerToggle = object : ActionBarDrawerToggle(this, drawer, R.string.drawer_open, R.string.drawer_close) { override fun onDrawerClosed(view: View) { supportActionBar!!.setTitle(R.string.drawer_close) super.onDrawerClosed(view) } override fun onDrawerOpened(drawerView: View) { supportActionBar!!.setTitle(R.string.drawer_open) super.onDrawerOpened(drawerView) } } drawer.setDrawerListener(drawerToggle) drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED) //Sets up the listview within the drawer val menuList = resources.getStringArray(R.array.menu) val list = findViewById<View>(R.id.optionList) as ListView list.adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, menuList) list.onItemClickListener = OnItemClickListener { parent, view, position, id -> Log.i("MainActivity", "Position $position") if (position == 0) { index = 0 supportFragmentManager.beginTransaction().replace(R.id.container, toggleFrag, "toggles").commit() } else if (position == 1) { index = 1 supportFragmentManager.beginTransaction().replace(R.id.container, nfcFrag, "nfc").commit() } drawer.closeDrawers() } //Make the actionbar clickable to bring out the drawer supportActionBar!!.setDisplayHomeAsUpEnabled(true) supportActionBar!!.setHomeButtonEnabled(true) //Displays the first fragment supportFragmentManager.beginTransaction().replace(R.id.container, toggleFrag, "toggles").commit() } //Toggles open the drawer override fun onOptionsItemSelected(item: MenuItem): Boolean { if (drawer.isDrawerOpen(GravityCompat.START)) { drawer.closeDrawers() } else { drawer.openDrawer(GravityCompat.START) } return true } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { when (requestCode) { CAMERA_CODE -> { if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) { toggleFrag.toggleLight() } else { Toast.makeText(this, "Need to enable all wifi permissions", Toast.LENGTH_SHORT).show() } return } } } }
app/src/main/java/com/macleod2486/androidswissknife/MainActivity.kt
1268153472
package com.safechat.firebase.conversation import junit.framework.Assert.assertEquals import org.junit.Test class FirebaseMessageTest { val myUid = "my-uid" val otherUid = "other-uid" val timestamp = 1466490821381 @Test fun shouldConvertMessageToFirebase() { val message = com.safechat.message.Message("text", false, false, timestamp) assertEquals(message, message.toFirebaseMessage(myUid, otherUid).toMessage(myUid, timestamp)) } @Test fun shouldConvertMineMessageToFirebase() { val message = com.safechat.message.Message("text", true, false, timestamp) assertEquals(message, message.toFirebaseMessage(myUid, otherUid).toMessage(myUid, timestamp)) } @Test fun shouldConvertReadMessageToFirebase() { val message = com.safechat.message.Message("text", false, true, timestamp) assertEquals(message, message.toFirebaseMessage(myUid, otherUid).toMessage(myUid, timestamp)) } @Test fun shouldConvertMineReadMessageToFirebase() { val message = com.safechat.message.Message("text", true, true, timestamp) assertEquals(message, message.toFirebaseMessage(myUid, otherUid).toMessage(myUid, timestamp)) } }
firebase/src/test/java/com/safechat/firebase/conversation/FirebaseMessageTest.kt
528897967
/* * Copyright (C) 2019. OpenLattice, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * You can contact the owner of the copyright at [email protected] * * */ package com.openlattice.organizations.events import com.openlattice.organizations.SecurablePrincipalList import java.util.UUID data class MembersRemovedFromOrganizationEvent(val organizationId: UUID, val members: SecurablePrincipalList)
src/main/kotlin/com/openlattice/organizations/events/MembersRemovedFromOrganizationEvent.kt
606154688
package org.http4k.cloudnative.health import com.natpryce.hamkrest.and import com.natpryce.hamkrest.assertion.assertThat import org.http4k.core.Method.GET import org.http4k.core.Request import org.http4k.core.Response import org.http4k.core.Status.Companion.I_M_A_TEAPOT import org.http4k.core.Status.Companion.OK import org.http4k.core.Status.Companion.SERVICE_UNAVAILABLE import org.http4k.hamkrest.hasBody import org.http4k.hamkrest.hasStatus import org.http4k.routing.bind import org.junit.jupiter.api.Test class HealthTest { private val health = Health(extraRoutes = arrayOf("/other" bind GET to { Response(I_M_A_TEAPOT) })) @Test fun liveness() { assertThat(health(Request(GET, "/liveness")), hasStatus(OK)) } @Test fun readiness() { assertThat(health(Request(GET, "/readiness")), hasStatus(OK).and(hasBody("success=true"))) } @Test fun `extra routes are callable`() { assertThat(health(Request(GET, "/other")), hasStatus(I_M_A_TEAPOT)) } @Test fun `readiness with extra checks`() { assertThat(Health(checks = listOf(check(true, "first"), check(false, "second")))(Request(GET, "/readiness")), hasStatus(SERVICE_UNAVAILABLE).and(hasBody("overall=false\nfirst=true\nsecond=false [foobar]"))) } @Test fun `readiness continues to run when check fails`() { assertThat(Health(checks = listOf(throws("boom"), check(true, "second")))(Request(GET, "/readiness")), hasStatus(SERVICE_UNAVAILABLE).and(hasBody("overall=false\nboom=false [foobar]\nsecond=true"))) } @Test fun `readiness with three checks`() { val checks = listOf(check(true, "first"), check(true, "second"), check(false, "third")) assertThat(Health(checks = checks)(Request(GET, "/readiness")), hasStatus(SERVICE_UNAVAILABLE).and(hasBody("overall=false\nfirst=true\nsecond=true\nthird=false [foobar]"))) } @Test fun `readiness with four checks`() { val checks = listOf(check(true, "first"), check(true, "second"), check(true, "third"), check(false, "fourth")) assertThat(Health(checks = checks)(Request(GET, "/readiness")), hasStatus(SERVICE_UNAVAILABLE).and(hasBody("overall=false\nfirst=true\nsecond=true\nthird=true\nfourth=false [foobar]"))) } @Test fun `readiness with three passing checks`() { val checks = listOf(check(true, "first"), check(true, "second"), check(true, "third")) assertThat(Health(checks = checks)(Request(GET, "/readiness")), hasStatus(OK).and(hasBody("overall=true\nfirst=true\nsecond=true\nthird=true"))) } private fun check(result: Boolean, name: String): ReadinessCheck = object : ReadinessCheck { override fun invoke(): ReadinessCheckResult = if (result) Completed(name) else Failed(name, "foobar") override val name: String = name } private fun throws(name: String): ReadinessCheck = object : ReadinessCheck { override fun invoke(): ReadinessCheckResult = throw Exception("foobar") override val name: String = name } }
http4k-cloudnative/src/test/kotlin/org/http4k/cloudnative/health/HealthTest.kt
290781053
package com.binarymonks.jj.core.scenes import com.badlogic.gdx.utils.Array import com.badlogic.gdx.utils.ObjectMap import com.binarymonks.jj.core.JJ import com.binarymonks.jj.core.api.ScenesAPI import com.binarymonks.jj.core.assets.AssetReference import com.binarymonks.jj.core.async.Bond import com.binarymonks.jj.core.async.OneTimeTask import com.binarymonks.jj.core.extensions.emptyGDXArray import com.binarymonks.jj.core.pools.Poolable import com.binarymonks.jj.core.pools.new import com.binarymonks.jj.core.pools.newArray import com.binarymonks.jj.core.pools.recycle import com.binarymonks.jj.core.specs.InstanceParams import com.binarymonks.jj.core.specs.SceneSpec import com.binarymonks.jj.core.specs.SceneSpecRef import com.binarymonks.jj.core.workshop.MasterFactory class Scenes : ScenesAPI { val masterFactory = MasterFactory() private val unresolvedSpecRefs: ObjectMap<String, SceneSpecRef> = ObjectMap() val sceneSpecs: ObjectMap<String, SceneSpec> = ObjectMap() private var dirty = false internal var rootScene: Scene? = null internal var scenesByGroupName = ObjectMap<String, Array<Scene>>() internal var inUpdate = false override fun instantiate(instanceParams: InstanceParams, scene: SceneSpec): Bond<Scene> { return instantiate(instanceParams, scene, rootScene) } internal fun instantiate(instanceParams: InstanceParams, scene: SceneSpec, parentScene: Scene?): Bond<Scene> { loadAssetsNow() val delayedCreate = new(CreateSceneFunction::class) @Suppress("UNCHECKED_CAST") val bond = new(Bond::class) as Bond<Scene> delayedCreate.set(scene, instanceParams, bond, parentScene) if (!JJ.B.physicsWorld.isUpdating) { JJ.tasks.addPrePhysicsTask(delayedCreate) } else { JJ.tasks.addPostPhysicsTask(delayedCreate) } return bond } override fun instantiate(instanceParams: InstanceParams, path: String): Bond<Scene> { loadAssetsNow() // To resolve any new SceneSpecRefs. return instantiate(instanceParams, sceneSpecs.get(path)) } internal fun instantiate(instanceParams: InstanceParams, path: String, parentScene: Scene?): Bond<Scene> { loadAssetsNow() // To resolve any new SceneSpecRefs. return instantiate(instanceParams, sceneSpecs.get(path), parentScene) } override fun instantiate(scene: SceneSpec): Bond<Scene> { return instantiate(InstanceParams.new(), scene) } override fun instantiate(path: String): Bond<Scene> { return instantiate(InstanceParams.new(), path) } override fun addSceneSpec(path: String, scene: SceneSpecRef) { unresolvedSpecRefs.put(path, scene) dirty = true } fun getScene(path: String): SceneSpec { return sceneSpecs.get(path) } override fun loadAssetsNow() { if (dirty) { var assets: Array<AssetReference> = getAllAssets() JJ.B.assets.loadNow(assets) unresolvedSpecRefs.forEach { sceneSpecs.put(it.key, it.value.resolve()) } unresolvedSpecRefs.clear() } dirty = false } private fun getAllAssets(): Array<AssetReference> { val assets: Array<AssetReference> = Array() for (entry in unresolvedSpecRefs) { assets.addAll(entry.value.getAssets()) } return assets } override fun destroyAll() { JJ.tasks.doOnceAfterPhysics { destroyAllScenes() } } override fun getScenesByGroupName(groupName: String, outResult: Array<Scene>){ if (scenesByGroupName.containsKey(groupName)) { outResult.addAll(scenesByGroupName[groupName]) } } /** * Adds scene to world. */ internal fun add(scene: Scene) { if (scene.groupName != null) { if (!scenesByGroupName.containsKey(scene.groupName)) { scenesByGroupName.put(scene.groupName, newArray()) } scenesByGroupName[scene.groupName].add(scene) } } /** *Removes a scene from the world. */ internal fun remove(scene: Scene) { if (scene.groupName != null) { scenesByGroupName[scene.groupName].removeValue(scene, true) } } fun update() { inUpdate = true rootScene?.update() inUpdate = false } internal fun destroyAllScenes() { for (entry in rootScene!!.sceneLayers.entries()) { val layerCopy: Array<Scene> = newArray() for (scene in entry.value) { layerCopy.add(scene) } for (scene in layerCopy) { scene.destroy() } recycle(layerCopy) } } } class CreateSceneFunction : OneTimeTask(), Poolable { internal var sceneSpec: SceneSpec? = null internal var instanceParams: InstanceParams? = null internal var bond: Bond<Scene>? = null internal var parentScene: Scene? = null operator fun set(sceneSpec: SceneSpec, instanceParams: InstanceParams, bond: Bond<Scene>, parentScene: Scene?) { this.sceneSpec = sceneSpec this.instanceParams = instanceParams.clone() this.bond = bond this.parentScene = parentScene } override fun doOnce() { val scene = JJ.B.scenes.masterFactory.createScene(sceneSpec!!, instanceParams!!, parentScene) bond!!.succeed(scene) recycle(instanceParams!!) recycle(this) } override fun reset() { sceneSpec = null instanceParams = null bond = null parentScene = null } }
jenjin-core/src/main/kotlin/com/binarymonks/jj/core/scenes/Scenes.kt
1428129807
package io.squark.yggdrasil.bootstrap import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.Closeable import java.io.File import java.io.FileNotFoundException import java.io.InputStream import java.net.URL import java.net.URLConnection import java.util.jar.JarEntry import java.util.jar.JarFile import java.util.jar.JarInputStream internal class NestedJarURLConnection(url: URL) : URLConnection(url), Closeable { private var _inputStream: InputStream? = null override fun close() { _inputStream ?: _inputStream!!.close() } override fun connect() { if (url.protocol != "jar") { throw NotImplementedError("Protocol ${url.protocol} not supported") } val parts = url.path.split("!/") if (parts.size < 2 || parts.size > 3) { throw IllegalArgumentException( "URL should have jar part followed by entry and optional subentry (jar://path/to/jar.jar!/entry/in/jar!/sub/entry). Was \"${url.path}\"") } val jar = parts[0] val entry = parts[1] val jarFile = JarFile(File(URL(jar).file)) val jarEntry = jarFile.getJarEntry(entry) if (parts.size == 3) { val subEntryName = parts[2] if (!jarEntry.name.endsWith(".jar")) { throw IllegalArgumentException("Only JAR entries can hold subEntries. Was ${jarEntry.name}") } val jarInputStream = JarInputStream(jarFile.getInputStream(jarEntry)) var subEntry: JarEntry? = jarInputStream.nextJarEntry var bytes: ByteArray? = null while (subEntry != null) { if (subEntryName == subEntry.name) { val buffer = ByteArray(2048) val outputStream = ByteArrayOutputStream() var len = jarInputStream.read(buffer) while (len > 0) { outputStream.write(buffer, 0, len) len = jarInputStream.read(buffer) } bytes = outputStream.toByteArray() outputStream.close() break } subEntry = jarInputStream.nextJarEntry continue } if (bytes == null) { throw FileNotFoundException("${url}") } _inputStream = ByteArrayInputStream(bytes) jarInputStream.close() jarFile.close() } else { _inputStream = jarFile.getInputStream(jarEntry) } } override fun getInputStream(): InputStream? { return _inputStream } }
yggdrasil-bootstrap/src/main/kotlin/io/squark/yggdrasil/bootstrap/NestedJarURLConnection.kt
2135690667
/* * Copyright (C) 2022 Block, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.cash.zipline /** * A function defined on an interface that extends [ZiplineService] and that may be bridged. */ interface ZiplineFunction<T : ZiplineService> { val name: String /** True if this function is [ZiplineService.close]. */ val isClose: Boolean }
zipline/src/commonMain/kotlin/app/cash/zipline/ZiplineFunction.kt
376725135
package org.jetbrains.jsonProtocol public interface ItemDescriptor { public fun description(): String? public fun type(): String public fun getEnum(): List<String>? public fun items(): ProtocolMetaModel.ArrayItemType public interface Named : Referenceable { public fun name(): String JsonOptionalField public fun shortName(): String? public fun optional(): Boolean } public interface Referenceable : ItemDescriptor { public fun ref(): String } public interface Type : ItemDescriptor { public fun properties(): List<ProtocolMetaModel.ObjectProperty>? } }
platform/script-debugger/protocol/schema-reader-generator/src/ItemDescriptor.kt
2827422452
/**************************************************************************************** * Copyright (c) 2020 lukstbit <[email protected]> * * * * This program is free software; you can redistribute it and/or modify it under * * the terms of the GNU General Public License as published by the Free Software * * Foundation; either version 3 of the License, or (at your option) any later * * version. * * * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with * * this program. If not, see <http://www.gnu.org/licenses/>. * ****************************************************************************************/ @file:Suppress("UnstableApiUsage") package com.ichi2.anki.lint.rules import com.android.tools.lint.detector.api.* import com.google.common.annotations.VisibleForTesting import com.ichi2.anki.lint.utils.Constants import com.ichi2.anki.lint.utils.LintUtils.isAnAllowedClass import com.intellij.psi.PsiMethod import org.jetbrains.uast.UCallExpression /** * This custom Lint rules will raise an error if a developer instantiates the SystemTime class directly * instead of using the Time class from a Collection. * * NOTE: For future reference, if you plan on creating a Lint rule which looks for a constructor invocation, make sure * that the target class has a constructor defined in its source code! */ class DirectSystemTimeInstantiation : Detector(), SourceCodeScanner { companion object { @VisibleForTesting const val ID = "DirectSystemTimeInstantiation" @VisibleForTesting const val DESCRIPTION = "Use the collection's getTime() method instead of instantiating SystemTime" private const val EXPLANATION = "Creating SystemTime instances directly means time cannot be controlled during" + " testing, so it is not allowed. Use the collection's getTime() method instead" private val implementation = Implementation( DirectSystemTimeInstantiation::class.java, Scope.JAVA_FILE_SCOPE ) val ISSUE: Issue = Issue.create( ID, DESCRIPTION, EXPLANATION, Constants.ANKI_TIME_CATEGORY, Constants.ANKI_TIME_PRIORITY, Constants.ANKI_TIME_SEVERITY, implementation ) } override fun getApplicableConstructorTypes() = listOf("com.ichi2.libanki.utils.SystemTime") override fun visitConstructor( context: JavaContext, node: UCallExpression, constructor: PsiMethod ) { super.visitConstructor(context, node, constructor) val foundClasses = context.uastFile!!.classes if (!isAnAllowedClass(foundClasses, "Storage", "CollectionHelper")) { context.report( ISSUE, node, context.getLocation(node), DESCRIPTION ) } } }
lint-rules/src/main/java/com/ichi2/anki/lint/rules/DirectSystemTimeInstantiation.kt
4240370139
package org.needhamtrack.nytc.settings import android.content.Context import android.content.SharedPreferences import android.preference.PreferenceManager class SharedPreferencesManager private constructor(context: Context) : UserSettings { private val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) companion object { private val LAST_IP = "last_ip" private val ACCOUNT_NAME = "account_name" private var instance: UserSettings? = null fun getInstance(context: Context): UserSettings { return instance ?: SharedPreferencesManager(context).apply { instance = this } } } override var lastIp: String get() = preferences.getString(LAST_IP, "") set(value) = preferences.edit().putString(LAST_IP, value).apply() override var accountName: String get() = preferences.getString(ACCOUNT_NAME, "") set(value) = preferences.edit().putString(ACCOUNT_NAME, value).apply() }
app/src/main/kotlin/org/needhamtrack/nytc/settings/SharedPreferencesManager.kt
2236326579
package io.envoyproxy.envoymobile /** * Headers representing an inbound response. */ class ResponseHeaders : Headers { /** * Internal constructor used by builders. * * @param headers: Headers to set. */ internal constructor(headers: Map<String, List<String>>) : super(HeadersContainer.create(headers)) internal constructor(container: HeadersContainer) : super(container) /** * HTTP status code received with the response. */ val httpStatus: Int? by lazy { value(":status")?.first()?.toIntOrNull()?.takeIf { it >= 0 } } /** * Convert the headers back to a builder for mutation. * * @return ResponseHeadersBuilder, The new builder. */ fun toResponseHeadersBuilder() = ResponseHeadersBuilder(container) }
mobile/library/kotlin/io/envoyproxy/envoymobile/ResponseHeaders.kt
3962417612
package de.westnordost.streetcomplete.data.osmnotes import android.util.Log import de.westnordost.osmapi.user.UserApi import de.westnordost.streetcomplete.ktx.format import de.westnordost.streetcomplete.ktx.saveToFile import java.io.File import java.io.IOException import java.net.URL import javax.inject.Inject import javax.inject.Named /** Downloads and stores the OSM avatars of users */ class AvatarsDownloader @Inject constructor( private val userApi: UserApi, @Named("AvatarsCacheDirectory") private val cacheDir: File ) { fun download(userIds: Collection<Long>) { if (!ensureCacheDirExists()) { Log.w(TAG, "Unable to create directories for avatars") return } val time = System.currentTimeMillis() for (userId in userIds) { val avatarUrl = getProfileImageUrl(userId) if (avatarUrl != null) { download(userId, avatarUrl) } } val seconds = (System.currentTimeMillis() - time) / 1000.0 Log.i(TAG, "Downloaded ${userIds.size} avatar images in ${seconds.format(1)}s") } private fun getProfileImageUrl(userId: Long): String? { return try { userApi.get(userId)?.profileImageUrl } catch (e : Exception) { Log.w(TAG, "Unable to query info for user id $userId") null } } /** download avatar for the given user and a known avatar url */ fun download(userId: Long, avatarUrl: String) { if (!ensureCacheDirExists()) return try { val avatarFile = File(cacheDir, "$userId") URL(avatarUrl).saveToFile(avatarFile) Log.d(TAG, "Downloaded file: ${avatarFile.path}") } catch (e: IOException) { Log.w(TAG, "Unable to download avatar for user id $userId") } } private fun ensureCacheDirExists(): Boolean { return cacheDir.exists() || cacheDir.mkdirs() } companion object { private const val TAG = "OsmAvatarsDownload" } }
app/src/main/java/de/westnordost/streetcomplete/data/osmnotes/AvatarsDownloader.kt
2379884908
@file:JvmName("Sdk28ServicesKt") package org.jetbrains.anko import android.content.Context import android.view.accessibility.AccessibilityManager import android.accounts.AccountManager import android.app.ActivityManager import android.app.AlarmManager import android.app.AppOpsManager import android.media.AudioManager import android.os.BatteryManager import android.bluetooth.BluetoothManager import android.hardware.camera2.CameraManager import android.view.accessibility.CaptioningManager import android.telephony.CarrierConfigManager import android.content.ClipboardManager import android.companion.CompanionDeviceManager import android.net.ConnectivityManager import android.hardware.ConsumerIrManager import android.app.admin.DevicePolicyManager import android.hardware.display.DisplayManager import android.app.DownloadManager import android.telephony.euicc.EuiccManager import android.hardware.fingerprint.FingerprintManager import android.os.HardwarePropertiesManager import android.hardware.input.InputManager import android.view.inputmethod.InputMethodManager import android.app.KeyguardManager import android.location.LocationManager import android.media.projection.MediaProjectionManager import android.media.session.MediaSessionManager import android.media.midi.MidiManager import android.app.usage.NetworkStatsManager import android.nfc.NfcManager import android.app.NotificationManager import android.net.nsd.NsdManager import android.os.PowerManager import android.print.PrintManager import android.content.RestrictionsManager import android.app.SearchManager import android.hardware.SensorManager import android.content.pm.ShortcutManager import android.os.storage.StorageManager import android.app.usage.StorageStatsManager import android.os.health.SystemHealthManager import android.telecom.TelecomManager import android.telephony.TelephonyManager import android.view.textclassifier.TextClassificationManager import android.media.tv.TvInputManager import android.app.UiModeManager import android.app.usage.UsageStatsManager import android.hardware.usb.UsbManager import android.os.UserManager import android.app.WallpaperManager import android.net.wifi.aware.WifiAwareManager import android.net.wifi.WifiManager import android.net.wifi.p2p.WifiP2pManager import android.view.WindowManager /** Returns the AccessibilityManager instance. **/ val Context.accessibilityManager: AccessibilityManager get() = getSystemService(Context.ACCESSIBILITY_SERVICE) as AccessibilityManager /** Returns the AccountManager instance. **/ val Context.accountManager: AccountManager get() = getSystemService(Context.ACCOUNT_SERVICE) as AccountManager /** Returns the ActivityManager instance. **/ val Context.activityManager: ActivityManager get() = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager /** Returns the AlarmManager instance. **/ val Context.alarmManager: AlarmManager get() = getSystemService(Context.ALARM_SERVICE) as AlarmManager /** Returns the AppOpsManager instance. **/ val Context.appOpsManager: AppOpsManager get() = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager /** Returns the AudioManager instance. **/ val Context.audioManager: AudioManager get() = getSystemService(Context.AUDIO_SERVICE) as AudioManager /** Returns the BatteryManager instance. **/ val Context.batteryManager: BatteryManager get() = getSystemService(Context.BATTERY_SERVICE) as BatteryManager /** Returns the BluetoothManager instance. **/ val Context.bluetoothManager: BluetoothManager get() = getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager /** Returns the CameraManager instance. **/ val Context.cameraManager: CameraManager get() = getSystemService(Context.CAMERA_SERVICE) as CameraManager /** Returns the CaptioningManager instance. **/ val Context.captioningManager: CaptioningManager get() = getSystemService(Context.CAPTIONING_SERVICE) as CaptioningManager /** Returns the CarrierConfigManager instance. **/ val Context.carrierConfigManager: CarrierConfigManager get() = getSystemService(Context.CARRIER_CONFIG_SERVICE) as CarrierConfigManager /** Returns the ClipboardManager instance. **/ val Context.clipboardManager: ClipboardManager get() = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager /** Returns the CompanionDeviceManager instance. **/ val Context.companionDeviceManager: CompanionDeviceManager get() = getSystemService(Context.COMPANION_DEVICE_SERVICE) as CompanionDeviceManager /** Returns the ConnectivityManager instance. **/ val Context.connectivityManager: ConnectivityManager get() = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager /** Returns the ConsumerIrManager instance. **/ val Context.consumerIrManager: ConsumerIrManager get() = getSystemService(Context.CONSUMER_IR_SERVICE) as ConsumerIrManager /** Returns the DevicePolicyManager instance. **/ val Context.devicePolicyManager: DevicePolicyManager get() = getSystemService(Context.DEVICE_POLICY_SERVICE) as DevicePolicyManager /** Returns the DisplayManager instance. **/ val Context.displayManager: DisplayManager get() = getSystemService(Context.DISPLAY_SERVICE) as DisplayManager /** Returns the DownloadManager instance. **/ val Context.downloadManager: DownloadManager get() = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager /** Returns the EuiccManager instance. **/ val Context.euiccManager: EuiccManager get() = getSystemService(Context.EUICC_SERVICE) as EuiccManager /** Returns the FingerprintManager instance. **/ val Context.fingerprintManager: FingerprintManager get() = getSystemService(Context.FINGERPRINT_SERVICE) as FingerprintManager /** Returns the HardwarePropertiesManager instance. **/ val Context.hardwarePropertiesManager: HardwarePropertiesManager get() = getSystemService(Context.HARDWARE_PROPERTIES_SERVICE) as HardwarePropertiesManager /** Returns the InputManager instance. **/ val Context.inputManager: InputManager get() = getSystemService(Context.INPUT_SERVICE) as InputManager /** Returns the InputMethodManager instance. **/ val Context.inputMethodManager: InputMethodManager get() = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager /** Returns the KeyguardManager instance. **/ val Context.keyguardManager: KeyguardManager get() = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager /** Returns the LocationManager instance. **/ val Context.locationManager: LocationManager get() = getSystemService(Context.LOCATION_SERVICE) as LocationManager /** Returns the MediaProjectionManager instance. **/ val Context.mediaProjectionManager: MediaProjectionManager get() = getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager /** Returns the MediaSessionManager instance. **/ val Context.mediaSessionManager: MediaSessionManager get() = getSystemService(Context.MEDIA_SESSION_SERVICE) as MediaSessionManager /** Returns the MidiManager instance. **/ val Context.midiManager: MidiManager get() = getSystemService(Context.MIDI_SERVICE) as MidiManager /** Returns the NetworkStatsManager instance. **/ val Context.networkStatsManager: NetworkStatsManager get() = getSystemService(Context.NETWORK_STATS_SERVICE) as NetworkStatsManager /** Returns the NfcManager instance. **/ val Context.nfcManager: NfcManager get() = getSystemService(Context.NFC_SERVICE) as NfcManager /** Returns the NotificationManager instance. **/ val Context.notificationManager: NotificationManager get() = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager /** Returns the NsdManager instance. **/ val Context.nsdManager: NsdManager get() = getSystemService(Context.NSD_SERVICE) as NsdManager /** Returns the PowerManager instance. **/ val Context.powerManager: PowerManager get() = getSystemService(Context.POWER_SERVICE) as PowerManager /** Returns the PrintManager instance. **/ val Context.printManager: PrintManager get() = getSystemService(Context.PRINT_SERVICE) as PrintManager /** Returns the RestrictionsManager instance. **/ val Context.restrictionsManager: RestrictionsManager get() = getSystemService(Context.RESTRICTIONS_SERVICE) as RestrictionsManager /** Returns the SearchManager instance. **/ val Context.searchManager: SearchManager get() = getSystemService(Context.SEARCH_SERVICE) as SearchManager /** Returns the SensorManager instance. **/ val Context.sensorManager: SensorManager get() = getSystemService(Context.SENSOR_SERVICE) as SensorManager /** Returns the ShortcutManager instance. **/ val Context.shortcutManager: ShortcutManager get() = getSystemService(Context.SHORTCUT_SERVICE) as ShortcutManager /** Returns the StorageManager instance. **/ val Context.storageManager: StorageManager get() = getSystemService(Context.STORAGE_SERVICE) as StorageManager /** Returns the StorageStatsManager instance. **/ val Context.storageStatsManager: StorageStatsManager get() = getSystemService(Context.STORAGE_STATS_SERVICE) as StorageStatsManager /** Returns the SystemHealthManager instance. **/ val Context.systemHealthManager: SystemHealthManager get() = getSystemService(Context.SYSTEM_HEALTH_SERVICE) as SystemHealthManager /** Returns the TelecomManager instance. **/ val Context.telecomManager: TelecomManager get() = getSystemService(Context.TELECOM_SERVICE) as TelecomManager /** Returns the TelephonyManager instance. **/ val Context.telephonyManager: TelephonyManager get() = getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager /** Returns the TextClassificationManager instance. **/ val Context.textClassificationManager: TextClassificationManager get() = getSystemService(Context.TEXT_CLASSIFICATION_SERVICE) as TextClassificationManager /** Returns the TvInputManager instance. **/ val Context.tvInputManager: TvInputManager get() = getSystemService(Context.TV_INPUT_SERVICE) as TvInputManager /** Returns the UiModeManager instance. **/ val Context.uiModeManager: UiModeManager get() = getSystemService(Context.UI_MODE_SERVICE) as UiModeManager /** Returns the UsageStatsManager instance. **/ val Context.usageStatsManager: UsageStatsManager get() = getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager /** Returns the UsbManager instance. **/ val Context.usbManager: UsbManager get() = getSystemService(Context.USB_SERVICE) as UsbManager /** Returns the UserManager instance. **/ val Context.userManager: UserManager get() = getSystemService(Context.USER_SERVICE) as UserManager /** Returns the WallpaperManager instance. **/ val Context.wallpaperManager: WallpaperManager get() = getSystemService(Context.WALLPAPER_SERVICE) as WallpaperManager /** Returns the WifiAwareManager instance. **/ val Context.wifiAwareManager: WifiAwareManager get() = getSystemService(Context.WIFI_AWARE_SERVICE) as WifiAwareManager /** Returns the WifiManager instance. **/ val Context.wifiManager: WifiManager get() = getSystemService(Context.WIFI_SERVICE) as WifiManager /** Returns the WifiP2pManager instance. **/ val Context.wifiP2pManager: WifiP2pManager get() = getSystemService(Context.WIFI_P2P_SERVICE) as WifiP2pManager /** Returns the WindowManager instance. **/ val Context.windowManager: WindowManager get() = getSystemService(Context.WINDOW_SERVICE) as WindowManager
anko/library/generated/sdk28/src/main/java/Services.kt
3031173670
/* * Copyright (C) 2014-2020 Arpit Khurana <[email protected]>, Vishal Nehra <[email protected]>, * Emmanuel Messulam<[email protected]>, Raymond Lai <airwave209gt at gmail.com> and Contributors. * * This file is part of Amaze File Manager. * * Amaze File Manager is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.amaze.filemanager.shadows import com.amaze.filemanager.utils.SmbUtil import jcifs.context.SingletonContext import jcifs.smb.SmbException import jcifs.smb.SmbFile import org.mockito.Mockito.* import org.robolectric.annotation.Implementation import org.robolectric.annotation.Implements @Implements(SmbUtil::class) class ShadowSmbUtil { companion object { const val PATH_CANNOT_DELETE_FILE = "smb://user:[email protected]/access/denied.file" const val PATH_CANNOT_MOVE_FILE = "smb://user:[email protected]/cannot/move.file" const val PATH_CANNOT_RENAME_OLDFILE = "smb://user:[email protected]/cannot/rename.file.old" const val PATH_CAN_RENAME_OLDFILE = "smb://user:[email protected]/rename/old.file" const val PATH_CAN_RENAME_NEWFILE = "smb://user:[email protected]/rename/new.file" var mockDeleteAccessDenied: SmbFile? = null var mockDeleteDifferentNetwork: SmbFile? = null var mockCannotRenameOld: SmbFile? = null var mockCanRename: SmbFile? = null init { mockDeleteAccessDenied = createInternal(PATH_CANNOT_DELETE_FILE).also { `when`(it.delete()).thenThrow(SmbException("Access is denied.")) `when`(it.exists()).thenReturn(true) } mockDeleteDifferentNetwork = createInternal(PATH_CANNOT_MOVE_FILE).also { `when`(it.delete()).thenThrow(SmbException("Cannot rename between different trees")) `when`(it.exists()).thenReturn(true) } mockCanRename = createInternal(PATH_CAN_RENAME_OLDFILE).also { doNothing().`when`(it).renameTo(any()) } mockCannotRenameOld = createInternal(PATH_CANNOT_RENAME_OLDFILE) `when`(mockCannotRenameOld!!.renameTo(any())) .thenThrow(SmbException("Access is denied.")) `when`(mockCannotRenameOld!!.exists()).thenReturn(true) } /** * Shadows SmbUtil.create() * * @see SmbUtil.create */ @JvmStatic @Implementation fun create(path: String): SmbFile { return when (path) { PATH_CANNOT_DELETE_FILE -> mockDeleteAccessDenied!! PATH_CANNOT_MOVE_FILE -> mockDeleteDifferentNetwork!! PATH_CANNOT_RENAME_OLDFILE -> mockCannotRenameOld!! PATH_CAN_RENAME_OLDFILE -> mockCanRename!! else -> createInternal(path).also { doNothing().`when`(it).delete() `when`(it.exists()).thenReturn(false) } } } private fun createInternal(path: String): SmbFile { return mock(SmbFile::class.java).also { `when`(it.name).thenReturn(path.substring(path.lastIndexOf('/') + 1)) `when`(it.path).thenReturn(path) `when`(it.context).thenReturn(SingletonContext.getInstance()) } } } }
app/src/test/java/com/amaze/filemanager/shadows/ShadowSmbUtil.kt
1375674645
package de.westnordost.streetcomplete.quests.building_type import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.osmquests.OsmFilterQuestType import de.westnordost.streetcomplete.data.osm.edits.update_tags.StringMapChangesBuilder import de.westnordost.streetcomplete.data.user.achievements.QuestTypeAchievement.BUILDING class AddBuildingType : OsmFilterQuestType<BuildingType>() { // in the case of man_made, historic, military, aeroway and power, these tags already contain // information about the purpose of the building, so no need to force asking it // or question would be confusing as there is no matching reply in available answers // same goes (more or less) for tourism, amenity, leisure. See #1854, #1891, #3233 override val elementFilter = """ ways, relations with (building = yes or building = unclassified) and !man_made and !historic and !military and !power and !tourism and !attraction and !amenity and !leisure and !aeroway and !description and location != underground and abandoned != yes and abandoned != building and abandoned:building != yes and ruins != yes and ruined != yes """ override val commitMessage = "Add building types" override val wikiLink = "Key:building" override val icon = R.drawable.ic_quest_building override val questTypeAchievements = listOf(BUILDING) override fun getTitle(tags: Map<String, String>) = R.string.quest_buildingType_title override fun createForm() = AddBuildingTypeForm() override fun applyAnswerTo(answer: BuildingType, changes: StringMapChangesBuilder) { if (answer.osmKey == "man_made") { changes.delete("building") changes.add("man_made", answer.osmValue) } else if (answer.osmKey != "building") { changes.addOrModify(answer.osmKey, answer.osmValue) if(answer == BuildingType.ABANDONED) { changes.deleteIfExists("disused") } if(answer == BuildingType.RUINS && changes.getPreviousValue("disused") == "no") { changes.deleteIfExists("disused") } if(answer == BuildingType.RUINS && changes.getPreviousValue("abandoned") == "no") { changes.deleteIfExists("abandoned") } } else { changes.modify("building", answer.osmValue) } } }
app/src/main/java/de/westnordost/streetcomplete/quests/building_type/AddBuildingType.kt
1296985939
package org.wordpress.android.fluxc.common import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.wordpress.android.fluxc.model.CommentModel import org.wordpress.android.fluxc.model.CommentStatus.APPROVED import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.model.comments.CommentsMapper import org.wordpress.android.fluxc.network.rest.wpcom.comment.CommentParent import org.wordpress.android.fluxc.network.rest.wpcom.comment.CommentWPComRestResponse import org.wordpress.android.fluxc.persistence.comments.CommentEntityList import org.wordpress.android.fluxc.persistence.comments.CommentsDao.CommentEntity import org.wordpress.android.fluxc.utils.DateTimeUtilsWrapper import java.util.Date class CommentsMapperTest { private val dateTimeUtilsWrapper: DateTimeUtilsWrapper = mock() private val mapper = CommentsMapper(dateTimeUtilsWrapper) @Test fun `xmlrpc dto is converted to entity`() { val comment = getDefaultComment(false).copy( authorProfileImageUrl = null, datePublished = "2021-07-29T21:29:27+00:00" ) val site = SiteModel().apply { id = comment.localSiteId selfHostedSiteId = comment.remoteSiteId } val xmlRpcDto = comment.toXmlRpcDto() whenever(dateTimeUtilsWrapper.timestampFromIso8601(any())).thenReturn(comment.publishedTimestamp) whenever(dateTimeUtilsWrapper.iso8601UTCFromDate(any())).thenReturn(comment.datePublished) val mappedEntity = mapper.commentXmlRpcDTOToEntity(xmlRpcDto, site) assertThat(mappedEntity).isEqualTo(comment) } @Test fun `xmlrpc dto list is converted to entity list`() { val commentList = getDefaultCommentList(false).map { it.copy(id = 0, authorProfileImageUrl = null) } val site = SiteModel().apply { id = commentList.first().localSiteId selfHostedSiteId = commentList.first().remoteSiteId } val xmlRpcDtoList = commentList.map { it.toXmlRpcDto() } whenever(dateTimeUtilsWrapper.timestampFromIso8601(any())).thenReturn(commentList.first().publishedTimestamp) whenever(dateTimeUtilsWrapper.iso8601UTCFromDate(any())).thenReturn(commentList.first().datePublished) val mappedEntityList = mapper.commentXmlRpcDTOToEntityList(xmlRpcDtoList.toTypedArray(), site) assertThat(mappedEntityList).isEqualTo(commentList) } @Test fun `dto is converted to entity`() { val comment = getDefaultComment(true).copy(datePublished = "2021-07-29T21:29:27+00:00") val site = SiteModel().apply { id = comment.localSiteId siteId = comment.remoteSiteId } val commentDto = comment.toDto() whenever(dateTimeUtilsWrapper.timestampFromIso8601(any())).thenReturn(comment.publishedTimestamp) val mappedEntity = mapper.commentDtoToEntity(commentDto, site) assertThat(mappedEntity).isEqualTo(comment) } @Test fun `entity is converted to model`() { val comment = getDefaultComment(true).copy(datePublished = "2021-07-29T21:29:27+00:00") val commentModel = comment.toModel() val mappedModel = mapper.commentEntityToLegacyModel(comment) assertModelsEqual(mappedModel, commentModel) } @Test fun `model is converted to entity`() { val comment = getDefaultComment(true).copy(datePublished = "2021-07-29T21:29:27+00:00") val commentModel = comment.toModel() val mappedEntity = mapper.commentLegacyModelToEntity(commentModel) assertThat(mappedEntity).isEqualTo(comment) } @Suppress("ComplexMethod") private fun assertModelsEqual(mappedModel: CommentModel, commentModel: CommentModel): Boolean { return mappedModel.id == commentModel.id && mappedModel.remoteCommentId == commentModel.remoteCommentId && mappedModel.remotePostId == commentModel.remotePostId && mappedModel.authorId == commentModel.authorId && mappedModel.localSiteId == commentModel.localSiteId && mappedModel.remoteSiteId == commentModel.remoteSiteId && mappedModel.authorUrl == commentModel.authorUrl && mappedModel.authorName == commentModel.authorName && mappedModel.authorEmail == commentModel.authorEmail && mappedModel.authorProfileImageUrl == commentModel.authorProfileImageUrl && mappedModel.postTitle == commentModel.postTitle && mappedModel.status == commentModel.status && mappedModel.datePublished == commentModel.datePublished && mappedModel.publishedTimestamp == commentModel.publishedTimestamp && mappedModel.content == commentModel.content && mappedModel.url == commentModel.url && mappedModel.hasParent == commentModel.hasParent && mappedModel.parentId == commentModel.parentId && mappedModel.iLike == commentModel.iLike } private fun CommentEntity.toDto(): CommentWPComRestResponse { val entity = this return CommentWPComRestResponse().apply { ID = entity.remoteCommentId URL = entity.url author = Author().apply { ID = entity.authorId URL = entity.authorUrl avatar_URL = entity.authorProfileImageUrl email = entity.authorEmail name = entity.authorName } content = entity.content date = entity.datePublished i_like = entity.iLike parent = CommentParent().apply { ID = entity.parentId } post = Post().apply { type = "post" title = entity.postTitle link = "https://public-api.wordpress.com/rest/v1.1/sites/185464053/posts/85" ID = entity.remotePostId } status = entity.status } } private fun CommentEntity.toModel(): CommentModel { val entity = this return CommentModel().apply { id = entity.id.toInt() remoteCommentId = entity.remoteCommentId remotePostId = entity.remotePostId authorId = entity.authorId localSiteId = entity.localSiteId remoteSiteId = entity.remoteSiteId authorUrl = entity.authorUrl authorName = entity.authorName authorEmail = entity.authorEmail authorProfileImageUrl = entity.authorProfileImageUrl postTitle = entity.postTitle status = entity.status datePublished = entity.datePublished publishedTimestamp = entity.publishedTimestamp content = entity.content url = entity.authorProfileImageUrl hasParent = entity.hasParent parentId = entity.parentId iLike = entity.iLike } } private fun CommentEntity.toXmlRpcDto(): HashMap<*, *> { return hashMapOf<String, Any?>( "parent" to this.parentId.toString(), "post_title" to this.postTitle, "author" to this.authorName, "link" to this.url, "date_created_gmt" to Date(), "comment_id" to this.remoteCommentId.toString(), "content" to this.content, "author_url" to this.authorUrl, "post_id" to this.remotePostId, "user_id" to this.authorId, "author_email" to this.authorEmail, "status" to this.status ) } private fun getDefaultComment(allowNulls: Boolean): CommentEntity { return CommentEntity( id = 0, remoteCommentId = 10, remotePostId = 100, authorId = 44, localSiteId = 10_000, remoteSiteId = 100_000, authorUrl = if (allowNulls) null else "https://test-debug-site.wordpress.com", authorName = if (allowNulls) null else "authorname", authorEmail = if (allowNulls) null else "[email protected]", authorProfileImageUrl = if (allowNulls) null else "https://gravatar.com/avatar/111222333", postTitle = if (allowNulls) null else "again", status = APPROVED.toString(), datePublished = if (allowNulls) null else "2021-05-12T15:10:40+02:00", publishedTimestamp = 1_000_000, content = if (allowNulls) null else "content example", url = if (allowNulls) null else "https://test-debug-site.wordpress.com/2021/02/25/again/#comment-137", hasParent = true, parentId = 1_000L, iLike = false ) } private fun getDefaultCommentList(allowNulls: Boolean): CommentEntityList { val comment = getDefaultComment(allowNulls) return listOf( comment.copy(id = 1, remoteCommentId = 10, datePublished = "2021-07-24T00:51:43+02:00"), comment.copy(id = 2, remoteCommentId = 20, datePublished = "2021-07-24T00:51:43+02:00"), comment.copy(id = 3, remoteCommentId = 30, datePublished = "2021-07-24T00:51:43+02:00"), comment.copy(id = 4, remoteCommentId = 40, datePublished = "2021-07-24T00:51:43+02:00") ) } }
example/src/test/java/org/wordpress/android/fluxc/common/CommentsMapperTest.kt
1502192171
package org.zaproxy.zap import java.io.File data class GitHubRepo(val owner: String, val name: String, val dir: File? = null) { override fun toString() = "$owner/$name" }
buildSrc/src/main/kotlin/org/zaproxy/zap/GitHubRepo.kt
2571000892
package ch.difty.scipamato.publ import ch.difty.scipamato.common.logger import ch.difty.scipamato.publ.config.ScipamatoPublicProperties import io.mockk.every import io.mockk.mockk import org.junit.jupiter.api.Test private val log = logger() class ScipamatoPublicApplicationTest { @Test fun withCommercialFontEnabled_willOutputLog() { val properties = mockk<ScipamatoPublicProperties> { every { isCommercialFontPresent } returns true every { isResponsiveIframeSupportEnabled } returns false } val app = ScipamatoPublicApplication(properties) log.info { "We should see single log about commercial font being enabled" } app.logSpecialConfiguration() // visually assert the respective log is on console (no automatic assertion) log.info { "----" } } @Test fun withPymEnabled_willOutputLog() { val properties = mockk<ScipamatoPublicProperties> { every { isCommercialFontPresent } returns false every { isResponsiveIframeSupportEnabled } returns true } val app = ScipamatoPublicApplication(properties) log.info("We should see single log about pym being enabled") app.logSpecialConfiguration() // visually assert the respective log is on console (no automatic assertion) log.info("----") } @Test fun withPropertiesDisabled_willNotOutputLogs() { val properties = mockk<ScipamatoPublicProperties> { every { isCommercialFontPresent } returns false every { isResponsiveIframeSupportEnabled } returns false } val app = ScipamatoPublicApplication(properties) log.info { "We should see no logs (about commercial fonts or pym)" } app.logSpecialConfiguration() // visually assert no logs are on console log.info { "----" } } }
public/public-web/src/test/kotlin/ch/difty/scipamato/publ/ScipamatoPublicApplicationTest.kt
1945870202
// Copyright 2022 The Cross-Media Measurement Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.wfanet.measurement.common.api interface Principal interface ResourcePrincipal : Principal { val resourceKey: ResourceKey } interface PrincipalLookup<T : Principal, K> { suspend fun getPrincipal(lookupKey: K): T? }
src/main/kotlin/org/wfanet/measurement/common/api/Principal.kt
2600318442
package ch.difty.scipamato.publ.web.pym /** * Enum defining the JavaScript snippets used in the context of providing responsive iframes with pym.js. */ enum class PymScripts(val id: String, val script: String) { INSTANTIATE("pymChild", "var pymChild = new pym.Child({ id: 'scipamato-public' });"), RESIZE("pymResize", "pymChild.sendHeight();"); }
public/public-web/src/main/kotlin/ch/difty/scipamato/publ/web/pym/PymScripts.kt
528341342
package `in`.hbb20.countrycodepickerproject import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.fragment.app.Fragment import com.hbb20.CountryCodePicker /** * A simple [Fragment] subclass. * create an instance of this fragment. */ class CustomMasterFragment: Fragment() { private lateinit var editTextCountryCustomMaster: EditText private lateinit var buttonSetCustomMaster: Button private lateinit var ccp: CountryCodePicker private lateinit var buttonNext: Button override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { // Inflate the layout for this fragment return inflater.inflate(R.layout.fragment_custom_master_list, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) assignViews() editTextWatcher() addClickListeners() } private fun addClickListeners() { buttonSetCustomMaster.setOnClickListener { val customMasterCountries: String try { customMasterCountries = editTextCountryCustomMaster.text.toString() ccp.setCustomMasterCountries(customMasterCountries) Toast.makeText(activity, "Master list has been changed. Tap on ccp to see the changes.", Toast.LENGTH_LONG).show() } catch (ex: Exception) { } } buttonNext.setOnClickListener { (activity as ExampleActivity).viewPager.currentItem = (activity as ExampleActivity).viewPager.currentItem + 1 } } private fun editTextWatcher() { editTextCountryCustomMaster.addTextChangedListener(object: TextWatcher { override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { buttonSetCustomMaster.text = "set '$s' as Custom Master List." } override fun afterTextChanged(s: Editable) { } }) } private fun assignViews() { editTextCountryCustomMaster = view!!.findViewById(R.id.editText_countryPreference) ccp = view!!.findViewById(R.id.ccp) buttonSetCustomMaster = view!!.findViewById(R.id.button_setCustomMaster) buttonNext = view!!.findViewById(R.id.button_next) } }
app/src/main/java/in/hbb20/countrycodepickerproject/CustomMasterFragment.kt
676411031
package com.jamieadkins.gwent.deck.builder.di import com.jamieadkins.gwent.di.FragmentScoped import com.jamieadkins.gwent.filter.FilterBottomSheetDialogFragment import com.jamieadkins.gwent.filter.FilterModule import com.jamieadkins.gwent.deck.builder.DeckDetailsFragment import com.jamieadkins.gwent.deck.builder.DeckDetailsModule import com.jamieadkins.gwent.deck.builder.leader.LeaderPickerDialog import com.jamieadkins.gwent.deck.builder.leader.LeaderPickerModule import com.jamieadkins.gwent.deck.builder.rename.RenameDeckDialog import com.jamieadkins.gwent.deck.builder.rename.RenameDeckModule import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class DeckBuilderFragmentInjectionModule private constructor() { @FragmentScoped @ContributesAndroidInjector(modules = [DeckDetailsModule::class]) internal abstract fun deckBuilder(): DeckDetailsFragment @FragmentScoped @ContributesAndroidInjector(modules = [LeaderPickerModule::class]) internal abstract fun leaderPicker(): LeaderPickerDialog @FragmentScoped @ContributesAndroidInjector(modules = [RenameDeckModule::class]) internal abstract fun renameDeck(): RenameDeckDialog @FragmentScoped @ContributesAndroidInjector(modules = [FilterModule::class]) internal abstract fun view(): FilterBottomSheetDialogFragment }
app/src/main/java/com/jamieadkins/gwent/deck/builder/di/DeckBuilderFragmentInjectionModule.kt
2693128519
package com.pr0gramm.app.sync import androidx.work.CoroutineWorker import androidx.work.ListenableWorker import com.pr0gramm.app.util.AndroidUtility import java.util.concurrent.CancellationException inline fun CoroutineWorker.retryOnError(block: () -> ListenableWorker.Result): ListenableWorker.Result { return try { block() } catch (err: CancellationException) { throw err } catch (err: Exception) { AndroidUtility.logToCrashlytics(err) ListenableWorker.Result.retry() } }
app/src/main/java/com/pr0gramm/app/sync/WorkerEx.kt
1651581936
package com.nikita.movies_shmoovies.common.network data class Movie(val id: String, val title: String, val poster_path: String, val release_date: String)
app/src/main/kotlin/com/nikita/movies_shmoovies/common/network/Movies.kt
1383013362
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.tests import com.intellij.openapi.project.DumbService import com.intellij.openapi.vcs.VcsBundle import com.intellij.testGuiFramework.fixtures.JBListPopupFixture import com.intellij.testGuiFramework.fixtures.ToolWindowFixture import com.intellij.testGuiFramework.framework.GuiTestUtil import com.intellij.ui.EditorComboBox import org.fest.swing.edt.GuiActionRunner import org.fest.swing.edt.GuiTask import org.junit.Ignore import org.junit.Test /** * @author Sergey Karashevich */ class GitGuiTest : GitGuiTestCase() { @Test @Ignore fun testGitImport(){ val vcsName = "Git" val gitApp = "path_to_git_repo" val projectPath = getMasterProjectDirPath(gitApp) welcomeFrame { checkoutFrom() JBListPopupFixture.findListPopup(myRobot).invokeAction(vcsName) dialog("Clone Repository") { val labelText = "Git Repository URL:" val editorComboBox = myRobot.finder().findByLabel(this.target(), labelText, EditorComboBox::class.java) GuiActionRunner.execute(object : GuiTask() { @Throws(Throwable::class) override fun executeInEDT() { editorComboBox.text = projectPath.absolutePath } }) button("Clone").click() } message(VcsBundle.message("checkout.title")).clickYes() dialog("Import Project") { button("Next").click() val textField = GuiTestUtil.findTextField(myRobot, "Project name:").click() button("Next").click() button("Next").click() button("Next").click() //libraries button("Next").click() //module dependencies button("Next").click() //select sdk button("Finish").click() } } val ideFrame = findIdeFrame() ideFrame.waitForBackgroundTasksToFinish() val projectView = ideFrame.projectView val testJavaPath = "src/First.java" val editor = ideFrame.editor editor.open(testJavaPath) ToolWindowFixture.showToolwindowStripes(myRobot) //prevent from ProjectLeak (if the project is closed during the indexing DumbService.getInstance(ideFrame.project).waitForSmartMode() } }
plugins/git4idea/tests/com/intellij/testGuiFramework/tests/GitGuiTest.kt
220225857
package com.lasthopesoftware.bluewater import android.annotation.SuppressLint import android.app.Application import android.app.NotificationManager import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.Environment import android.os.StrictMode import android.os.StrictMode.VmPolicy import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.work.Configuration import androidx.work.WorkManager import ch.qos.logback.classic.AsyncAppender import ch.qos.logback.classic.Level import ch.qos.logback.classic.Logger import ch.qos.logback.classic.LoggerContext import ch.qos.logback.classic.android.LogcatAppender import ch.qos.logback.classic.encoder.PatternLayoutEncoder import ch.qos.logback.classic.spi.ILoggingEvent import ch.qos.logback.core.rolling.RollingFileAppender import ch.qos.logback.core.rolling.TimeBasedRollingPolicy import ch.qos.logback.core.util.StatusPrinter import com.lasthopesoftware.bluewater.client.browsing.items.media.files.ServiceFile import com.lasthopesoftware.bluewater.client.browsing.items.media.files.properties.playstats.UpdatePlayStatsOnCompleteRegistration import com.lasthopesoftware.bluewater.client.browsing.library.access.LibraryRepository import com.lasthopesoftware.bluewater.client.browsing.library.access.session.SelectedBrowserLibraryIdentifierProvider import com.lasthopesoftware.bluewater.client.browsing.library.repository.LibraryId import com.lasthopesoftware.bluewater.client.browsing.library.request.read.StorageReadPermissionsRequestNotificationBuilder import com.lasthopesoftware.bluewater.client.browsing.library.request.read.StorageReadPermissionsRequestedBroadcaster import com.lasthopesoftware.bluewater.client.browsing.library.request.write.StorageWritePermissionsRequestNotificationBuilder import com.lasthopesoftware.bluewater.client.browsing.library.request.write.StorageWritePermissionsRequestedBroadcaster import com.lasthopesoftware.bluewater.client.connection.receivers.SessionConnectionRegistrationsMaintainer import com.lasthopesoftware.bluewater.client.connection.selected.SelectedConnection import com.lasthopesoftware.bluewater.client.connection.selected.SelectedConnectionSettingsChangeReceiver import com.lasthopesoftware.bluewater.client.connection.session.ConnectionSessionManager import com.lasthopesoftware.bluewater.client.connection.session.ConnectionSessionSettingsChangeReceiver import com.lasthopesoftware.bluewater.client.connection.settings.changes.ObservableConnectionSettingsLibraryStorage import com.lasthopesoftware.bluewater.client.playback.service.receivers.devices.pebble.PebbleFileChangedNotificationRegistration import com.lasthopesoftware.bluewater.client.playback.service.receivers.scrobble.PlaybackFileStartedScrobblerRegistration import com.lasthopesoftware.bluewater.client.playback.service.receivers.scrobble.PlaybackFileStoppedScrobblerRegistration import com.lasthopesoftware.bluewater.client.stored.library.items.files.StoredFileAccess import com.lasthopesoftware.bluewater.client.stored.library.items.files.system.uri.MediaFileUriProvider import com.lasthopesoftware.bluewater.client.stored.sync.SyncScheduler import com.lasthopesoftware.bluewater.settings.repository.access.CachingApplicationSettingsRepository.Companion.getApplicationSettingsRepository import com.lasthopesoftware.bluewater.shared.android.messages.MessageBus import com.lasthopesoftware.bluewater.shared.exceptions.LoggerUncaughtExceptionHandler import com.lasthopesoftware.compilation.DebugFlag import com.namehillsoftware.handoff.promises.Promise import org.slf4j.LoggerFactory import java.io.File open class MainApplication : Application() { companion object { private var isWorkManagerInitialized = false } private val notificationManagerLazy by lazy { getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager } private val storageReadPermissionsRequestNotificationBuilderLazy by lazy { StorageReadPermissionsRequestNotificationBuilder(this) } private val storageWritePermissionsRequestNotificationBuilderLazy by lazy { StorageWritePermissionsRequestNotificationBuilder(this) } private val messageBus by lazy { MessageBus(LocalBroadcastManager.getInstance(this)) } private val applicationSettings by lazy { getApplicationSettingsRepository() } @SuppressLint("DefaultLocale") override fun onCreate() { super.onCreate() initializeLogging() Thread.setDefaultUncaughtExceptionHandler(LoggerUncaughtExceptionHandler) Promise.Rejections.setUnhandledRejectionsReceiver(LoggerUncaughtExceptionHandler) registerAppBroadcastReceivers() if (!isWorkManagerInitialized) { WorkManager.initialize(this, Configuration.Builder().build()) isWorkManagerInitialized = true } SyncScheduler .promiseIsScheduled(this) .then { isScheduled -> if (!isScheduled) SyncScheduler.scheduleSync(this) } } private fun registerAppBroadcastReceivers() { messageBus.registerReceiver(object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val libraryId = intent.getIntExtra(MediaFileUriProvider.mediaFileFoundFileKey, -1) if (libraryId < 0) return val fileKey = intent.getIntExtra(MediaFileUriProvider.mediaFileFoundFileKey, -1) if (fileKey == -1) return val mediaFileId = intent.getIntExtra(MediaFileUriProvider.mediaFileFoundMediaId, -1) if (mediaFileId == -1) return val mediaFilePath = intent.getStringExtra(MediaFileUriProvider.mediaFileFoundPath) if (mediaFilePath.isNullOrEmpty()) return LibraryRepository(context) .getLibrary(LibraryId(libraryId)) .then { library -> if (library != null) { val storedFileAccess = StoredFileAccess( context ) storedFileAccess.addMediaFile(library, ServiceFile(fileKey), mediaFileId, mediaFilePath) } } } }, IntentFilter(MediaFileUriProvider.mediaFileFoundEvent)) messageBus.registerReceiver(object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val libraryId = intent.getIntExtra(StorageReadPermissionsRequestedBroadcaster.ReadPermissionsLibraryId, -1) if (libraryId < 0) return notificationManagerLazy.notify( 336, storageReadPermissionsRequestNotificationBuilderLazy .buildReadPermissionsRequestNotification(libraryId)) } }, IntentFilter(StorageReadPermissionsRequestedBroadcaster.ReadPermissionsNeeded)) messageBus.registerReceiver(object : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { val libraryId = intent.getIntExtra(StorageWritePermissionsRequestedBroadcaster.WritePermissionsLibraryId, -1) if (libraryId < 0) return notificationManagerLazy.notify( 396, storageWritePermissionsRequestNotificationBuilderLazy .buildWritePermissionsRequestNotification(libraryId)) } }, IntentFilter(StorageWritePermissionsRequestedBroadcaster.WritePermissionsNeeded)) messageBus.registerReceiver( ConnectionSessionSettingsChangeReceiver(ConnectionSessionManager.get(this)), IntentFilter(ObservableConnectionSettingsLibraryStorage.connectionSettingsUpdated) ) messageBus.registerReceiver( SelectedConnectionSettingsChangeReceiver( SelectedBrowserLibraryIdentifierProvider(applicationSettings), messageBus), IntentFilter(ObservableConnectionSettingsLibraryStorage.connectionSettingsUpdated) ) val connectionDependentReceiverRegistrations = listOf( UpdatePlayStatsOnCompleteRegistration(), PlaybackFileStartedScrobblerRegistration(), PlaybackFileStoppedScrobblerRegistration(), PebbleFileChangedNotificationRegistration()) messageBus.registerReceiver( SessionConnectionRegistrationsMaintainer(messageBus, connectionDependentReceiverRegistrations), IntentFilter(SelectedConnection.buildSessionBroadcast)) } private fun initializeLogging() { val lc = LoggerFactory.getILoggerFactory() as LoggerContext lc.reset() // setup LogcatAppender val logcatEncoder = PatternLayoutEncoder() logcatEncoder.context = lc logcatEncoder.pattern = "[%thread] %msg%n" logcatEncoder.start() val logcatAppender = LogcatAppender() logcatAppender.context = lc logcatAppender.encoder = logcatEncoder logcatAppender.start() // add the newly created appenders to the root logger; // qualify Logger to disambiguate from org.slf4j.Logger val rootLogger = LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME) as Logger rootLogger.level = Level.WARN rootLogger.addAppender(logcatAppender) if (Environment.MEDIA_MOUNTED == Environment.getExternalStorageState() && getExternalFilesDir(null) != null) { val asyncAppender = AsyncAppender() asyncAppender.context = lc asyncAppender.name = "ASYNC" val externalFilesDir = getExternalFilesDir(null) if (externalFilesDir != null) { val logDir = File(externalFilesDir.path + File.separator + "logs") if (!logDir.exists()) logDir.mkdirs() val filePle = PatternLayoutEncoder() filePle.pattern = "%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" filePle.context = lc filePle.start() val rollingFileAppender = RollingFileAppender<ILoggingEvent>() rollingFileAppender.lazy = true rollingFileAppender.isAppend = true rollingFileAppender.context = lc rollingFileAppender.encoder = filePle val rollingPolicy = TimeBasedRollingPolicy<ILoggingEvent>() rollingPolicy.fileNamePattern = File(logDir, "%d{yyyy-MM-dd}.log").absolutePath rollingPolicy.maxHistory = 30 rollingPolicy.setParent(rollingFileAppender) // parent and context required! rollingPolicy.context = lc rollingPolicy.start() rollingFileAppender.rollingPolicy = rollingPolicy rollingFileAppender.start() asyncAppender.addAppender(rollingFileAppender) } // UNCOMMENT TO TWEAK OPTIONAL SETTINGS // excluding caller data (used for stack traces) improves appender's performance asyncAppender.isIncludeCallerData = !DebugFlag.isDebugCompilation asyncAppender.start() rootLogger.addAppender(asyncAppender) StatusPrinter.print(lc) } val logger = LoggerFactory.getLogger(javaClass) logger.info("Uncaught exceptions logging to custom uncaught exception handler.") if (!DebugFlag.isDebugCompilation) return rootLogger.level = Level.DEBUG logger.info("DEBUG_MODE active") StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() // or .detectAll() for all detectable problems .penaltyLog() .build()) StrictMode.setVmPolicy(VmPolicy.Builder() .detectLeakedSqlLiteObjects() .penaltyLog() .build()) } }
projectBlueWater/src/main/java/com/lasthopesoftware/bluewater/MainApplication.kt
2482272270
/* * ************************************************************************ * MoviepediaBrowserTvFragment.kt * ************************************************************************* * Copyright © 2019 VLC authors and VideoLAN * Author: Nicolas POMEPUY * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. * ************************************************************************** * * */ package org.videolan.television.ui.browser import android.content.Intent import android.os.Bundle import android.view.View import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.GridLayoutManager import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.ObsoleteCoroutinesApi import org.videolan.medialibrary.interfaces.Medialibrary import org.videolan.moviepedia.database.models.MediaMetadataType import org.videolan.moviepedia.database.models.MediaMetadataWithImages import org.videolan.moviepedia.provider.MediaScrapingProvider import org.videolan.resources.CATEGORY import org.videolan.resources.CATEGORY_VIDEOS import org.videolan.resources.HEADER_MOVIES import org.videolan.resources.HEADER_TV_SHOW import org.videolan.resources.util.getFromMl import org.videolan.television.ui.* import org.videolan.television.viewmodel.MediaScrapingBrowserViewModel import org.videolan.television.viewmodel.getMoviepediaBrowserModel import org.videolan.vlc.R import org.videolan.vlc.gui.view.EmptyLoadingState import org.videolan.vlc.interfaces.IEventsHandler import java.util.* @UseExperimental(ObsoleteCoroutinesApi::class) @ExperimentalCoroutinesApi class MediaScrapingBrowserTvFragment : BaseBrowserTvFragment<MediaMetadataWithImages>() { override fun provideAdapter(eventsHandler: IEventsHandler<MediaMetadataWithImages>, itemSize: Int): TvItemAdapter { return MediaScrapingTvItemAdapter((viewModel as MediaScrapingBrowserViewModel).category, this, itemSize) } override fun getDisplayPrefId() = "display_tv_moviepedia_${(viewModel as MediaScrapingBrowserViewModel).category}" override lateinit var adapter: TvItemAdapter override fun getTitle() = when ((viewModel as MediaScrapingBrowserViewModel).category) { HEADER_TV_SHOW -> getString(R.string.header_tvshows) HEADER_MOVIES -> getString(R.string.header_movies) else -> getString(R.string.video) } override fun getCategory(): Long = (viewModel as MediaScrapingBrowserViewModel).category override fun getColumnNumber() = when ((viewModel as MediaScrapingBrowserViewModel).category) { CATEGORY_VIDEOS -> resources.getInteger(R.integer.tv_videos_col_count) else -> resources.getInteger(R.integer.tv_songs_col_count) } companion object { fun newInstance(type: Long) = MediaScrapingBrowserTvFragment().apply { arguments = Bundle().apply { this.putLong(CATEGORY, type) } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = getMoviepediaBrowserModel(arguments?.getLong(CATEGORY, HEADER_MOVIES) ?: HEADER_MOVIES) (viewModel.provider as MediaScrapingProvider).pagedList.observe(this, Observer { items -> binding.emptyLoading.post { submitList(items) binding.emptyLoading.state = if (items.isEmpty()) EmptyLoadingState.EMPTY else EmptyLoadingState.NONE //headers val nbColumns = if ((viewModel as MediaScrapingBrowserViewModel).sort == Medialibrary.SORT_ALPHA || (viewModel as MediaScrapingBrowserViewModel).sort == Medialibrary.SORT_DEFAULT) 9 else 1 binding.headerList.layoutManager = GridLayoutManager(requireActivity(), nbColumns) headerAdapter.sortType = (viewModel as MediaScrapingBrowserViewModel).sort val headerItems = ArrayList<String>() viewModel.provider.headers.run { for (i in 0 until size()) { headerItems.add(valueAt(i)) } } headerAdapter.items = headerItems headerAdapter.notifyDataSetChanged() } }) (viewModel.provider as MediaScrapingProvider).loading.observe(this, Observer { if (it) binding.emptyLoading.state = EmptyLoadingState.LOADING }) (viewModel.provider as MediaScrapingProvider).liveHeaders.observe(this, Observer { headerAdapter.notifyDataSetChanged() }) } override fun onClick(v: View, position: Int, item: MediaMetadataWithImages) { when (item.metadata.type) { MediaMetadataType.TV_SHOW -> { val intent = Intent(activity, MediaScrapingTvshowDetailsActivity::class.java) intent.putExtra(TV_SHOW_ID, item.metadata.moviepediaId) requireActivity().startActivity(intent) } else -> { item.metadata.mlId?.let { lifecycleScope.launchWhenStarted { val media = requireActivity().getFromMl { getMedia(it) } TvUtil.showMediaDetail(requireActivity(), media) } } } } } override fun onLongClick(v: View, position: Int, item: MediaMetadataWithImages): Boolean { when (item.metadata.type) { MediaMetadataType.TV_SHOW -> { val intent = Intent(activity, MediaScrapingTvshowDetailsActivity::class.java) intent.putExtra(TV_SHOW_ID, item.metadata.moviepediaId) requireActivity().startActivity(intent) } else -> { item.metadata.mlId?.let { lifecycleScope.launchWhenStarted { val media = requireActivity().getFromMl { getMedia(it) } TvUtil.showMediaDetail(requireActivity(), media) } } } } return true } }
application/television/src/main/java/org/videolan/television/ui/browser/MediaScrapingBrowserTvFragment.kt
565099804
/* * ****************************************************************************** * Copyright 2014-2017 Spectra Logic Corporation. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"). You may not use * this file except in compliance with the License. A copy of the License is located at * * http://www.apache.org/licenses/LICENSE-2.0 * * or in the "license" file accompanying this file. * This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR * CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * **************************************************************************** */ package com.spectralogic.ds3autogen.go.generators.client.command import com.spectralogic.ds3autogen.go.models.client.ReadCloserBuildLine import com.spectralogic.ds3autogen.go.models.client.RequestBuildLine import java.util.* /** * The Go generator for client commands that have a string request payload * that is not specified within the contract. * * Used to generate the commands: * GetBlobPersistenceRequest * ReplicatePutJobRequest */ class StringPayloadCommandGenerator : BaseCommandGenerator() { /** * Retrieves the request builder line for adding the request payload in string format. */ override fun toReaderBuildLine(): Optional<RequestBuildLine> { return Optional.of(ReadCloserBuildLine("buildStreamFromString(request.RequestPayload)")) } }
ds3-autogen-go/src/main/kotlin/com/spectralogic/ds3autogen/go/generators/client/command/StringPayloadCommandGenerator.kt
2130219810
package net.mastrgamr.rettiwt.views.activities import android.app.Activity import android.content.Intent import android.os.Bundle import android.util.Log import com.twitter.sdk.android.core.Callback import com.twitter.sdk.android.core.Result import com.twitter.sdk.android.core.TwitterException import com.twitter.sdk.android.core.TwitterSession import com.twitter.sdk.android.core.identity.TwitterLoginButton import es.dmoral.prefs.Prefs import net.mastrgamr.rettiwt.R /* * Documentation: https://docs.fabric.io/android/twitter/log-in-with-twitter.html */ class LoginActivity : Activity() { private val TAG = javaClass.simpleName private var logBtn: TwitterLoginButton? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) //if an access token is defined in the preferences //skip the login flow altogether and start the main app if(Prefs.with(this).read("access_token").isNotEmpty()){ Log.d(TAG, "Token found, start Main app.") startActivity(Intent(this, MainActivity::class.java)) finish() } logBtn = findViewById(R.id.login_button) as TwitterLoginButton logBtn!!.callback = object : Callback<TwitterSession>() { override fun success(result: Result<TwitterSession>) { // Do something with result, which provides a TwitterSession for making API calls Log.d(TAG, result.data.userName) // Write the tokens to Preferences // WARNING: Usually not too safe, but this is an open source app. You know what you signed up for. Prefs.with(this@LoginActivity).write("access_token", result.data.authToken.token) Prefs.with(this@LoginActivity).write("secret", result.data.authToken.secret) } override fun failure(exception: TwitterException) { } } } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) // Pass the activity result to the login button. logBtn!!.onActivityResult(requestCode, resultCode, data) Log.d(TAG, "Result Code: " + resultCode) if(resultCode == -1) { //on successful login -- P.S. WTF is the TwitterAPI Enum code for this!? startActivity(Intent(this, MainActivity::class.java)) finish() } // Example of static Auth Session // val session = Twitter.getSessionManager().activeSession // val authToken = session.authToken // val token = authToken.token // val secret = authToken.secret } }
app/src/main/java/net/mastrgamr/rettiwt/views/activities/LoginActivity.kt
845789732
package com.github.pgutkowski.kgraphql.request import com.github.pgutkowski.kgraphql.ExecutionException import com.github.pgutkowski.kgraphql.RequestException import com.github.pgutkowski.kgraphql.getIterableElementType import com.github.pgutkowski.kgraphql.isIterable import com.github.pgutkowski.kgraphql.schema.structure2.LookupSchema import kotlin.reflect.KClass import kotlin.reflect.KType @Suppress("UNCHECKED_CAST") data class Variables( private val typeDefinitionProvider: LookupSchema, private val variablesJson: VariablesJson, private val variables: List<OperationVariable>? ) { /** * map and return object of requested class */ fun <T : Any> get(kClass: KClass<T>, kType: KType, key: String, transform: (value: String) -> Any?): T? { val variable = variables?.find { key == it.name } ?: throw IllegalArgumentException("Variable '$key' was not declared for this operation") val isIterable = kClass.isIterable() validateVariable(typeDefinitionProvider.typeReference(kType), variable) var value = variablesJson.get(kClass, kType, key.substring(1)) if(value == null && variable.defaultValue != null){ value = transformDefaultValue(transform, variable.defaultValue, kClass) } value?.let { if (isIterable && kType.getIterableElementType()?.isMarkedNullable == false) { for (element in value as Iterable<*>) { if (element == null) { throw RequestException( "Invalid argument value $value from variable $key, expected list with non null arguments" ) } } } } return value } private fun <T : Any> transformDefaultValue(transform: (value: String) -> Any?, defaultValue: String, kClass: KClass<T>): T? { val transformedDefaultValue = transform.invoke(defaultValue) when { transformedDefaultValue == null -> return null kClass.isInstance(transformedDefaultValue) -> return transformedDefaultValue as T? else -> { throw ExecutionException("Invalid transform function returned ") } } } fun validateVariable(expectedType: TypeReference, variable: OperationVariable){ val variableType = variable.type val invalidName = expectedType.name != variableType.name val invalidIsList = expectedType.isList != variableType.isList val invalidNullability = !expectedType.isNullable && variableType.isNullable && variable.defaultValue == null val invalidElementNullability = !expectedType.isElementNullable && variableType.isElementNullable if(invalidName || invalidIsList || invalidNullability || invalidElementNullability){ throw RequestException("Invalid variable ${variable.name} argument type $variableType, expected $expectedType") } } }
src/main/kotlin/com/github/pgutkowski/kgraphql/request/Variables.kt
3733651794
/* The MIT License (MIT) Copyright (c) 2016 Tom Needham Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.thomas.needham.neurophidea.examples.kotlin import org.neuroph.core.NeuralNetwork import org.neuroph.core.learning.SupervisedTrainingElement import org.neuroph.core.learning.TrainingSet import org.neuroph.nnet.Hopfield import org.neuroph.nnet.learning.BackPropagation import java.io.* import java.util.* object TestHopfield { @JvmStatic var inputSize = 8 @JvmStatic var outputSize = 1 @JvmStatic var network: NeuralNetwork? = null @JvmStatic var trainingSet: TrainingSet<SupervisedTrainingElement>? = null @JvmStatic var testingSet: TrainingSet<SupervisedTrainingElement>? = null @JvmStatic var layers = arrayOf(8, 8, 1) @JvmStatic fun loadNetwork() { network = NeuralNetwork.load("D:/GitHub/Neuroph-Intellij-Plugin/TestHopfield.nnet") } @JvmStatic fun trainNetwork() { val list = ArrayList<Int>() for (layer in layers) { list.add(layer) } network = Hopfield(inputSize + outputSize) trainingSet = TrainingSet<SupervisedTrainingElement>(inputSize, outputSize) trainingSet = TrainingSet.createFromFile("D:/GitHub/NeuralNetworkTest/Classroom Occupation Data.csv", inputSize, outputSize, ",") as TrainingSet<SupervisedTrainingElement>? val learningRule = BackPropagation() (network as NeuralNetwork).learningRule = learningRule (network as NeuralNetwork).learn(trainingSet) (network as NeuralNetwork).save("D:/GitHub/Neuroph-Intellij-Plugin/TestHopfield.nnet") } @JvmStatic fun testNetwork() { var input = "" val fromKeyboard = BufferedReader(InputStreamReader(System.`in`)) val testValues = ArrayList<Double>() var testValuesDouble: DoubleArray do { try { println("Enter test values or \"\": ") input = fromKeyboard.readLine() if (input == "") { break } input = input.replace(" ", "") val stringVals = input.split(",".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() testValues.clear() for (`val` in stringVals) { testValues.add(java.lang.Double.parseDouble(`val`)) } } catch (ioe: IOException) { ioe.printStackTrace(System.err) } catch (nfe: NumberFormatException) { nfe.printStackTrace(System.err) } testValuesDouble = DoubleArray(testValues.size) for (t in testValuesDouble.indices) { testValuesDouble[t] = testValues[t].toDouble() } network?.setInput(*testValuesDouble) network?.calculate() } while (input != "") } @JvmStatic fun testNetworkAuto(setPath: String) { var total: Double = 0.0 val list = ArrayList<Int>() val outputLine = ArrayList<String>() for (layer in layers) { list.add(layer) } testingSet = TrainingSet.createFromFile(setPath, inputSize, outputSize, ",") as TrainingSet<SupervisedTrainingElement>? val count: Int = testingSet?.elements()?.size!! var averageDeviance = 0.0 var resultString = "" try { val file = File("Results " + setPath) val fw = FileWriter(file) val bw = BufferedWriter(fw) for (i in 0..testingSet?.elements()?.size!! - 1) { val expected: Double val calculated: Double network?.setInput(*testingSet?.elementAt(i)!!.input) network?.calculate() calculated = network?.output!![0] expected = testingSet?.elementAt(i)?.idealArray!![0] println("Calculated Output: " + calculated) println("Expected Output: " + expected) println("Deviance: " + (calculated - expected)) averageDeviance += Math.abs(Math.abs(calculated) - Math.abs(expected)) total += network?.output!![0] resultString = "" for (cols in 0..testingSet?.elementAt(i)?.inputArray?.size!! - 1) { resultString += testingSet?.elementAt(i)?.inputArray!![cols].toString() + ", " } for (t in 0..network?.output!!.size - 1) { resultString += network?.output!![t].toString() + ", " } resultString = resultString.substring(0, resultString.length - 2) resultString += "" bw.write(resultString) bw.flush() println() println("Average: " + (total / count).toString()) println("Average Deviance % : " + (averageDeviance / count * 100).toString()) bw.flush() bw.close() } } catch (ex: IOException) { ex.printStackTrace() } } }
neuroph-plugin/src/com/thomas/needham/neurophidea/examples/kotlin/TestHopfield.kt
3782735153
package net.nemerosa.ontrack.extension.notifications.webhooks.auth import com.fasterxml.jackson.databind.JsonNode import net.nemerosa.ontrack.json.parse import net.nemerosa.ontrack.model.annotations.APIDescription import net.nemerosa.ontrack.model.annotations.APILabel import net.nemerosa.ontrack.model.form.Form import net.nemerosa.ontrack.model.form.passwordField import net.nemerosa.ontrack.model.form.textField import org.springframework.stereotype.Component import java.net.http.HttpRequest @Component class HeaderWebhookAuthenticator : AbstractWebhookAuthenticator<HeaderWebhookAuthenticatorConfig>() { override val type: String = "header" override val displayName: String = "HTTP Header authentication" override fun getForm(config: HeaderWebhookAuthenticatorConfig?): Form = Form.create() .textField(HeaderWebhookAuthenticatorConfig::name, config?.name) .passwordField(HeaderWebhookAuthenticatorConfig::value) override fun validateConfig(node: JsonNode): HeaderWebhookAuthenticatorConfig = node.parse() override fun authenticate(config: HeaderWebhookAuthenticatorConfig, builder: HttpRequest.Builder) { builder.header(config.name, config.value) } } data class HeaderWebhookAuthenticatorConfig( @APILabel("Header name") @APIDescription("Name of the header to send to the webhook") val name: String, @APILabel("Header value") @APIDescription("Value of the header to send to the webhook") val value: String, )
ontrack-extension-notifications/src/main/java/net/nemerosa/ontrack/extension/notifications/webhooks/auth/HeaderWebhookAuthenticator.kt
1119429026
package net.nemerosa.ontrack.model.labels import net.nemerosa.ontrack.common.toRGBColor open class Label( val id: Int, val category: String?, val name: String, val description: String?, val color: String, val computedBy: LabelProviderDescription? ) { /** * Foreground colour */ val foregroundColor: String get() = color.toRGBColor().toBlackOrWhite().toString() /** * Representation */ fun getDisplay() = if (category != null) { "$category:$name" } else { name } companion object { fun categoryAndNameFromDisplay(display: String): Pair<String?, String> { val index = display.indexOf(':') return if (index >= 0) { val category = display.substring(0, index).trim().takeIf { it.isNotBlank() } val name = display.substring(index + 1).trim() category to name } else { null to display } } } }
ontrack-model/src/main/java/net/nemerosa/ontrack/model/labels/Label.kt
1418768284
/** * Copyright 2013 Olivier Goutay (olivierg13) * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * * http://www.apache.org/licenses/LICENSE-2.0 * * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.og.finance.ether.network.apis import com.google.gson.annotations.SerializedName /** * Created by olivier.goutay on 3/7/16. */ class KrakenResultApi(@SerializedName("XETHZUSD") var price: KrakenPriceApi?) : Api()
app/src/main/java/com/og/finance/ether/network/apis/KrakenResultApi.kt
2147220601
package com.jraska.github.client.identity.internal import com.jraska.github.client.time.TimeProvider class TestTimeProvider(private var elapsed: Long = 0) : TimeProvider { override fun elapsed(): Long { return elapsed } fun elapsed(elapsedMillis: Long): TestTimeProvider { this.elapsed = elapsedMillis return this } fun advanceTime(difference: Long): TestTimeProvider { if (difference < 0) { throw IllegalArgumentException("Can only advance time forward") } elapsed += difference return this } }
feature/identity/src/test/java/com/jraska/github/client/identity/internal/TestTimeProvider.kt
1818639473
package net.nemerosa.ontrack.extension.indicators.ui.graphql import graphql.schema.GraphQLFieldDefinition import net.nemerosa.ontrack.extension.indicators.ui.ProjectIndicators import net.nemerosa.ontrack.graphql.schema.GQLProjectEntityFieldContributor import net.nemerosa.ontrack.model.structure.Project import net.nemerosa.ontrack.model.structure.ProjectEntity import net.nemerosa.ontrack.model.structure.ProjectEntityType import org.springframework.stereotype.Component @Component class ProjectIndicatorsGraphQLFieldContributor( private val projectIndicators: GQLTypeProjectIndicators ) : GQLProjectEntityFieldContributor { override fun getFields(projectEntityClass: Class<out ProjectEntity>, projectEntityType: ProjectEntityType): List<GraphQLFieldDefinition>? { return if (projectEntityType == ProjectEntityType.PROJECT) { listOf( GraphQLFieldDefinition.newFieldDefinition() .name("projectIndicators") .description("List of project indicators") .type(projectIndicators.typeRef) .dataFetcher { env -> val project: Project = env.getSource() ProjectIndicators(project) } .build() ) } else { null } } }
ontrack-extension-indicators/src/main/java/net/nemerosa/ontrack/extension/indicators/ui/graphql/ProjectIndicatorsGraphQLFieldContributor.kt
3824246017
/* * Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ package kotlinx.cli import kotlin.reflect.KProperty internal expect fun exitProcess(status: Int): Nothing /** * Queue of arguments descriptors. * Arguments can have several values, so one descriptor can be returned several times. */ internal class ArgumentsQueue(argumentsDescriptors: List<ArgDescriptor<*, *>>) { /** * Map of arguments descriptors and their current usage number. */ private val argumentsUsageNumber = linkedMapOf(*argumentsDescriptors.map { it to 0 }.toTypedArray()) /** * Get next descriptor from queue. */ fun pop(): String? { if (argumentsUsageNumber.isEmpty()) return null val (currentDescriptor, usageNumber) = argumentsUsageNumber.iterator().next() currentDescriptor.number?.let { // Parse all arguments for current argument description. if (usageNumber + 1 >= currentDescriptor.number) { // All needed arguments were provided. argumentsUsageNumber.remove(currentDescriptor) } else { argumentsUsageNumber[currentDescriptor] = usageNumber + 1 } } return currentDescriptor.fullName } } /** * A property delegate that provides access to the argument/option value. */ interface ArgumentValueDelegate<T> { /** * The value of an option or argument parsed from command line. * * Accessing this value before [ArgParser.parse] method is called will result in an exception. * * @see CLIEntity.value */ var value: T /** Provides the value for the delegated property getter. Returns the [value] property. * @throws IllegalStateException in case of accessing the value before [ArgParser.parse] method is called. */ operator fun getValue(thisRef: Any?, property: KProperty<*>): T = value /** Sets the [value] to the [ArgumentValueDelegate.value] property from the delegated property setter. * This operation is possible only after command line arguments were parsed with [ArgParser.parse] * @throws IllegalStateException in case of resetting value before command line arguments are parsed. */ operator fun setValue(thisRef: Any?, property: KProperty<*>, value: T) { this.value = value } } /** * Abstract base class for subcommands. */ @ExperimentalCli abstract class Subcommand(val name: String, val actionDescription: String): ArgParser(name) { /** * Execute action if subcommand was provided. */ abstract fun execute() val helpMessage: String get() = " $name - $actionDescription\n" } /** * Argument parsing result. * Contains name of subcommand which was called. * * @property commandName name of command which was called. */ class ArgParserResult(val commandName: String) /** * Arguments parser. * * @property programName the name of the current program. * @property useDefaultHelpShortName specifies whether to register "-h" option for printing the usage information. * @property prefixStyle the style of option prefixing. * @property skipExtraArguments specifies whether the extra unmatched arguments in a command line string * can be skipped without producing an error message. */ open class ArgParser( val programName: String, var useDefaultHelpShortName: Boolean = true, var prefixStyle: OptionPrefixStyle = OptionPrefixStyle.LINUX, var skipExtraArguments: Boolean = false, var strictSubcommandOptionsOrder: Boolean = false ) { /** * Map of options: key - full name of option, value - pair of descriptor and parsed values. */ private val options = mutableMapOf<String, ParsingValue<*, *>>() /** * Map of arguments: key - full name of argument, value - pair of descriptor and parsed values. */ private val arguments = mutableMapOf<String, ParsingValue<*, *>>() /** * Map with declared options. */ private val declaredOptions = mutableListOf<CLIEntityWrapper>() /** * Map with declared arguments. */ private val declaredArguments = mutableListOf<CLIEntityWrapper>() /** * State of parser. Stores last parsing result or null. */ private var parsingState: ArgParserResult? = null /** * Map of subcommands. */ @OptIn(ExperimentalCli::class) protected val subcommands = mutableMapOf<String, Subcommand>() /** * Mapping for short options names for quick search. */ private val shortNames = mutableMapOf<String, ParsingValue<*, *>>() /** * Used prefix form for full option form. */ protected val optionFullFormPrefix = if (prefixStyle == OptionPrefixStyle.JVM) "-" else "--" /** * Used prefix form for short option form. */ protected val optionShortFromPrefix = "-" /** * Name with all commands that should be executed. */ protected val fullCommandName = mutableListOf(programName) /** * Flag to recognize if CLI entities can be treated as options. */ protected var treatAsOption = true /** * Arguments which should be parsed with subcommands. */ private val subcommandsArguments = mutableListOf<String>() /** * Options which should be parsed with subcommands. */ private val subcommandsOptions = mutableListOf<String>() /** * Subcommand used in commmand line arguments. */ private var usedSubcommand: Subcommand? = null internal var outputAndTerminate: (message: String, exitCode: Int) -> Nothing = { message, exitCode -> println(message) exitProcess(exitCode) } /** * The way an option/argument has got its value. */ enum class ValueOrigin { /* The value was parsed from command line arguments. */ SET_BY_USER, /* The value was missing in command line, therefore the default value was used. */ SET_DEFAULT_VALUE, /* The value is not initialized by command line values or by default values. */ UNSET, /* The value was redefined after parsing manually (usually with the property setter). */ REDEFINED, /* The value is undefined, because parsing wasn't called. */ UNDEFINED } /** * The style of option prefixing. */ enum class OptionPrefixStyle { /* Linux style: the full name of an option is prefixed with two hyphens "--" and the short name — with one "-". */ LINUX, /* JVM style: both full and short names are prefixed with one hyphen "-". */ JVM, /* GNU style: the full name of an option is prefixed with two hyphens "--" and "=" between options and value and the short name — with one "-". Detailed information https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html */ GNU } @Deprecated("OPTION_PREFIX_STYLE is deprecated. Please, use OptionPrefixStyle.", ReplaceWith("OptionPrefixStyle", "kotlinx.cli.OptionPrefixStyle")) @Suppress("TOPLEVEL_TYPEALIASES_ONLY") typealias OPTION_PREFIX_STYLE = OptionPrefixStyle /** * Declares a named option and returns an object which can be used to access the option value * after all arguments are parsed or to delegate a property for accessing the option value to. * * By default, the option supports only a single value, is optional, and has no default value, * therefore its value's type is `T?`. * * You can alter the option properties by chaining extensions for the option type on the returned object: * - [AbstractSingleOption.default] to provide a default value that is used when the option is not specified; * - [SingleNullableOption.required] to make the option non-optional; * - [AbstractSingleOption.delimiter] to allow specifying multiple values in one command line argument with a delimiter; * - [AbstractSingleOption.multiple] to allow specifying the option several times. * * @param type The type describing how to parse an option value from a string, * an instance of [ArgType], e.g. [ArgType.String] or [ArgType.Choice]. * @param fullName the full name of the option, can be omitted if the option name is inferred * from the name of a property delegated to this option. * @param shortName the short name of the option, `null` if the option cannot be specified in a short form. * @param description the description of the option used when rendering the usage information. * @param deprecatedWarning the deprecation message for the option. * Specifying anything except `null` makes this option deprecated. The message is rendered in a help message and * issued as a warning when the option is encountered when parsing command line arguments. */ fun <T : Any> option( type: ArgType<T>, fullName: String? = null, shortName: String ? = null, description: String? = null, deprecatedWarning: String? = null ): SingleNullableOption<T> { if (prefixStyle == OptionPrefixStyle.GNU && shortName != null) require(shortName.length == 1) { """ GNU standard for options allow to use short form which consists of one character. For more information, please, see https://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html """.trimIndent() } val option = SingleNullableOption(OptionDescriptor(optionFullFormPrefix, optionShortFromPrefix, type, fullName, shortName, description, deprecatedWarning = deprecatedWarning), CLIEntityWrapper()) option.owner.entity = option declaredOptions.add(option.owner) return option } /** * Check usage of required property for arguments. * Make sense only for several last arguments. */ private fun inspectRequiredAndDefaultUsage() { var previousArgument: ParsingValue<*, *>? = null arguments.forEach { (_, currentArgument) -> previousArgument?.let { previous -> // Previous argument has default value. if (previous.descriptor.defaultValueSet) { if (!currentArgument.descriptor.defaultValueSet && currentArgument.descriptor.required) { error("Default value of argument ${previous.descriptor.fullName} will be unused, " + "because next argument ${currentArgument.descriptor.fullName} is always required and has no default value.") } } // Previous argument is optional. if (!previous.descriptor.required) { if (!currentArgument.descriptor.defaultValueSet && currentArgument.descriptor.required) { error("Argument ${previous.descriptor.fullName} will be always required, " + "because next argument ${currentArgument.descriptor.fullName} is always required.") } } } previousArgument = currentArgument } } /** * Declares an argument and returns an object which can be used to access the argument value * after all arguments are parsed or to delegate a property for accessing the argument value to. * * By default, the argument supports only a single value, is required, and has no default value, * therefore its value's type is `T`. * * You can alter the argument properties by chaining extensions for the argument type on the returned object: * - [AbstractSingleArgument.default] to provide a default value that is used when the argument is not specified; * - [SingleArgument.optional] to allow omitting the argument; * - [AbstractSingleArgument.multiple] to require the argument to have exactly the number of values specified; * - [AbstractSingleArgument.vararg] to allow specifying an unlimited number of values for the _last_ argument. * * @param type The type describing how to parse an option value from a string, * an instance of [ArgType], e.g. [ArgType.String] or [ArgType.Choice]. * @param fullName the full name of the argument, can be omitted if the argument name is inferred * from the name of a property delegated to this argument. * @param description the description of the argument used when rendering the usage information. * @param deprecatedWarning the deprecation message for the argument. * Specifying anything except `null` makes this argument deprecated. The message is rendered in a help message and * issued as a warning when the argument is encountered when parsing command line arguments. */ fun <T : Any> argument( type: ArgType<T>, fullName: String? = null, description: String? = null, deprecatedWarning: String? = null ) : SingleArgument<T, DefaultRequiredType.Required> { val argument = SingleArgument<T, DefaultRequiredType.Required>(ArgDescriptor(type, fullName, 1, description, deprecatedWarning = deprecatedWarning), CLIEntityWrapper()) argument.owner.entity = argument declaredArguments.add(argument.owner) return argument } /** * Registers one or more subcommands. * * @param subcommandsList subcommands to add. */ @ExperimentalCli fun subcommands(vararg subcommandsList: Subcommand) { subcommandsList.forEach { if (it.name in subcommands) { error("Subcommand with name ${it.name} was already defined.") } // Set same settings as main parser. it.prefixStyle = prefixStyle it.useDefaultHelpShortName = useDefaultHelpShortName it.strictSubcommandOptionsOrder = strictSubcommandOptionsOrder fullCommandName.forEachIndexed { index, namePart -> it.fullCommandName.add(index, namePart) } it.outputAndTerminate = outputAndTerminate subcommands[it.name] = it } } /** * Outputs an error message adding the usage information after it. * * @param message error message. */ private fun printError(message: String): Nothing { outputAndTerminate("$message\n${makeUsage()}", 127) } /** * Save value as argument value. * * @param arg string with argument value. * @param argumentsQueue queue with active argument descriptors. */ private fun saveAsArg(arg: String, argumentsQueue: ArgumentsQueue): Boolean { // Find next uninitialized arguments. val name = argumentsQueue.pop() name?.let { val argumentValue = arguments[name]!! argumentValue.descriptor.deprecatedWarning?.let { printWarning(it) } argumentValue.addValue(arg) return true } return false } /** * Treat value as argument value. * * @param arg string with argument value. * @param argumentsQueue queue with active argument descriptors. */ private fun treatAsArgument(arg: String, argumentsQueue: ArgumentsQueue) { if (!saveAsArg(arg, argumentsQueue)) { usedSubcommand?.let { (if (treatAsOption) subcommandsOptions else subcommandsArguments).add(arg) } ?: printError("Too many arguments! Couldn't process argument $arg!") } } /** * Save value as option value. */ private fun <T : Any, U: Any> saveAsOption(parsingValue: ParsingValue<T, U>, value: String) { parsingValue.addValue(value) } /** * Try to recognize and save command line element as full form of option. * * @param candidate string with candidate in options. * @param argIterator iterator over command line arguments. */ private fun recognizeAndSaveOptionFullForm(candidate: String, argIterator: Iterator<String>): Boolean { if (prefixStyle == OptionPrefixStyle.GNU && candidate == optionFullFormPrefix) { // All other arguments after `--` are treated as non-option arguments. treatAsOption = false return false } if (!candidate.startsWith(optionFullFormPrefix)) return false val optionString = candidate.substring(optionFullFormPrefix.length) val argValue = if (prefixStyle == OptionPrefixStyle.GNU) null else options[optionString] if (argValue != null) { saveStandardOptionForm(argValue, argIterator) return true } else { // Check GNU style of options. if (prefixStyle == OptionPrefixStyle.GNU) { // Option without a parameter. if (options[optionString]?.descriptor?.type?.hasParameter == false) { saveOptionWithoutParameter(options[optionString]!!) return true } // Option with parameters. val optionParts = optionString.split('=', limit = 2) if (optionParts.size != 2) return false if (options[optionParts[0]] != null) { saveAsOption(options[optionParts[0]]!!, optionParts[1]) return true } } } return false } /** * Save option without parameter. * * @param argValue argument value with all information about option. */ internal fun saveOptionWithoutParameter(argValue: ParsingValue<*, *>) { // Boolean flags. if (argValue.descriptor.fullName == "help") { usedSubcommand?.let { it.parse(listOf("${it.optionFullFormPrefix}${argValue.descriptor.fullName}")) } outputAndTerminate(makeUsage(), 0) } saveAsOption(argValue, "true") } /** * Save option described with standard separated form `--name value`. * * @param argValue argument value with all information about option. * @param argIterator iterator over command line arguments. */ private fun saveStandardOptionForm(argValue: ParsingValue<*, *>, argIterator: Iterator<String>) { if (argValue.descriptor.type.hasParameter) { if (argIterator.hasNext()) { saveAsOption(argValue, argIterator.next()) } else { // An error, option with value without value. printError("No value for ${argValue.descriptor.textDescription}") } } else { saveOptionWithoutParameter(argValue) } } /** * Try to recognize and save command line element as short form of option. * * @param candidate string with candidate in options. * @param argIterator iterator over command line arguments. */ private fun recognizeAndSaveOptionShortForm(candidate: String, argIterator: Iterator<String>): Boolean { if (!candidate.startsWith(optionShortFromPrefix) || optionFullFormPrefix != optionShortFromPrefix && candidate.startsWith(optionFullFormPrefix)) return false // Try to find exact match. val option = candidate.substring(optionShortFromPrefix.length) val argValue = shortNames[option] if (argValue != null) { saveStandardOptionForm(argValue, argIterator) } else { if (prefixStyle != OptionPrefixStyle.GNU || option.isEmpty()) return false // Try to find collapsed form. val firstOption = shortNames["${option[0]}"] ?: return false // Form with value after short form without separator. if (firstOption.descriptor.type.hasParameter) { saveAsOption(firstOption, option.substring(1)) } else { // Form with several short forms as one string. val otherBooleanOptions = option.substring(1) saveOptionWithoutParameter(firstOption) for (opt in otherBooleanOptions) { shortNames["$opt"]?.let { if (it.descriptor.type.hasParameter) { printError( "Option $optionShortFromPrefix$opt can't be used in option combination $candidate, " + "because parameter value of type ${it.descriptor.type.description} should be " + "provided for current option." ) } }?: printError("Unknown option $optionShortFromPrefix$opt in option combination $candidate.") saveOptionWithoutParameter(shortNames["$opt"]!!) } } } return true } /** * Parses the provided array of command line arguments. * After a successful parsing, the options and arguments declared in this parser get their values and can be accessed * with the properties delegated to them. * * @param args the array with command line arguments. * * @return an [ArgParserResult] if all arguments were parsed successfully. * Otherwise, prints the usage information and terminates the program execution. * @throws IllegalStateException in case of attempt of calling parsing several times. */ fun parse(args: Array<String>): ArgParserResult = parse(args.asList()) protected fun parse(args: List<String>): ArgParserResult { check(parsingState == null) { "Parsing of command line options can be called only once." } // Add help option. val helpDescriptor = if (useDefaultHelpShortName) OptionDescriptor<Boolean, Boolean>( optionFullFormPrefix, optionShortFromPrefix, ArgType.Boolean, "help", "h", "Usage info" ) else OptionDescriptor( optionFullFormPrefix, optionShortFromPrefix, ArgType.Boolean, "help", description = "Usage info" ) val helpOption = SingleNullableOption(helpDescriptor, CLIEntityWrapper()) helpOption.owner.entity = helpOption declaredOptions.add(helpOption.owner) // Add default list with arguments if there can be extra free arguments. if (skipExtraArguments) { argument(ArgType.String, "").vararg() } // Clean options and arguments maps. options.clear() arguments.clear() // Map declared options and arguments to maps. declaredOptions.forEachIndexed { index, option -> val value = option.entity?.delegate as ParsingValue<*, *> value.descriptor.fullName?.let { // Add option. if (options.containsKey(it)) { error("Option with full name $it was already added.") } with(value.descriptor as OptionDescriptor) { if (shortName != null && shortNames.containsKey(shortName)) { error("Option with short name ${shortName} was already added.") } shortName?.let { shortNames[it] = value } } options[it] = value } ?: error("Option was added, but unnamed. Added option under №${index + 1}") } declaredArguments.forEachIndexed { index, argument -> val value = argument.entity?.delegate as ParsingValue<*, *> value.descriptor.fullName?.let { // Add option. if (arguments.containsKey(it)) { error("Argument with full name $it was already added.") } arguments[it] = value } ?: error("Argument was added, but unnamed. Added argument under №${index + 1}") } // Make inspections for arguments. inspectRequiredAndDefaultUsage() listOf(arguments, options).forEach { it.forEach { (_, value) -> value.valueOrigin = ValueOrigin.UNSET } } val argumentsQueue = ArgumentsQueue(arguments.map { it.value.descriptor as ArgDescriptor<*, *> }) usedSubcommand = null subcommandsOptions.clear() subcommandsArguments.clear() val argIterator = args.listIterator() try { while (argIterator.hasNext()) { val arg = argIterator.next() // Check for subcommands. if (arg !in subcommands) { // Parse arguments from command line. if (treatAsOption && arg.startsWith('-')) { // Candidate in being option. // Option is found. if (!(recognizeAndSaveOptionShortForm(arg, argIterator) || recognizeAndSaveOptionFullForm(arg, argIterator)) ) { // State is changed so next options are arguments. if (!treatAsOption) { // Argument is found. treatAsArgument(argIterator.next(), argumentsQueue) } else { usedSubcommand?.let { subcommandsOptions.add(arg) } ?: run { // Try save as argument. if (!saveAsArg(arg, argumentsQueue)) { printError("Unknown option $arg") } } } } } else { // Argument is found. treatAsArgument(arg, argumentsQueue) } } else { usedSubcommand = subcommands[arg] if (strictSubcommandOptionsOrder) { break } } } // Postprocess results of parsing. options.values.union(arguments.values).forEach { value -> // Not inited, append default value if needed. if (value.isEmpty()) { value.addDefaultValue() } if (value.valueOrigin != ValueOrigin.SET_BY_USER && value.descriptor.required) { printError("Value for ${value.descriptor.textDescription} should be always provided in command line.") } } // Parse arguments for subcommand. usedSubcommand?.let { if (strictSubcommandOptionsOrder) { it.parse(args.slice(argIterator.nextIndex() until args.size)) } else { it.parse(subcommandsOptions + listOfNotNull("--".takeUnless { treatAsOption }) + subcommandsArguments) } it.execute() parsingState = ArgParserResult(it.name) return parsingState!! } } catch (exception: ParsingException) { printError(exception.message!!) } parsingState = ArgParserResult(programName) return parsingState!! } /** * Creates a message with the usage information. */ internal fun makeUsage(): String { val result = StringBuilder() result.append("Usage: ${fullCommandName.joinToString(" ")} options_list\n") if (subcommands.isNotEmpty()) { result.append("Subcommands: \n") subcommands.forEach { (_, subcommand) -> result.append(subcommand.helpMessage) } result.append("\n") } if (arguments.isNotEmpty()) { result.append("Arguments: \n") arguments.forEach { result.append(it.value.descriptor.helpMessage) } } if (options.isNotEmpty()) { result.append("Options: \n") options.forEach { result.append(it.value.descriptor.helpMessage) } } return result.toString() } } /** * Output warning. * * @param message warning message. */ internal fun printWarning(message: String) { println("WARNING $message") }
core/commonMain/src/ArgParser.kt
1700134134
package no.tornado.fxsample.workspace import javafx.application.Application import tornadofx.App import tornadofx.importStylesheet /** * Created by miguelius on 04/09/2017. */ class WorkspaceApp : App() { override val primaryView = DemoWorkspace::class init { importStylesheet(Styles::class) } } fun main(args: Array<String>) { Application.launch(WorkspaceApp::class.java, *args) }
workspace/src/main/kotlin/no/tornado/fxsample/workspace/WorkspaceApp.kt
2899113321
package be.florien.anyflow.feature.customView import android.content.Context import android.graphics.Canvas import android.util.AttributeSet import android.view.MotionEvent import android.view.View import be.florien.anyflow.R import kotlin.math.absoluteValue import kotlin.math.min /** * Created by florien on 8/01/18. */ class PlayerControls @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr) { /** * Attributes */ private val playPauseIconAnimator: PlayPauseIconAnimator = PlayPauseIconAnimator(context) private val previousIconAnimator: PreviousIconAnimator = PreviousIconAnimator(context) private val playPlayerPainter: PlayPlayerPainter = PlayPlayerPainter(context, playPauseIconAnimator, previousIconAnimator) private val scrollPlayerPainter: ScrollPlayerPainter = ScrollPlayerPainter(context, playPauseIconAnimator, previousIconAnimator) private var currentPlayerPainter: PlayerPainter = playPlayerPainter set(value) { field.onValuesComputed = {} value.onValuesComputed = { invalidate() } field = value field.currentState = field.currentState } // Variable changing due to usage var shouldShowBuffering: Boolean = false var hasPrevious: Boolean get() = currentPlayerPainter.hasPrevious set(value) { playPlayerPainter.hasPrevious = value scrollPlayerPainter.hasPrevious = value } var hasNext: Boolean get() = currentPlayerPainter.hasNext set(value) { playPlayerPainter.hasNext = value scrollPlayerPainter.hasNext = value } // Variables that can be configured by XML attributes var currentDuration: Int set(value) { playPlayerPainter.playingDuration = value } get() = playPlayerPainter.playingDuration var state = PlayPauseIconAnimator.STATE_PLAY_PAUSE_PAUSE set(value) { currentPlayerPainter.currentState = value field = value } var actionListener: OnActionListener? = null var totalDuration: Int = 0 set(value) { field = if (value == 0) Int.MAX_VALUE else value scrollPlayerPainter.totalDuration = field playPlayerPainter.totalDuration = field } private var progressAnimDuration: Int = 10000 // Calculations private var lastDownEventX = 0f /** * Constructor */ init { if (attrs != null) { val typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.PlayerControls) currentDuration = typedArray.getInt(R.styleable.PlayerControls_currentDuration, currentDuration) totalDuration = typedArray.getInt(R.styleable.PlayerControls_totalDuration, totalDuration) progressAnimDuration = typedArray.getInt(R.styleable.PlayerControls_progressAnimDuration, progressAnimDuration) state = typedArray.getInteger(R.styleable.PlayerControls_state, PlayPauseIconAnimator.STATE_PLAY_PAUSE_PAUSE) playPlayerPainter.retrieveLayoutProperties(typedArray) scrollPlayerPainter.retrieveLayoutProperties(typedArray) typedArray.recycle() } currentPlayerPainter = playPlayerPainter } /** * Overridden methods */ override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val widthMode = MeasureSpec.getMode(widthMeasureSpec) val widthSize = MeasureSpec.getSize(widthMeasureSpec) val heightMode = MeasureSpec.getMode(heightMeasureSpec) val heightSize = MeasureSpec.getSize(heightMeasureSpec) val idealButtonSize = currentPlayerPainter.smallestButtonWidth val desiredWidth = when (widthMode) { MeasureSpec.AT_MOST -> widthSize MeasureSpec.EXACTLY -> widthSize MeasureSpec.UNSPECIFIED -> idealButtonSize else -> idealButtonSize } val desiredHeight = when (heightMode) { MeasureSpec.AT_MOST -> min(heightSize, idealButtonSize) MeasureSpec.EXACTLY -> heightSize MeasureSpec.UNSPECIFIED -> idealButtonSize else -> idealButtonSize } setMeasuredDimension(desiredWidth, desiredHeight) playPlayerPainter.measure(desiredWidth, desiredHeight) scrollPlayerPainter.measure(desiredWidth, desiredHeight) } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { super.onLayout(changed, left, top, right, bottom) currentPlayerPainter.computePreviousIcon() } override fun onDraw(canvas: Canvas) { currentPlayerPainter.draw(canvas, width, height) } override fun onTouchEvent(event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN -> { lastDownEventX = event.x scrollPlayerPainter.durationOnTouchStart = currentDuration } MotionEvent.ACTION_MOVE -> { scrollPlayerPainter.scrollOffset = (event.x - lastDownEventX) if (scrollPlayerPainter.scrollOffset.absoluteValue > playPlayerPainter.smallestButtonWidth && currentPlayerPainter != scrollPlayerPainter) { currentPlayerPainter = scrollPlayerPainter } } MotionEvent.ACTION_UP -> { when (currentPlayerPainter.getButtonClicked(lastDownEventX.toInt(), event.x.toInt())) { PlayerPainter.CLICK_PREVIOUS -> actionListener?.onPreviousClicked() PlayerPainter.CLICK_PLAY_PAUSE -> actionListener?.onPlayPauseClicked() PlayerPainter.CLICK_NEXT -> actionListener?.onNextClicked() else -> { actionListener?.onCurrentDurationChanged(scrollPlayerPainter.duration.toLong()) } } lastDownEventX = 0f currentPlayerPainter = playPlayerPainter } else -> return super.onTouchEvent(event) } return true } /** * Listeners */ interface OnActionListener { fun onPreviousClicked() fun onNextClicked() fun onPlayPauseClicked() fun onCurrentDurationChanged(newDuration: Long) } companion object { const val NO_VALUE = -15 } }
app/src/main/java/be/florien/anyflow/feature/customView/PlayerControls.kt
689585987
package treehou.se.habit.ui.widget import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebSettings import android.webkit.WebView import android.webkit.WebViewClient import se.treehou.ng.ohcommunicator.connector.models.OHLinkedPage import se.treehou.ng.ohcommunicator.connector.models.OHServer import se.treehou.ng.ohcommunicator.services.IServerHandler import treehou.se.habit.R import treehou.se.habit.ui.adapter.WidgetAdapter import treehou.se.habit.util.logging.Logger import javax.inject.Inject class WidgetWebViewFactory @Inject constructor() : WidgetFactory { @Inject lateinit var logger: Logger @Inject lateinit var server: OHServer @Inject lateinit var page: OHLinkedPage @Inject lateinit var serverHandler: IServerHandler override fun createViewHolder(parent: ViewGroup): WidgetAdapter.WidgetViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.widget_web_view, parent, false) return WebWidgetViewHolder(view) } inner class WebWidgetViewHolder(view: View) : WidgetBaseHolder(view, server, page) { private var webView: WebView = view as WebView init { setupWebView() } override fun bind(itemWidget: WidgetAdapter.WidgetItem) { super.bind(itemWidget) val lp = webView.layoutParams val heightInRows = widget.height val desiredHeightPixels = if (heightInRows is Int && heightInRows > 0) (heightInRows * context.resources.getDimension(R.dimen.webview_row_height)).toInt() else ViewGroup.LayoutParams.WRAP_CONTENT if (lp.height != desiredHeightPixels) { lp.height = desiredHeightPixels webView.layoutParams = lp } if (widget.url != null) { webView.loadUrl(widget.url) } } @SuppressLint("SetJavaScriptEnabled") private fun setupWebView() { val client = WebViewClient() webView.webViewClient = client val settings = webView.settings settings.javaScriptEnabled = true settings.javaScriptCanOpenWindowsAutomatically = true webView.isFocusableInTouchMode = true settings.cacheMode = WebSettings.LOAD_NO_CACHE settings.domStorageEnabled = true settings.databaseEnabled = true settings.setAppCacheEnabled(true) } } companion object { const val TAG = "WidgetSwitchFactory" } }
mobile/src/main/java/treehou/se/habit/ui/widget/WidgetWebViewFactory.kt
2261605369
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mcp.gradle.datahandler import com.demonwav.mcdev.platform.mcp.McpModuleSettings import com.demonwav.mcdev.platform.mcp.gradle.McpModelData import com.demonwav.mcdev.platform.mcp.gradle.tooling.McpModelFG2 import com.demonwav.mcdev.platform.mcp.srg.SrgType import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.project.ModuleData import org.gradle.tooling.model.idea.IdeaModule import org.jetbrains.plugins.gradle.model.data.GradleSourceSetData import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext object McpModelFG2Handler : McpModelDataHandler { override fun build( gradleModule: IdeaModule, node: DataNode<ModuleData>, resolverCtx: ProjectResolverContext ) { val data = resolverCtx.getExtraProject(gradleModule, McpModelFG2::class.java) ?: return val state = McpModuleSettings.State( data.minecraftVersion, data.mcpVersion, data.mappingFiles.find { it.endsWith("mcp-srg.srg") }, SrgType.SRG ) val modelData = McpModelData( node.data, state, null, null ) node.createChild( McpModelData.KEY, McpModelData( node.data, McpModuleSettings.State( data.minecraftVersion, data.mcpVersion, data.mappingFiles.find { it.endsWith("mcp-srg.srg") }, SrgType.SRG ), null, null ) ) for (child in node.children) { val childData = child.data if (childData is GradleSourceSetData) { child.createChild(McpModelData.KEY, modelData.copy(module = childData)) } } } }
src/main/kotlin/platform/mcp/gradle/datahandler/McpModelFG2Handler.kt
1363934083
package de.xikolo.models.dao.base import androidx.lifecycle.LiveData import de.xikolo.extensions.asLiveData import io.realm.Realm import io.realm.RealmObject import io.realm.RealmQuery import io.realm.Sort import kotlin.reflect.KClass /** * The base class for data access objects. * * Inherit this class to implement a data access object for a certain model class. * Subclasses should be the only ones in the project who implement Realm-specific code, * like database queries. We agreed on some conventions: * - single entity request methods begin with `find`, collection requests begin with `all` * - managed requests with results wrapped as `LiveData` are implemented as instance methods * - unmanaged requests with plain object/list results are implemented in an `Unmanaged` object * * @param T the type of the model this class belongs to. * @property clazz the model's class. * @realm realm the managed Realm instance for managed requests. */ open class BaseDao<T : RealmObject>(private val clazz: KClass<T>, val realm: Realm) { var defaultSort: Pair<String, Sort>? = null fun query(): RealmQuery<T> = realm.where(clazz.java) open val unmanaged = object { } open fun find(id: String?): LiveData<T> = query() .equalTo("id", id) .findFirstAsync() .asLiveData() fun all(vararg equalToClauses: Pair<String, Any?>): LiveData<List<T>> { val query = query() for (equalTo in equalToClauses) { val value = equalTo.second when (value) { is String -> query.equalTo(equalTo.first, value) is Boolean -> query.equalTo(equalTo.first, value) } } defaultSort?.let { query.sort(it.first, it.second) } return query.findAllAsync().asLiveData() } }
app/src/main/java/de/xikolo/models/dao/base/BaseDao.kt
330725009
package de.axelrindle.broadcaster import de.axelrindle.broadcaster.model.JsonMessage import de.axelrindle.broadcaster.model.Message import de.axelrindle.broadcaster.model.MessageMapper import de.axelrindle.broadcaster.model.SimpleMessage import de.axelrindle.broadcaster.util.Align import de.axelrindle.broadcaster.util.Formatter import de.axelrindle.pocketknife.util.ChatUtils.formatColors import net.md_5.bungee.api.ChatMessageType import net.md_5.bungee.api.chat.BaseComponent import net.md_5.bungee.api.chat.TextComponent import org.apache.commons.lang.math.RandomUtils import org.bukkit.Bukkit import org.bukkit.entity.Player import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.player.PlayerJoinEvent import org.bukkit.event.player.PlayerQuitEvent import java.util.* import java.util.stream.Collectors /** * The [BroadcastingThread] class is responsible for starting and stopping for * scheduling a repeating task that broadcasts the configured messages. */ object BroadcastingThread { private var id: Int = -1 private var index = 0 private var lastRandomIndex: Int = 0 internal val running: Boolean get() = id != -1 internal var paused = false internal var messages: List<Message> = emptyList() private set private val spaceComponent = TextComponent(" ") /** * Reads entries from the `messages.yml` file and maps the to their * respective [Message] object representation. */ fun loadMessages() { messages = plugin.config.access("messages")!! .getList("Messages", emptyList<Message>())!! .stream() .map(MessageMapper::mapConfigEntry) .filter(Objects::nonNull) .collect(Collectors.toList<Message>()) } /** * Starts the scheduled message broadcast. */ fun start() { if (running) throw RuntimeException("AlreadyRunning") if (messages.isEmpty()) throw RuntimeException("NoMessagesLoaded") paused = false // config options val interval = plugin.config.access("config")!!.getInt("Cast.Interval") id = Bukkit.getScheduler().scheduleSyncRepeatingTask( plugin, getRunnable(plugin, messages), interval * 20L, interval * 20L // 20L is one "Tick" (Minecraft Second) in Minecraft. To calculate the period, we need to multiply the interval seconds with the length of one Tick. ) } /** * Stops the broadcasting task. * * @param pause Whether to pause instead of stopping. Pausing will not reset the message index. */ fun stop(pause: Boolean = false) { if (! running) throw RuntimeException("AlreadyStopped") Bukkit.getScheduler().cancelTask(id) id = -1 if (pause) paused = true else index = 0 } private fun getRunnable(plugin: Broadcaster, messages: List<Message>): Runnable { val config = plugin.config.access("config")!! val prefix = formatColors(config.getString("Cast.Prefix")!!) val needsPermission = config.getBoolean("Cast.NeedPermissionToSee") val randomize = config.getBoolean("Cast.Randomize") val maxIndex = messages.size val prefixComponent = TextComponent.fromLegacyText(prefix) return Runnable { // get a message val theMessage = if (randomize) getRandomMessage(messages) else messages[index] // further actions depend on the message type if (theMessage is SimpleMessage) { val message = Formatter.format(theMessage.getText()) // check for center alignment if (message.startsWith("%c")) { broadcastCentered(prefix, message.replace("%c", ""), needsPermission) } else { broadcast("$prefix $message", getPermission(needsPermission)) } } else if (theMessage is JsonMessage) { val components = prefixComponent .plus(spaceComponent) .plus(theMessage.components) broadcastComponent(components, getPermission(needsPermission)) } // don't change index if randomizing if (randomize) return@Runnable index++ if (index == maxIndex) index = 0 } } private fun getPermission(needsPermission: Boolean): String? { return if (needsPermission) "broadcaster.see" else null } private fun broadcast(message: String, permission: String?) { if (permission == null) Bukkit.broadcastMessage(message) else Bukkit.broadcast(message, permission) } private fun broadcastCentered(prefix: String, message: String, needsPermission: Boolean) { val permission = getPermission(needsPermission) val list = Align.center(message, prefix) list.forEach { broadcast("$prefix $it", permission) } } private fun broadcastComponent(components: Array<BaseComponent>, permission: String?) { Bukkit.getConsoleSender().spigot().sendMessage(*components) Bukkit.getServer().onlinePlayers.forEach { player -> if (permission == null || player.hasPermission(permission) || player.isOp) { player.spigot().sendMessage(ChatMessageType.CHAT, *components) } } } /** * Returns a random message from a list. * * @param messages A [List] of messages. * @return A randomly selected message. */ private fun getRandomMessage(messages: List<Message>): Message { // get a random index val rand = RandomUtils.nextInt(messages.size) // make sure no message appears twice in a row return if (rand == lastRandomIndex) // if we got the same index as before, generate a new one // Note: using recursion here getRandomMessage(messages) else { // we got a different index, so save it and return the appropriate message lastRandomIndex = rand messages[rand] } } /** * Listens for player events to pause or resume the broadcast. */ class EventListener : Listener { /** * Called when a [Player] joins the server. Used to resume the broadcast if it has * been paused due to no players being online. */ @EventHandler fun onPlayerJoin(event: PlayerJoinEvent) { if (paused) { plugin.logger.info("Broadcasting resumed.") start() } } /** * Called when a [Player] leaves the server. Used to pause the broadcast if no players * are online anymore. */ @EventHandler fun onPlayerQuit(event: PlayerQuitEvent) { val pauseOnEmpty = plugin.config.access("config")!! .getBoolean("Cast.PauseOnEmptyServer") val onlinePlayers = Bukkit.getOnlinePlayers().size - 1 if (pauseOnEmpty && onlinePlayers <= 0) { plugin.logger.info("Broadcasting paused.") stop(true) } } } }
src/main/kotlin/de/axelrindle/broadcaster/BroadcastingThread.kt
2620884687
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2021 minecraft-dev * * MIT License */ package com.demonwav.mcdev.platform.mixin.action import com.demonwav.mcdev.util.toArray import com.intellij.ide.util.PsiClassListCellRenderer import com.intellij.psi.PsiClass import com.intellij.ui.components.JBList import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import javax.swing.JPanel import javax.swing.ListModel class FindMixinsComponent(classes: List<PsiClass>) : MouseAdapter() { private lateinit var classList: JBList<PsiClass> lateinit var panel: JPanel private set init { @Suppress("UNCHECKED_CAST") classList.model = JBList.createDefaultListModel(*classes.toArray()) as ListModel<PsiClass> classList.cellRenderer = PsiClassListCellRenderer() classList.addMouseListener(this) } override fun mouseClicked(e: MouseEvent) { classList.selectedValue?.takeIf(PsiClass::canNavigate)?.navigate(true) } }
src/main/kotlin/platform/mixin/action/FindMixinsComponent.kt
4290656919
package com.google.firebase.samples.apps.mlkit.languageid.kotlin import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import android.text.TextUtils import android.util.Log import android.widget.Toast import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage import com.google.firebase.samples.apps.mlkit.languageid.R import com.google.firebase.samples.apps.mlkit.languageid.databinding.ActivityMainBinding import java.util.ArrayList import java.util.Locale class MainActivity : AppCompatActivity() { private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) with(binding) { buttonIdLanguage.setOnClickListener { val input = inputText.text?.toString() input?.let { inputText.text?.clear() identifyLanguage(it) } } buttonIdAll.setOnClickListener { val input = inputText.text?.toString() input?.let { inputText.text?.clear() identifyPossibleLanguages(input) } } } } private fun identifyPossibleLanguages(inputText: String) { val languageIdentification = FirebaseNaturalLanguage .getInstance().languageIdentification languageIdentification .identifyPossibleLanguages(inputText) .addOnSuccessListener(this@MainActivity) { identifiedLanguages -> val detectedLanguages = ArrayList<String>(identifiedLanguages.size) for (language in identifiedLanguages) { detectedLanguages.add( String.format( Locale.US, "%s (%3f)", language.languageCode, language.confidence ) ) } binding.outputText.append( String.format( Locale.US, "\n%s - [%s]", inputText, TextUtils.join(", ", detectedLanguages) ) ) } .addOnFailureListener(this@MainActivity) { e -> Log.e(TAG, "Language identification error", e) Toast.makeText( this@MainActivity, R.string.language_id_error, Toast.LENGTH_SHORT ).show() } } private fun identifyLanguage(inputText: String) { val languageIdentification = FirebaseNaturalLanguage .getInstance().languageIdentification languageIdentification .identifyLanguage(inputText) .addOnSuccessListener(this@MainActivity) { s -> binding.outputText.append( String.format( Locale.US, "\n%s - %s", inputText, s ) ) } .addOnFailureListener(this@MainActivity) { e -> Log.e(TAG, "Language identification error", e) Toast.makeText( this@MainActivity, R.string.language_id_error, Toast.LENGTH_SHORT ).show() } } companion object { private const val TAG = "MainActivity" } }
mlkit-langid/app/src/main/java/com/google/firebase/samples/apps/mlkit/languageid/kotlin/MainActivity.kt
1229833482
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.lang.psi.patterns import com.intellij.patterns.ElementPattern import com.intellij.patterns.PatternCondition import com.intellij.psi.PsiMethod import com.intellij.util.ProcessingContext import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall class GroovyClosurePattern : GroovyExpressionPattern<GrClosableBlock, GroovyClosurePattern>(GrClosableBlock::class.java) { fun inMethod(methodPattern: ElementPattern<out PsiMethod>) = with(object : PatternCondition<GrClosableBlock>("closureInMethod") { override fun accepts(closure: GrClosableBlock, context: ProcessingContext?): Boolean { val parent = closure.parent val call = when (parent) { is GrCall -> { if (closure !in parent.closureArguments) return false parent } is GrArgumentList -> { val grandParent = parent.parent as? GrCall ?: return false if (grandParent.closureArguments.isNotEmpty()) return false if (grandParent.expressionArguments.lastOrNull() != closure) return false grandParent } else -> return false } context?.put(closureCallKey, call) val method = call.resolveMethod() ?: return false return methodPattern.accepts(method) } }) }
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/patterns/GroovyClosurePattern.kt
515346896
package app.cash.sqldelight.dialects.mysql.grammar.mixins import com.alecstrong.sql.psi.core.SqlAnnotationHolder import com.alecstrong.sql.psi.core.psi.impl.SqlBinaryEqualityExprImpl import com.intellij.lang.ASTNode internal class MySqlBinaryEqualityExpr(node: ASTNode) : SqlBinaryEqualityExprImpl(node) { override fun annotate(annotationHolder: SqlAnnotationHolder) { if (node.getChildren(null).getOrNull(2)?.text == "==") { annotationHolder.createErrorAnnotation(this, "Expected '=' but got '=='.") } super.annotate(annotationHolder) } }
dialects/mysql/src/main/kotlin/app/cash/sqldelight/dialects/mysql/grammar/mixins/MySqlBinaryEqualityExpr.kt
1210898328
package com.andreapivetta.kolor import com.andreapivetta.kolor.Kolor.ESCAPE /** * The amount of codes required in order to jump from a foreground code to a background code. Equal to 10. For example, * the foreground code for blue is "[33m", its respective background code is "[43m" */ private const val BG_JUMP = 10 /** * An enumeration of colors supported by most terminals. Can be applied to both foreground and background. */ enum class Color(baseCode: Int) { BLACK(30), RED(31), GREEN(32), YELLOW(33), BLUE(34), MAGENTA(35), CYAN(36), LIGHT_GRAY(37), DARK_GRAY(90), LIGHT_RED(91), LIGHT_GREEN(92), LIGHT_YELLOW(93), LIGHT_BLUE(94), LIGHT_MAGENTA(95), LIGHT_CYAN(96), WHITE(97); /** ANSI modifier string to apply the color to the text itself */ val foreground: String = "$ESCAPE[${baseCode}m" /** ANSI modifier string to apply the color the text's background */ val background: String = "$ESCAPE[${baseCode + BG_JUMP}m" }
src/main/kotlin/com/andreapivetta/kolor/Color.kt
749724663
// // (C) Copyright 2018-2019 Martin E. Nordberg III // Apache 2.0 License // package jvm.katydid.css.stylesheets import o.katydid.css.colors.* import o.katydid.css.measurements.pt import o.katydid.css.measurements.px import o.katydid.css.styles.builders.* import o.katydid.css.styles.makeStyle import o.katydid.css.stylesheets.KatydidStyleSheet import o.katydid.css.stylesheets.makeStyleSheet import o.katydid.css.types.EFontStyle import org.junit.jupiter.api.Test import kotlin.test.assertEquals @Suppress("RemoveRedundantBackticks") class StyleSheetTests { private fun checkStyle( expectedCss: String, build: KatydidStyleSheet.() -> Unit ) { assertEquals(expectedCss, makeStyleSheet(build).toString()) } @Test fun `A simple style sheet can be constructed from selectors and styles`() { val css = """ |div { | height: 23px; | width: 30px; |} | |div.wider { | width: 45px; |} | """.trimMargin() + "\n" checkStyle(css) { "div" { height(23.px) width(30.px) } "div.wider" { width(45.px) } } } @Test fun `A nested style sheet can be constructed from selectors and styles`() { val css = """ |div { | height: 23px; | width: 30px; |} | |div.wider { | width: 45px; |} | |div.wider span { | color: green; |} | """.trimMargin() + "\n" checkStyle(css) { "div" { height(23.px) width(30.px) "&.wider" { width(45.px) "span" { color(green) } } } } } @Test fun `Nested styles can reference the parent selector after the nested selector`() { val css = """ |a { | color: honeydew; |} | |a:hover { | color: aquamarine; |} | |td a { | color: chartreuse; |} | """.trimMargin() + "\n" checkStyle(css) { "a" { color(honeydew) "&:hover" { color(aquamarine) } "td &" { color(chartreuse) } } } } @Test fun `Comma-separated selectors are handled`() { val css = """ |td, |th, |div { | font-size: 10pt; | font-style: italic; |} | """.trimMargin() + "\n" checkStyle(css) { " td,th, div " { fontSize(10.pt) fontStyle(EFontStyle.italic) } } } @Test fun `Selectors can be combined with the or operator`() { val css = """ |td, |th, |div { | font-size: 10pt; | font-style: italic; |} | """.trimMargin() + "\n" checkStyle(css) { "td" or "th" or "div" { fontSize(10.pt) fontStyle(EFontStyle.italic) } } } @Test fun `Nesting works with the or operator inside the nesting`() { val css = """ |td { | font-size: 10pt; | font-style: italic; |} | |td div, |td span { | color: green; |} | """.trimMargin() + "\n" checkStyle(css) { "td" { fontSize(10.pt) fontStyle(EFontStyle.italic) "div" or "span" { color(green) } } } } @Test fun `Nesting works with the or operator outside the nesting`() { val css = """ |td, |th { | font-size: 10pt; | font-style: italic; |} | |td div, |th div { | color: green; |} | """.trimMargin() + "\n" checkStyle(css) { "td" or "th" { fontSize(10.pt) fontStyle(EFontStyle.italic) "div" { color(green) } } } } @Test fun `Nesting works with the or operator at both levels`() { val css = """ |nav, |td, |th { | font-size: 10pt; | font-style: italic; |} | |nav div, |nav span, |td div, |td span, |th div, |th span { | color: green; |} | """.trimMargin() + "\n" checkStyle(css) { "nav" or "td" or "th" { fontSize(10.pt) fontStyle(EFontStyle.italic) "div" or "span" { color(green) } } } } @Test fun `Three layers of nesting works with the or operator`() { val css = """ |nav, |td, |th { | font-size: 10pt; | font-style: italic; |} | |nav.quirky, |td.quirky, |th.quirky { | max-width: 45px; |} | |nav.quirky div, |nav.quirky span, |td.quirky div, |td.quirky span, |th.quirky div, |th.quirky span { | color: green; |} | """.trimMargin() + "\n" checkStyle(css) { "nav" or "td" or "th" { fontSize(10.pt) fontStyle(EFontStyle.italic) "&.quirky" { maxWidth(45.px) "div" or "span" { color(green) } } } } } @Test fun `Three layers of nesting works when the top level has no styles`() { val css = """ |nav.quirky, |td.quirky, |th.quirky { | max-width: 45px; |} | |nav.quirky div, |nav.quirky span, |td.quirky div, |td.quirky span, |th.quirky div, |th.quirky span { | color: green; |} | """.trimMargin() + "\n" checkStyle(css) { "nav" or "td" or "th" { "&.quirky" { maxWidth(45.px) "div" or "span" { color(green) } } } } } @Test fun `Three layers of nesting works when the middle level has no styles`() { val css = """ |nav, |td, |th { | font-size: 10pt; | font-style: italic; |} | |nav.quirky div, |nav.quirky span, |td.quirky div, |td.quirky span, |th.quirky div, |th.quirky span { | color: green; |} | """.trimMargin() + "\n" checkStyle(css) { "nav" or "td" or "th" { fontSize(10.pt) fontStyle(EFontStyle.italic) "&.quirky" { "div" or "span" { color(green) } } } } } @Test fun `Style blocks can include other styles`() { val css = """ |div { | height: 23px; | background-color: gray; | color: blue; | width: 30px; |} | |div.wider { | width: 45px; |} | """.trimMargin() + "\n" checkStyle(css) { val commonColors = makeStyle { backgroundColor(gray) color(blue) } "div" { height(23.px) include(commonColors) width(30.px) "&.wider" { width(45.px) } } } } @Test fun `One style sheet can include another`() { val css = """ |div, |span { | background-color: gray; | color: blue; |} | |div { | height: 23px; | width: 30px; |} | |div.wider { | width: 45px; |} | """.trimMargin() + "\n" val commonColors = makeStyleSheet { "div" or "span" { backgroundColor(gray) color(blue) } } checkStyle(css) { include(commonColors) "div" { height(23.px) width(30.px) "&.wider" { width(45.px) } } } } @Test fun `An empty style rule results in no output`() { val css = "" checkStyle(css) { ".stuff" {} ".morestuff" {} } } }
Katydid-CSS-JVM/src/test/kotlin/jvm/katydid/css/stylesheets/StyleSheetTests.kt
4166210486
package com.telenav.osv.tasks.model import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName data class OperationLog( @SerializedName("id") @Expose val id: Int, @SerializedName("resourceType") @Expose val resourceType: String, @SerializedName("resourceId") @Expose val resourceId: String, @SerializedName("action") @Expose val action: Int, @SerializedName("actionValue") @Expose val actionValue: String?, @SerializedName("note") @Expose val note: String? = null, @SerializedName("createdByName") @Expose val createdByName: String, @SerializedName("createdBy") @Expose val createdBy: Int, @SerializedName("updatedAt") @Expose val updatedAt: Long )
app/src/main/java/com/telenav/osv/tasks/model/OperationLog.kt
2652547624
package org.wikipedia.util import android.content.Context import android.graphics.Color import android.graphics.Typeface import android.icu.text.CompactDecimalFormat import android.os.Build import android.text.SpannableString import android.text.Spanned import android.text.style.BackgroundColorSpan import android.text.style.ForegroundColorSpan import android.text.style.StyleSpan import android.widget.EditText import android.widget.TextView import androidx.annotation.IntRange import androidx.core.text.parseAsHtml import androidx.core.text.toSpanned import okio.ByteString.Companion.encodeUtf8 import org.wikipedia.R import org.wikipedia.dataclient.WikiSite import org.wikipedia.page.PageTitle import org.wikipedia.staticdata.UserAliasData import java.nio.charset.StandardCharsets import java.text.Collator import java.text.Normalizer import java.util.* import kotlin.math.absoluteValue import kotlin.math.roundToInt object StringUtil { private const val CSV_DELIMITER = "," fun listToCsv(list: List<String?>): String { return list.joinToString(CSV_DELIMITER) } fun csvToList(csv: String): List<String> { return delimiterStringToList(csv, CSV_DELIMITER) } fun delimiterStringToList(delimitedString: String, delimiter: String): List<String> { return delimitedString.split(delimiter).filter { it.isNotBlank() } } fun md5string(s: String): String { return s.encodeUtf8().md5().hex() } fun strip(str: CharSequence?): CharSequence { // TODO: remove this function once Kotlin conversion of consumers is complete. return if (str.isNullOrEmpty()) "" else str.trim() } fun intToHexStr(i: Int): String { return String.format("x%08x", i) } fun addUnderscores(text: String?): String { return text.orEmpty().replace(" ", "_") } fun removeUnderscores(text: String?): String { return text.orEmpty().replace("_", " ") } fun dbNameToLangCode(wikiDbName: String): String { return (if (wikiDbName.endsWith("wiki")) wikiDbName.substring(0, wikiDbName.length - "wiki".length) else wikiDbName) .replace("_", "-") } fun removeSectionAnchor(text: String?): String { text.orEmpty().let { return if (it.contains("#")) it.substring(0, it.indexOf("#")) else it } } fun removeNamespace(text: String): String { return if (text.length > text.indexOf(":")) { text.substring(text.indexOf(":") + 1) } else { text } } fun removeHTMLTags(text: String?): String { return fromHtml(text).toString() } fun removeStyleTags(text: String): String { return text.replace("<style.*?</style>".toRegex(), "") } fun removeCiteMarkup(text: String): String { return text.replace("<cite.*?>".toRegex(), "").replace("</cite>".toRegex(), "") } fun sanitizeAbuseFilterCode(code: String): String { return code.replace("[⧼⧽]".toRegex(), "") } fun normalizedEquals(str1: String?, str2: String?): Boolean { return if (str1 == null || str2 == null) { str1 == null && str2 == null } else (Normalizer.normalize(str1, Normalizer.Form.NFC) == Normalizer.normalize(str2, Normalizer.Form.NFC)) } fun fromHtml(source: String?): Spanned { var sourceStr = source ?: return "".toSpanned() if ("<" !in sourceStr && "&" !in sourceStr) { // If the string doesn't contain any hints of HTML entities, then skip the expensive // processing that fromHtml() performs. return sourceStr.toSpanned() } sourceStr = sourceStr.replace("&#8206;", "\u200E") .replace("&#8207;", "\u200F") .replace("&amp;", "&") // HACK: We don't want to display "images" in the html string, because they will just show // up as a green square. Therefore, let's just disable the parsing of images by renaming // <img> tags to something that the native Html parser doesn't recognize. // This automatically covers both <img></img> and <img /> variations. sourceStr = sourceStr.replace("<img ", "<figure ").replace("</img>", "</figure>") return sourceStr.parseAsHtml() } fun highlightEditText(editText: EditText, parentText: String, highlightText: String) { val words = highlightText.split("\\s".toRegex()).filter { it.isNotBlank() } var pos = 0 var firstPos = 0 for (word in words) { pos = parentText.indexOf(word, pos) if (pos == -1) { break } else if (firstPos == 0) { firstPos = pos } } if (pos == -1) { pos = parentText.indexOf(words.last()) firstPos = pos } if (pos >= 0) { editText.setSelection(firstPos, pos + words.last().length) } } fun boldenKeywordText(textView: TextView, parentText: String, searchQuery: String?) { var parentTextStr = parentText val startIndex = indexOf(parentTextStr, searchQuery) if (startIndex >= 0 && !isIndexInsideHtmlTag(parentTextStr, startIndex)) { parentTextStr = (parentTextStr.substring(0, startIndex) + "<strong>" + parentTextStr.substring(startIndex, startIndex + searchQuery!!.length) + "</strong>" + parentTextStr.substring(startIndex + searchQuery.length)) } textView.text = fromHtml(parentTextStr) } fun highlightAndBoldenText(textView: TextView, input: String?, shouldBolden: Boolean, highlightColor: Int) { if (!input.isNullOrEmpty()) { val spannableString = SpannableString(textView.text) val caseInsensitiveSpannableString = SpannableString(textView.text.toString().lowercase()) var indexOfKeyword = caseInsensitiveSpannableString.toString().lowercase().indexOf(input.lowercase()) while (indexOfKeyword >= 0) { spannableString.setSpan(BackgroundColorSpan(highlightColor), indexOfKeyword, indexOfKeyword + input.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) spannableString.setSpan(ForegroundColorSpan(Color.BLACK), indexOfKeyword, indexOfKeyword + input.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) if (shouldBolden) { spannableString.setSpan(StyleSpan(Typeface.BOLD), indexOfKeyword, indexOfKeyword + input.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } indexOfKeyword = caseInsensitiveSpannableString.indexOf(input.lowercase(), indexOfKeyword + input.length) } textView.text = spannableString } } private fun isIndexInsideHtmlTag(text: String, index: Int): Boolean { var tagStack = 0 for (i in text.indices) { if (text[i] == '<') { tagStack++ } else if (text[i] == '>') { tagStack-- } if (i == index) { break } } return tagStack > 0 } // case insensitive indexOf, also more lenient with similar chars, like chars with accents private fun indexOf(original: String, search: String?): Int { if (!search.isNullOrEmpty()) { val collator = Collator.getInstance() collator.strength = Collator.PRIMARY for (i in 0..original.length - search.length) { if (collator.equals(search, original.substring(i, i + search.length))) { return i } } } return -1 } fun getBase26String(@IntRange(from = 1) number: Int): String { var num = number val base = 26 var str = "" while (--num >= 0) { str = ('A' + num % base) + str num /= base } return str } fun utf8Indices(s: String): IntArray { val indices = IntArray(s.toByteArray(StandardCharsets.UTF_8).size) var ptr = 0 var count = 0 for (i in s.indices) { val c = s.codePointAt(i) when { c <= 0x7F -> count = 1 c <= 0x7FF -> count = 2 c <= 0xFFFF -> count = 3 c <= 0x1FFFFF -> count = 4 } for (j in 0 until count) { if (ptr < indices.size) { indices[ptr++] = i } } } return indices } fun userPageTitleFromName(userName: String, wiki: WikiSite): PageTitle { return PageTitle(UserAliasData.valueFor(wiki.languageCode), userName, wiki) } fun getPageViewText(context: Context, pageViews: Long): String { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { val primaryLocale = context.resources.configuration.locales[0] val decimalFormat = CompactDecimalFormat.getInstance(primaryLocale, CompactDecimalFormat.CompactStyle.SHORT) return decimalFormat.format(pageViews) } return when { pageViews < 1000 -> pageViews.toString() pageViews < 1000000 -> { context.getString( R.string.view_top_read_card_pageviews_k_suffix, (pageViews / 1000f).roundToInt() ) } else -> { context.getString( R.string.view_top_read_card_pageviews_m_suffix, (pageViews / 1000000f).roundToInt() ) } } } fun getDiffBytesText(context: Context, diffSize: Int): String { return context.resources.getQuantityString(R.plurals.edit_diff_bytes, diffSize.absoluteValue, if (diffSize > 0) "+$diffSize" else diffSize.toString()) } fun capitalize(str: String?): String? { return str?.replaceFirstChar { if (it.isLowerCase()) it.titlecase(Locale.getDefault()) else it.toString() } } }
app/src/main/java/org/wikipedia/util/StringUtil.kt
3170475253
package com.lch.menote.note.model import com.lchli.pinedrecyclerlistview.library.ListSectionData /** * Created by Administrator on 2017/9/22. */ internal data class NotePinedData(val viewType: Int, val noteType: String): ListSectionData(viewType)
host/src/main/java/com/lch/menote/note/model/NotePinedData.kt
1162701421
package com.stripe.android.identity.navigation import android.os.Bundle import android.view.LayoutInflater import android.view.ViewGroup import androidx.annotation.IdRes import androidx.compose.ui.platform.ComposeView import androidx.compose.ui.platform.ViewCompositionStrategy import androidx.compose.ui.res.stringResource import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import com.stripe.android.camera.AppSettingsOpenable import com.stripe.android.identity.R import com.stripe.android.identity.analytics.IdentityAnalyticsRequestFactory.Companion.SCREEN_NAME_ERROR import com.stripe.android.identity.networking.models.CollectedDataParam import com.stripe.android.identity.ui.ErrorScreen import com.stripe.android.identity.ui.ErrorScreenButton import com.stripe.android.identity.utils.navigateToUploadFragment /** * Fragment to show user denies camera permission. */ internal class CameraPermissionDeniedFragment( private val appSettingsOpenable: AppSettingsOpenable, identityViewModelFactory: ViewModelProvider.Factory ) : BaseErrorFragment(identityViewModelFactory) { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ) = ComposeView(requireContext()).apply { val scanType = arguments?.getSerializable(ARG_SCAN_TYPE) as? CollectedDataParam.Type setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed) setContent { ErrorScreen( title = stringResource(id = R.string.camera_permission), message1 = stringResource(id = R.string.grant_camera_permission_text), message2 = scanType?.let { stringResource(R.string.upload_file_text, it.getDisplayName()) }, topButton = scanType?.let { ErrorScreenButton( buttonText = stringResource(id = R.string.file_upload) ) { identityViewModel.screenTracker.screenTransitionStart(SCREEN_NAME_ERROR) navigateToUploadFragment( it.toUploadDestinationId(), shouldShowTakePhoto = false, shouldShowChoosePhoto = true ) } }, bottomButton = ErrorScreenButton( buttonText = stringResource(id = R.string.app_settings) ) { appSettingsOpenable.openAppSettings() // navigate back to DocSelectFragment, so that when user is back to the app from settings // the camera permission check can be triggered again from there. findNavController().navigate(R.id.action_cameraPermissionDeniedFragment_to_docSelectionFragment) } ) } } private fun CollectedDataParam.Type.getDisplayName() = when (this) { CollectedDataParam.Type.IDCARD -> { getString(R.string.id_card) } CollectedDataParam.Type.DRIVINGLICENSE -> { getString(R.string.driver_license) } CollectedDataParam.Type.PASSPORT -> { getString(R.string.passport) } } internal companion object { const val ARG_SCAN_TYPE = "scanType" @IdRes private fun CollectedDataParam.Type.toUploadDestinationId() = when (this) { CollectedDataParam.Type.IDCARD -> R.id.action_cameraPermissionDeniedFragment_to_IDUploadFragment CollectedDataParam.Type.DRIVINGLICENSE -> R.id.action_cameraPermissionDeniedFragment_to_driverLicenseUploadFragment CollectedDataParam.Type.PASSPORT -> R.id.action_cameraPermissionDeniedFragment_to_passportUploadFragment } } }
identity/src/main/java/com/stripe/android/identity/navigation/CameraPermissionDeniedFragment.kt
582132921
package com.github.kotlinz.kotlinz.data.reader import com.github.kotlinz.kotlinz.K1 import com.github.kotlinz.kotlinz.type.applicative.Applicative interface ReaderApplicative<R> : Applicative<K1<Reader.T, R>> { override fun <A> pure(v: A): Reader<R, A> = Reader { r -> v } override fun <A, B> ap(f: K1<K1<Reader.T, R>, (A) -> B>, v: K1<K1<Reader.T, R>, A>): Reader<R, B> { val reader = Reader.narrow(v) val readerf = Reader.narrow(f) return Reader { r -> Reader.narrow(fmap(readerf.run(r), reader)).run(r) } } }
src/main/kotlin/com/github/kotlinz/kotlinz/data/reader/ReaderApplicative.kt
3677488900
package abi43_0_0.expo.modules.brightness import abi43_0_0.expo.modules.core.ExportedModule import abi43_0_0.expo.modules.core.ModuleRegistry import abi43_0_0.expo.modules.core.ModuleRegistryDelegate import abi43_0_0.expo.modules.core.Promise import abi43_0_0.expo.modules.core.errors.InvalidArgumentException import abi43_0_0.expo.modules.core.interfaces.ActivityProvider import abi43_0_0.expo.modules.interfaces.permissions.Permissions import abi43_0_0.expo.modules.core.interfaces.ExpoMethod import android.Manifest import android.app.Activity import android.content.Context import android.os.Build import android.provider.Settings import android.view.WindowManager import java.lang.Exception import kotlin.math.roundToInt class BrightnessModule( reactContext: Context?, private val moduleRegistryDelegate: ModuleRegistryDelegate = ModuleRegistryDelegate() ) : ExportedModule(reactContext) { private val permissionModule: Permissions by moduleRegistry() private val activityProvider: ActivityProvider by moduleRegistry() private inline fun <reified T> moduleRegistry() = moduleRegistryDelegate.getFromModuleRegistry<T>() override fun getName(): String { return "ExpoBrightness" } override fun onCreate(moduleRegistry: ModuleRegistry) { moduleRegistryDelegate.onCreate(moduleRegistry) } @ExpoMethod fun requestPermissionsAsync(promise: Promise?) { Permissions.askForPermissionsWithPermissionsManager(permissionModule, promise, Manifest.permission.WRITE_SETTINGS) } @ExpoMethod fun getPermissionsAsync(promise: Promise?) { Permissions.getPermissionsWithPermissionsManager(permissionModule, promise, Manifest.permission.WRITE_SETTINGS) } @ExpoMethod fun setBrightnessAsync(brightnessValue: Float, promise: Promise) { val activity = currentActivity activity.runOnUiThread { try { val lp = activity.window.attributes lp.screenBrightness = brightnessValue activity.window.attributes = lp // must be done on UI thread promise.resolve(null) } catch (e: Exception) { promise.reject("ERR_BRIGHTNESS", "Failed to set the current screen brightness", e) } } } @ExpoMethod fun getBrightnessAsync(promise: Promise) { val activity = currentActivity activity.runOnUiThread { val lp = activity.window.attributes if (lp.screenBrightness == WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE) { // system brightness is not overridden by the current activity, so just resolve with it getSystemBrightnessAsync(promise) } else { promise.resolve(lp.screenBrightness) } } } @ExpoMethod fun getSystemBrightnessAsync(promise: Promise) { try { val brightnessMode = Settings.System.getInt( currentActivity.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE ) if (brightnessMode == Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC) { val brightness = Settings.System.getFloat( currentActivity.contentResolver, // https://stackoverflow.com/questions/29349153/change-adaptive-brightness-level-programatically // this setting cannot be changed starting in targetSdkVersion 23, but it can still be read "screen_auto_brightness_adj" ) promise.resolve((brightness + 1.0f) / 2) } else { val brightness = Settings.System.getString( currentActivity.contentResolver, Settings.System.SCREEN_BRIGHTNESS ) promise.resolve(brightness.toInt() / 255f) } } catch (e: Exception) { promise.reject("ERR_BRIGHTNESS_SYSTEM", "Failed to get the system brightness value", e) } } @ExpoMethod fun setSystemBrightnessAsync(brightnessValue: Float, promise: Promise) { try { // we have to just check this every time // if we try to store a value for this permission, there is no way to know if the user has changed it if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.System.canWrite(currentActivity)) { promise.reject("ERR_BRIGHTNESS_PERMISSIONS_DENIED", "WRITE_SETTINGS permission has not been granted") return } // manual mode must be set in order to change system brightness (sets the automatic mode off) Settings.System.putInt( currentActivity.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL ) Settings.System.putInt( currentActivity.contentResolver, Settings.System.SCREEN_BRIGHTNESS, (brightnessValue * 255).roundToInt() ) promise.resolve(null) } catch (e: Exception) { promise.reject("ERR_BRIGHTNESS_SYSTEM", "Failed to set the system brightness value", e) } } @ExpoMethod fun useSystemBrightnessAsync(promise: Promise) { val activity = currentActivity activity.runOnUiThread { try { val lp = activity.window.attributes lp.screenBrightness = WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE activity.window.attributes = lp // must be done on UI thread promise.resolve(null) } catch (e: Exception) { promise.reject("ERR_BRIGHTNESS", "Failed to set the brightness of the current screen", e) } } } @ExpoMethod fun isUsingSystemBrightnessAsync(promise: Promise) { val activity = currentActivity activity.runOnUiThread { val lp = activity.window.attributes promise.resolve(lp.screenBrightness == WindowManager.LayoutParams.BRIGHTNESS_OVERRIDE_NONE) } } @ExpoMethod fun getSystemBrightnessModeAsync(promise: Promise) { try { val brightnessMode = Settings.System.getInt( currentActivity.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE ) promise.resolve(brightnessModeNativeToJS(brightnessMode)) } catch (e: Exception) { promise.reject("ERR_BRIGHTNESS_MODE", "Failed to get the system brightness mode", e) } } @ExpoMethod fun setSystemBrightnessModeAsync(brightnessMode: Int, promise: Promise) { try { // we have to just check this every time // if we try to store a value for this permission, there is no way to know if the user has changed it if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.System.canWrite(currentActivity)) { promise.reject("ERR_BRIGHTNESS_PERMISSIONS_DENIED", "WRITE_SETTINGS permission has not been granted") return } Settings.System.putInt( currentActivity.contentResolver, Settings.System.SCREEN_BRIGHTNESS_MODE, brightnessModeJSToNative(brightnessMode) ) promise.resolve(null) } catch (e: InvalidArgumentException) { promise.reject(e) } catch (e: Exception) { promise.reject("ERR_BRIGHTNESS_MODE", "Failed to set the system brightness mode", e) } } private fun brightnessModeNativeToJS(nativeValue: Int): Int { return when (nativeValue) { Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC -> 1 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL -> 2 else -> 0 } } @Throws(InvalidArgumentException::class) private fun brightnessModeJSToNative(jsValue: Int): Int { return when (jsValue) { 1 -> Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC 2 -> Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL else -> throw InvalidArgumentException("Unsupported brightness mode $jsValue") } } private val currentActivity: Activity get() = activityProvider.currentActivity }
android/versioned-abis/expoview-abi43_0_0/src/main/java/abi43_0_0/expo/modules/brightness/BrightnessModule.kt
140007199
package abi42_0_0.host.exp.exponent.modules.api.components.webview.events import abi42_0_0.com.facebook.react.bridge.WritableMap import abi42_0_0.com.facebook.react.uimanager.events.Event import abi42_0_0.com.facebook.react.uimanager.events.RCTEventEmitter /** * Event emitted when the WebView's process has crashed or was killed by the OS. */ class TopRenderProcessGoneEvent(viewId: Int, private val mEventData: WritableMap) : Event<TopRenderProcessGoneEvent>(viewId) { companion object { const val EVENT_NAME = "topRenderProcessGone" } override fun getEventName(): String = EVENT_NAME override fun canCoalesce(): Boolean = false override fun getCoalescingKey(): Short = 0 override fun dispatch(rctEventEmitter: RCTEventEmitter) = rctEventEmitter.receiveEvent(viewTag, eventName, mEventData) }
android/versioned-abis/expoview-abi42_0_0/src/main/java/abi42_0_0/host/exp/exponent/modules/api/components/webview/events/TopRenderProcessGoneEvent.kt
2261832331
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.text import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Canvas import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.LayoutCoordinates import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.text.MultiParagraphIntrinsics import androidx.compose.ui.text.SpanStyle import androidx.compose.ui.text.TextLayoutResult import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.EditProcessor import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.ImeOptions import androidx.compose.ui.text.input.KeyboardCapitalization import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.OffsetMapping import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.input.TextInputService import androidx.compose.ui.text.input.TextInputSession import androidx.compose.ui.text.input.TransformedText import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.text.style.TextDecoration import com.google.common.truth.Truth.assertThat import org.mockito.kotlin.any import org.mockito.kotlin.eq import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import org.junit.Before import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @OptIn(InternalFoundationTextApi::class) @RunWith(JUnit4::class) class TextFieldDelegateTest { private lateinit var canvas: Canvas private lateinit var mDelegate: TextDelegate private lateinit var processor: EditProcessor private lateinit var onValueChange: (TextFieldValue) -> Unit private lateinit var onEditorActionPerformed: (Any) -> Unit private lateinit var textInputService: TextInputService private lateinit var layoutCoordinates: LayoutCoordinates private lateinit var multiParagraphIntrinsics: MultiParagraphIntrinsics private lateinit var textLayoutResultProxy: TextLayoutResultProxy private lateinit var textLayoutResult: TextLayoutResult /** * Test implementation of offset map which doubles the offset in transformed text. */ private val skippingOffsetMap = object : OffsetMapping { override fun originalToTransformed(offset: Int): Int = offset * 2 override fun transformedToOriginal(offset: Int): Int = offset / 2 } @Before fun setup() { mDelegate = mock() canvas = mock() processor = mock() onValueChange = mock() onEditorActionPerformed = mock() textInputService = mock() layoutCoordinates = mock() multiParagraphIntrinsics = mock() textLayoutResult = mock() textLayoutResultProxy = mock() whenever(textLayoutResultProxy.value).thenReturn(textLayoutResult) } @Test fun test_setCursorOffset() { val position = Offset(100f, 200f) val offset = 10 val editorState = TextFieldValue(text = "Hello, World", selection = TextRange(1)) whenever(processor.toTextFieldValue()).thenReturn(editorState) whenever(textLayoutResultProxy.getOffsetForPosition(position)).thenReturn(offset) TextFieldDelegate.setCursorOffset( position, textLayoutResultProxy, processor, OffsetMapping.Identity, onValueChange ) verify(onValueChange, times(1)).invoke( eq(TextFieldValue(text = editorState.text, selection = TextRange(offset))) ) } @Test fun on_focus() { val editorState = TextFieldValue(text = "Hello, World", selection = TextRange(1)) val imeOptions = ImeOptions( singleLine = true, capitalization = KeyboardCapitalization.Sentences, keyboardType = KeyboardType.Phone, imeAction = ImeAction.Search ) val textInputSession: TextInputSession = mock() whenever( textInputService.startInput( eq(editorState), eq(imeOptions), any(), eq(onEditorActionPerformed) ) ).thenReturn(textInputSession) val actual = TextFieldDelegate.onFocus( textInputService = textInputService, value = editorState, editProcessor = processor, imeOptions = imeOptions, onValueChange = onValueChange, onImeActionPerformed = onEditorActionPerformed ) verify(textInputService).startInput( eq( TextFieldValue( text = editorState.text, selection = editorState.selection ) ), eq(imeOptions), any(), eq(onEditorActionPerformed) ) assertThat(actual).isEqualTo(textInputSession) } @Test fun on_blur_with_hiding() { val editorState = TextFieldValue( text = "Hello, World", selection = TextRange(1), composition = TextRange(3, 5) ) whenever(processor.toTextFieldValue()).thenReturn(editorState) val textInputSession = mock<TextInputSession>() TextFieldDelegate.onBlur(textInputSession, processor, onValueChange) inOrder(textInputSession) { verify(textInputSession).dispose() } verify(onValueChange, times(1)).invoke( eq(editorState.copy(composition = null)) ) } @Test fun check_setCursorOffset_uses_offset_map() { val position = Offset(100f, 200f) val offset = 10 val editorState = TextFieldValue(text = "Hello, World", selection = TextRange(1)) whenever(processor.toTextFieldValue()).thenReturn(editorState) whenever(textLayoutResultProxy.getOffsetForPosition(position)).thenReturn(offset) TextFieldDelegate.setCursorOffset( position, textLayoutResultProxy, processor, skippingOffsetMap, onValueChange ) verify(onValueChange, times(1)).invoke( eq(TextFieldValue(text = editorState.text, selection = TextRange(offset / 2))) ) } @Test fun use_identity_mapping_if_none_visual_transformation() { val transformedText = VisualTransformation.None.filter( AnnotatedString(text = "Hello, World") ) val visualText = transformedText.text val offsetMapping = transformedText.offsetMapping assertThat(visualText.text).isEqualTo("Hello, World") for (i in 0..visualText.text.length) { // Identity mapping returns if no visual filter is provided. assertThat(offsetMapping.originalToTransformed(i)).isEqualTo(i) assertThat(offsetMapping.transformedToOriginal(i)).isEqualTo(i) } } @Test fun apply_composition_decoration() { val identityOffsetMapping = object : OffsetMapping { override fun originalToTransformed(offset: Int): Int = offset override fun transformedToOriginal(offset: Int): Int = offset } val input = TransformedText( text = AnnotatedString.Builder().apply { pushStyle(SpanStyle(color = Color.Red)) append("Hello, World") }.toAnnotatedString(), offsetMapping = identityOffsetMapping ) val result = TextFieldDelegate.applyCompositionDecoration( compositionRange = TextRange(3, 6), transformed = input ) assertThat(result.text.text).isEqualTo(input.text.text) assertThat(result.text.spanStyles.size).isEqualTo(2) assertThat(result.text.spanStyles).contains( AnnotatedString.Range(SpanStyle(textDecoration = TextDecoration.Underline), 3, 6) ) } @Test fun apply_composition_decoration_with_offsetmap() { val offsetAmount = 5 val offsetMapping = object : OffsetMapping { override fun originalToTransformed(offset: Int): Int = offsetAmount + offset override fun transformedToOriginal(offset: Int): Int = offset - offsetAmount } val input = TransformedText( text = AnnotatedString.Builder().apply { append(" ".repeat(offsetAmount)) append("Hello World") }.toAnnotatedString(), offsetMapping = offsetMapping ) val range = TextRange(0, 2) val result = TextFieldDelegate.applyCompositionDecoration( compositionRange = range, transformed = input ) assertThat(result.text.spanStyles.size).isEqualTo(1) assertThat(result.text.spanStyles).contains( AnnotatedString.Range( SpanStyle(textDecoration = TextDecoration.Underline), range.start + offsetAmount, range.end + offsetAmount ) ) } }
compose/foundation/foundation/src/test/kotlin/androidx/compose/foundation/text/TextFieldDelegateTest.kt
3464318609
package com.riaektiv.fdp.endpoint import com.riaektiv.fdp.common.messages.MessageHeader import com.riaektiv.fdp.proxy.messages.Response import org.springframework.amqp.rabbit.core.RabbitTemplate /** * Created: 1/28/2018, 5:07 PM Eastern Time * * @author Sergey Chuykov */ class RabbitMQEndpointCallbackActor<RES : Response> : ActorFactory<EndpointCallback<*>, RabbitMQEndpointCallbackActor<*>>(), EndpointCallback<RES> { private var rabbitTemplate: RabbitTemplate? = null fun setRabbitTemplate(rabbitTemplate: RabbitTemplate) { this.rabbitTemplate = rabbitTemplate } override fun getActorType(): Class<EndpointCallback<*>> { return EndpointCallback::class.java } override fun onResponse(response: RES, header: MessageHeader) { try { logger.info("< {} replyTo={} correlationId={}", response, header.replyTo, header.correlationId) rabbitTemplate!!.convertAndSend("fdp.main", "fdp.reply", response) { message -> val correlationId = header.correlationId if (correlationId != null) { @Suppress("DEPRECATION") message.messageProperties.correlationId = correlationId.toByteArray() } message } } catch (e: Exception) { logger.error(e.message, e) } } }
fdp-service/src/main/java/com/riaektiv/fdp/endpoint/RabbitMQEndpointCallbackActor.kt
2749611808
package com.twilio.video.examples.advancedcameracapturer import android.Manifest import android.app.Activity import android.app.AlertDialog import android.content.DialogInterface import android.content.pm.PackageManager import android.graphics.Bitmap import android.hardware.Camera import android.os.Bundle import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.view.View import android.widget.Button import android.widget.ImageView import android.widget.Toast import com.twilio.video.CameraCapturer import com.twilio.video.CameraParameterUpdater import com.twilio.video.LocalVideoTrack import com.twilio.video.VideoView import tvi.webrtc.Camera1Enumerator /** * This example demonstrates advanced use cases of [com.twilio.video.CameraCapturer]. Current * use cases shown are as follows: * * 1. Setting Custom [android.hardware.Camera.Parameters] * 2. Taking a picture while capturing */ class AdvancedCameraCapturerActivity : Activity() { private lateinit var videoView: VideoView private lateinit var toggleFlashButton: Button private lateinit var takePictureButton: Button private lateinit var pictureImageView: ImageView private lateinit var pictureDialog: AlertDialog private val backCameraId by lazy { val camera1Enumerator = Camera1Enumerator() val cameraId = camera1Enumerator.deviceNames.find { camera1Enumerator.isBackFacing(it) } requireNotNull(cameraId) } private val cameraCapturer by lazy { CameraCapturer(this, backCameraId) } private val localVideoTrack by lazy { LocalVideoTrack.create(this, true, cameraCapturer) } private var flashOn = false private val toggleFlashButtonClickListener = View.OnClickListener { toggleFlash() } private val takePictureButtonClickListener = View.OnClickListener { takePicture() } /** * An example of a [CameraParameterUpdater] that shows how to toggle the flash of a * camera if supported by the device. */ @Suppress("DEPRECATION") private val flashToggler = CameraParameterUpdater { parameters: Camera.Parameters -> if (parameters.flashMode != null) { val flashMode = if (flashOn) Camera.Parameters.FLASH_MODE_OFF else Camera.Parameters.FLASH_MODE_TORCH parameters.flashMode = flashMode flashOn = !flashOn } else { Toast.makeText( this@AdvancedCameraCapturerActivity, R.string.flash_not_supported, Toast.LENGTH_LONG ).show() } } /** * An example of a [tvi.webrtc.VideoProcessor] that decodes the preview image to a [Bitmap] * and shows the result in an alert dialog. */ private val photographer by lazy { Photographer(videoView) } public override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_advanced_camera_capturer) videoView = findViewById<View>(R.id.video_view) as VideoView toggleFlashButton = findViewById<View>(R.id.toggle_flash_button) as Button takePictureButton = findViewById<View>(R.id.take_picture_button) as Button pictureImageView = layoutInflater.inflate( R.layout.picture_image_view, findViewById(android.R.id.content), false ) as ImageView pictureDialog = AlertDialog.Builder(this) .setView(pictureImageView) .setTitle(null) .setPositiveButton( R.string.close ) { dialog: DialogInterface, _: Int -> dialog.dismiss() }.create() if (!checkPermissionForCamera()) { requestPermissionForCamera() } else { addCameraVideo() } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<String>, grantResults: IntArray ) { if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) { var cameraPermissionGranted = true for (grantResult in grantResults) { cameraPermissionGranted = cameraPermissionGranted and (grantResult == PackageManager.PERMISSION_GRANTED) } if (cameraPermissionGranted) { addCameraVideo() } else { Toast.makeText( this, R.string.permissions_needed, Toast.LENGTH_LONG ).show() finish() } } } override fun onDestroy() { localVideoTrack?.removeSink(videoView) localVideoTrack?.release() super.onDestroy() } private fun checkPermissionForCamera(): Boolean { val resultCamera = ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) return resultCamera == PackageManager.PERMISSION_GRANTED } private fun requestPermissionForCamera() { ActivityCompat.requestPermissions( this, arrayOf(Manifest.permission.CAMERA), CAMERA_PERMISSION_REQUEST_CODE ) } private fun addCameraVideo() { localVideoTrack?.videoSource?.setVideoProcessor(photographer) toggleFlashButton.setOnClickListener(toggleFlashButtonClickListener) takePictureButton.setOnClickListener(takePictureButtonClickListener) } private fun toggleFlash() { // Request an update to camera parameters with flash toggler cameraCapturer.updateCameraParameters(flashToggler) } private fun takePicture() { photographer.takePicture { bitmap: Bitmap? -> bitmap?.let { runOnUiThread { showPicture(it) } } } } private fun showPicture(bitmap: Bitmap) { pictureImageView.setImageBitmap(bitmap) pictureDialog.show() } companion object { private const val CAMERA_PERMISSION_REQUEST_CODE = 100 } }
exampleAdvancedCameraCapturer/src/main/java/com/twilio/video/examples/advancedcameracapturer/AdvancedCameraCapturerActivity.kt
1392795236
package org.jetbrains.fortran.lang.psi.mixin import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.impl.source.tree.LeafPsiElement import org.jetbrains.fortran.lang.FortranTypes import org.jetbrains.fortran.lang.FortranTypes.IDENTIFIER import org.jetbrains.fortran.lang.psi.FortranConstructNameDecl import org.jetbrains.fortran.lang.psi.ext.FortranNamedElementImpl abstract class FortranConstructNameDeclImplMixin(node : ASTNode) : FortranNamedElementImpl(node), FortranConstructNameDecl { override fun getNameIdentifier(): PsiElement = notNullChild<PsiElement>(findChildByType(IDENTIFIER)) override fun setName(name: String): PsiElement? { val keyNode : LeafPsiElement = findNotNullChildByType(FortranTypes.IDENTIFIER) node.replaceChild(keyNode.node, LeafPsiElement(FortranTypes.IDENTIFIER, name).node) return this } fun getLabelValue() : String = nameIdentifier.text }
src/main/java/org/jetbrains/fortran/lang/psi/mixin/FortranConstructNameDeclImplMixin.kt
2851897644
package org.jetbrains.fortran.lang.psi.mixin import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.stubs.IStubElementType import com.intellij.psi.util.PsiTreeUtil import org.jetbrains.fortran.lang.psi.* import org.jetbrains.fortran.lang.psi.ext.FortranNamedElement import org.jetbrains.fortran.lang.psi.impl.FortranProgramUnitImpl import org.jetbrains.fortran.lang.stubs.FortranProgramUnitStub abstract class FortranSeparateModuleSubprogramImplMixin : FortranProgramUnitImpl, FortranNamedElement, FortranSeparateModuleSubprogram { constructor(node: ASTNode) : super(node) constructor(stub: FortranProgramUnitStub, nodeType: IStubElementType<*, *>) : super(stub, nodeType) override fun getNameIdentifier(): PsiElement? = mpSubprogramStmt.entityDecl override val variables: List<FortranNamedElement> get() = PsiTreeUtil.getStubChildrenOfTypeAsList(block, FortranTypeDeclarationStmt::class.java) .flatMap { PsiTreeUtil.getStubChildrenOfTypeAsList(it, FortranEntityDecl::class.java) } override val unit: FortranNamedElement? get() = PsiTreeUtil.getStubChildOfType( PsiTreeUtil.getStubChildOfType(this, FortranMpSubprogramStmt::class.java), FortranEntityDecl::class.java ) override val usedModules: List<FortranDataPath> get() = PsiTreeUtil.getStubChildrenOfTypeAsList(block, FortranUseStmt::class.java) .mapNotNull { it.dataPath } override val types: List<FortranNamedElement> get() = PsiTreeUtil.getStubChildrenOfTypeAsList(block, FortranDerivedTypeDef::class.java) .mapNotNull { it.derivedTypeStmt.typeDecl } }
src/main/java/org/jetbrains/fortran/lang/psi/mixin/FortranSeparateModuleSubprogramImplMixin.kt
1302484812
/* * Copyright (c) 2017-2019 Yui * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package moe.kyubey.akatsuki.commands import me.aurieh.ares.exposed.async.asyncTransaction import moe.kyubey.akatsuki.Akatsuki import moe.kyubey.akatsuki.annotations.Alias import moe.kyubey.akatsuki.annotations.Argument import moe.kyubey.akatsuki.annotations.Arguments import moe.kyubey.akatsuki.annotations.Load import moe.kyubey.akatsuki.db.schema.Tags import moe.kyubey.akatsuki.entities.Command import moe.kyubey.akatsuki.entities.Context import moe.kyubey.akatsuki.utils.I18n import org.jetbrains.exposed.sql.insert import org.jetbrains.exposed.sql.select import org.jetbrains.exposed.sql.update @Load @Arguments( Argument("name", "string"), Argument("content", "string") ) @Alias("editpasta", "editahh") class EditTag : Command() { override val desc = "Edit tags" override fun run(ctx: Context) { val name = ctx.args["name"] as String val content = ctx.args["content"] as String asyncTransaction(Akatsuki.pool) { val tag = Tags.select { Tags.tagName.eq(name) }.firstOrNull() ?: return@asyncTransaction ctx.send( I18n.parse( ctx.lang.getString("tag_not_found"), mapOf("username" to ctx.author.name) ) ) if (tag[Tags.ownerId] != ctx.author.idLong) { return@asyncTransaction ctx.send( I18n.parse( ctx.lang.getString("tag_not_owner"), mapOf("username" to ctx.author.name) ) ) } Tags.update({ Tags.tagName.eq(name) }) { it[tagContent] = content } ctx.send( I18n.parse( ctx.lang.getString("tag_edited"), mapOf("name" to name) ) ) }.execute() } }
src/main/kotlin/moe/kyubey/akatsuki/commands/EditTag.kt
1471325931
/* * The MIT License (MIT) * <p/> * Copyright (c) 2016 Vimeo * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.vimeo.stag.processor import com.vimeo.stag.processor.dummy.DummyGenericClass import com.vimeo.stag.processor.utils.Preconditions import org.junit.Assert.assertTrue import java.lang.reflect.InvocationTargetException import javax.lang.model.element.TypeElement import javax.lang.model.type.DeclaredType import javax.lang.model.type.TypeMirror import javax.lang.model.util.Elements import javax.lang.model.util.Types internal object Utils { internal lateinit var elements: Elements internal lateinit var types: Types private fun safeTypes(): Types { Preconditions.checkNotNull(types) return types } @Throws(Exception::class) fun <T> testZeroArgumentConstructorFinalClass(clazz: Class<T>) { var exceptionThrown = false try { val constructor = clazz.getDeclaredConstructor() constructor.isAccessible = true constructor.newInstance() } catch (e: InvocationTargetException) { if (e.cause is UnsupportedOperationException) { exceptionThrown = true } } assertTrue(exceptionThrown) } /** * Gets the parameterized class with the given parameters. * * @param clazz the class to parameterize. * @param parameters the parameters to use. * @return the declared type mirror with the correct type parameters. */ fun getParameterizedClass(clazz: Class<*>, vararg parameters: Class<*>): DeclaredType { val rootType = elements.getTypeElement(clazz.name) val params = parameters.map { elements.getTypeElement(it.name).asType() }.toTypedArray() return safeTypes().getDeclaredType(rootType, *params) } fun getElementFromClass(clazz: Class<*>): TypeElement = elements.getTypeElement(clazz.name) fun getTypeMirrorFromClass(clazz: Class<*>): TypeMirror { val element = getElementFromClass(clazz) return element.asType() } fun getElementFromObject(`object`: Any): TypeElement = elements.getTypeElement(`object`.javaClass.name) fun getTypeMirrorFromObject(`object`: Any): TypeMirror { val element = getElementFromObject(`object`) return element.asType() } fun getGenericVersionOfClass(clazz: Class<*>): TypeMirror { val params = elements.getTypeElement(clazz.name).typeParameters val genericTypes = arrayOfNulls<TypeMirror>(params.size) for (n in genericTypes.indices) { genericTypes[n] = params[n].asType() } return safeTypes().getDeclaredType(elements.getTypeElement(DummyGenericClass::class.java.name), *genericTypes) } }
stag-library-compiler/src/test/java/com/vimeo/stag/processor/Utils.kt
2829462907
package com.twitter.meil_mitu.twitter4hk.api.media import com.twitter.meil_mitu.twitter4hk.AbsOauth import com.twitter.meil_mitu.twitter4hk.AbsPost import com.twitter.meil_mitu.twitter4hk.OauthType import com.twitter.meil_mitu.twitter4hk.converter.IMediaConverter import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException import java.io.File class Upload<TMedia>( oauth: AbsOauth, protected val json: IMediaConverter<TMedia>, media: File) : AbsPost<TMedia>(oauth) { var media: File? by fileParam("media") override val url = "https://upload.twitter.com/1.1/media/upload.json" override val allowOauthType = OauthType.oauth1 override val isAuthorization = true init { this.media = media } @Throws(Twitter4HKException::class) override fun call(): TMedia { return json.toMedia(oauth.post(this)) } }
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/api/media/Upload.kt
1189165205
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.lang.core.types.infer import com.intellij.openapi.project.Project import com.intellij.psi.util.CachedValueProvider import com.intellij.psi.util.CachedValuesManager import org.jetbrains.annotations.TestOnly import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.* import org.rust.lang.core.resolve.* import org.rust.lang.core.resolve.ref.MethodResolveVariant import org.rust.lang.core.resolve.ref.pathPsiSubst import org.rust.lang.core.resolve.ref.resolvePathRaw import org.rust.lang.core.types.* import org.rust.lang.core.types.consts.* import org.rust.lang.core.types.infer.TypeError.ConstMismatch import org.rust.lang.core.types.infer.TypeError.TypeMismatch import org.rust.lang.core.types.regions.Region import org.rust.lang.core.types.ty.* import org.rust.lang.core.types.ty.Mutability.IMMUTABLE import org.rust.lang.core.types.ty.Mutability.MUTABLE import org.rust.lang.utils.RsDiagnostic import org.rust.lang.utils.snapshot.CombinedSnapshot import org.rust.lang.utils.snapshot.Snapshot import org.rust.openapiext.Testmark import org.rust.openapiext.recursionGuard import org.rust.openapiext.testAssert import org.rust.stdext.* import org.rust.stdext.RsResult.Err import org.rust.stdext.RsResult.Ok fun inferTypesIn(element: RsInferenceContextOwner): RsInferenceResult { val items = element.knownItems val paramEnv = if (element is RsItemElement) ParamEnv.buildFor(element) else ParamEnv.EMPTY val lookup = ImplLookup(element.project, element.containingCrate, items, paramEnv) return recursionGuard(element, { lookup.ctx.infer(element) }, memoize = false) ?: error("Can not run nested type inference") } sealed class Adjustment: TypeFoldable<Adjustment> { abstract val target: Ty override fun superVisitWith(visitor: TypeVisitor): Boolean = target.visitWith(visitor) class NeverToAny(override val target: Ty) : Adjustment() { override fun superFoldWith(folder: TypeFolder): Adjustment = NeverToAny(target.foldWith(folder)) } class Deref( override val target: Ty, /** Non-null if dereference has been done using Deref/DerefMut trait */ val overloaded: Mutability? ) : Adjustment() { override fun superFoldWith(folder: TypeFolder): Adjustment = Deref(target.foldWith(folder), overloaded) } class BorrowReference( override val target: TyReference ) : Adjustment() { val region: Region = target.region val mutability: Mutability = target.mutability override fun superFoldWith(folder: TypeFolder): Adjustment = BorrowReference(target.foldWith(folder) as TyReference) } class BorrowPointer( override val target: TyPointer, ) : Adjustment() { val mutability: Mutability = target.mutability override fun superFoldWith(folder: TypeFolder): Adjustment = BorrowPointer(target.foldWith(folder) as TyPointer) } class MutToConstPointer(override val target: TyPointer) : Adjustment() { override fun superFoldWith(folder: TypeFolder): Adjustment = MutToConstPointer(target.foldWith(folder) as TyPointer) } class Unsize(override val target: Ty) : Adjustment() { override fun superFoldWith(folder: TypeFolder): Adjustment = Unsize(target.foldWith(folder)) } } interface RsInferenceData { fun getExprAdjustments(expr: RsElement): List<Adjustment> fun getExprType(expr: RsExpr): Ty fun getExpectedExprType(expr: RsExpr): ExpectedType fun getPatType(pat: RsPat): Ty fun getPatFieldType(patField: RsPatField): Ty fun getResolvedPath(expr: RsPathExpr): List<ResolvedPath> fun isOverloadedOperator(expr: RsExpr): Boolean fun getBindingType(binding: RsPatBinding): Ty = when (val parent = binding.parent) { is RsPat -> getPatType(parent) is RsPatField -> getPatFieldType(parent) else -> TyUnknown // impossible } fun getExprTypeAdjusted(expr: RsExpr): Ty = getExprAdjustments(expr).lastOrNull()?.target ?: getExprType(expr) } /** * [RsInferenceResult] is an immutable per-function map * from expressions to their types. */ class RsInferenceResult( val exprTypes: Map<RsExpr, Ty>, val patTypes: Map<RsPat, Ty>, val patFieldTypes: Map<RsPatField, Ty>, private val expectedExprTypes: Map<RsExpr, ExpectedType>, private val resolvedPaths: Map<RsPathExpr, List<ResolvedPath>>, private val resolvedMethods: Map<RsMethodCall, InferredMethodCallInfo>, private val resolvedFields: Map<RsFieldLookup, List<RsElement>>, private val adjustments: Map<RsElement, List<Adjustment>>, private val overloadedOperators: Set<RsElement>, val diagnostics: List<RsDiagnostic> ) : RsInferenceData { private val timestamp: Long = System.nanoTime() override fun getExprAdjustments(expr: RsElement): List<Adjustment> = adjustments[expr] ?: emptyList() override fun getExprType(expr: RsExpr): Ty = exprTypes[expr] ?: TyUnknown override fun getPatType(pat: RsPat): Ty = patTypes[pat] ?: TyUnknown override fun getPatFieldType(patField: RsPatField): Ty = patFieldTypes[patField] ?: TyUnknown override fun getExpectedExprType(expr: RsExpr): ExpectedType = expectedExprTypes[expr] ?: ExpectedType.UNKNOWN override fun getResolvedPath(expr: RsPathExpr): List<ResolvedPath> = resolvedPaths[expr] ?: emptyList() override fun isOverloadedOperator(expr: RsExpr): Boolean = expr in overloadedOperators fun getResolvedMethod(call: RsMethodCall): List<MethodResolveVariant> = resolvedMethods[call]?.resolveVariants ?: emptyList() fun getResolvedMethodType(call: RsMethodCall): TyFunction? = resolvedMethods[call]?.type fun getResolvedMethodSubst(call: RsMethodCall): Substitution = resolvedMethods[call]?.subst ?: emptySubstitution fun getResolvedField(call: RsFieldLookup): List<RsElement> = resolvedFields[call] ?: emptyList() @TestOnly fun isExprTypeInferred(expr: RsExpr): Boolean = expr in exprTypes @TestOnly fun getTimestamp(): Long = timestamp companion object { @JvmStatic val EMPTY: RsInferenceResult = RsInferenceResult( emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptyMap(), emptySet(), emptyList(), ) } } /** * A mutable object, which is filled while we walk function body top down. */ class RsInferenceContext( val project: Project, val lookup: ImplLookup, val items: KnownItems ) : RsInferenceData { val fulfill: FulfillmentContext = FulfillmentContext(this, lookup) private val exprTypes: MutableMap<RsExpr, Ty> = hashMapOf() private val patTypes: MutableMap<RsPat, Ty> = hashMapOf() private val patFieldTypes: MutableMap<RsPatField, Ty> = hashMapOf() private val expectedExprTypes: MutableMap<RsExpr, ExpectedType> = hashMapOf() private val resolvedPaths: MutableMap<RsPathExpr, List<ResolvedPath>> = hashMapOf() private val resolvedMethods: MutableMap<RsMethodCall, InferredMethodCallInfo> = hashMapOf() private val resolvedFields: MutableMap<RsFieldLookup, List<RsElement>> = hashMapOf() private val pathRefinements: MutableList<Pair<RsPathExpr, TraitRef>> = mutableListOf() private val methodRefinements: MutableList<Pair<RsMethodCall, TraitRef>> = mutableListOf() private val adjustments: MutableMap<RsElement, MutableList<Adjustment>> = hashMapOf() private val overloadedOperators: MutableSet<RsElement> = hashSetOf() val diagnostics: MutableList<RsDiagnostic> = mutableListOf() private val intUnificationTable: UnificationTable<TyInfer.IntVar, TyInteger> = UnificationTable() private val floatUnificationTable: UnificationTable<TyInfer.FloatVar, TyFloat> = UnificationTable() private val varUnificationTable: UnificationTable<TyInfer.TyVar, Ty> = UnificationTable() private val constUnificationTable: UnificationTable<CtInferVar, Const> = UnificationTable() private val projectionCache: ProjectionCache = ProjectionCache() fun startSnapshot(): Snapshot = CombinedSnapshot( intUnificationTable.startSnapshot(), floatUnificationTable.startSnapshot(), varUnificationTable.startSnapshot(), constUnificationTable.startSnapshot(), projectionCache.startSnapshot() ) inline fun <T> probe(action: () -> T): T { val snapshot = startSnapshot() try { return action() } finally { snapshot.rollback() } } inline fun <T : Any> commitIfNotNull(action: () -> T?): T? { val snapshot = startSnapshot() val result = action() if (result == null) snapshot.rollback() else snapshot.commit() return result } fun infer(element: RsInferenceContextOwner): RsInferenceResult { when (element) { is RsFunction -> { val retTy = normalizeAssociatedTypesIn(element.rawReturnType).value val fctx = RsTypeInferenceWalker(this, retTy) fctx.extractParameterBindings(element) element.block?.let { fctx.inferFnBody(it) } } is RsReplCodeFragment -> { element.context.inference?.let { patTypes.putAll(it.patTypes) patFieldTypes.putAll(it.patFieldTypes) exprTypes.putAll(it.exprTypes) } RsTypeInferenceWalker(this, TyUnknown).inferReplCodeFragment(element) } is RsPath -> { val declaration = resolvePathRaw(element, lookup).singleOrNull()?.element as? RsGenericDeclaration if (declaration != null) { val constParameters = mutableListOf<RsConstParameter>() val constArguments = mutableListOf<RsElement>() for ((param, value) in pathPsiSubst(element, declaration).constSubst) { if (value is RsPsiSubstitution.Value.Present) { constParameters += param constArguments += value.value } } RsTypeInferenceWalker(this, TyUnknown).inferConstArgumentTypes(constParameters, constArguments) } } else -> { val (retTy, expr) = when (element) { is RsConstant -> element.typeReference?.rawType to element.expr is RsConstParameter -> element.typeReference?.rawType to element.expr is RsArrayType -> TyInteger.USize.INSTANCE to element.expr is RsVariantDiscriminant -> { val enum = element.contextStrict<RsEnumItem>() enum?.reprType to element.expr } is RsExpressionCodeFragment -> { element.context.inference?.let { patTypes.putAll(it.patTypes) patFieldTypes.putAll(it.patFieldTypes) exprTypes.putAll(it.exprTypes) } null to element.expr } else -> error( "Type inference is not implemented for PSI element of type " + "`${element.javaClass}` that implement `RsInferenceContextOwner`" ) } if (expr != null) { RsTypeInferenceWalker(this, retTy ?: TyUnknown).inferLambdaBody(expr) } } } fulfill.selectWherePossible() fallbackUnresolvedTypeVarsIfPossible() fulfill.selectWherePossible() exprTypes.replaceAll { _, ty -> fullyResolve(ty) } expectedExprTypes.replaceAll { _, ty -> fullyResolveWithOrigins(ty) } patTypes.replaceAll { _, ty -> fullyResolve(ty) } patFieldTypes.replaceAll { _, ty -> fullyResolve(ty) } // replace types in diagnostics for better quick fixes diagnostics.replaceAll { if (it is RsDiagnostic.TypeError) fullyResolve(it) else it } adjustments.replaceAll { _, it -> it.mapToMutableList { fullyResolve(it) } } performPathsRefinement(lookup) resolvedPaths.values.asSequence().flatten() .forEach { it.subst = it.subst.foldValues(fullTypeWithOriginsResolver) } resolvedMethods.replaceAll { _, ty -> fullyResolveWithOrigins(ty) } return RsInferenceResult( exprTypes, patTypes, patFieldTypes, expectedExprTypes, resolvedPaths, resolvedMethods, resolvedFields, adjustments, overloadedOperators, diagnostics ) } private fun fallbackUnresolvedTypeVarsIfPossible() { val allTypes = exprTypes.values.asSequence() + patTypes.values.asSequence() + patFieldTypes.values.asSequence() + expectedExprTypes.values.asSequence().map { it.ty } for (ty in allTypes) { ty.visitInferTys { tyInfer -> val rty = shallowResolve(tyInfer) if (rty is TyInfer) { fallbackIfPossible(rty) } false } } } private fun fallbackIfPossible(ty: TyInfer) { when (ty) { is TyInfer.IntVar -> intUnificationTable.unifyVarValue(ty, TyInteger.DEFAULT) is TyInfer.FloatVar -> floatUnificationTable.unifyVarValue(ty, TyFloat.DEFAULT) is TyInfer.TyVar -> Unit } } private fun performPathsRefinement(lookup: ImplLookup) { for ((path, traitRef) in pathRefinements) { val variant = resolvedPaths[path]?.firstOrNull() ?: continue val fnName = (variant.element as? RsFunction)?.name val impl = lookup.select(resolveTypeVarsIfPossible(traitRef)).ok()?.impl as? RsImplItem ?: continue val fn = impl.expandedMembers.functions.find { it.name == fnName } ?: continue val source = RsCachedImplItem.forImpl(impl).explicitImpl val result = ResolvedPath.AssocItem(fn, source) result.subst = variant.subst // TODO remap subst resolvedPaths[path] = listOf(result) } for ((call, traitRef) in methodRefinements) { val info = resolvedMethods[call] ?: continue val variant = info.resolveVariants.firstOrNull() ?: continue val impl = lookup.select(resolveTypeVarsIfPossible(traitRef)).ok()?.impl as? RsImplItem ?: continue val fn = impl.expandedMembers.functions.find { it.name == variant.name } ?: continue val source = RsCachedImplItem.forImpl(impl).explicitImpl // TODO remap subst resolvedMethods[call] = info.copy(resolveVariants = listOf(variant.copy(element = fn, source = source))) } } override fun getExprAdjustments(expr: RsElement): List<Adjustment> { return adjustments[expr] ?: emptyList() } override fun getExprType(expr: RsExpr): Ty { return exprTypes[expr] ?: TyUnknown } override fun getPatType(pat: RsPat): Ty { return patTypes[pat] ?: TyUnknown } override fun getPatFieldType(patField: RsPatField): Ty { return patFieldTypes[patField] ?: TyUnknown } override fun getExpectedExprType(expr: RsExpr): ExpectedType { return expectedExprTypes[expr] ?: ExpectedType.UNKNOWN } override fun getResolvedPath(expr: RsPathExpr): List<ResolvedPath> { return resolvedPaths[expr] ?: emptyList() } override fun isOverloadedOperator(expr: RsExpr): Boolean = expr in overloadedOperators fun isTypeInferred(expr: RsExpr): Boolean { return exprTypes.containsKey(expr) } fun writeExprTy(psi: RsExpr, ty: Ty) { exprTypes[psi] = ty } fun writePatTy(psi: RsPat, ty: Ty) { patTypes[psi] = ty } fun writePatFieldTy(psi: RsPatField, ty: Ty) { patFieldTypes[psi] = ty } fun writeExpectedExprTy(psi: RsExpr, ty: Ty) { expectedExprTypes[psi] = ExpectedType(ty) } fun writeExpectedExprTyCoercable(psi: RsExpr) { expectedExprTypes.computeIfPresent(psi) { _, v -> v.copy(coercable = true) } } fun writePath(path: RsPathExpr, resolved: List<ResolvedPath>) { resolvedPaths[path] = resolved } fun writePathSubst(path: RsPathExpr, subst: Substitution) { resolvedPaths[path]?.singleOrNull()?.subst = subst } fun writeResolvedMethod(call: RsMethodCall, resolvedTo: List<MethodResolveVariant>) { resolvedMethods[call] = InferredMethodCallInfo(resolvedTo) } fun writeResolvedMethodSubst(call: RsMethodCall, subst: Substitution, ty: TyFunction) { resolvedMethods[call]?.let { it.subst = subst it.type = ty } } fun writeResolvedField(lookup: RsFieldLookup, resolvedTo: List<RsElement>) { resolvedFields[lookup] = resolvedTo } fun registerPathRefinement(path: RsPathExpr, traitRef: TraitRef) { pathRefinements.add(Pair(path, traitRef)) } private fun registerMethodRefinement(path: RsMethodCall, traitRef: TraitRef) { methodRefinements.add(Pair(path, traitRef)) } fun addDiagnostic(diagnostic: RsDiagnostic) { if (diagnostic.element.containingFile.isPhysical) { diagnostics.add(diagnostic) } } fun applyAdjustment(expr: RsElement, adjustment: Adjustment) { applyAdjustments(expr, listOf(adjustment)) } fun applyAdjustments(expr: RsElement, adjustment: List<Adjustment>) { if (adjustment.isEmpty()) return val unwrappedExpr = if (expr is RsExpr) { unwrapParenExprs(expr) } else { expr } val isAutoborrowMut = adjustment.any { it is Adjustment.BorrowReference && it.mutability == MUTABLE } adjustments.getOrPut(unwrappedExpr) { mutableListOf() }.addAll(adjustment) if (isAutoborrowMut && unwrappedExpr is RsExpr) { convertPlaceDerefsToMutable(unwrappedExpr) } } fun writeOverloadedOperator(expr: RsExpr) { overloadedOperators += expr } fun reportTypeMismatch(element: RsElement, expected: Ty, actual: Ty) { addDiagnostic(RsDiagnostic.TypeError(element, expected, actual)) } @Suppress("MemberVisibilityCanBePrivate") fun canCombineTypes(ty1: Ty, ty2: Ty): Boolean { return probe { combineTypes(ty1, ty2).isOk } } private fun combineTypesIfOk(ty1: Ty, ty2: Ty): Boolean { return combineTypesIfOkResolved(shallowResolve(ty1), shallowResolve(ty2)) } private fun combineTypesIfOkResolved(ty1: Ty, ty2: Ty): Boolean { val snapshot = startSnapshot() val res = combineTypesResolved(ty1, ty2).isOk if (res) { snapshot.commit() } else { snapshot.rollback() } return res } fun combineTypes(ty1: Ty, ty2: Ty): RelateResult { return combineTypesResolved(shallowResolve(ty1), shallowResolve(ty2)) } private fun combineTypesResolved(ty1: Ty, ty2: Ty): RelateResult { return when { ty1 is TyInfer.TyVar -> combineTyVar(ty1, ty2) ty2 is TyInfer.TyVar -> combineTyVar(ty2, ty1) else -> when { ty1 is TyInfer -> combineIntOrFloatVar(ty1, ty2) ty2 is TyInfer -> combineIntOrFloatVar(ty2, ty1) else -> combineTypesNoVars(ty1, ty2) } } } private fun combineTyVar(ty1: TyInfer.TyVar, ty2: Ty): RelateResult { when (ty2) { is TyInfer.TyVar -> varUnificationTable.unifyVarVar(ty1, ty2) else -> { val ty1r = varUnificationTable.findRoot(ty1) val isTy2ContainsTy1 = ty2.visitWith(object : TypeVisitor { override fun visitTy(ty: Ty): Boolean = when { ty is TyInfer.TyVar && varUnificationTable.findRoot(ty) == ty1r -> true ty.hasTyInfer -> ty.superVisitWith(this) else -> false } }) if (isTy2ContainsTy1) { // "E0308 cyclic type of infinite size" TypeInferenceMarks.CyclicType.hit() varUnificationTable.unifyVarValue(ty1r, TyUnknown) } else { varUnificationTable.unifyVarValue(ty1r, ty2) } } } return Ok(Unit) } private fun combineIntOrFloatVar(ty1: TyInfer, ty2: Ty): RelateResult { when (ty1) { is TyInfer.IntVar -> when (ty2) { is TyInfer.IntVar -> intUnificationTable.unifyVarVar(ty1, ty2) is TyInteger -> intUnificationTable.unifyVarValue(ty1, ty2) else -> return Err(TypeMismatch(ty1, ty2)) } is TyInfer.FloatVar -> when (ty2) { is TyInfer.FloatVar -> floatUnificationTable.unifyVarVar(ty1, ty2) is TyFloat -> floatUnificationTable.unifyVarValue(ty1, ty2) else -> return Err(TypeMismatch(ty1, ty2)) } is TyInfer.TyVar -> error("unreachable") } return Ok(Unit) } fun combineTypesNoVars(ty1: Ty, ty2: Ty): RelateResult = when { ty1 === ty2 -> Ok(Unit) ty1 is TyPrimitive && ty2 is TyPrimitive && ty1.javaClass == ty2.javaClass -> Ok(Unit) ty1 is TyTypeParameter && ty2 is TyTypeParameter && ty1 == ty2 -> Ok(Unit) ty1 is TyProjection && ty2 is TyProjection && ty1.target == ty2.target && combineBoundElements(ty1.trait, ty2.trait) -> { combineTypes(ty1.type, ty2.type) } ty1 is TyReference && ty2 is TyReference && ty1.mutability == ty2.mutability -> { combineTypes(ty1.referenced, ty2.referenced) } ty1 is TyPointer && ty2 is TyPointer && ty1.mutability == ty2.mutability -> { combineTypes(ty1.referenced, ty2.referenced) } ty1 is TyArray && ty2 is TyArray && (ty1.size == null || ty2.size == null || ty1.size == ty2.size) -> combineTypes(ty1.base, ty2.base).and { combineConsts(ty1.const, ty2.const) } ty1 is TySlice && ty2 is TySlice -> combineTypes(ty1.elementType, ty2.elementType) ty1 is TyTuple && ty2 is TyTuple && ty1.types.size == ty2.types.size -> { combineTypePairs(ty1.types.zip(ty2.types)) } ty1 is TyFunction && ty2 is TyFunction && ty1.paramTypes.size == ty2.paramTypes.size -> { combineTypePairs(ty1.paramTypes.zip(ty2.paramTypes)) .and { combineTypes(ty1.retType, ty2.retType) } } ty1 is TyAdt && ty2 is TyAdt && ty1.item == ty2.item -> { combineTypePairs(ty1.typeArguments.zip(ty2.typeArguments)) .and { combineConstPairs(ty1.constArguments.zip(ty2.constArguments)) } } ty1 is TyTraitObject && ty2 is TyTraitObject && // TODO: Use all trait bounds combineBoundElements(ty1.traits.first(), ty2.traits.first()) -> Ok(Unit) ty1 is TyAnon && ty2 is TyAnon && ty1.definition != null && ty1.definition == ty2.definition -> Ok(Unit) ty1 is TyNever || ty2 is TyNever -> Ok(Unit) else -> Err(TypeMismatch(ty1, ty2)) } fun combineConsts(const1: Const, const2: Const): RelateResult { return combineConstsResolved(shallowResolve(const1), shallowResolve(const2)) } private fun combineConstsResolved(const1: Const, const2: Const): RelateResult = when { const1 is CtInferVar -> combineConstVar(const1, const2) const2 is CtInferVar -> combineConstVar(const2, const1) else -> combineConstsNoVars(const1, const2) } private fun combineConstVar(const1: CtInferVar, const2: Const): RelateResult { if (const2 is CtInferVar) { constUnificationTable.unifyVarVar(const1, const2) } else { val const1r = constUnificationTable.findRoot(const1) constUnificationTable.unifyVarValue(const1r, const2) } return Ok(Unit) } private fun combineConstsNoVars(const1: Const, const2: Const): RelateResult = when { const1 === const2 -> Ok(Unit) const1 is CtUnknown || const2 is CtUnknown -> Ok(Unit) const1 is CtUnevaluated || const2 is CtUnevaluated -> Ok(Unit) const1 == const2 -> Ok(Unit) else -> Err(ConstMismatch(const1, const2)) } fun combineTypePairs(pairs: List<Pair<Ty, Ty>>): RelateResult = combinePairs(pairs, ::combineTypes) fun combineConstPairs(pairs: List<Pair<Const, Const>>): RelateResult = combinePairs(pairs, ::combineConsts) private fun <T : Kind> combinePairs(pairs: List<Pair<T, T>>, combine: (T, T) -> RelateResult): RelateResult { var canUnify: RelateResult = Ok(Unit) for ((k1, k2) in pairs) { canUnify = combine(k1, k2).and { canUnify } } return canUnify } fun combineTraitRefs(ref1: TraitRef, ref2: TraitRef): Boolean = ref1.trait.element == ref2.trait.element && combineTypes(ref1.selfTy, ref2.selfTy).isOk && ref1.trait.subst.zipTypeValues(ref2.trait.subst).all { (a, b) -> combineTypes(a, b).isOk } && ref1.trait.subst.zipConstValues(ref2.trait.subst).all { (a, b) -> combineConsts(a, b).isOk } fun <T : RsElement> combineBoundElements(be1: BoundElement<T>, be2: BoundElement<T>): Boolean = be1.element == be2.element && combineTypePairs(be1.subst.zipTypeValues(be2.subst)).isOk && combineConstPairs(be1.subst.zipConstValues(be2.subst)).isOk && combineTypePairs(zipValues(be1.assoc, be2.assoc)).isOk fun tryCoerce(inferred: Ty, expected: Ty): CoerceResult { if (inferred === expected) { return Ok(CoerceOk()) } if (inferred == TyNever) { return Ok(CoerceOk(adjustments = listOf(Adjustment.NeverToAny(expected)))) } if (inferred is TyInfer.TyVar) { return combineTypes(inferred, expected).into() } val unsize = commitIfNotNull { coerceUnsized(inferred, expected) } if (unsize != null) { return Ok(unsize) } return when { // Coerce reference to pointer inferred is TyReference && expected is TyPointer && coerceMutability(inferred.mutability, expected.mutability) -> { combineTypes(inferred.referenced, expected.referenced).map { CoerceOk( adjustments = listOf( Adjustment.Deref(inferred.referenced, overloaded = null), Adjustment.BorrowPointer(expected) ) ) } } // Coerce mutable pointer to const pointer inferred is TyPointer && inferred.mutability.isMut && expected is TyPointer && !expected.mutability.isMut -> { combineTypes(inferred.referenced, expected.referenced).map { CoerceOk(adjustments = listOf(Adjustment.MutToConstPointer(expected))) } } // Coerce references inferred is TyReference && expected is TyReference && coerceMutability(inferred.mutability, expected.mutability) -> { coerceReference(inferred, expected) } else -> combineTypes(inferred, expected).into() } } // &[T; n] or &mut [T; n] -> &[T] // or &mut [T; n] -> &mut [T] // or &Concrete -> &Trait, etc. // Mirrors rustc's `coerce_unsized` // https://github.com/rust-lang/rust/blob/97d48bec2d/compiler/rustc_typeck/src/check/coercion.rs#L486 private fun coerceUnsized(source: Ty, target: Ty): CoerceOk? { if (source is TyInfer.TyVar || target is TyInfer.TyVar) return null // Optimization: return early if unsizing is not needed to match types if (target.isScalar || canCombineTypes(source, target)) return null val unsizeTrait = items.Unsize ?: return null val coerceUnsizedTrait = items.CoerceUnsized ?: return null val traits = listOf(unsizeTrait, coerceUnsizedTrait) val reborrow = when { source is TyReference && target is TyReference -> { if (!coerceMutability(source.mutability, target.mutability)) return null Pair( Adjustment.Deref(source.referenced, overloaded = null), Adjustment.BorrowReference(TyReference(source.referenced, target.mutability)) ) } source is TyReference && target is TyPointer -> { if (!coerceMutability(source.mutability, target.mutability)) return null Pair( Adjustment.Deref(source.referenced, overloaded = null), Adjustment.BorrowPointer(TyPointer(source.referenced, target.mutability)) ) } else -> null } val coerceSource = reborrow?.second?.target ?: source val adjustments = listOfNotNull( reborrow?.first, reborrow?.second, Adjustment.Unsize(target) ) val resultObligations = mutableListOf<Obligation>() val queue = dequeOf(Obligation(Predicate.Trait(TraitRef(coerceSource, coerceUnsizedTrait.withSubst(target))))) while (!queue.isEmpty()) { val obligation = queue.removeFirst() val predicate = resolveTypeVarsIfPossible(obligation.predicate) if (predicate is Predicate.Trait && predicate.trait.trait.element in traits) { when (val selection = lookup.select(predicate.trait, obligation.recursionDepth)) { SelectionResult.Err -> return null is SelectionResult.Ok -> queue += selection.result.nestedObligations SelectionResult.Ambiguous -> if (predicate.trait.trait.element == unsizeTrait) { val selfTy = predicate.trait.selfTy val unsizeTy = predicate.trait.trait.singleParamValue if (selfTy is TyInfer.TyVar && unsizeTy is TyTraitObject && typeVarIsSized(selfTy)) { resultObligations += obligation } else { return null } } else { return null } } } else { resultObligations += obligation continue } } return CoerceOk(adjustments, resultObligations) } private fun typeVarIsSized(ty: TyInfer.TyVar): Boolean { return fulfill.pendingObligations .mapNotNull { it.obligation.predicate as? Predicate.Trait } .any { it.trait.selfTy == ty && it.trait.trait.element == items.Sized } } private fun coerceMutability(from: Mutability, to: Mutability): Boolean = from == to || from.isMut && !to.isMut /** * Reborrows `&mut A` to `&mut B` and `&(mut) A` to `&B`. * To match `A` with `B`, autoderef will be performed */ private fun coerceReference(inferred: TyReference, expected: TyReference): CoerceResult { val autoderef = lookup.coercionSequence(inferred) for (derefTy in autoderef.drop(1)) { // TODO proper handling of lifetimes val derefTyRef = TyReference(derefTy, expected.mutability, expected.region) if (combineTypesIfOk(derefTyRef, expected)) { // Deref `&a` to `a` and then reborrow as `&a`. No-op. See rustc's `coerce_borrowed_pointer` val isTrivialReborrow = autoderef.stepCount() == 1 && inferred.mutability == expected.mutability && !expected.mutability.isMut if (!isTrivialReborrow) { val adjustments = autoderef.steps().toAdjustments(items) + listOf(Adjustment.BorrowReference(derefTyRef)) return Ok(CoerceOk(adjustments)) } return Ok(CoerceOk()) } } return Err(TypeMismatch(inferred, expected)) } fun <T : TypeFoldable<T>> shallowResolve(value: T): T = value.foldWith(shallowResolver) private inner class ShallowResolver : TypeFolder { override fun foldTy(ty: Ty): Ty = shallowResolve(ty) override fun foldConst(const: Const): Const = if (const is CtInferVar) { constUnificationTable.findValue(const) ?: const } else { const } private fun shallowResolve(ty: Ty): Ty { if (ty !is TyInfer) return ty return when (ty) { is TyInfer.IntVar -> intUnificationTable.findValue(ty) ?: ty is TyInfer.FloatVar -> floatUnificationTable.findValue(ty) ?: ty is TyInfer.TyVar -> varUnificationTable.findValue(ty)?.let(this::shallowResolve) ?: ty } } } private val shallowResolver: ShallowResolver = ShallowResolver() fun <T : TypeFoldable<T>> resolveTypeVarsIfPossible(value: T): T = value.foldWith(opportunisticVarResolver) private inner class OpportunisticVarResolver : TypeFolder { override fun foldTy(ty: Ty): Ty { if (!ty.needsInfer) return ty val res = shallowResolve(ty) return res.superFoldWith(this) } override fun foldConst(const: Const): Const { if (!const.hasCtInfer) return const val res = shallowResolve(const) return res.superFoldWith(this) } } private val opportunisticVarResolver: OpportunisticVarResolver = OpportunisticVarResolver() /** * Full type resolution replaces all type and const variables with their concrete results. */ fun <T : TypeFoldable<T>> fullyResolve(value: T): T { val resolved = value.foldWith(fullTypeResolver) testAssert { !resolved.hasTyPlaceholder } return resolved } private inner class FullTypeResolver : TypeFolder { override fun foldTy(ty: Ty): Ty { if (!ty.needsInfer) return ty val res = shallowResolve(ty) return if (res is TyInfer) TyUnknown else res.superFoldWith(this) } override fun foldConst(const: Const): Const = if (const is CtInferVar) { constUnificationTable.findValue(const) ?: CtUnknown } else { const } } private val fullTypeResolver: FullTypeResolver = FullTypeResolver() /** * Similar to [fullyResolve], but replaces unresolved [TyInfer.TyVar] to its [TyInfer.TyVar.origin] * instead of [TyUnknown] */ fun <T : TypeFoldable<T>> fullyResolveWithOrigins(value: T): T { return value.foldWith(fullTypeWithOriginsResolver) } private inner class FullTypeWithOriginsResolver : TypeFolder { override fun foldTy(ty: Ty): Ty { if (!ty.needsInfer) return ty return when (val res = shallowResolve(ty)) { is TyUnknown -> (ty as? TyInfer.TyVar)?.origin as? TyTypeParameter ?: TyUnknown is TyInfer.TyVar -> res.origin as? TyTypeParameter ?: TyUnknown is TyInfer -> TyUnknown else -> res.superFoldWith(this) } } override fun foldConst(const: Const): Const = if (const is CtInferVar) { constUnificationTable.findValue(const) ?: CtUnknown } else { const } } private val fullTypeWithOriginsResolver: FullTypeWithOriginsResolver = FullTypeWithOriginsResolver() fun typeVarForParam(ty: TyTypeParameter): Ty = TyInfer.TyVar(ty) fun constVarForParam(const: CtConstParameter): Const = CtInferVar(const) fun <T : TypeFoldable<T>> fullyNormalizeAssociatedTypesIn(ty: T): T { val (normalizedTy, obligations) = normalizeAssociatedTypesIn(ty) obligations.forEach(fulfill::registerPredicateObligation) fulfill.selectWherePossible() return fullyResolve(normalizedTy) } /** Deeply normalize projection types. See [normalizeProjectionType] */ fun <T : TypeFoldable<T>> normalizeAssociatedTypesIn(ty: T, recursionDepth: Int = 0): TyWithObligations<T> { val obligations = mutableListOf<Obligation>() val normTy = ty.foldTyProjectionWith { val normTy = normalizeProjectionType(it, recursionDepth) obligations += normTy.obligations normTy.value } return TyWithObligations(normTy, obligations) } /** * Normalize a specific projection like `<T as Trait>::Item`. * The result is always a type (and possibly additional obligations). * If ambiguity arises, which implies that * there are unresolved type variables in the projection, we will * substitute a fresh type variable `$X` and generate a new * obligation `<T as Trait>::Item == $X` for later. */ private fun normalizeProjectionType(projectionTy: TyProjection, recursionDepth: Int): TyWithObligations<Ty> { return optNormalizeProjectionType(projectionTy, recursionDepth) ?: run { val tyVar = TyInfer.TyVar(projectionTy) val obligation = Obligation(recursionDepth + 1, Predicate.Projection(projectionTy, tyVar)) TyWithObligations(tyVar, listOf(obligation)) } } /** * Normalize a specific projection like `<T as Trait>::Item`. * The result is always a type (and possibly additional obligations). * Returns `null` in the case of ambiguity, which indicates that there * are unbound type variables. */ fun optNormalizeProjectionType(projectionTy: TyProjection, recursionDepth: Int): TyWithObligations<Ty>? = optNormalizeProjectionTypeResolved(resolveTypeVarsIfPossible(projectionTy) as TyProjection, recursionDepth) /** See [optNormalizeProjectionType] */ private fun optNormalizeProjectionTypeResolved( projectionTy: TyProjection, recursionDepth: Int ): TyWithObligations<Ty>? { if (projectionTy.type is TyInfer.TyVar) return null return when (val cacheResult = projectionCache.tryStart(projectionTy)) { ProjectionCacheEntry.Ambiguous -> { // If we found ambiguity the last time, that generally // means we will continue to do so until some type in the // key changes (and we know it hasn't, because we just // fully resolved it). // TODO rustc has an exception for closure types here null } ProjectionCacheEntry.InProgress -> { // While normalized A::B we are asked to normalize A::B. TypeInferenceMarks.RecursiveProjectionNormalization.hit() TyWithObligations(TyUnknown) } ProjectionCacheEntry.Error -> { // TODO report an error. See rustc's `normalize_to_error` TyWithObligations(TyUnknown) } is ProjectionCacheEntry.NormalizedTy -> { var ty = cacheResult.ty // If we find the value in the cache, then return it along // with the obligations that went along with it. Note // that, when using a fulfillment context, these // obligations could in principle be ignored: they have // already been registered when the cache entry was // created (and hence the new ones will quickly be // discarded as duplicated). But when doing trait // evaluation this is not the case. // (See rustc's https://github.com/rust-lang/rust/issues/43132 ) if (!hasUnresolvedTypeVars(ty.value)) { // Once we have inferred everything we need to know, we // can ignore the `obligations` from that point on. ty = TyWithObligations(ty.value) projectionCache.putTy(projectionTy, ty) } ty } null -> { when (val selResult = lookup.selectProjection(projectionTy, recursionDepth)) { is SelectionResult.Ok -> { val result = selResult.result ?: TyWithObligations(projectionTy) projectionCache.putTy(projectionTy, pruneCacheValueObligations(result)) result } is SelectionResult.Err -> { projectionCache.error(projectionTy) // TODO report an error. See rustc's `normalize_to_error` TyWithObligations(TyUnknown) } is SelectionResult.Ambiguous -> { projectionCache.ambiguous(projectionTy) null } } } } } /** * If there are unresolved type variables, then we need to include * any subobligations that bind them, at least until those type * variables are fully resolved. */ private fun pruneCacheValueObligations(ty: TyWithObligations<Ty>): TyWithObligations<Ty> { if (!hasUnresolvedTypeVars(ty.value)) return TyWithObligations(ty.value) // I don't completely understand why we leave the only projection // predicates here, but here is the comment from rustc about it // // If we found a `T: Foo<X = U>` predicate, let's check // if `U` references any unresolved type // variables. In principle, we only care if this // projection can help resolve any of the type // variables found in `result.value` -- but we just // check for any type variables here, for fear of // indirect obligations (e.g., we project to `?0`, // but we have `T: Foo<X = ?1>` and `?1: Bar<X = // ?0>`). // // We are only interested in `T: Foo<X = U>` predicates, where // `U` references one of `unresolved_type_vars`. val obligations = ty.obligations .filter { it.predicate is Predicate.Projection && hasUnresolvedTypeVars(it.predicate) } return TyWithObligations(ty.value, obligations) } private fun <T : TypeFoldable<T>> hasUnresolvedTypeVars(_ty: T): Boolean = _ty.visitWith(object : TypeVisitor { override fun visitTy(ty: Ty): Boolean { val resolvedTy = shallowResolve(ty) return when { resolvedTy is TyInfer -> true resolvedTy.hasTyInfer -> resolvedTy.superVisitWith(this) else -> false } } }) fun <T : TypeFoldable<T>> hasResolvableTypeVars(ty: T): Boolean = ty.visitInferTys { it != shallowResolve(it) } /** Return true if [ty] was instantiated or unified with another type variable */ fun isTypeVarAffected(ty: TyInfer.TyVar): Boolean = varUnificationTable.findRoot(ty) != ty || varUnificationTable.findValue(ty) != null fun instantiateBounds( bounds: List<Predicate>, subst: Substitution = emptySubstitution, recursionDepth: Int = 0 ): Sequence<Obligation> { return bounds.asSequence() .map { it.substitute(subst) } .map { normalizeAssociatedTypesIn(it, recursionDepth) } .flatMap { it.obligations.asSequence() + Obligation(recursionDepth, it.value) } } fun instantiateBounds( element: RsGenericDeclaration, selfTy: Ty? = null, subst: Substitution = emptySubstitution ): Substitution { val map = run { val typeSubst = element .generics .associateWith { typeVarForParam(it) } .let { if (selfTy != null) it + (TyTypeParameter.self() to selfTy) else it } val constSubst = element .constGenerics .associateWith { constVarForParam(it) } subst + Substitution(typeSubst = typeSubst, constSubst = constSubst) } instantiateBounds(element.predicates, map).forEach(fulfill::registerPredicateObligation) return map } /** Checks that [selfTy] satisfies all trait bounds of the [source] */ fun canEvaluateBounds(source: TraitImplSource, selfTy: Ty): Boolean { return when (source) { is TraitImplSource.ExplicitImpl -> canEvaluateBounds(source.value, selfTy) is TraitImplSource.Derived, is TraitImplSource.Builtin -> { if (source.value.typeParameters.isNotEmpty()) return true lookup.canSelect(TraitRef(selfTy, BoundElement(source.value as RsTraitItem))) } else -> return true } } /** Checks that [selfTy] satisfies all trait bounds of the [impl] */ private fun canEvaluateBounds(impl: RsImplItem, selfTy: Ty): Boolean { val ff = FulfillmentContext(this, lookup) val subst = Substitution( typeSubst = impl.generics.associateWith { typeVarForParam(it) }, constSubst = impl.constGenerics.associateWith { constVarForParam(it) } ) return probe { instantiateBounds(impl.predicates, subst).forEach(ff::registerPredicateObligation) impl.typeReference?.rawType?.substitute(subst)?.let { combineTypes(selfTy, it) } ff.selectUntilError() } } fun instantiateMethodOwnerSubstitution( callee: AssocItemScopeEntryBase<*>, methodCall: RsMethodCall? = null ): Substitution = instantiateMethodOwnerSubstitution(callee.source, callee.selfTy, callee.element, methodCall) fun instantiateMethodOwnerSubstitution( callee: MethodPick, methodCall: RsMethodCall? = null ): Substitution = instantiateMethodOwnerSubstitution(callee.source, callee.formalSelfTy, callee.element, methodCall) private fun instantiateMethodOwnerSubstitution( source: TraitImplSource, selfTy: Ty, element: RsAbstractable, methodCall: RsMethodCall? = null ): Substitution = when (source) { is TraitImplSource.ExplicitImpl -> { val impl = source.value val typeParameters = instantiateBounds(impl) source.type?.substitute(typeParameters)?.let { combineTypes(selfTy, it) } if (element.owner is RsAbstractableOwner.Trait) { source.implementedTrait?.substitute(typeParameters)?.subst ?: emptySubstitution } else { typeParameters } } is TraitImplSource.TraitBound -> lookup.getEnvBoundTransitivelyFor(selfTy) .find { it.element == source.value }?.subst ?: emptySubstitution is TraitImplSource.ProjectionBound -> { val ty = selfTy as TyProjection val subst = ty.trait.subst + mapOf(TyTypeParameter.self() to ty.type).toTypeSubst() val bound = ty.trait.element.bounds .find { it.trait.element == source.value && probe { combineTypes(it.selfTy.substitute(subst), ty) }.isOk } bound?.trait?.subst?.substituteInValues(subst) ?: emptySubstitution } is TraitImplSource.Derived -> emptySubstitution is TraitImplSource.Object -> when (selfTy) { is TyAnon -> selfTy.getTraitBoundsTransitively() .find { it.element == source.value }?.subst ?: emptySubstitution is TyTraitObject -> selfTy.getTraitBoundsTransitively() .find { it.element == source.value }?.subst ?: emptySubstitution else -> emptySubstitution } is TraitImplSource.Collapsed, is TraitImplSource.Builtin -> { // Method has been resolved to a trait, so we should add a predicate // `Self : Trait<Args>` to select args and also refine method path if possible. // Method path refinement needed if there are multiple impls of the same trait to the same type val trait = source.value as RsTraitItem val typeParameters = instantiateBounds(trait) val subst = Substitution( typeSubst = trait.generics.associateBy { it }, constSubst = trait.constGenerics.associateBy { it } ) val boundTrait = BoundElement(trait, subst).substitute(typeParameters) val traitRef = TraitRef(selfTy, boundTrait) fulfill.registerPredicateObligation(Obligation(Predicate.Trait(traitRef))) if (methodCall != null) { registerMethodRefinement(methodCall, traitRef) } typeParameters } is TraitImplSource.Trait -> { // It's possible in type-qualified UFCS paths (like `<A as Trait>::Type`) during completion emptySubstitution } } /** * Convert auto-derefs, indices, etc of an expression from `Deref` and `Index` * into `DerefMut` and `IndexMut` respectively. */ fun convertPlaceDerefsToMutable(receiver: RsExpr) { val exprs = mutableListOf(receiver) while (true) { exprs += when (val expr = exprs.last()) { is RsIndexExpr -> expr.containerExpr is RsUnaryExpr -> if (expr.isDereference) expr.expr else null is RsDotExpr -> if (expr.fieldLookup != null) expr.expr else null is RsParenExpr -> expr.expr else -> null } ?: break } for (expr in exprs.asReversed()) { val exprAdjustments = adjustments[expr] exprAdjustments?.forEachIndexed { i, adjustment -> if (adjustment is Adjustment.Deref && adjustment.overloaded == IMMUTABLE) { exprAdjustments[i] = Adjustment.Deref(adjustment.target, MUTABLE) } } val base = unwrapParenExprs( when (expr) { is RsIndexExpr -> expr.containerExpr is RsUnaryExpr -> if (expr.isDereference) expr.expr else null else -> null } ?: continue ) val baseAdjustments = adjustments[base] ?: continue baseAdjustments.forEachIndexed { i, adjustment -> if (adjustment is Adjustment.BorrowReference && adjustment.mutability == IMMUTABLE) { baseAdjustments[i] = Adjustment.BorrowReference(adjustment.target.copy(mutability = MUTABLE)) } } val lastAdjustment = baseAdjustments.lastOrNull() if (lastAdjustment is Adjustment.Unsize && baseAdjustments.getOrNull(baseAdjustments.lastIndex - 1) is Adjustment.BorrowReference && lastAdjustment.target is TyReference) { baseAdjustments[baseAdjustments.lastIndex] = Adjustment.Unsize((lastAdjustment.target as TyReference).copy(mutability = MUTABLE)) } } } } val RsGenericDeclaration.generics: List<TyTypeParameter> get() = typeParameters.map { TyTypeParameter.named(it) } val RsGenericDeclaration.constGenerics: List<CtConstParameter> get() = constParameters.map { CtConstParameter(it) } val RsGenericDeclaration.bounds: List<TraitRef> get() = predicates.mapNotNull { (it as? Predicate.Trait)?.trait } val RsGenericDeclaration.predicates: List<Predicate> get() = CachedValuesManager.getCachedValue(this) { CachedValueProvider.Result.create( doGetPredicates(), rustStructureOrAnyPsiModificationTracker ) } private fun RsGenericDeclaration.doGetPredicates(): List<Predicate> { val whereBounds = whereClause?.wherePredList.orEmpty().asSequence() .flatMap { val selfTy = it.typeReference?.rawType ?: return@flatMap emptySequence<PsiPredicate>() it.typeParamBounds?.polyboundList.toPredicates(selfTy) } val bounds = typeParameters.asSequence().flatMap { val selfTy = TyTypeParameter.named(it) it.typeParamBounds?.polyboundList.toPredicates(selfTy) } val assocTypes = if (this is RsTraitItem) { expandedMembers.types.map { TyProjection.valueOf(it) } } else { emptyList() } val assocTypeBounds = assocTypes.asSequence().flatMap { it.target.typeParamBounds?.polyboundList.toPredicates(it) } val explicitPredicates = (bounds + whereBounds + assocTypeBounds).toList() val sized = knownItems.Sized val implicitPredicates = if (sized != null) { val sizedBounds = explicitPredicates.mapNotNullToSet { when (it) { is PsiPredicate.Unbound -> it.selfTy is PsiPredicate.Bound -> if (it.predicate is Predicate.Trait && it.predicate.trait.trait.element == sized) { it.predicate.trait.selfTy } else { null } } } (generics.asSequence() + assocTypes.asSequence()) .filter { it !in sizedBounds } .map { Predicate.Trait(TraitRef(it, sized.withSubst())) } } else { emptySequence() } return explicitPredicates.mapNotNull { (it as? PsiPredicate.Bound)?.predicate } + implicitPredicates } private fun List<RsPolybound>?.toPredicates(selfTy: Ty): Sequence<PsiPredicate> = orEmpty().asSequence() .flatMap { bound -> if (bound.hasQ) { // ?Sized return@flatMap sequenceOf(PsiPredicate.Unbound(selfTy)) } val traitRef = bound.bound.traitRef ?: return@flatMap emptySequence<PsiPredicate>() val boundTrait = traitRef.resolveToBoundTrait() ?: return@flatMap emptySequence<PsiPredicate>() val assocTypeBounds = traitRef.path.assocTypeBindings.asSequence() .flatMap nestedFlatMap@{ val assoc = it.path.reference?.resolve() as? RsTypeAlias ?: return@nestedFlatMap emptySequence<PsiPredicate>() val projectionTy = TyProjection.valueOf(selfTy, assoc) val typeRef = it.typeReference if (typeRef != null) { // T: Iterator<Item = Foo> // ~~~~~~~~~~ expands to predicate `T::Item = Foo` sequenceOf(PsiPredicate.Bound(Predicate.Equate(projectionTy, typeRef.rawType))) } else { // T: Iterator<Item: Debug> // ~~~~~~~~~~~ equivalent to `T::Item: Debug` it.polyboundList.toPredicates(projectionTy) } } val constness = if (bound.hasConst) { BoundConstness.ConstIfConst } else { BoundConstness.NotConst } sequenceOf(PsiPredicate.Bound(Predicate.Trait(TraitRef(selfTy, boundTrait), constness))) + assocTypeBounds } private sealed class PsiPredicate { data class Bound(val predicate: Predicate) : PsiPredicate() data class Unbound(val selfTy: Ty) : PsiPredicate() } data class TyWithObligations<out T>( val value: T, val obligations: List<Obligation> = emptyList() ) fun <T> TyWithObligations<T>.withObligations(addObligations: List<Obligation>) = TyWithObligations(value, obligations + addObligations) sealed class ResolvedPath { abstract val element: RsElement var subst: Substitution = emptySubstitution class Item(override val element: RsElement, val isVisible: Boolean) : ResolvedPath() class AssocItem( override val element: RsAbstractable, val source: TraitImplSource ) : ResolvedPath() companion object { fun from(entry: ScopeEntry, context: RsElement): ResolvedPath? { return if (entry is AssocItemScopeEntry) { AssocItem(entry.element, entry.source) } else { entry.element?.let { val isVisible = entry.isVisibleFrom(context.containingMod) Item(it, isVisible) } } } fun from(entry: AssocItemScopeEntry): ResolvedPath = AssocItem(entry.element, entry.source) } } data class InferredMethodCallInfo( val resolveVariants: List<MethodResolveVariant>, var subst: Substitution = emptySubstitution, var type: TyFunction? = null, ) : TypeFoldable<InferredMethodCallInfo> { override fun superFoldWith(folder: TypeFolder): InferredMethodCallInfo = InferredMethodCallInfo( resolveVariants, subst.foldValues(folder), type?.foldWith(folder) as? TyFunction ) override fun superVisitWith(visitor: TypeVisitor): Boolean { val type = type return subst.visitValues(visitor) || type != null && type.visitWith(visitor) } } data class MethodPick( val element: RsFunction, /** A type that should be unified with `Self` type of the `impl` */ val formalSelfTy: Ty, /** An actual type of `self` inside the method. Can differ from [formalSelfTy] because of `&mut self`, etc */ val methodSelfTy: Ty, val derefCount: Int, val source: TraitImplSource, val derefSteps: List<Autoderef.AutoderefStep>, val autorefOrPtrAdjustment: AutorefOrPtrAdjustment?, val isValid: Boolean ) { fun toMethodResolveVariant(): MethodResolveVariant = MethodResolveVariant(element.name!!, element, formalSelfTy, derefCount, source) sealed class AutorefOrPtrAdjustment { data class Autoref(val mutability: Mutability, val unsize: Boolean) : AutorefOrPtrAdjustment() object ToConstPtr : AutorefOrPtrAdjustment() } companion object { fun from( m: MethodResolveVariant, methodSelfTy: Ty, derefSteps: List<Autoderef.AutoderefStep>, autorefOrPtrAdjustment: AutorefOrPtrAdjustment? ) = MethodPick(m.element, m.selfTy, methodSelfTy, m.derefCount, m.source, derefSteps, autorefOrPtrAdjustment, true) fun from(m: MethodResolveVariant) = MethodPick(m.element, m.selfTy, TyUnknown, m.derefCount, m.source, emptyList(), null, false) } } typealias RelateResult = RsResult<Unit, TypeError> private inline fun RelateResult.and(rhs: () -> RelateResult): RelateResult = if (isOk) rhs() else this sealed class TypeError { class TypeMismatch(val ty1: Ty, val ty2: Ty) : TypeError() class ConstMismatch(val const1: Const, val const2: Const) : TypeError() } typealias CoerceResult = RsResult<CoerceOk, TypeError> data class CoerceOk( val adjustments: List<Adjustment> = emptyList(), val obligations: List<Obligation> = emptyList() ) fun RelateResult.into(): CoerceResult = map { CoerceOk() } data class ExpectedType(val ty: Ty, val coercable: Boolean = false) : TypeFoldable<ExpectedType> { override fun superFoldWith(folder: TypeFolder): ExpectedType = copy(ty = ty.foldWith(folder)) override fun superVisitWith(visitor: TypeVisitor): Boolean = ty.visitWith(visitor) companion object { val UNKNOWN: ExpectedType = ExpectedType(TyUnknown) } } object TypeInferenceMarks { object CyclicType : Testmark() object RecursiveProjectionNormalization : Testmark() object QuestionOperator : Testmark() object MethodPickTraitScope : Testmark() object MethodPickTraitsOutOfScope : Testmark() object MethodPickCheckBounds : Testmark() object MethodPickDerefOrder : Testmark() object MethodPickCollapseTraits : Testmark() object WinnowSpecialization : Testmark() object WinnowParamCandidateWins : Testmark() object WinnowParamCandidateLoses : Testmark() object WinnowObjectOrProjectionCandidateWins : Testmark() object TraitSelectionOverflow : Testmark() object MacroExprDepthLimitReached : Testmark() object UnsizeToTraitObject : Testmark() object UnsizeArrayToSlice : Testmark() object UnsizeStruct : Testmark() object UnsizeTuple : Testmark() }
src/main/kotlin/org/rust/lang/core/types/infer/TypeInference.kt
1676981043
package com.twitter.meil_mitu.twitter4hk.converter import com.squareup.okhttp.Response import com.twitter.meil_mitu.twitter4hk.ResponseData import com.twitter.meil_mitu.twitter4hk.exception.Twitter4HKException interface ISearchResultConverter<TSearchResult> : IJsonConverter { @Throws(Twitter4HKException::class) fun toSearchResultResponseData(res: Response): ResponseData<TSearchResult> }
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/converter/ISearchResultConverter.kt
2156331662
package org.jetbrains.dokka import java.io.File interface Location { val path: String get fun relativePathTo(other: Location, anchor: String? = null): String } /** * Represents locations in the documentation in the form of [path](File). * * $file: [File] for this location * $path: [String] representing path of this location */ data class FileLocation(val file: File) : Location { override val path: String get() = file.path override fun relativePathTo(other: Location, anchor: String?): String { if (other !is FileLocation) { throw IllegalArgumentException("$other is not a FileLocation") } if (file.path.substringBeforeLast(".") == other.file.path.substringBeforeLast(".") && anchor == null) { return "./${file.name}" } val ownerFolder = file.parentFile!! val relativePath = ownerFolder.toPath().relativize(other.file.toPath()).toString().replace(File.separatorChar, '/') return if (anchor == null) relativePath else relativePath + "#" + anchor } } fun relativePathToNode(qualifiedName: List<String>, hasMembers: Boolean): String { val parts = qualifiedName.map { identifierToFilename(it) }.filterNot { it.isEmpty() } return if (!hasMembers) { // leaf node, use file in owner's folder parts.joinToString("/") } else { parts.joinToString("/") + (if (parts.none()) "" else "/") + "index" } } fun relativePathToNode(node: DocumentationNode) = relativePathToNode(node.path.map { it.name }, node.members.any()) fun identifierToFilename(path: String): String { val escaped = path.replace('<', '-').replace('>', '-') val lowercase = escaped.replace("[A-Z]".toRegex()) { matchResult -> "-" + matchResult.value.toLowerCase() } return if (lowercase == "index") "--index--" else lowercase } fun NodeLocationAwareGenerator.relativePathToLocation(owner: DocumentationNode, node: DocumentationNode): String { return location(owner).relativePathTo(location(node), null) } fun NodeLocationAwareGenerator.relativePathToRoot(from: Location): File { val file = File(from.path).parentFile return root.relativeTo(file) } fun File.toUnixString() = toString().replace(File.separatorChar, '/')
core/src/main/kotlin/Locations/Location.kt
1622244488
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.security.config.web.server import io.mockk.every import io.mockk.mockkObject import io.mockk.verify import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.ApplicationContext import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.security.authentication.ReactiveAuthenticationManager import org.springframework.security.authentication.TestingAuthenticationToken import org.springframework.security.config.annotation.web.reactive.EnableWebFluxSecurity import org.springframework.security.config.oauth2.client.CommonOAuth2Provider import org.springframework.security.config.test.SpringTestContext import org.springframework.security.config.test.SpringTestContextExtension import org.springframework.security.core.Authentication import org.springframework.security.oauth2.client.registration.InMemoryReactiveClientRegistrationRepository import org.springframework.security.oauth2.client.registration.ReactiveClientRegistrationRepository import org.springframework.security.oauth2.client.web.server.ServerAuthorizationRequestRepository import org.springframework.security.oauth2.client.web.server.WebSessionOAuth2ServerAuthorizationRequestRepository import org.springframework.security.oauth2.core.endpoint.OAuth2AuthorizationRequest import org.springframework.security.oauth2.core.endpoint.OAuth2ParameterNames import org.springframework.security.oauth2.server.resource.web.server.ServerBearerTokenAuthenticationConverter import org.springframework.security.web.server.SecurityWebFilterChain import org.springframework.security.web.server.authentication.ServerAuthenticationConverter import org.springframework.test.web.reactive.server.WebTestClient import org.springframework.web.reactive.config.EnableWebFlux import reactor.core.publisher.Mono /** * Tests for [ServerOAuth2ClientDsl] * * @author Eleftheria Stein */ @ExtendWith(SpringTestContextExtension::class) class ServerOAuth2ClientDslTests { @JvmField val spring = SpringTestContext(this) private lateinit var client: WebTestClient @Autowired fun setup(context: ApplicationContext) { this.client = WebTestClient .bindToApplicationContext(context) .configureClient() .build() } @Test fun `OAuth2 client when custom client registration repository then bean is not required`() { this.spring.register(ClientRepoConfig::class.java).autowire() } @EnableWebFluxSecurity @EnableWebFlux open class ClientRepoConfig { @Bean open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { return http { authorizeExchange { authorize(anyExchange, authenticated) } oauth2Client { clientRegistrationRepository = InMemoryReactiveClientRegistrationRepository( CommonOAuth2Provider.GOOGLE .getBuilder("google").clientId("clientId").clientSecret("clientSecret") .build() ) } } } } @Test fun `OAuth2 client when authorization request repository configured then custom repository used`() { this.spring.register(AuthorizationRequestRepositoryConfig::class.java, ClientConfig::class.java).autowire() mockkObject(AuthorizationRequestRepositoryConfig.AUTHORIZATION_REQUEST_REPOSITORY) every { AuthorizationRequestRepositoryConfig.AUTHORIZATION_REQUEST_REPOSITORY.loadAuthorizationRequest(any()) } returns Mono.empty() this.client.get() .uri { it.path("/") .queryParam(OAuth2ParameterNames.CODE, "code") .queryParam(OAuth2ParameterNames.STATE, "state") .build() } .exchange() verify(exactly = 1) { AuthorizationRequestRepositoryConfig.AUTHORIZATION_REQUEST_REPOSITORY.loadAuthorizationRequest(any()) } } @EnableWebFluxSecurity @EnableWebFlux open class AuthorizationRequestRepositoryConfig { companion object { val AUTHORIZATION_REQUEST_REPOSITORY : ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> = WebSessionOAuth2ServerAuthorizationRequestRepository() } @Bean open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { return http { oauth2Client { authorizationRequestRepository = AUTHORIZATION_REQUEST_REPOSITORY } } } } @Test fun `OAuth2 client when authentication converter configured then custom converter used`() { this.spring.register(AuthenticationConverterConfig::class.java, ClientConfig::class.java).autowire() mockkObject(AuthenticationConverterConfig.AUTHORIZATION_REQUEST_REPOSITORY) mockkObject(AuthenticationConverterConfig.AUTHENTICATION_CONVERTER) every { AuthenticationConverterConfig.AUTHORIZATION_REQUEST_REPOSITORY.loadAuthorizationRequest(any()) } returns Mono.just(OAuth2AuthorizationRequest.authorizationCode() .authorizationUri("https://example.com/login/oauth/authorize") .clientId("clientId") .redirectUri("/authorize/oauth2/code/google") .build()) every { AuthenticationConverterConfig.AUTHENTICATION_CONVERTER.convert(any()) } returns Mono.empty() this.client.get() .uri { it.path("/authorize/oauth2/code/google") .queryParam(OAuth2ParameterNames.CODE, "code") .queryParam(OAuth2ParameterNames.STATE, "state") .build() } .exchange() verify(exactly = 1) { AuthenticationConverterConfig.AUTHENTICATION_CONVERTER.convert(any()) } } @EnableWebFluxSecurity @EnableWebFlux open class AuthenticationConverterConfig { companion object { val AUTHORIZATION_REQUEST_REPOSITORY: ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> = WebSessionOAuth2ServerAuthorizationRequestRepository() val AUTHENTICATION_CONVERTER: ServerAuthenticationConverter = ServerBearerTokenAuthenticationConverter() } @Bean open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { return http { oauth2Client { authorizationRequestRepository = AUTHORIZATION_REQUEST_REPOSITORY authenticationConverter = AUTHENTICATION_CONVERTER } } } } @Test fun `OAuth2 client when authentication manager configured then custom manager used`() { this.spring.register(AuthenticationManagerConfig::class.java, ClientConfig::class.java).autowire() mockkObject(AuthenticationManagerConfig.AUTHORIZATION_REQUEST_REPOSITORY) mockkObject(AuthenticationManagerConfig.AUTHENTICATION_CONVERTER) mockkObject(AuthenticationManagerConfig.AUTHENTICATION_MANAGER) every { AuthenticationManagerConfig.AUTHORIZATION_REQUEST_REPOSITORY.loadAuthorizationRequest(any()) } returns Mono.just(OAuth2AuthorizationRequest.authorizationCode() .authorizationUri("https://example.com/login/oauth/authorize") .clientId("clientId") .redirectUri("/authorize/oauth2/code/google") .build()) every { AuthenticationManagerConfig.AUTHENTICATION_CONVERTER.convert(any()) } returns Mono.just(TestingAuthenticationToken("a", "b", "c")) every { AuthenticationManagerConfig.AUTHENTICATION_MANAGER.authenticate(any()) } returns Mono.empty() this.client.get() .uri { it.path("/authorize/oauth2/code/google") .queryParam(OAuth2ParameterNames.CODE, "code") .queryParam(OAuth2ParameterNames.STATE, "state") .build() } .exchange() verify(exactly = 1) { AuthenticationManagerConfig.AUTHENTICATION_MANAGER.authenticate(any()) } } @EnableWebFluxSecurity @EnableWebFlux open class AuthenticationManagerConfig { companion object { val AUTHORIZATION_REQUEST_REPOSITORY: ServerAuthorizationRequestRepository<OAuth2AuthorizationRequest> = WebSessionOAuth2ServerAuthorizationRequestRepository() val AUTHENTICATION_CONVERTER: ServerAuthenticationConverter = ServerBearerTokenAuthenticationConverter() val AUTHENTICATION_MANAGER: ReactiveAuthenticationManager = NoopReactiveAuthenticationManager() } @Bean open fun springWebFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain { return http { oauth2Client { authorizationRequestRepository = AUTHORIZATION_REQUEST_REPOSITORY authenticationConverter = AUTHENTICATION_CONVERTER authenticationManager = AUTHENTICATION_MANAGER } } } } class NoopReactiveAuthenticationManager: ReactiveAuthenticationManager { override fun authenticate(authentication: Authentication?): Mono<Authentication> { return Mono.empty() } } @Configuration open class ClientConfig { @Bean open fun clientRegistrationRepository(): ReactiveClientRegistrationRepository { return InMemoryReactiveClientRegistrationRepository( CommonOAuth2Provider.GOOGLE .getBuilder("google").clientId("clientId").clientSecret("clientSecret") .build() ) } } }
config/src/test/kotlin/org/springframework/security/config/web/server/ServerOAuth2ClientDslTests.kt
4026402001
/* Copyright 2017-2020 Charles Korn. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package batect.execution.model.events import batect.docker.DockerNetwork import batect.testutils.on import com.natpryce.hamkrest.assertion.assertThat import com.natpryce.hamkrest.equalTo import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe object TaskNetworkCreatedEventSpec : Spek({ describe("a 'task network created' event") { val network = DockerNetwork("some-network") val event = TaskNetworkCreatedEvent(network) on("toString()") { it("returns a human-readable representation of itself") { assertThat(event.toString(), equalTo("TaskNetworkCreatedEvent(network ID: 'some-network')")) } } } })
app/src/unitTest/kotlin/batect/execution/model/events/TaskNetworkCreatedEventSpec.kt
3885065757
/* * Copyright 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.room.writer import androidx.room.vo.Entity /** * Sorts the entities by their foreign key dependencies. For example, when Entity A depends on * Entity B, A is ordered before B. */ class EntityDeleteComparator : Comparator<Entity> { override fun compare(lhs: Entity, rhs: Entity): Int { val ltr = lhs.shouldBeDeletedAfter(rhs) val rtl = rhs.shouldBeDeletedAfter(lhs) return when { ltr == rtl -> 0 ltr -> -1 rtl -> 1 else -> 0 // Never happens } } }
room/room-compiler/src/main/kotlin/androidx/room/writer/EntityDeleteComparator.kt
2118915348
/* * Copyright (C) 2017 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.lifecycle import androidx.lifecycle.model.AdapterClass import androidx.lifecycle.model.EventMethod import androidx.lifecycle.model.EventMethodCall import androidx.lifecycle.model.InputModel import androidx.lifecycle.model.LifecycleObserverInfo import com.google.common.collect.HashMultimap import javax.annotation.processing.ProcessingEnvironment import javax.lang.model.element.TypeElement import javax.tools.Diagnostic private fun mergeAndVerifyMethods( processingEnv: ProcessingEnvironment, type: TypeElement, classMethods: List<EventMethod>, parentMethods: List<EventMethod> ): List<EventMethod> { // need to update parent methods like that because: // 1. visibility can be expanded // 2. we want to preserve order val updatedParentMethods = parentMethods.map { parentMethod -> val overrideMethod = classMethods.find { (method) -> processingEnv.elementUtils.overrides(method, parentMethod.method, type) } if (overrideMethod != null) { if (overrideMethod.onLifecycleEvent != parentMethod.onLifecycleEvent) { processingEnv.messager.printMessage( Diagnostic.Kind.ERROR, ErrorMessages.INVALID_STATE_OVERRIDE_METHOD, overrideMethod.method ) } overrideMethod } else { parentMethod } } return updatedParentMethods + classMethods.filterNot { updatedParentMethods.contains(it) } } fun flattenObservers( processingEnv: ProcessingEnvironment, world: Map<TypeElement, LifecycleObserverInfo> ): List<LifecycleObserverInfo> { val flattened: MutableMap<LifecycleObserverInfo, LifecycleObserverInfo> = mutableMapOf() fun traverse(observer: LifecycleObserverInfo) { if (observer in flattened) { return } if (observer.parents.isEmpty()) { flattened[observer] = observer return } observer.parents.forEach(::traverse) val methods = observer.parents .map(flattened::get) .fold(emptyList<EventMethod>()) { list, parentObserver -> mergeAndVerifyMethods( processingEnv, observer.type, parentObserver!!.methods, list ) } flattened[observer] = LifecycleObserverInfo( observer.type, mergeAndVerifyMethods(processingEnv, observer.type, observer.methods, methods) ) } world.values.forEach(::traverse) return flattened.values.toList() } private fun needsSyntheticAccess(type: TypeElement, eventMethod: EventMethod): Boolean { val executable = eventMethod.method return type.getPackageQName() != eventMethod.packageName() && (executable.isPackagePrivate() || executable.isProtected()) } private fun validateMethod( processingEnv: ProcessingEnvironment, world: InputModel, type: TypeElement, eventMethod: EventMethod ): Boolean { if (!needsSyntheticAccess(type, eventMethod)) { // no synthetic calls - no problems return true } if (world.isRootType(eventMethod.type)) { // we will generate adapters for them, so we can generate all accessors return true } if (world.hasSyntheticAccessorFor(eventMethod)) { // previously generated adapter already has synthetic return true } processingEnv.messager.printMessage( Diagnostic.Kind.WARNING, ErrorMessages.failedToGenerateAdapter(type, eventMethod), type ) return false } fun transformToOutput( processingEnv: ProcessingEnvironment, world: InputModel ): List<AdapterClass> { val flatObservers = flattenObservers(processingEnv, world.observersInfo) val syntheticMethods = HashMultimap.create<TypeElement, EventMethodCall>() val adapterCalls = flatObservers // filter out everything that arrived from jars .filter { (type) -> world.isRootType(type) } // filter out if it needs SYNTHETIC access and we can't generate adapter for it .filter { (type, methods) -> methods.all { eventMethod -> validateMethod(processingEnv, world, type, eventMethod) } } .map { (type, methods) -> val calls = methods.map { eventMethod -> if (needsSyntheticAccess(type, eventMethod)) { EventMethodCall(eventMethod, eventMethod.type) } else { EventMethodCall(eventMethod) } } calls.filter { it.syntheticAccess != null }.forEach { eventMethod -> syntheticMethods.put(eventMethod.method.type, eventMethod) } type to calls }.toMap() return adapterCalls .map { (type, calls) -> val methods = syntheticMethods.get(type) ?: emptySet() val synthetic = methods.map { eventMethod -> eventMethod!!.method.method }.toSet() AdapterClass(type, calls, synthetic) } }
lifecycle/lifecycle-compiler/src/main/kotlin/androidx/lifecycle/transformation.kt
1332843954
package com.sedsoftware.yaptalker.presentation.mapper import com.sedsoftware.yaptalker.domain.entity.base.EditedPost import com.sedsoftware.yaptalker.presentation.model.base.EditedPostModel import io.reactivex.functions.Function import javax.inject.Inject class EditedPostModelMapper @Inject constructor() : Function<EditedPost, EditedPostModel> { override fun apply(item: EditedPost): EditedPostModel = EditedPostModel(text = item.text) }
app/src/main/java/com/sedsoftware/yaptalker/presentation/mapper/EditedPostModelMapper.kt
2028612404
/* * Copyright 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.wear.watchface.complications.data import android.os.Parcel import android.os.Parcelable import com.google.common.truth.FailureMetadata import com.google.common.truth.Subject import com.google.common.truth.Truth internal class ParcelableSubject(metadata: FailureMetadata?, private val subject: Parcelable?) : Subject(metadata, subject) { private class ParcelableSubjectFactory : Factory<ParcelableSubject, Parcelable> { override fun createSubject( metadata: FailureMetadata?, subject: Parcelable? ) = ParcelableSubject(metadata, subject) } fun hasSameSerializationAs(parcelable: Parcelable) { check("hasSameSerializationAs()").that(subject).isNotNull() check("hasSameSerializationAs()").that(parcelable).isNotNull() check("hasSameSerializationAs()").that(serializeParcelable(subject!!)) .isEqualTo(serializeParcelable(parcelable)) } fun hasDifferentSerializationAs(parcelable: Parcelable) { check("hasDifferentSerializationAs()").that(subject).isNotNull() check("hasDifferentSerializationAs()").that(parcelable).isNotNull() check("hasDifferentSerializationAs()").that(serializeParcelable(subject!!)) .isNotEqualTo(serializeParcelable(parcelable)) } private fun serializeParcelable(parcelable: Parcelable) = Parcel.obtain().apply { parcelable.writeToParcel(this, 0) }.marshall() internal companion object { @JvmStatic fun assertThat(parcelable: Parcelable): ParcelableSubject { return Truth.assertAbout(FACTORY).that(parcelable) } @JvmField val FACTORY: Factory<ParcelableSubject, Parcelable> = ParcelableSubjectFactory() } }
wear/watchface/watchface-complications-data/src/test/java/androidx/wear/watchface/complications/data/ParcelableSubject.kt
2412759034
/* * Copyright LWJGL. All rights reserved. * License terms: https://www.lwjgl.org/license */ package org.lwjgl.ovr.templates import org.lwjgl.generator.* import org.lwjgl.ovr.OVR_PACKAGE val OVR_Keys = "OVRKeys".nativeClass(packageName = OVR_PACKAGE, prefix = "OVR") { documentation = "Keys for libOVR's CAPI calls." StringConstant( "Keys for property function calls.", "KEY_USER".."User", // string "KEY_NAME".."Name", // string "KEY_GENDER".."Gender", // string "Male", "Female", or "Unknown" "KEY_PLAYER_HEIGHT".."PlayerHeight", // float meters "KEY_EYE_HEIGHT".."EyeHeight", // float meters "KEY_NECK_TO_EYE_DISTANCE".."NeckEyeDistance", // float[2] meters "KEY_EYE_TO_NOSE_DISTANCE".."EyeToNoseDist" // float[2] meters ) StringConstant( "", "DEFAULT_GENDER".."Unknown" // string ) FloatConstant( "Default measurements empirically determined at Oculus.", "DEFAULT_PLAYER_HEIGHT"..1.778f, "DEFAULT_EYE_HEIGHT"..1.675f, "DEFAULT_NECK_TO_EYE_HORIZONTAL"..0.0805f, "DEFAULT_NECK_TO_EYE_VERTICAL"..0.075f ) StringConstant( "int, allowed values are defined in {@code enum ovrPerfHudMode}", "PERF_HUDE_MODE".."PerfHudMode" ) StringConstant("int, allowed values are defined in {@code enum ovrLayerHudMode}.", "LAYER_HUD_MODE".."LayerHudMode") StringConstant("int, the layer to show.", "LAYER_HUD_CURRENT_LAYER".."LayerHudCurrentLayer") StringConstant("bool, hide other layers when the hud is enabled.", "LAYER_HUD_SHOW_ALL_LAYERS".."LayerHudShowAll") StringConstant( "", "DEBUG_HUD_STEREO_MODE".."DebugHudStereoMode", // int, allowed values are defined in enum ovrDebugHudStereoMode "DEBUG_HUD_STEREO_GUIDE_INFO_ENABLE".."DebugHudStereoGuideInfoEnable", // bool "DEBUG_HUD_STEREO_GUIDE_SIZE".."DebugHudStereoGuideSize2f", // float[2] "DEBUG_HUD_STEREO_GUIDE_POSITION".."DebugHudStereoGuidePosition3f", // float[3] "DEBUG_HUD_STEREO_GUIDE_YAWPITCHROLL".."DebugHudStereoGuideYawPitchRoll3f", // float[3] "DEBUG_HUD_STEREO_GUIDE_COLOR".."DebugHudStereoGuideColor4f" // float[4] ) }
modules/templates/src/main/kotlin/org/lwjgl/ovr/templates/OVR_Keys.kt
3127417064
package org.elm.lang.core.psi import com.intellij.openapi.application.runWriteAction import com.intellij.openapi.vfs.VfsUtil import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiDocumentManager import org.elm.fileTreeFromText import org.elm.lang.ElmTestBase import org.elm.lang.core.psi.ElmGlobalModificationTrackerTest.TestAction.INC import org.intellij.lang.annotations.Language internal class ElmGlobalModificationTrackerTest : ElmTestBase() { fun `test comment`() = doTest(TestAction.NOT_INC, """ -- {-caret-} """) fun `test function`() = doTest(INC, """ {-caret-} """, "main = ()") fun `test unannotated function name`() = doTest(INC, """ main{-caret-} = () """) fun `test unannotated function params`() = doTest(INC, """ main a {-caret-} = () """) fun `test unannotated function body`() = doTest(INC, """ main = {-caret-} """, "()") fun `test annotation`() = doTest(INC, """ main : () -> {-caret-} main a = a """, "()") fun `test annotated function name`() = doTest(INC, """ main : () main{-caret-} = () """) fun `test annotated function params`() = doTest(TestAction.NOT_INC, """ main : () -> () main a {-caret-} = () """) fun `test annotated function body`() = doTest(TestAction.NOT_INC, """ main : () main = {-caret-} """, "()") fun `test nested function name in annotated parent`() = doTest(TestAction.NOT_INC, """ main : () main = let foo{-caret-} = () in foo """, "()") fun `test nested function body in annotated parent`() = doTest(TestAction.NOT_INC, """ main : () main = let foo = {-caret-} in foo """, "()") fun `test type`() = doTest(INC, """ type T = T {-caret-} """) fun `test type alias`() = doTest(INC, """ type alias R = { {-caret-} } """) fun `test replace function with comment`() = doTest(INC, """ main : () {-caret-}main = () """, "-- ") fun `test vfs file change`() = doVfsTest(INC, """ --@ Main.elm import Foo exposing (..) --^ --@ Foo.elm module Foo exposing (..) -- foo = () """) { file -> VfsUtil.saveText(file, VfsUtil.loadText(file).replace("--", "")) } fun `test vfs file removal`() = doVfsTest(INC, """ --@ Main.elm import Foo exposing (..) --^ --@ Foo.elm module Foo exposing (..) foo = () """) { file -> file.delete(null) } fun `test vfs file rename`() = doVfsTest(INC, """ --@ Main.elm import Foo exposing (..) --^ --@ Foo.elm module Foo exposing (..) foo = () """) { file -> file.rename(null, "Bar.elm") } fun `test vfs directory removal`() = doVfsTest(INC, """ --@ Main.elm import Foo.Bar exposing (..) --^ --@ Foo/Bar.elm module Bar exposing (..) foo = () """, "Foo") { file -> file.delete(null) } private enum class TestAction(val function: (Long, Long) -> Boolean, val comment: String) { INC({ a, b -> a > b }, "Modification counter expected to be incremented, but it remained the same"), NOT_INC({ a, b -> a == b }, "Modification counter expected to remain the same, but it was incremented") } private fun checkModCount(op: TestAction, action: () -> Unit) { PsiDocumentManager.getInstance(project).commitAllDocuments() val modTracker = project.modificationTracker val oldCount = modTracker.modificationCount action() PsiDocumentManager.getInstance(project).commitAllDocuments() check(op.function(modTracker.modificationCount, oldCount)) { op.comment } } private fun checkModCount(op: TestAction, @Language("Elm") code: String, text: String) { InlineFile(code).withCaret() checkModCount(op) { myFixture.type(text) } } private fun doTest(op: TestAction, @Language("Elm") code: String, text: String = "a") { checkModCount(op, code, text) } private fun doVfsTest(op: TestAction, @Language("Elm") code: String, filename: String = "Foo.elm", action: (VirtualFile) -> Unit) { val p = fileTreeFromText(code).createAndOpenFileWithCaretMarker() val file = p.psiFile(filename).virtualFile!! checkModCount(op) { runWriteAction { action(file) } } } }
src/test/kotlin/org/elm/lang/core/psi/ElmGlobalModificationTrackerTest.kt
2494754387
package com.castlefrog.agl.domains.backgammon import com.castlefrog.agl.State /** * Represents a backgammon state as an array of byte locations. * @param locations each location is 0 if no pieces are at that location and positive for * the number of pieces player 1 has there and negative for the number of * pieces player 2 has there. * @param dice two values in range 0-5 that represent die faces 1 to 6 each; order does not matter * @param agentTurn current players turn */ class BackgammonState( val locations: ByteArray = byteArrayOf( 0, 2, 0, 0, 0, 0, -5, 0, -3, 0, 0, 0, 5, -5, 0, 0, 0, 3, 0, 5, 0, 0, 0, 0, -2, 0 ), val dice: ByteArray = ByteArray(N_DICE), var agentTurn: Int = 0 ) : State<BackgammonState> { override fun copy(): BackgammonState { val locations = ByteArray(N_LOCATIONS) System.arraycopy(this.locations, 0, locations, 0, N_LOCATIONS) val dice = ByteArray(N_DICE) System.arraycopy(this.dice, 0, dice, 0, N_DICE) return BackgammonState(locations, dice, agentTurn) } override fun equals(other: Any?): Boolean { if (this === other) { return true } if (other !is BackgammonState) { return false } return locations.contentEquals(other.locations) && ((dice[0] == other.dice[0] && dice[1] == other.dice[1]) || (dice[0] == other.dice[1] && dice[1] == other.dice[0])) && agentTurn == other.agentTurn } override fun hashCode(): Int { val dice = if (dice[0] < dice[1]) { intArrayOf(dice[1].toInt(), dice[0].toInt()) } else { intArrayOf(dice[0].toInt(), dice[1].toInt()) } return (agentTurn * 11 + locations.contentHashCode()) * 17 + dice.contentHashCode() } override fun toString(): String { val output = StringBuilder(" ").append(agentTurn).append(" - ") val dice = if (dice[0] < dice[1]) { intArrayOf(dice[1].toInt(), dice[0].toInt()) } else { intArrayOf(dice[0].toInt(), dice[1].toInt()) } output.append("[").append(dice[0] + 1).append("][").append(dice[1] + 1).append("]\n") for (i in 12 downTo 7) { if (locations[i] >= 0) { output.append(" ") } output.append(locations[i].toInt()) } output.append("|") for (i in 6 downTo 1) { if (locations[i] >= 0) { output.append(" ") } output.append(locations[i].toInt()) } output.append(" [").append(locations[0].toInt()).append("]\n") output.append("------------|------------\n") for (i in 13..18) { if (locations[i] >= 0) { output.append(" ") } output.append(locations[i].toInt()) } output.append("|") var i = 19 while (i < 25) { if (locations[i] >= 0) { output.append(" ") } output.append(locations[i].toInt()) i += 1 } output.append(" [").append(locations[25].toInt()).append("]") return output.toString() } companion object { const val N_PLAYERS = 2 const val N_DICE = 2 const val N_DIE_FACES = 6 const val N_LOCATIONS = 26 } }
src/main/kotlin/com/castlefrog/agl/domains/backgammon/BackgammonState.kt
444827687
/* * Jooby https://jooby.io * Apache License Version 2.0 https://jooby.io/LICENSE.txt * Copyright 2014 Edgar Espina */ package io.jooby import io.jooby.Router.DELETE import io.jooby.Router.GET import io.jooby.Router.HEAD import io.jooby.Router.OPTIONS import io.jooby.Router.PATCH import io.jooby.Router.POST import io.jooby.Router.PUT import io.jooby.Router.TRACE import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext import kotlinx.coroutines.CoroutineExceptionHandler import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart import kotlinx.coroutines.asCoroutineDispatcher import kotlinx.coroutines.launch internal class RouterCoroutineScope(override val coroutineContext: CoroutineContext) : CoroutineScope class CoroutineRouter(val coroutineStart: CoroutineStart, val router: Router) { val coroutineScope: CoroutineScope by lazy { RouterCoroutineScope(router.worker.asCoroutineDispatcher()) } private var extraCoroutineContextProvider: HandlerContext.() -> CoroutineContext = { EmptyCoroutineContext } fun launchContext(provider: HandlerContext.() -> CoroutineContext) { extraCoroutineContextProvider = provider } @RouterDsl fun get(pattern: String, handler: suspend HandlerContext.() -> Any) = route(GET, pattern, handler) @RouterDsl fun post(pattern: String, handler: suspend HandlerContext.() -> Any) = route(POST, pattern, handler) @RouterDsl fun put(pattern: String, handler: suspend HandlerContext.() -> Any) = route(PUT, pattern, handler) @RouterDsl fun delete(pattern: String, handler: suspend HandlerContext.() -> Any) = route(DELETE, pattern, handler) @RouterDsl fun patch(pattern: String, handler: suspend HandlerContext.() -> Any) = route(PATCH, pattern, handler) @RouterDsl fun head(pattern: String, handler: suspend HandlerContext.() -> Any) = route(HEAD, pattern, handler) @RouterDsl fun trace(pattern: String, handler: suspend HandlerContext.() -> Any) = route(TRACE, pattern, handler) @RouterDsl fun options(pattern: String, handler: suspend HandlerContext.() -> Any) = route(OPTIONS, pattern, handler) fun route(method: String, pattern: String, handler: suspend HandlerContext.() -> Any): Route = router .route(method, pattern) { ctx -> val handlerContext = HandlerContext(ctx) launch(handlerContext) { val result = handler(handlerContext) if (result != ctx) { ctx.render(result) } } } .setHandle(handler) .attribute("coroutine", true) internal fun launch(handlerContext: HandlerContext, block: suspend CoroutineScope.() -> Unit) { val exceptionHandler = CoroutineExceptionHandler { _, x -> handlerContext.ctx.sendError(x) } val coroutineContext = exceptionHandler + handlerContext.extraCoroutineContextProvider() coroutineScope.launch(coroutineContext, coroutineStart, block) } }
jooby/src/main/kotlin/io/jooby/CoroutineRouter.kt
825354062
/* * Copyright 2017 Peter Kenji Yamanaka * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.pyamsoft.powermanager.manage import com.pyamsoft.powermanager.manage.ManageTargets.AIRPLANE import com.pyamsoft.powermanager.manage.ManageTargets.BLUETOOTH import com.pyamsoft.powermanager.manage.ManageTargets.DATA import com.pyamsoft.powermanager.manage.ManageTargets.DATA_SAVER import com.pyamsoft.powermanager.manage.ManageTargets.DOZE import com.pyamsoft.powermanager.manage.ManageTargets.SYNC import com.pyamsoft.powermanager.manage.ManageTargets.WIFI import com.pyamsoft.powermanager.manage.bus.ManageBus import dagger.Module import dagger.Provides import io.reactivex.Scheduler import javax.inject.Named @Module class ManageModule { @Provides @Named("manage_wifi") internal fun provideWifi( @Named("manage_wifi_interactor") interactor: ManageInteractor, @Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler, bus: ManageBus): ManagePresenter { return object : ManagePresenter(interactor, bus, obsScheduler, subScheduler) { override val target: ManageTargets get() = WIFI } } @Provides @Named("manage_data") internal fun provideData( @Named("manage_data_interactor") interactor: ManageInteractor, @Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler, bus: ManageBus): ManagePresenter { return object : ManagePresenter(interactor, bus, obsScheduler, subScheduler) { override val target: ManageTargets get() = DATA } } @Provides @Named("manage_bluetooth") internal fun provideBluetooth( @Named("manage_bluetooth_interactor") interactor: ManageInteractor, @Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler, bus: ManageBus): ManagePresenter { return object : ManagePresenter(interactor, bus, obsScheduler, subScheduler) { override val target: ManageTargets get() = BLUETOOTH } } @Provides @Named("manage_sync") internal fun provideSync( @Named("manage_sync_interactor") interactor: ManageInteractor, @Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler, bus: ManageBus): ManagePresenter { return object : ManagePresenter(interactor, bus, obsScheduler, subScheduler) { override val target: ManageTargets get() = SYNC } } @Provides @Named("manage_airplane") internal fun provideAirplane( @Named("manage_airplane_interactor") interactor: ManageInteractor, @Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler, bus: ManageBus): ManagePresenter { return object : ManagePresenter(interactor, bus, obsScheduler, subScheduler) { override val target: ManageTargets get() = AIRPLANE } } @Provides @Named("manage_doze") internal fun provideDoze( @Named("manage_doze_interactor") interactor: ManageInteractor, @Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler, bus: ManageBus): ManagePresenter { return object : ManagePresenter(interactor, bus, obsScheduler, subScheduler) { override val target: ManageTargets get() = DOZE } } @Provides @Named("manage_data_saver") internal fun provideDataSaver( @Named("manage_data_saver_interactor") interactor: ManageInteractor, @Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler, bus: ManageBus): ManagePresenter { return object : ManagePresenter(interactor, bus, obsScheduler, subScheduler) { override val target: ManageTargets get() = DATA_SAVER } } @Provides @Named("exception_wifi") internal fun provideWifiException( @Named("exception_wifi_interactor") interactor: ExceptionInteractor, @Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler, bus: ManageBus): ExceptionPresenter { return object : ExceptionPresenter(interactor, bus, obsScheduler, subScheduler) { override val target: ManageTargets get() = WIFI } } @Provides @Named("exception_data") internal fun provideDataException( @Named("exception_data_interactor") interactor: ExceptionInteractor, @Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler, bus: ManageBus): ExceptionPresenter { return object : ExceptionPresenter(interactor, bus, obsScheduler, subScheduler) { override val target: ManageTargets get() = DATA } } @Provides @Named("exception_bluetooth") internal fun provideBluetoothException( @Named("exception_bluetooth_interactor") interactor: ExceptionInteractor, @Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler, bus: ManageBus): ExceptionPresenter { return object : ExceptionPresenter(interactor, bus, obsScheduler, subScheduler) { override val target: ManageTargets get() = BLUETOOTH } } @Provides @Named("exception_sync") internal fun provideSyncException( @Named("exception_sync_interactor") interactor: ExceptionInteractor, @Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler, bus: ManageBus): ExceptionPresenter { return object : ExceptionPresenter(interactor, bus, obsScheduler, subScheduler) { override val target: ManageTargets get() = SYNC } } @Provides @Named("exception_airplane") internal fun provideAirplaneException( @Named("exception_airplane_interactor") interactor: ExceptionInteractor, @Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler, bus: ManageBus): ExceptionPresenter { return object : ExceptionPresenter(interactor, bus, obsScheduler, subScheduler) { override val target: ManageTargets get() = AIRPLANE } } @Provides @Named("exception_doze") internal fun provideDozeException( @Named("exception_doze_interactor") interactor: ExceptionInteractor, @Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler, bus: ManageBus): ExceptionPresenter { return object : ExceptionPresenter(interactor, bus, obsScheduler, subScheduler) { override val target: ManageTargets get() = DOZE } } @Provides @Named("exception_data_saver") internal fun provideDataSaverException( @Named("exception_data_saver_interactor") interactor: ExceptionInteractor, @Named("obs") obsScheduler: Scheduler, @Named("sub") subScheduler: Scheduler, bus: ManageBus): ExceptionPresenter { return object : ExceptionPresenter(interactor, bus, obsScheduler, subScheduler) { override val target: ManageTargets get() = DATA_SAVER } } }
powermanager-manage/src/main/java/com/pyamsoft/powermanager/manage/ManageModule.kt
677469697
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.android.libraries.car.calendarsync.feature import android.Manifest.permission import android.content.Context import android.provider.CalendarContract import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import androidx.test.rule.GrantPermissionRule import com.google.android.connecteddevice.calendarsync.proto.Calendar import com.google.android.connecteddevice.calendarsync.proto.Calendars import com.google.android.connecteddevice.calendarsync.proto.TimeZone import com.google.android.libraries.car.calendarsync.feature.CalendarSyncManager.Companion.KEY_CALENDAR_IDS import com.google.android.libraries.car.calendarsync.feature.CalendarSyncManager.Companion.KEY_ENABLED import com.google.android.libraries.car.calendarsync.feature.CalendarSyncManager.Companion.key import com.google.android.libraries.car.calendarsync.feature.repository.CalendarRepository import com.google.android.libraries.car.trustagent.Car import com.google.common.collect.ImmutableSet import com.google.common.time.ZoneIds import com.google.common.truth.Truth.assertThat import com.nhaarman.mockitokotlin2.any import com.nhaarman.mockitokotlin2.anyOrNull import com.nhaarman.mockitokotlin2.argumentCaptor import com.nhaarman.mockitokotlin2.doReturn import com.nhaarman.mockitokotlin2.eq import com.nhaarman.mockitokotlin2.mock import com.nhaarman.mockitokotlin2.whenever import java.time.Clock import java.time.Instant import java.time.ZonedDateTime import java.time.temporal.ChronoUnit import java.util.UUID import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.Mockito.never import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.robolectric.Shadows.shadowOf import org.robolectric.shadows.ShadowContentResolver import org.robolectric.shadows.ShadowLooper @RunWith(AndroidJUnit4::class) class CalendarSyncManagerTest { private val zoneId = ZoneIds.googleZoneId() private val zonedDateTime = ZonedDateTime.of(2020, 3, 10, 11, 12, 13, 14, zoneId) private val fixedTimeClock = Clock.fixed(zonedDateTime.toInstant(), zoneId) private val context = ApplicationProvider.getApplicationContext<Context>() private val carId = UUID.randomUUID() private val mockCar: Car = mock { on { deviceId } doReturn carId } private val calendarId1 = "111" private val calendarId2 = "222" // Create a dummy value that contains a unique field we can use to recognize its bytes. private val calendars = Calendars.newBuilder() .setDeviceTimeZone(TimeZone.newBuilder().setName("DummyTimeZone")).build() private lateinit var calendarSyncManager: CalendarSyncManager private lateinit var mockCalendarRepository: CalendarRepository private val sharedPreferences by lazy { context.getSharedPreferences("CalendarSyncManagerTest", Context.MODE_PRIVATE) } @get:Rule val grantPermissionRule: GrantPermissionRule = GrantPermissionRule.grant( permission.READ_CALENDAR ) @Before fun setUp() { mockCalendarRepository = mock() // Make sure something is returned whenever we do not care about the returned content. whenever( mockCalendarRepository.getCalendars(any(), any(), any()) ) doReturn calendars whenever( mockCalendarRepository.getCalendars(any(), any()) ) doReturn calendars calendarSyncManager = CalendarSyncManager( context, mockCalendarRepository, fixedTimeClock, sharedPreferences ) } @Test fun onCarConnected_enabled_withIds_queriesCalendarsFromStartOfDay() { calendarSyncManager.enableCar(carId) calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1, calendarId2), carId) calendarSyncManager.notifyCarConnected(mockCar) val expectedCalendarIds = setOf(Integer.parseInt(calendarId1), Integer.parseInt(calendarId2)) val expectedStartInstant = zonedDateTime.truncatedTo(ChronoUnit.DAYS).toInstant() argumentCaptor<Instant>().apply { verify(mockCalendarRepository).getCalendars(eq(expectedCalendarIds), capture(), capture()) assertThat(firstValue).isEqualTo(expectedStartInstant) assertThat(firstValue).isLessThan(secondValue) } } @Test fun onCarConnected_enabled_withIds_doesSync() { calendarSyncManager.enableCar(carId) calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId) calendarSyncManager.notifyCarConnected(mockCar) verify(mockCar).sendMessage(calendars.toByteArray(), CalendarSyncManager.FEATURE_ID) } @Test fun onCarConnected_enabled_emptyIds_doesNotSync() { calendarSyncManager.enableCar(carId) calendarSyncManager.notifyCarConnected(mockCar) verify(mockCar, never()).sendMessage(anyOrNull(), anyOrNull()) } @Test fun onCarConnected_disabled_doesNotSync() { calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId) calendarSyncManager.notifyCarConnected(mockCar) verify(mockCar, never()).sendMessage(anyOrNull(), anyOrNull()) } @Test fun onCarConnected_syncsOnNextDay() { calendarSyncManager.enableCar(carId) calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId) calendarSyncManager.notifyCarConnected(mockCar) var foundScheduledTaskTomorrow = false val loopers = ShadowLooper.getAllLoopers() for (looper in loopers) { val shadowLooper: ShadowLooper = shadowOf(looper) val tomorrowDateTime = zonedDateTime.plusDays(1).truncatedTo(ChronoUnit.DAYS) if (zonedDateTime.plus(shadowLooper.nextScheduledTaskTime) >= tomorrowDateTime) { foundScheduledTaskTomorrow = true // Run tomorrows task so we can assert it caused a sync. shadowLooper.runOneTask() } } assertThat(foundScheduledTaskTomorrow).isTrue() verify(mockCar, times(2)) .sendMessage(calendars.toByteArray(), CalendarSyncManager.FEATURE_ID) } fun onCarDisassociated_disablesCalendarSync() { calendarSyncManager.enableCar(carId) calendarSyncManager.onCarDisassociated(carId) assertThat(calendarSyncManager.isCarEnabled(carId)).isFalse() } @Test fun onCarDisassociated_removesCarPreferences() { calendarSyncManager.enableCar(carId) calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId) // Another car calendarSyncManager.enableCar(UUID.randomUUID()) calendarSyncManager.onCarDisassociated(carId) assertThat(sharedPreferences.contains(key(KEY_CALENDAR_IDS, carId))).isFalse() assertThat(sharedPreferences.contains(key(KEY_ENABLED, carId))).isFalse() assertThat(sharedPreferences.all).isNotEmpty() } @Test fun onAllCarsDisassociated_disablesCalendarSync() { calendarSyncManager.enableCar(carId) calendarSyncManager.onAllCarsDisassociated() assertThat(calendarSyncManager.isCarEnabled(carId)).isFalse() } @Test fun onAllCarsDisassociated_clearsAllPreferences() { sharedPreferences.edit().putString("key", "value").apply() calendarSyncManager.onAllCarsDisassociated() assertThat(sharedPreferences.all).isEmpty() } @Test fun enableCar_storesValue() { calendarSyncManager.enableCar(carId) assertThat( sharedPreferences.getBoolean( key(CalendarSyncManager.KEY_ENABLED, carId), false ) ).isTrue() } @Test fun enableCar_withoutStoredCalendarIds_doesNotSync() { calendarSyncManager.notifyCarConnected(mockCar) calendarSyncManager.enableCar(carId) verify(mockCar, never()).sendMessage(any(), eq(CalendarSyncManager.FEATURE_ID)) } @Test fun enableCar_withStoredCalendarIds_doesSync() { calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId) calendarSyncManager.notifyCarConnected(mockCar) calendarSyncManager.enableCar(carId) verify(mockCar).sendMessage(calendars.toByteArray(), CalendarSyncManager.FEATURE_ID) } @Test fun enableCar_disconnected_withStoredCalendarIds_doesNotSync() { calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId) calendarSyncManager.enableCar(carId) verify(mockCar, never()).sendMessage(any(), eq(CalendarSyncManager.FEATURE_ID)) } @Test fun disableCar_storesValue() { calendarSyncManager.disableCar(carId) assertThat( sharedPreferences.getBoolean( key(CalendarSyncManager.KEY_ENABLED, carId), true ) ).isFalse() } @Test fun disableCar_withStoredCalendarIds_doesSync() { calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId) calendarSyncManager.notifyCarConnected(mockCar) calendarSyncManager.disableCar(carId) verify(mockCar).sendMessage(any(), eq(CalendarSyncManager.FEATURE_ID)) } @Test fun disableCar_withoutStoredCalendarIds_doesNotSync() { calendarSyncManager.notifyCarConnected(mockCar) calendarSyncManager.disableCar(carId) verify(mockCar, never()).sendMessage(any(), eq(CalendarSyncManager.FEATURE_ID)) } @Test fun disableCar_disconnected_withStoredCalendarIds_doesNotSync() { calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId) calendarSyncManager.disableCar(carId) verify(mockCar, never()).sendMessage(any(), eq(CalendarSyncManager.FEATURE_ID)) } @Test fun isCarEnabled_noStoredPreferences_returnFalse() { assertThat(calendarSyncManager.isCarEnabled(carId)).isFalse() } @Test fun getCalendarIdsToSync_calendarsInRepository_returnsCalendars() { val calendarIds = setOf("first", "second", "third") whenever( mockCalendarRepository.getCalendars(any(), any()) ) doReturn generateEmptyCalendars(calendarIds) assertThat(calendarSyncManager.getCalendarIdsToSync(carId)).isEqualTo(calendarIds) } @Test fun getCalendarIdsToSync_noCalendarsInRepository_returnEmptyList() { assertThat(calendarSyncManager.getCalendarIdsToSync(carId)).isEmpty() } @Test fun getCalendarIdsToSync() { calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1, calendarId2), carId) assertThat(calendarSyncManager.getCalendarIdsToSync(carId)) .containsExactly(calendarId1, calendarId2) assertThat(calendarSyncManager.getCalendarIdsToSync(UUID.randomUUID())).isEmpty() } @Test fun setCalendarIdsToSync_storesValue() { calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1, calendarId2), carId) val storedCalendars = sharedPreferences.getStringSet( key(CalendarSyncManager.KEY_CALENDAR_IDS, carId), ImmutableSet.of() )!! assertThat(storedCalendars).containsExactly(calendarId1, calendarId2) } @Test fun setCalendarIdsToSync_doesSyncNewCalendar() { calendarSyncManager.notifyCarConnected(mockCar) configureCarPreferences( carId, enable = true, calendarIds = setOf(calendarId1, calendarId2) ) val newCalendarId = "333" calendarSyncManager.setCalendarIdsToSync( setOf(calendarId1, calendarId2, newCalendarId), carId ) verify(mockCalendarRepository) .getCalendars(eq(setOf(Integer.parseInt(newCalendarId))), any(), any()) verify(mockCar).sendMessage(calendars.toByteArray(), CalendarSyncManager.FEATURE_ID) } @Test fun setCalendarIdsToSync_doesSyncRemovedCalendar() { calendarSyncManager.notifyCarConnected(mockCar) configureCarPreferences( carId, enable = true, calendarIds = setOf(calendarId1, calendarId2) ) calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId) val calendarsToRemove = generateEmptyCalendars(setOf(calendarId2)) verify(mockCar) .sendMessage(calendarsToRemove.toByteArray(), CalendarSyncManager.FEATURE_ID) verify(mockCalendarRepository, never()).getCalendars(any(), any(), any()) } @Test fun setCalendarIdsToSync_onDisabledCar_doesNotSync() { calendarSyncManager.notifyCarConnected(mockCar) configureCarPreferences(carId, enable = false, calendarIds = setOf()) calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1), carId) verify(mockCar, never()).sendMessage(anyOrNull(), anyOrNull()) } @Test fun carsConnected_registersCalendarObserver() { calendarSyncManager.enableCar(carId) // Register another car which should not start another observer. val carId2 = UUID.randomUUID() val mockCar2: Car = mock { on { deviceId } doReturn carId2 } calendarSyncManager.enableCar(carId2) val contentResolver: ShadowContentResolver = shadowOf(context.contentResolver) assertThat(contentResolver.getContentObservers(CalendarContract.Instances.CONTENT_URI)) .isEmpty() // Connect the cars. calendarSyncManager.notifyCarConnected(mockCar) calendarSyncManager.notifyCarConnected(mockCar2) assertThat(contentResolver.getContentObservers(CalendarContract.Instances.CONTENT_URI)) .hasSize(1) } @Test fun carsDisconnected_unregistersCalendarObserver() { calendarSyncManager.enableCar(carId) // Register another car which should not start another observer. val carId2 = UUID.randomUUID() val mockCar2: Car = mock { on { deviceId } doReturn carId2 } calendarSyncManager.enableCar(carId2) // Connect the cars. calendarSyncManager.notifyCarConnected(mockCar) calendarSyncManager.notifyCarConnected(mockCar2) val shadowContentResolver = shadowOf(context.contentResolver) assertThat(shadowContentResolver.getContentObservers(CalendarContract.Instances.CONTENT_URI)) .isNotEmpty() // Disconnect the first car to remove it and trigger onCarDisconnected. argumentCaptor<Car.Callback>().apply { verify(mockCar).setCallback(capture(), eq(CalendarSyncManager.FEATURE_ID)) firstValue.onDisconnected() assertThat(shadowContentResolver.getContentObservers(CalendarContract.Instances.CONTENT_URI)) .isNotEmpty() } // Only removing the last car should stop observing the calendar event instances. argumentCaptor<Car.Callback>().apply { verify(mockCar2).setCallback(capture(), eq(CalendarSyncManager.FEATURE_ID)) firstValue.onDisconnected() assertThat(shadowContentResolver.getContentObservers(CalendarContract.Instances.CONTENT_URI)) .isEmpty() } } @Test fun eventsChanged_syncToCar() { calendarSyncManager.enableCar(carId) calendarSyncManager.setCalendarIdsToSync(setOf(calendarId1, calendarId2), carId) calendarSyncManager.notifyCarConnected(mockCar) idleAllLoopers() val shadowContentResolver = shadowOf(context.contentResolver) val observer = shadowContentResolver.getContentObservers(CalendarContract.Instances.CONTENT_URI).first() observer.dispatchChange(false, null) idleAllLoopers() // The first sync will occur on connection, the second due to the changed events. verify(mockCar, times(2)) .sendMessage(calendars.toByteArray(), CalendarSyncManager.FEATURE_ID) } /** Creates a [Calendars] proto with the given calendar ids. */ private fun generateEmptyCalendars(calendarIds: Set<String>): Calendars { val calendarList = calendarIds.map { Calendar.newBuilder().setUuid(it).build() } return Calendars.newBuilder().addAllCalendar(calendarList).build() } /** Configure preferences for the given carId. */ private fun configureCarPreferences( carId: UUID, enable: Boolean, calendarIds: Set<String> ) { sharedPreferences.edit() .clear() .putBoolean(key(KEY_ENABLED, carId), enable) .putStringSet(key(KEY_CALENDAR_IDS, carId), calendarIds) .apply() } private fun idleAllLoopers() = ShadowLooper.getAllLoopers().forEach { shadowOf(it).idle() } }
calendarsync/tests/unit/src/com/google/android/libraries/car/calendarsync/feature/CalendarSyncManagerTest.kt
2683022159
/* * Copyright (c) 2017. tangzx([email protected]) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tang.intellij.test.refactoring import com.tang.intellij.test.LuaTestBase class RenameTest : LuaTestBase() { fun `test rename file`() = checkByDirectory(""" --- A.lua print("a") --- B.lua require('A') """, """ --- C.lua print("a") --- B.lua require('C') """) { val file = myFixture.configureFromTempProjectFile("A.lua") myFixture.renameElement(file, "C.lua") } }
src/test/kotlin/com/tang/intellij/test/refactoring/RenameTest.kt
2258609734
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.schedule.email.project import com.mycollab.schedule.email.SendingRelayEmailNotificationAction interface ProjectRiskRelayEmailNotificationAction : SendingRelayEmailNotificationAction
mycollab-services/src/main/java/com/mycollab/schedule/email/project/ProjectRiskRelayEmailNotificationAction.kt
3389636984
package com.raxdenstudios.square.sample import android.app.Application import com.google.firebase.FirebaseApp import com.raxdenstudios.square.InterceptorManager import com.raxdenstudios.square.interceptor.commons.InterceptorCommonsFactory /** * Created by Ángel Gómez on 12/06/2017. */ class AppApplication : Application() { override fun onCreate() { super.onCreate() val builder = InterceptorManager.Builder() .addInterceptorFactory(InterceptorCommonsFactory()) .build() builder.init(this) FirebaseApp.initializeApp(this) } }
sample/src/main/java/com/raxdenstudios/square/sample/AppApplication.kt
2577970469
/* * Copyright 2018 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JvmName("Main") package helloworld import java.nio.file.Paths fun main(args: Array<String>) { if (!Paths.get("tests", "smoke", "data", "datafile.txt").toFile().exists()) { System.err.println("could not read datafile") System.exit(1) } println("bang bang") System.out.println("boom") }
src/test/data/jvm/basic/helloworld/Main.kt
1876627344
package com.example.demo.api.realestate.handler.properties.links.linked_by import com.example.demo.api.realestate.handler.common.response.PropertyDto data class PropertyLinkedByResponse( val linkedBy: List<PropertyDto>, val property: PropertyDto )
src/main/kotlin/com/example/demo/api/realestate/handler/properties/links/linked_by/response.kt
2586139913
package ca.fuwafuwa.kaku.Ocr import android.graphics.Bitmap import ca.fuwafuwa.kaku.TextDirection data class OcrParams(val bitmap: Bitmap, val originalBitmap: Bitmap, val box: BoxParams, val textDirection: TextDirection, val instantMode: Boolean) { override fun toString() : String { return "Box: $box InstantOCR: $instantMode TextDirection: $textDirection" } }
app/src/main/java/ca/fuwafuwa/kaku/Ocr/OcrParams.kt
4175161847
package io.bluerain.tweets.fragment import android.os.Bundle import android.support.v7.widget.LinearLayoutManager import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.PopupMenu import android.widget.TextView import io.bluerain.tweets.R import io.bluerain.tweets.adapter.BaseRecyclerViewAdapter import io.bluerain.tweets.adapter.BaseRecyclerViewHolder import io.bluerain.tweets.base.BaseFragment import io.bluerain.tweets.data.models.ArticleModel import io.bluerain.tweets.data.models.isNormal import io.bluerain.tweets.data.models.isTop import io.bluerain.tweets.data.models.statusToString import io.bluerain.tweets.fragment.ArticlesFragment.Companion.LIST_DATA import io.bluerain.tweets.presenter.BlogPresenter import io.bluerain.tweets.ui.ArticleInfoActivity import io.bluerain.tweets.ui.ShowCommentsActivity import io.bluerain.tweets.view.IBlogView import kotlinx.android.synthetic.main.fragment_article_main.* /** * Created by hentioe on 17-4-26. * 博客列表页面 */ class ArticlesFragment : BaseFragment<BlogPresenter, IBlogView>(), IBlogView { override fun providePresenter(): BlogPresenter { return BlogPresenter() } override fun initEvent() { refresh_blog.setOnRefreshListener { initListView(ArrayList<ArticleModel>()) presenter.updateList() } } companion object { var LIST_DATA: List<ArticleModel> = ArrayList() } override fun stopRefreshing() { refresh_blog.isRefreshing = false } override fun initListView(list: List<ArticleModel>) { updateArticleList(list) LIST_DATA = list } fun updateArticleList(list: List<ArticleModel>) { simple_list_view_blog.setHasFixedSize(true) simple_list_view_blog.layoutManager = LinearLayoutManager(context) simple_list_view_blog.adapter = ArticleRecyclerAdapter(list, this) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? { return inflater!!.inflate(R.layout.fragment_article_main, container, false) } } class ArticleRecyclerViewHolder(items: View) : BaseRecyclerViewHolder(items) { val titleView = find(R.id.recycler_item_article_title) as TextView val commentTotalView = find(R.id.recycler_item_article_comment_total) as TextView val moreView = find(R.id.recycler_item_article_more) as ImageView val statusView = find(R.id.article_comment_status_recycler_item) as TextView val topView = find(R.id.article_comment_top_recycler_item) as TextView } class ArticleRecyclerAdapter(items: List<ArticleModel>, val fragment: ArticlesFragment) : BaseRecyclerViewAdapter<ArticleRecyclerViewHolder, ArticleModel>(items, R.layout.recycler_item_article) { override fun onCreateViewHolderByView(itemView: View): ArticleRecyclerViewHolder { return ArticleRecyclerViewHolder(itemView) } override fun onBindViewHolder(holder: ArticleRecyclerViewHolder, position: Int) { val model = getModel(position) holder.titleView.text = model.title holder.commentTotalView.text = "${model.commentTotal} 评论" if (!model.isNormal()) { holder.statusView.text = model.statusToString() holder.statusView.visibility = View.VISIBLE } else { holder.statusView.visibility = View.GONE } if (model.isTop()) holder.topView.visibility = View.VISIBLE else holder.topView.visibility = View.GONE super.onBindViewHolder(holder, position) } override fun onBindEvent(holder: ArticleRecyclerViewHolder, position: Int) { val article = LIST_DATA[position] holder.titleView.setOnClickListener { ArticleInfoActivity.launch(fragment.activity, article.query) } val popupMenu = PopupMenu(fragment.context, holder.moreView) popupMenu.menuInflater.inflate(R.menu.popup_menu_admin_article_more, popupMenu.menu) holder.moreView.setOnClickListener { popupMenu.show() } popupMenu.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.admin_article_popup_menu_top -> fragment.presenter.topArticle(article.id, false) R.id.admin_article_popup_menu_cancel_top -> fragment.presenter.topArticle(article.id, true) R.id.admin_article_popup_menu_normal -> fragment.presenter.normalArticle(article.id) R.id.admin_article_popup_menu_hidden -> fragment.presenter.hiddenArticle(article.id) R.id.admin_article_popup_menu_recycle -> fragment.presenter.recycleArticle(article.id) R.id.admin_article_popup_menu_delete -> fragment.presenter.deleteArticle(article.id) } return@setOnMenuItemClickListener true } holder.commentTotalView.setOnClickListener { ShowCommentsActivity.launch(fragment.activity, 0, article.id) } } }
app/src/main/kotlin/io/bluerain/tweets/fragment/ArticleFragment.kt
1359552884
/* * Copyright (C) 2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.w3.tests.lang import com.intellij.lang.LanguageASTFactory import com.intellij.openapi.extensions.PluginId import com.intellij.psi.PsiElement import org.hamcrest.CoreMatchers.`is` import org.junit.jupiter.api.* import uk.co.reecedunn.intellij.plugin.core.extensions.registerServiceInstance import uk.co.reecedunn.intellij.plugin.core.tests.assertion.assertThat import uk.co.reecedunn.intellij.plugin.core.tests.parser.ParsingTestCase import uk.co.reecedunn.intellij.plugin.w3.lang.FullTextSyntaxValidator import uk.co.reecedunn.intellij.plugin.w3.lang.W3CSpecifications import uk.co.reecedunn.intellij.plugin.xpath.lang.FullTextSpec import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathASTFactory import uk.co.reecedunn.intellij.plugin.xpath.parser.XPathParserDefinition import uk.co.reecedunn.intellij.plugin.xpm.lang.configuration.XpmLanguageConfiguration import uk.co.reecedunn.intellij.plugin.xpm.lang.diagnostics.XpmDiagnostics import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidation import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidator import uk.co.reecedunn.intellij.plugin.xquery.ast.xquery.XQueryModule import uk.co.reecedunn.intellij.plugin.xquery.lang.XQuery import uk.co.reecedunn.intellij.plugin.xquery.parser.XQueryASTFactory import uk.co.reecedunn.intellij.plugin.xquery.parser.XQueryParserDefinition import uk.co.reecedunn.intellij.plugin.xquery.project.settings.XQueryProjectSettings import xqt.platform.intellij.xpath.XPath @Suppress("ClassName") @DisplayName("XQuery IntelliJ Plugin - Syntax Validation - XQuery Full Text") class XQueryFullTextSyntaxValidatorTest : ParsingTestCase<XQueryModule>("xqy", XQueryParserDefinition(), XPathParserDefinition()), XpmDiagnostics { override val pluginId: PluginId = PluginId.getId("XQueryFullTextSyntaxValidatorTest") // region ParsingTestCase override fun registerServicesAndExtensions() { super.registerServicesAndExtensions() project.registerServiceInstance(XQueryProjectSettings::class.java, XQueryProjectSettings()) addExplicitExtension(LanguageASTFactory.INSTANCE, XPath, XPathASTFactory()) addExplicitExtension(LanguageASTFactory.INSTANCE, XQuery, XQueryASTFactory()) XpmSyntaxValidator.register(this, FullTextSyntaxValidator) } // endregion // region XpmDiagnostics val report: StringBuffer = StringBuffer() @BeforeEach fun reset() { report.delete(0, report.length) } override fun error(element: PsiElement, code: String, description: String) { if (report.isNotEmpty()) { report.append('\n') } report.append("E $code(${element.textOffset}:${element.textOffset + element.textLength}): $description") } override fun warning(element: PsiElement, code: String, description: String) { if (report.isNotEmpty()) { report.append('\n') } report.append("W $code(${element.textOffset}:${element.textOffset + element.textLength}): $description") } val validator: XpmSyntaxValidation = XpmSyntaxValidation() // endregion @Suppress("PrivatePropertyName") private val XQUERY_1_0 = XpmLanguageConfiguration(XQuery.VERSION_1_0, W3CSpecifications.REC) @Suppress("PrivatePropertyName") private val FULL_TEXT_1_0 = XpmLanguageConfiguration(XQuery.VERSION_1_0, W3CSpecifications.REC) .withImplementations(FullTextSpec.REC_1_0_20110317) @Nested @DisplayName("XQuery 3.1 with Full Text EBNF (24) FTOptionDecl") internal inner class FTOptionDecl { @Test @DisplayName("without Full Text") fun notSupported() { val file = parse<XQueryModule>("declare ft-option using language \"en-IE\";")[0] validator.configuration = XQUERY_1_0 validator.validate(file, this@XQueryFullTextSyntaxValidatorTest) assertThat( report.toString(), `is`( """ E XPST0003(8:17): W3C Specifications REC does not support XQuery and XPath Full Text 1.0 constructs. """.trimIndent() ) ) } @Test @DisplayName("with Full Text") fun supported() { val file = parse<XQueryModule>("declare ft-option using language \"en-IE\";")[0] validator.configuration = FULL_TEXT_1_0 validator.validate(file, this@XQueryFullTextSyntaxValidatorTest) assertThat(report.toString(), `is`("")) } } @Nested @DisplayName("XQuery 3.1 with Full Text EBNF (37) FTScoreVar") internal inner class FTScoreVar { @Test @DisplayName("without Full Text") fun notSupported() { val file = parse<XQueryModule>("for \$x score \$y in \$z return \$x")[0] validator.configuration = XQUERY_1_0 validator.validate(file, this@XQueryFullTextSyntaxValidatorTest) assertThat( report.toString(), `is`( """ E XPST0003(7:12): W3C Specifications REC does not support XQuery and XPath Full Text 1.0 constructs. """.trimIndent() ) ) } @Test @DisplayName("with Full Text") fun supported() { val file = parse<XQueryModule>("for \$x score \$y in \$z return \$x")[0] validator.configuration = FULL_TEXT_1_0 validator.validate(file, this@XQueryFullTextSyntaxValidatorTest) assertThat(report.toString(), `is`("")) } } @Nested @DisplayName("XQuery 3.1 with Full Text EBNF (51) FTContainsExpr") internal inner class FTContainsExpr { @Test @DisplayName("without Full Text") fun notSupported() { val file = parse<XQueryModule>("title contains text \"lorem\"")[0] validator.configuration = XQUERY_1_0 validator.validate(file, this@XQueryFullTextSyntaxValidatorTest) assertThat( report.toString(), `is`( """ E XPST0003(6:14): W3C Specifications REC does not support XQuery and XPath Full Text 1.0 constructs. """.trimIndent() ) ) } @Test @DisplayName("with Full Text") fun supported() { val file = parse<XQueryModule>("title contains text \"lorem\"")[0] validator.configuration = FULL_TEXT_1_0 validator.validate(file, this@XQueryFullTextSyntaxValidatorTest) assertThat(report.toString(), `is`("")) } } }
src/plugin-w3/test/uk/co/reecedunn/intellij/plugin/w3/tests/lang/XQueryFullTextSyntaxValidatorTest.kt
1349102267