repo_name
stringlengths 7
81
| path
stringlengths 4
242
| copies
stringclasses 95
values | size
stringlengths 1
6
| content
stringlengths 3
991k
| license
stringclasses 15
values |
---|---|---|---|---|---|
buxapp/gradle-foss-dependencies | src/main/kotlin/com/getbux/android/gradle/extension/ModuleDataExtension.kt | 1 | 127 | package com.getbux.android.gradle.extension
import com.github.jk1.license.ModuleData
val ModuleData.id get() = "$group:$name" | apache-2.0 |
mgramin/sql-boot | src/test/kotlin/com/github/mgramin/sqlboot/model/resourcetype/impl/sql/SqlResourceTypeTest.kt | 1 | 4536 | /*
* The MIT License (MIT)
* <p>
* Copyright (c) 2016-2019 Maksim Gramin
* <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 NON-INFRINGEMENT. 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.github.mgramin.sqlboot.model.resourcetype.impl.sql
import com.github.mgramin.sqlboot.model.connection.SimpleDbConnection
import com.github.mgramin.sqlboot.model.uri.impl.DbUri
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.core.io.FileSystemResource
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.context.junit.jupiter.SpringExtension
/**
* @author Maksim Gramin ([email protected])
* @version $Id: 3d61942b737e9bf2768c93c6058e1ec55929b6f3 $
* @since 0.1
*/
@ExtendWith(SpringExtension::class)
@ContextConfiguration(locations = ["/test_config.xml"])
class SqlResourceTypeTest {
private val db = SimpleDbConnection()
init {
db.name ="unit_test_db"
db.baseFolder = FileSystemResource("conf/h2/database")
db.url = "jdbc:h2:mem:;INIT=RUNSCRIPT FROM 'classpath:schema.sql';"
db.paginationQueryTemplate = "${'$'}{query} offset ${'$'}{uri.pageSize()*(uri.pageNumber()-1)} limit ${'$'}{uri.pageSize()}"
}
@Test
fun name() {
val name = SqlResourceType(arrayListOf("table", "tbl", "t"), "", listOf(db)).name()
assertEquals("table", name)
}
@Test
fun aliases() {
val aliases = SqlResourceType(arrayListOf("table", "tbl", "t"), "", listOf(db)).aliases()
assertEquals(arrayListOf("table", "tbl", "t"), aliases)
}
@Test
fun read() {
val sql = """select *
| from (select table_schema as "@schema"
| , table_name as "@table"
| from information_schema.tables)""".trimMargin()
val type =
SqlResourceType(
aliases = arrayListOf("table"),
sql = sql,
connections = listOf(db))
assertEquals(46, type.read(DbUri("table/m.column")).count().block())
}
@Test
fun read2() {
val sql = """select *
| from (select table_schema as "@schema"
| , table_name as "@table"
| , column_name as "@column"
| from information_schema.columns)""".trimMargin()
val type =
SqlResourceType(
aliases = arrayListOf("column"),
sql = sql,
connections = listOf(db))
assertEquals(347, type.read(DbUri("column/main_schema.users")).count().block())
}
@Test
fun path() {
val sql = """select @schema
| , @table
| , @column
| from (select table_schema as "@schema"
| , table_name as "@table"
| , column_name as "@column"
| from information_schema.columns)""".trimMargin()
val type =
SqlResourceType(
aliases = arrayListOf("column"),
sql = sql,
connections = listOf(db))
assertEquals("[schema, table, column]", type.path().toString())
}
@Test
fun metaData() {
}
} | mit |
olivierperez/crapp | lib/src/main/java/fr/o80/sample/lib/core/presenter/Presenter.kt | 1 | 851 | package fr.o80.sample.lib.core.presenter
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.disposables.Disposable
/**
* @author Olivier Perez
*/
open class Presenter<out T : PresenterView> {
private var viewUnsafe: PresenterView? = null
private val disposables = CompositeDisposable()
fun attach(view: PresenterView?) {
this.viewUnsafe = view
}
fun dettach() {
disposables.clear()
viewUnsafe = null
}
@Suppress("UNCHECKED_CAST")
val view: T
get() {
when (viewUnsafe) {
null -> throw RuntimeException("Trying to access view after it has been dettached.")
else -> return viewUnsafe as T
}
}
protected fun addDisposable(disposable: Disposable) {
disposables.add(disposable)
}
}
| apache-2.0 |
da1z/intellij-community | uast/uast-tests/test/org/jetbrains/uast/test/java/SimpleJavaRenderLogTest.kt | 1 | 1616 | /*
* 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 org.jetbrains.uast.test.java
import org.junit.Test
class SimpleJavaRenderLogTest : AbstractJavaRenderLogTest() {
@Test
fun testDataClass() = doTest("DataClass/DataClass.java")
@Test
fun testEnumSwitch() = doTest("Simple/EnumSwitch.java")
@Test
fun testLocalClass() = doTest("Simple/LocalClass.java")
@Test
fun testReturnX() = doTest("Simple/ReturnX.java")
@Test
fun testJava() = doTest("Simple/Simple.java")
@Test
fun testClass() = doTest("Simple/SuperTypes.java")
@Test
fun testTryWithResources() = doTest("Simple/TryWithResources.java")
@Test
fun testEnumValueMembers() = doTest("Simple/EnumValueMembers.java")
@Test
fun testQualifiedConstructorCall() = doTest("Simple/QualifiedConstructorCall.java")
@Test
fun testAnonymousClassWithParameters() = doTest("Simple/AnonymousClassWithParameters.java")
@Test
fun testVariableAnnotation() = doTest("Simple/VariableAnnotation.java")
@Test
fun testPackageInfo() = doTest("Simple/package-info.java")
}
| apache-2.0 |
kvakil/venus | src/main/kotlin/venus/riscv/insts/srai.kt | 1 | 256 | package venus.riscv.insts
import venus.riscv.insts.dsl.ShiftImmediateInstruction
val srai = ShiftImmediateInstruction(
name = "srai",
funct3 = 0b101,
funct7 = 0b0100000,
eval32 = { a, b -> if (b == 0) a else (a shr b) }
)
| mit |
santoslucas/guarda-filme-android | app/src/androidTest/java/com/guardafilme/ExampleInstrumentedTest.kt | 1 | 632 | package com.guardafilme
import android.support.test.InstrumentationRegistry
import android.support.test.runner.AndroidJUnit4
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.Assert.*
/**
* Instrumented test, which will execute on an Android device.
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
@Test
fun useAppContext() {
// Context of the app under test.
val appContext = InstrumentationRegistry.getTargetContext()
assertEquals("com.guardafilme", appContext.packageName)
}
}
| gpl-3.0 |
cyclestreets/android | libraries/cyclestreets-view/src/main/java/net/cyclestreets/views/place/PlaceView.kt | 1 | 287 | package net.cyclestreets.views.place
import net.cyclestreets.view.R
import android.content.Context
import android.util.AttributeSet
class PlaceView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) :
PlaceViewBase(context, R.layout.placetextview, attrs)
| gpl-3.0 |
prt2121/android-workspace | Everywhere/app/src/main/kotlin/com/prt2121/everywhere/MainActivity.kt | 1 | 2834 | package com.prt2121.everywhere
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.Window
import android.webkit.WebView
import android.webkit.WebViewClient
import net.smartam.leeloo.client.OAuthClient
import net.smartam.leeloo.client.URLConnectionClient
import net.smartam.leeloo.client.request.OAuthClientRequest
import net.smartam.leeloo.common.exception.OAuthSystemException
import net.smartam.leeloo.common.message.types.GrantType
import org.jetbrains.anko.async
/**
* Created by pt2121 on 1/17/16.
*/
class MainActivity : BaseActivity() {
val CONSUMER_KEY by lazy { getString(R.string.consumer_key) }
val CONSUMER_SECRET by lazy { getString(R.string.consumer_secret) }
override fun onCreate(savedInstanceState: Bundle?) {
requestWindowFeature(Window.FEATURE_NO_TITLE)
super.onCreate(savedInstanceState)
val webView = WebView(this)
webView.setWebViewClient(LoginWebViewClient())
setContentView(webView)
webView.settings.javaScriptEnabled = true
try {
val request = OAuthClientRequest
.authorizationLocation(AUTH_URL)
.setClientId(CONSUMER_KEY)
.setRedirectURI(REDIRECT_URI)
.buildQueryMessage()
webView.loadUrl("${request.locationUri}&response_type=code&set_mobile=on")
} catch (e: OAuthSystemException) {
println("OAuth request failed ${e.message}")
}
}
inner class LoginWebViewClient : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
val uri = Uri.parse(url)
val code = uri.getQueryParameter("code")
val error = uri.getQueryParameter("error")
if (code != null) {
val request = OAuthClientRequest.tokenLocation(TOKEN_URL)
.setGrantType(GrantType.AUTHORIZATION_CODE)
.setClientId(CONSUMER_KEY)
.setClientSecret(CONSUMER_SECRET)
.setRedirectURI(REDIRECT_URI)
.setCode(code)
.buildBodyMessage()
val oAuthClient = OAuthClient(URLConnectionClient())
async() {
val response = oAuthClient.accessToken(request)
TokenStorage(this@MainActivity).save(response.accessToken)
runOnUiThread {
val intent = Intent(this@MainActivity, GroupActivity::class.java)
intent.putExtra(ACCESS_EXTRA, response.accessToken)
startActivity(intent)
finish()
}
}
} else if (error != null) {
println("error $error")
}
return false
}
}
companion object {
const val AUTH_URL = "https://secure.meetup.com/oauth2/authorize"
const val TOKEN_URL = "https://secure.meetup.com/oauth2/access"
const val REDIRECT_URI = "http://prt2121.github.io"
const val ACCESS_EXTRA = "access_token"
}
} | apache-2.0 |
kevinhinterlong/archwiki-viewer | app/src/main/java/com/jtmcn/archwiki/viewer/MainActivity.kt | 2 | 5317 | package com.jtmcn.archwiki.viewer
import android.app.SearchManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import com.jtmcn.archwiki.viewer.data.SearchResult
import com.jtmcn.archwiki.viewer.data.getSearchQuery
import com.jtmcn.archwiki.viewer.tasks.Fetch
import com.jtmcn.archwiki.viewer.utils.getTextZoom
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.toolbar.*
import timber.log.Timber
import java.util.*
class MainActivity : AppCompatActivity() {
private lateinit var searchView: SearchView
private lateinit var searchMenuItem: MenuItem
private var currentSuggestions: List<SearchResult>? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
wikiViewer.buildView(progressBar, supportActionBar)
handleIntent(intent)
}
override fun onResume() {
super.onResume()
updateWebSettings()
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
handleIntent(intent)
}
private fun handleIntent(intent: Intent?) {
if (intent == null) {
return
}
if (Intent.ACTION_SEARCH == intent.action) {
val query = intent.getStringExtra(SearchManager.QUERY)
wikiViewer.passSearch(query!!)
hideSearchView()
} else if (Intent.ACTION_VIEW == intent.action) {
val url = intent.dataString
wikiViewer.wikiClient.shouldOverrideUrlLoading(wikiViewer, url!!)
}
}
/**
* Update the font size used in the webview.
*/
private fun updateWebSettings() {
wikiViewer.settings.textZoom = getTextZoom(this)
}
override fun onPrepareOptionsMenu(menu: Menu): Boolean {
val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager
searchMenuItem = menu.findItem(R.id.menu_search)
searchView = searchMenuItem.actionView as SearchView
searchView.setOnQueryTextFocusChangeListener { _, hasFocus ->
if (!hasFocus) {
hideSearchView()
}
}
searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName))
searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
override fun onQueryTextSubmit(query: String): Boolean {
wikiViewer.passSearch(query)
return false
}
override fun onQueryTextChange(newText: String): Boolean {
if (newText.isEmpty()) {
setCursorAdapter(ArrayList())
return true
} else {
val searchUrl = getSearchQuery(newText)
Fetch.search({
currentSuggestions = it
setCursorAdapter(currentSuggestions)
}, searchUrl)
return true
}
}
})
searchView.setOnSuggestionListener(object : SearchView.OnSuggestionListener {
override fun onSuggestionSelect(position: Int): Boolean {
return false
}
override fun onSuggestionClick(position: Int): Boolean {
val (pageName, pageURL) = currentSuggestions!![position]
Timber.d("Opening '$pageName' from search suggestion.")
wikiViewer.wikiClient.shouldOverrideUrlLoading(wikiViewer, pageURL)
hideSearchView()
return true
}
})
return true
}
private fun hideSearchView() {
searchMenuItem.collapseActionView()
wikiViewer.requestFocus() //pass control back to the wikiview
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
val inflater = menuInflater
inflater.inflate(R.menu.menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.menu_share -> {
val wikiPage = wikiViewer.currentWebPage
if (wikiPage != null) {
val sharingIntent = Intent()
sharingIntent.type = TEXT_PLAIN_MIME
sharingIntent.action = Intent.ACTION_SEND
sharingIntent.putExtra(Intent.EXTRA_TITLE, wikiPage.pageTitle)
sharingIntent.putExtra(Intent.EXTRA_TEXT, wikiPage.pageUrl)
startActivity(Intent.createChooser(sharingIntent, null))
}
}
R.id.refresh -> wikiViewer.onRefresh()
R.id.menu_settings -> startActivity(Intent(this, PreferencesActivity::class.java))
R.id.exit -> finish()
}
return super.onOptionsItemSelected(item)
}
private fun setCursorAdapter(currentSuggestions: List<SearchResult>?) {
searchView.suggestionsAdapter = SearchResultsAdapter.getCursorAdapter(this, currentSuggestions!!)
}
} | apache-2.0 |
Adventech/sabbath-school-android-2 | common/storage/src/main/java/app/ss/storage/db/dao/BibleVersionDao.kt | 1 | 1457 | /*
* Copyright (c) 2022. Adventech <[email protected]>
*
* 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 app.ss.storage.db.dao
import androidx.room.Dao
import androidx.room.Query
import app.ss.storage.db.entity.BibleVersionEntity
@Dao
interface BibleVersionDao : BaseDao<BibleVersionEntity> {
@Query("SELECT * FROM bible_version WHERE language = :language")
fun get(language: String): BibleVersionEntity?
}
| mit |
PolymerLabs/arcs | javatests/arcs/core/allocator/AllocatorUnitTest.kt | 1 | 21993 | /*
* Copyright 2021 Google LLC.
*
* This code may only be used under the BSD style license found at
* http://polymer.github.io/LICENSE.txt
*
* Code distributed by Google as part of this project is also subject to an additional IP rights
* grant found at
* http://polymer.github.io/PATENTS.txt
*/
package arcs.core.allocator
import arcs.core.common.ArcId
import arcs.core.common.Id
import arcs.core.common.toArcId
import arcs.core.data.Annotation
import arcs.core.data.Capabilities
import arcs.core.data.CollectionType
import arcs.core.data.EntityType
import arcs.core.data.FieldType
import arcs.core.data.HandleMode
import arcs.core.data.Plan
import arcs.core.data.ReferenceType
import arcs.core.data.SchemaRegistry
import arcs.core.data.SingletonType
import arcs.core.data.builder.handle
import arcs.core.data.builder.particle
import arcs.core.data.builder.plan
import arcs.core.data.builder.schema
import arcs.core.host.ArcHost
import arcs.core.host.ArcHostException
import arcs.core.host.ArcHostNotFoundException
import arcs.core.host.ArcState
import arcs.core.host.ArcStateChangeCallback
import arcs.core.host.ArcStateChangeRegistration
import arcs.core.host.HostRegistry
import arcs.core.host.ParticleIdentifier
import arcs.core.host.ParticleNotFoundException
import arcs.core.storage.CapabilitiesResolver
import arcs.core.storage.api.DriverAndKeyConfigurator
import arcs.core.storage.testutil.DummyStorageKey
import arcs.core.util.Log
import arcs.core.util.plus
import arcs.core.util.testutil.LogRule
import arcs.core.util.traverse
import com.google.common.truth.Truth.assertThat
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
import kotlin.test.assertFailsWith
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.test.TestCoroutineScope
import kotlinx.coroutines.test.runBlockingTest
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
@ExperimentalCoroutinesApi
@RunWith(JUnit4::class)
class AllocatorUnitTest {
private lateinit var scope: TestCoroutineScope
private lateinit var hostRegistry: FakeHostRegistry
private lateinit var partitionMap: FakePartitionSerialization
private lateinit var allocator: Allocator
@get:Rule
val log = LogRule(Log.Level.Warning)
@Before
fun setUp() {
DriverAndKeyConfigurator.configure(null)
scope = TestCoroutineScope()
hostRegistry = FakeHostRegistry()
partitionMap = FakePartitionSerialization()
allocator = Allocator(hostRegistry, partitionMap, scope)
}
@After
fun tearDown() {
scope.cleanupTestCoroutines()
SchemaRegistry.clearForTest()
}
@Test
fun startArcForPlan_populatesSchemaRegistry() = scope.runBlockingTest {
val schema1 = schema("abcdef")
val schema2 = schema("ghijkl")
val schema3 = schema("mnopqr")
val plan = plan {
handle(DummyStorageKey("handle1")) {
type = CollectionType(EntityType(schema1))
}
handle(DummyStorageKey("handle2")) {
type = SingletonType(EntityType(schema2))
}
handle(DummyStorageKey("handle3")) {
type = SingletonType(ReferenceType(EntityType(schema3)))
}
}
allocator.startArcForPlan(plan)
assertThat(SchemaRegistry.getSchema("abcdef")).isEqualTo(schema1)
assertThat(SchemaRegistry.getSchema("ghijkl")).isEqualTo(schema2)
assertThat(SchemaRegistry.getSchema("mnopqr")).isEqualTo(schema3)
}
@Test
fun startArcForPlan_withExistingPartitions_returnsValidArc() = scope.runBlockingTest {
val arcIdStr = "myArc"
partitionMap.set(
listOf(
Plan.Partition(arcIdStr, "hostOne", emptyList()),
Plan.Partition(arcIdStr, "hostTwo", emptyList()),
Plan.Partition(arcIdStr, "hostThree", emptyList())
)
)
val plan = plan { arcId = arcIdStr }
val arc = allocator.startArcForPlan(plan)
assertThat(arc.id).isEqualTo(arcIdStr.toArcId())
assertThat(arc.partitions).containsExactly(
Plan.Partition(arcIdStr, "hostOne", emptyList()),
Plan.Partition(arcIdStr, "hostTwo", emptyList()),
Plan.Partition(arcIdStr, "hostThree", emptyList())
)
}
@Test
fun startArcForPlan_noExistingPartitions_withArcId() = scope.runBlockingTest {
val host1 = FakeArcHost("Host1", listOf(PARTICLE1, PARTICLE2))
val host2 = FakeArcHost("Host2", listOf(PARTICLE3))
hostRegistry.registerHost(host1)
hostRegistry.registerHost(host2)
val partitions = listOf(
Plan.Partition("!:myArc", "Host1", listOf(PARTICLE1, PARTICLE2)),
Plan.Partition("!:myArc", "Host2", listOf(PARTICLE3))
)
val plan = plan {
arcId = "myArc"
add(PARTICLE1)
add(PARTICLE2)
add(PARTICLE3)
}
val arc = allocator.startArcForPlan(plan)
assertThat(arc.id).isEqualTo("myArc".toArcId())
assertThat(arc.partitions).hasSize(2)
val actualHost1Partition = arc.partitions.find { it.arcHost == "Host1" }
assertThat(actualHost1Partition!!.particles).isEqualTo(partitions[0].particles)
val actualHost2Partition = arc.partitions.find { it.arcHost == "Host2" }
assertThat(actualHost2Partition!!.particles).isEqualTo(partitions[1].particles)
assertThat(partitionMap.setPartitionsCallValue).isEqualTo(arc.partitions)
}
@Test
fun startArcForPlan_noExistingPartitions_withArcIdForTesting() = scope.runBlockingTest {
val host1 = FakeArcHost("Host1", listOf(PARTICLE1, PARTICLE2))
val host2 = FakeArcHost("Host2", listOf(PARTICLE3))
hostRegistry.registerHost(host1)
hostRegistry.registerHost(host2)
val partitions = listOf(
Plan.Partition("!:arc", "Host1", listOf(PARTICLE1, PARTICLE2)),
Plan.Partition("!:arc", "Host2", listOf(PARTICLE3))
)
val plan = plan {
add(PARTICLE1)
add(PARTICLE2)
add(PARTICLE3)
}
val arc = allocator.startArcForPlan(plan)
assertThat(arc.id.idTreeString).isEqualTo("arc")
assertThat(arc.partitions).hasSize(2)
val actualHost1Partition = arc.partitions.find { it.arcHost == "Host1" }
assertThat(actualHost1Partition!!.particles).isEqualTo(partitions[0].particles)
val actualHost2Partition = arc.partitions.find { it.arcHost == "Host2" }
assertThat(actualHost2Partition!!.particles).isEqualTo(partitions[1].particles)
assertThat(partitionMap.setPartitionsCallValue).isEqualTo(arc.partitions)
}
@Test
fun startArcForPlan_noExistingPartitionsNoAvailableHosts() = scope.runBlockingTest {
val plan = plan {
add(PARTICLE1)
add(PARTICLE2)
}
val host1 = FakeArcHost("Host1", listOf(PARTICLE1))
hostRegistry.registerHost(host1)
assertFailsWith<ParticleNotFoundException> { allocator.startArcForPlan(plan) }
}
@Test
fun startArcForPlan_whenHostThrows_reThrowsAndStops() = scope.runBlockingTest {
val host1 = FakeArcHost("HostOne", listOf(PARTICLE1))
host1.throwExceptionOnStart = true
val host2 = FakeArcHost("HostTwo", listOf(PARTICLE2))
hostRegistry.registerHost(host1)
hostRegistry.registerHost(host2)
val plan = plan {
add(PARTICLE1)
add(PARTICLE2)
}
assertFailsWith<ArcHostException> { allocator.startArcForPlan(plan) }
// Check that both hosts have been asked to stop the arc.
assertThat(host1.stopArcPartition).isNotNull()
assertThat(host2.stopArcPartition).isNotNull()
}
@Test
fun stopArc_clearsPartitionsFromPartitionSerialization() = scope.runBlockingTest {
val host1 = FakeArcHost("HostOne", listOf(PARTICLE1))
val host2 = FakeArcHost("HostTwo", listOf(PARTICLE2))
hostRegistry.registerHost(host1)
hostRegistry.registerHost(host2)
partitionMap.set(
listOf(
Plan.Partition("!:myArc", "HostOne", listOf(PARTICLE1)),
Plan.Partition("!:myArc", "HostTwo", listOf(PARTICLE2))
)
)
allocator.stopArc("myArc".toArcId())
assertThat(partitionMap.readAndClearPartitionsArcId).isEqualTo("myArc".toArcId())
assertThat(host1.stopArcPartition).isEqualTo(
Plan.Partition("!:myArc", "HostOne", listOf(PARTICLE1))
)
assertThat(host2.stopArcPartition).isEqualTo(
Plan.Partition("!:myArc", "HostTwo", listOf(PARTICLE2))
)
}
@Test
fun lookupArcHost_throwsWhenNotFound() = scope.runBlockingTest {
assertFailsWith<ArcHostNotFoundException> {
allocator.lookupArcHost(hostId = "Definitely not registered")
}
}
@Test
fun lookupArcHost_returnsHostIfFound() = scope.runBlockingTest {
val host = FakeArcHost("myArcHost", emptyList())
hostRegistry.registerHost(host)
assertThat(allocator.lookupArcHost("myArcHost")).isEqualTo(host)
}
@Test
fun findArcHostByParticle_throwsWhenNotFound() = scope.runBlockingTest {
assertFailsWith<ParticleNotFoundException> { allocator.findArcHostByParticle(PARTICLE1) }
}
@Test
fun findArcHostByParticle_findsSupportingHost() = scope.runBlockingTest {
val host1 = FakeArcHost("Host1", listOf(PARTICLE1))
val host2 = FakeArcHost("Host2", listOf(PARTICLE2))
hostRegistry.registerHost(host1)
hostRegistry.registerHost(host2)
assertThat(allocator.findArcHostByParticle(PARTICLE1)).isEqualTo(host1)
assertThat(allocator.findArcHostByParticle(PARTICLE2)).isEqualTo(host2)
}
@Test
fun createNonSerializing_exercise() = scope.runBlockingTest {
val allocator = Allocator.createNonSerializing(hostRegistry, scope)
val host1 = FakeArcHost("HostOne", listOf(PARTICLE1))
val host2 = FakeArcHost("HostTwo", listOf(PARTICLE2))
hostRegistry.registerHost(host1)
hostRegistry.registerHost(host2)
val plan = plan {
add(PARTICLE1)
add(PARTICLE2)
}
val arc = allocator.startArcForPlan(plan)
allocator.stopArc(arc.id)
}
/**
* Test that adding an unmapped particle to a plan results in that plan being unable to be
* started.
*/
@Test
fun verifyAdditionalUnknownParticleThrows() = scope.runBlockingTest {
val unknownParticle = Plan.Particle(
particleName = "Unknown Particle",
location = "unknown.Particle",
handles = emptyMap()
)
val host1 = FakeArcHost("HostOne", listOf(PARTICLE1))
val host2 = FakeArcHost("HostTwo", listOf(PARTICLE2))
hostRegistry.registerHost(host1)
hostRegistry.registerHost(host2)
val plan = plan {
add(PARTICLE1)
add(PARTICLE2)
}
invariant_addUnmappedParticle_generatesError(plan, hostRegistry, unknownParticle)
}
/**
* Test that PersonPlan can be started with a hostRegistry established for this purpose.
*/
@Test
fun startArcForPlan_canPartitionArcInExternalHosts() = runBlocking {
val host1 = FakeArcHost("HostOne", listOf(PARTICLE1))
val host2 = FakeArcHost("HostTwo", listOf(PARTICLE2))
hostRegistry.registerHost(host1)
hostRegistry.registerHost(host2)
val plan = plan {
add(PARTICLE1)
add(PARTICLE2)
}
invariant_planWithOnly_mappedParticles_willResolve(plan, hostRegistry)
}
/**
* Tests that the Recipe is properly partitioned so that [ReadingHost] contains only
* [ReadPerson] with associated handles and connections, and [WritingHost] contains only
* [WritePerson] with associated handles and connections.
*/
@Test
fun startArcForPlan_computesPartitions(): Unit = scope.runBlockingTest {
val readingHost = FakeArcHost("ReadingHost", listOf(READ_PARTICLE))
val writingHost = FakeArcHost("WritingHost", listOf(WRITE_PARTICLE))
val pureHost = FakeArcHost("PureHost", listOf(PURE_PARTICLE))
hostRegistry.registerHost(readingHost)
hostRegistry.registerHost(writingHost)
hostRegistry.registerHost(pureHost)
val arc = allocator.startArcForPlan(PLAN)
val allStorageKeyLens = Plan.Particle.handlesLens.traverse() +
Plan.HandleConnection.handleLens +
Plan.Handle.storageKeyLens
// fetch the allocator replaced key
val readPersonKey = findPartitionFor(
arc.partitions, "ReadParticle"
).particles[0].handles["person"]?.storageKey!!
val writePersonKey = findPartitionFor(
arc.partitions, "WriteParticle"
).particles[0].handles["person"]?.storageKey!!
val purePartition = findPartitionFor(arc.partitions, "PureParticle")
val storageKeyLens = Plan.HandleConnection.handleLens + Plan.Handle.storageKeyLens
assertThat(arc.partitions).containsExactly(
Plan.Partition(
arc.id.toString(),
readingHost.hostId,
// replace the CreatableKeys with the allocated keys
listOf(allStorageKeyLens.mod(READ_PARTICLE) { readPersonKey })
),
Plan.Partition(
arc.id.toString(),
writingHost.hostId,
// replace the CreatableKeys with the allocated keys
listOf(allStorageKeyLens.mod(WRITE_PARTICLE) { writePersonKey })
),
Plan.Partition(
arc.id.toString(),
pureHost.hostId,
// replace the CreatableKeys with the allocated keys
listOf(
Plan.Particle.handlesLens.mod(purePartition.particles[0]) {
mapOf(
"inputPerson" to storageKeyLens.mod(it["inputPerson"]!!) { readPersonKey },
"outputPerson" to storageKeyLens.mod(it["outputPerson"]!!) { writePersonKey }
)
}
)
)
)
allocator.stopArc(arc.id)
}
@Test
fun startArcForPlan_createsStorageKeys() = scope.runBlockingTest {
val readingHost = FakeArcHost("ReadingHost", listOf(READ_PARTICLE))
hostRegistry.registerHost(readingHost)
val plan = plan {
add(PERSON_INPUT_HANDLE)
add(READ_PARTICLE)
}
val fakeStorageKeyCreator = FakeStorageKeyCreator()
allocator = Allocator(hostRegistry, partitionMap, scope, fakeStorageKeyCreator)
allocator.startArcForPlan(plan)
assertThat(fakeStorageKeyCreator.createdStorageKeys).isTrue()
}
@Test
fun startArcForPlan_verifyStorageKeysNotOverwritten() = scope.runBlockingTest {
val idGenerator = Id.Generator.newSession()
val testArcId = idGenerator.newArcId("Test")
val resolver = CapabilitiesResolver(CapabilitiesResolver.Options(testArcId))
val inputPerson = resolver.createStorageKey(
Capabilities.fromAnnotation(Annotation.createCapability("tiedToArc")),
EntityType(PERSON_SCHEMA),
"inputParticle"
)
val outputPerson = resolver.createStorageKey(
Capabilities.fromAnnotation(Annotation.createCapability("tiedToArc")),
EntityType(PERSON_SCHEMA),
"outputParticle"
)
val newInputHandle = PERSON_INPUT_HANDLE.copy(storageKey = inputPerson)
val newOutputHandle = PERSON_OUTPUT_HANDLE.copy(storageKey = outputPerson)
val handleLens = Plan.particleLens.traverse() +
Plan.Particle.handlesLens.traverse() +
Plan.HandleConnection.handleLens
val updatedPlan = handleLens.mod(PLAN) { handle ->
val key = handle.storageKey as DummyStorageKey
when (key.key) {
"create://personInputHandle" -> newInputHandle
"create://personOutputHandle" -> newOutputHandle
else -> handle
}
}.copy(handles = listOf(newInputHandle, newOutputHandle))
val readingHost = FakeArcHost(
"ReadingHost",
listOf(updatedPlan.particles.find { it.location.contains("ReadParticle") }!!)
)
val writingHost = FakeArcHost(
"WritingHost",
listOf(updatedPlan.particles.find { it.location.contains("WriteParticle") }!!)
)
val pureHost = FakeArcHost(
"PureHost",
listOf(updatedPlan.particles.find { it.location.contains("PureParticle") }!!)
)
hostRegistry.registerHost(readingHost)
hostRegistry.registerHost(writingHost)
hostRegistry.registerHost(pureHost)
val arc = allocator.startArcForPlan(updatedPlan)
val testKeys = listOf(inputPerson, outputPerson)
arc.partitions.flatMap { it.particles }.forEach { particle ->
particle.handles.forEach { (_, connection) ->
assertThat(connection.storageKey).isIn(testKeys)
}
}
}
@Test
fun startArcForPlan_startsArcHosts() = scope.runBlockingTest {
val readingHost = FakeArcHost("ReadingHost", listOf(READ_PARTICLE))
val writingHost = FakeArcHost("WritingHost", listOf(WRITE_PARTICLE))
val pureHost = FakeArcHost("PureHost", listOf(PURE_PARTICLE))
hostRegistry.registerHost(readingHost)
hostRegistry.registerHost(writingHost)
hostRegistry.registerHost(pureHost)
val arc = allocator.startArcForPlan(PLAN)
arc.partitions.forEach {
val host = allocator.lookupArcHost(it.arcHost) as FakeArcHost
assertThat(host.lookupArcHostStatusResult).isEqualTo(ArcState.Running)
}
}
@Test
fun startArcForPlan_onlyUnknownParticles_throws() = scope.runBlockingTest {
val readingHost = FakeArcHost("ReadingHost", listOf(READ_PARTICLE))
val writingHost = FakeArcHost("WritingHost", listOf(WRITE_PARTICLE))
val pureHost = FakeArcHost("PureHost", listOf(PURE_PARTICLE))
hostRegistry.registerHost(readingHost)
hostRegistry.registerHost(writingHost)
hostRegistry.registerHost(pureHost)
val particleLens = Plan.particleLens.traverse()
val plan = particleLens.mod(PLAN) { particle ->
particle.copy(
particleName = "Unknown ${particle.particleName}",
location = "unknown.${particle.location}"
)
}
assertFailsWith<ParticleNotFoundException> {
allocator.startArcForPlan(plan)
}
}
private fun findPartitionFor(
partitions: List<Plan.Partition>,
particleName: String
) = partitions.find { partition ->
partition.particles.any { it.particleName == particleName }
}!!
private class FakeHostRegistry : HostRegistry() {
private val hosts = mutableSetOf<ArcHost>()
override suspend fun availableArcHosts(): List<ArcHost> = hosts.toList()
override suspend fun registerHost(host: ArcHost) {
hosts.add(host)
}
override suspend fun unregisterHost(host: ArcHost) {
hosts.remove(host)
}
}
private class FakePartitionSerialization : Allocator.PartitionSerialization {
var setPartitionsCallValue: List<Plan.Partition>? = null
var readAndClearPartitionsArcId: ArcId? = null
override suspend fun set(partitions: List<Plan.Partition>) {
setPartitionsCallValue = partitions
}
override suspend fun readPartitions(arcId: ArcId): List<Plan.Partition> {
return setPartitionsCallValue ?: emptyList()
}
override suspend fun readAndClearPartitions(arcId: ArcId): List<Plan.Partition> {
readAndClearPartitionsArcId = arcId
val value = setPartitionsCallValue ?: emptyList()
setPartitionsCallValue = emptyList()
return value
}
}
private class FakeArcHost(
override val hostId: String,
val particles: Collection<Plan.Particle>
) : ArcHost {
var lookupArcHostStatusResult = ArcState.NeverStarted
var startArcPartition: Plan.Partition? = null
var stopArcPartition: Plan.Partition? = null
var throwExceptionOnStart: Boolean = false
override suspend fun registeredParticles(): List<ParticleIdentifier> {
return particles.map { ParticleIdentifier.from(it.location) }
}
override suspend fun startArc(partition: Plan.Partition) = suspendCoroutine<Unit> { cont ->
startArcPartition = partition
if (throwExceptionOnStart) {
cont.resumeWithException(ArcHostException("Uh oh!", "Stack"))
lookupArcHostStatusResult = ArcState.Error
} else {
cont.resume(Unit)
lookupArcHostStatusResult = ArcState.Running
}
}
override suspend fun stopArc(partition: Plan.Partition) {
stopArcPartition = partition
}
override suspend fun lookupArcHostStatus(partition: Plan.Partition): ArcState {
return lookupArcHostStatusResult
}
override suspend fun isHostForParticle(particle: Plan.Particle): Boolean {
return particles.any { it == particle }
}
override suspend fun pause() = Unit
override suspend fun unpause() = Unit
override suspend fun waitForArcIdle(arcId: String) = Unit
override suspend fun addOnArcStateChange(
arcId: ArcId,
block: ArcStateChangeCallback
): ArcStateChangeRegistration {
return ArcStateChangeRegistration("asdf")
}
}
class FakeStorageKeyCreator : Allocator.StorageKeyCreator {
var createdStorageKeys: Boolean = false
override fun createStorageKeysIfNecessary(
arcId: ArcId,
idGenerator: Id.Generator,
plan: Plan
): Plan {
createdStorageKeys = true
return plan
}
}
companion object {
val PARTICLE1 = particle("MyParticle", "com.arcs.MyParticle")
val PARTICLE2 = particle("YourParticle", "com.arcs.YourParticle")
val PARTICLE3 = particle("OurParticle", "com.arcs.OurParticle")
val PERSON_SCHEMA = schema("Person") {
singletons {
"name" to FieldType.Text
}
hash = "abcdf"
}
val PERSON_INPUT_HANDLE = handle(DummyStorageKey("create://personInputHandle")) {
type = SingletonType(EntityType(PERSON_SCHEMA))
}
val PERSON_OUTPUT_HANDLE = handle(DummyStorageKey("create://personOutputHandle")) {
type = SingletonType(EntityType(PERSON_SCHEMA))
}
val READ_PARTICLE = particle("ReadParticle", "com.arcs.ReadParticle") {
handleConnection("person", HandleMode.Read, PERSON_INPUT_HANDLE)
}
val WRITE_PARTICLE = particle("WriteParticle", "com.arcs.WriteParticle") {
handleConnection("person", HandleMode.Write, PERSON_OUTPUT_HANDLE)
}
val PURE_PARTICLE = particle("PureParticle", "com.arcs.PureParticle") {
handleConnection("inputPerson", HandleMode.Read, PERSON_INPUT_HANDLE)
handleConnection("outputPerson", HandleMode.Write, PERSON_OUTPUT_HANDLE)
}
val PLAN = plan {
add(READ_PARTICLE)
add(WRITE_PARTICLE)
add(PURE_PARTICLE)
add(PERSON_INPUT_HANDLE)
add(PERSON_OUTPUT_HANDLE)
}
}
}
| bsd-3-clause |
Maccimo/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/branchedTransformations/IfThenToElvisInspection.kt | 2 | 5745 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections.branchedTransformations
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.KtNodeTypes
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.formatter.rightMarginOrDefault
import org.jetbrains.kotlin.idea.inspections.AbstractApplicabilityBasedInspection
import org.jetbrains.kotlin.idea.intentions.branchedTransformations.*
import org.jetbrains.kotlin.idea.util.CommentSaver
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.bindingContextUtil.isUsedAsExpression
import org.jetbrains.kotlin.resolve.calls.util.getType
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import javax.swing.JComponent
class IfThenToElvisInspection @JvmOverloads constructor(
@JvmField var highlightStatement: Boolean = false,
private val inlineWithPrompt: Boolean = true
) : AbstractApplicabilityBasedInspection<KtIfExpression>(KtIfExpression::class.java) {
override fun inspectionText(element: KtIfExpression): String = KotlinBundle.message("if.then.foldable.to")
override val defaultFixText: String get() = INTENTION_TEXT
override fun isApplicable(element: KtIfExpression): Boolean = isApplicableTo(element, expressionShouldBeStable = true)
override fun inspectionHighlightType(element: KtIfExpression): ProblemHighlightType =
if (element.shouldBeTransformed() && (highlightStatement || element.isUsedAsExpression(element.analyze(BodyResolveMode.PARTIAL_WITH_CFA))))
super.inspectionHighlightType(element)
else
ProblemHighlightType.INFORMATION
override fun applyTo(element: KtIfExpression, project: Project, editor: Editor?) {
convert(element, editor, inlineWithPrompt)
}
override fun inspectionHighlightRangeInElement(element: KtIfExpression) = element.fromIfKeywordToRightParenthesisTextRangeInThis()
override fun createOptionsPanel(): JComponent = MultipleCheckboxOptionsPanel(this).also {
it.addCheckbox(KotlinBundle.message("report.also.on.statement"), "highlightStatement")
}
companion object {
val INTENTION_TEXT get() = KotlinBundle.message("replace.if.expression.with.elvis.expression")
fun convert(element: KtIfExpression, editor: Editor?, inlineWithPrompt: Boolean) {
val ifThenToSelectData = element.buildSelectTransformationData() ?: return
val factory = KtPsiFactory(element)
val commentSaver = CommentSaver(element, saveLineBreaks = false)
val margin = element.containingKtFile.rightMarginOrDefault
val elvis = runWriteAction {
val replacedBaseClause = ifThenToSelectData.replacedBaseClause(factory)
val negatedClause = ifThenToSelectData.negatedClause!!
val newExpr = element.replaced(
factory.createExpressionByPattern(
elvisPattern(replacedBaseClause.textLength + negatedClause.textLength + 5 >= margin),
replacedBaseClause,
negatedClause
)
)
(KtPsiUtil.deparenthesize(newExpr) as KtBinaryExpression).also {
commentSaver.restore(it)
}
}
if (editor != null) {
elvis.inlineLeftSideIfApplicable(editor, inlineWithPrompt)
with(IfThenToSafeAccessInspection) {
(elvis.left as? KtSafeQualifiedExpression)?.renameLetParameter(editor)
}
}
}
fun isApplicableTo(element: KtIfExpression, expressionShouldBeStable: Boolean): Boolean {
val ifThenToSelectData = element.buildSelectTransformationData() ?: return false
if (expressionShouldBeStable &&
!ifThenToSelectData.receiverExpression.isStableSimpleExpression(ifThenToSelectData.context)
) return false
val type = element.getType(ifThenToSelectData.context) ?: return false
if (KotlinBuiltIns.isUnit(type)) return false
return ifThenToSelectData.clausesReplaceableByElvis()
}
private fun KtExpression.isNullOrBlockExpression(): Boolean {
val innerExpression = this.unwrapBlockOrParenthesis()
return innerExpression is KtBlockExpression || innerExpression.node.elementType == KtNodeTypes.NULL
}
private fun IfThenToSelectData.clausesReplaceableByElvis(): Boolean =
when {
baseClause == null || negatedClause == null || negatedClause.isNullOrBlockExpression() ->
false
negatedClause is KtThrowExpression && negatedClause.throwsNullPointerExceptionWithNoArguments() ->
false
baseClause.evaluatesTo(receiverExpression) ->
true
baseClause.anyArgumentEvaluatesTo(receiverExpression) ->
true
hasImplicitReceiverReplaceableBySafeCall() || baseClause.hasFirstReceiverOf(receiverExpression) ->
!baseClause.hasNullableType(context)
else ->
false
}
}
}
| apache-2.0 |
Hexworks/zircon | zircon.core/src/commonMain/kotlin/org/hexworks/zircon/api/dsl/component/ToggleButtonDsl.kt | 1 | 849 | package org.hexworks.zircon.api.dsl.component
import org.hexworks.zircon.api.builder.component.ToggleButtonBuilder
import org.hexworks.zircon.api.component.Container
import org.hexworks.zircon.api.component.ToggleButton
import org.hexworks.zircon.api.component.builder.base.BaseContainerBuilder
/**
* Creates a new [ToggleButton] using the component builder DSL and returns it.
*/
fun buildToggleButton(init: ToggleButtonBuilder.() -> Unit): ToggleButton =
ToggleButtonBuilder.newBuilder().apply(init).build()
/**
* Creates a new [ToggleButton] using the component builder DSL, adds it to the
* receiver [BaseContainerBuilder] it and returns the [ToggleButton].
*/
fun <T : BaseContainerBuilder<*, *>> T.toggleButton(
init: ToggleButtonBuilder.() -> Unit
): ToggleButton = buildChildFor(this, ToggleButtonBuilder.newBuilder(), init)
| apache-2.0 |
pyamsoft/pydroid | ui/src/main/java/com/pyamsoft/pydroid/ui/internal/test/TestImageLoader.kt | 1 | 3116 | /*
* Copyright 2022 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.pydroid.ui.internal.test
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import androidx.annotation.CheckResult
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
import coil.ComponentRegistry
import coil.ImageLoader
import coil.decode.DataSource.MEMORY
import coil.disk.DiskCache
import coil.memory.MemoryCache
import coil.request.DefaultRequestOptions
import coil.request.Disposable
import coil.request.ErrorResult
import coil.request.ImageRequest
import coil.request.ImageResult
import coil.request.SuccessResult
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.async
/** Only use for tests/previews */
private class TestImageLoader(context: Context) : ImageLoader {
private val context = context.applicationContext
private val loadingDrawable by lazy(LazyThreadSafetyMode.NONE) { ColorDrawable(Color.BLACK) }
private val successDrawable by lazy(LazyThreadSafetyMode.NONE) { ColorDrawable(Color.GREEN) }
private val disposable =
object : Disposable {
override val isDisposed: Boolean = true
override val job: Deferred<ImageResult> =
MainScope().async<ImageResult> {
ErrorResult(
drawable = null,
request = ImageRequest.Builder(context).build(),
throwable = RuntimeException("Test"),
)
}
override fun dispose() {}
}
override val components: ComponentRegistry = ComponentRegistry()
override val defaults: DefaultRequestOptions = DefaultRequestOptions()
override val diskCache: DiskCache? = null
override val memoryCache: MemoryCache? = null
override fun enqueue(request: ImageRequest): Disposable {
request.apply {
target?.onStart(placeholder = loadingDrawable)
target?.onSuccess(result = successDrawable)
}
return disposable
}
override suspend fun execute(request: ImageRequest): ImageResult {
return SuccessResult(
drawable = successDrawable,
request = request,
dataSource = MEMORY,
)
}
override fun newBuilder(): ImageLoader.Builder {
return ImageLoader.Builder(context)
}
override fun shutdown() {}
}
/** Only use for tests/previews */
@Composable
@CheckResult
internal fun createNewTestImageLoader(): ImageLoader {
val context = LocalContext.current
return TestImageLoader(context)
}
| apache-2.0 |
gonzalonm/sample-my-shopping | data/src/main/kotlin/com/lalosoft/myshopping/data/repository/CloudItemRepository.kt | 1 | 1163 | package com.lalosoft.myshopping.data.repository
import com.lalosoft.myshopping.domain.Item
import com.lalosoft.myshopping.domain.repository.ItemDataCallback
import com.lalosoft.myshopping.domain.repository.ItemRepository
import org.json.JSONObject
class CloudItemRepository : BaseCloudRepository(), ItemRepository {
val ITEMS_URL = "$HOST/items"
override fun getAllItems(userId: String, callback: ItemDataCallback) {
val url = ITEMS_URL + "/" + userId
api.doGetRequest(url, { apiResponse ->
if (apiResponse.success) {
callback.retrieveItemsSuccess(convertToList(apiResponse.content))
} else {
callback.retrieveItemsFailure()
}
})
}
private fun convertToList(content: String?): List<Item> {
val list = arrayListOf<Item>()
val json = JSONObject(content)
val jsonArray = json.getJSONArray("items")
var pos = 0
while (pos < jsonArray.length()) {
val jsonItem = jsonArray.getJSONObject(pos)
list.add(Item.fromJson(jsonItem.toString()))
pos++
}
return list
}
} | apache-2.0 |
JetBrains/ideavim | src/main/java/com/maddyhome/idea/vim/helper/CommandLineHelper.kt | 1 | 2882 | /*
* Copyright 2003-2022 The IdeaVim authors
*
* Use of this source code is governed by an MIT-style
* license that can be found in the LICENSE.txt file or at
* https://opensource.org/licenses/MIT.
*/
package com.maddyhome.idea.vim.helper
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.maddyhome.idea.vim.action.change.Extension
import com.maddyhome.idea.vim.api.VimEditor
import com.maddyhome.idea.vim.newapi.ij
import com.maddyhome.idea.vim.newapi.vim
import com.maddyhome.idea.vim.ui.ModalEntry
import com.maddyhome.idea.vim.ui.ex.ExEntryPanel
import java.awt.event.KeyEvent
import javax.swing.KeyStroke
@Service
class CommandLineHelper : VimCommandLineHelper {
override fun inputString(vimEditor: VimEditor, prompt: String, finishOn: Char?): String? {
val editor = vimEditor.ij
if (vimEditor.vimStateMachine.isDotRepeatInProgress) {
val input = Extension.consumeString()
return input ?: error("Not enough strings saved: ${Extension.lastExtensionHandler}")
}
if (ApplicationManager.getApplication().isUnitTestMode) {
val builder = StringBuilder()
val inputModel = TestInputModel.getInstance(editor)
var key: KeyStroke? = inputModel.nextKeyStroke()
while (key != null &&
!key.isCloseKeyStroke() && key.keyCode != KeyEvent.VK_ENTER &&
(finishOn == null || key.keyChar != finishOn)
) {
val c = key.keyChar
if (c != KeyEvent.CHAR_UNDEFINED) {
builder.append(c)
}
key = inputModel.nextKeyStroke()
}
if (finishOn != null && key != null && key.keyChar == finishOn) {
builder.append(key.keyChar)
}
Extension.addString(builder.toString())
return builder.toString()
} else {
var text: String? = null
// XXX: The Ex entry panel is used only for UI here, its logic might be inappropriate for input()
val exEntryPanel = ExEntryPanel.getInstanceWithoutShortcuts()
exEntryPanel.activate(editor, EditorDataContext.init(editor), prompt.ifEmpty { " " }, "", 1)
ModalEntry.activate(editor.vim) { key: KeyStroke ->
return@activate when {
key.isCloseKeyStroke() -> {
exEntryPanel.deactivate(true)
false
}
key.keyCode == KeyEvent.VK_ENTER -> {
text = exEntryPanel.text
exEntryPanel.deactivate(true)
false
}
finishOn != null && key.keyChar == finishOn -> {
exEntryPanel.handleKey(key)
text = exEntryPanel.text
exEntryPanel.deactivate(true)
false
}
else -> {
exEntryPanel.handleKey(key)
true
}
}
}
if (text != null) {
Extension.addString(text!!)
}
return text
}
}
}
| mit |
JStege1206/AdventOfCode | aoc-common/src/test/kotlin/nl/jstege/adventofcode/aoccommon/utils/extensions/IterableExtensionsTest.kt | 1 | 287 | package nl.jstege.adventofcode.aoccommon.utils.extensions
import org.junit.Test
import kotlin.test.assertEquals
/**
*
* @author Jelle Stege
*/
class IterableExtensionsTest {
@Test
fun testScan() {
assertEquals(listOf(0, 1, 3, 6), (1..3).scan(0, Int::plus))
}
}
| mit |
edwardharks/Aircraft-Recognition | androidcommon/src/main/kotlin/com/edwardharker/aircraftrecognition/repository/realm/model/RealmAircraftFilterOption.kt | 1 | 337 | package com.edwardharker.aircraftrecognition.repository.realm.model
import androidx.annotation.Keep
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
@Keep
open class RealmAircraftFilterOption(
@PrimaryKey open var id: String = "",
open var name: String = "",
open var value: String = ""
) : RealmObject()
| gpl-3.0 |
wordpress-mobile/WordPress-Android | WordPress/src/main/java/org/wordpress/android/ui/activitylog/list/HeaderItemViewHolder.kt | 1 | 438 | package org.wordpress.android.ui.activitylog.list
import android.view.ViewGroup
import android.widget.TextView
import org.wordpress.android.R
class HeaderItemViewHolder(parent: ViewGroup) : ActivityLogViewHolder(parent, R.layout.activity_log_list_header_item) {
private val header: TextView = itemView.findViewById(R.id.activity_header_text)
fun bind(item: ActivityLogListItem.Header) {
header.text = item.text
}
}
| gpl-2.0 |
fengzhizi715/SAF-Kotlin-Utils | saf-kotlin-utils/src/main/java/com/safframework/utils/AppUtils.kt | 1 | 5406 | package com.safframework.utils
import android.app.ActivityManager
import android.app.ActivityManager.MemoryInfo
import android.app.ActivityManager.RunningAppProcessInfo
import android.content.Context
import android.content.pm.PackageManager
import android.util.Log
import com.safframework.tony.common.reflect.Reflect
import java.lang.reflect.InvocationTargetException
/**
* Created by tony on 2017/2/26.
*/
private var mContext: Context? = null
/**
* 获取全局的context,也就是Application Context
* @return
*/
fun getApplicationContext(): Context? {
if (mContext == null) {
mContext = Reflect.on("android.app.ActivityThread").call("currentApplication").get()
}
return mContext
}
/**
* 获取手机系统SDK版本
*
* @return
*/
fun getSDKVersion(): Int = android.os.Build.VERSION.SDK_INT
/**
* 是否Dalvik模式
*
* @return 结果
*/
fun isDalvik(): Boolean = "Dalvik" == getCurrentRuntimeValue()
/**
* 是否ART模式
*
* @return 结果
*/
fun isART(): Boolean {
val currentRuntime = getCurrentRuntimeValue()
return "ART" == currentRuntime || "ART debug build" == currentRuntime
}
/**
* 获取手机当前的Runtime
*
* @return 正常情况下可能取值Dalvik, ART, ART debug build;
*/
fun getCurrentRuntimeValue(): String {
try {
val systemProperties = Class.forName("android.os.SystemProperties")
try {
val get = systemProperties.getMethod("get",
String::class.java, String::class.java) ?: return "WTF?!"
try {
val value = get.invoke(
systemProperties, "persist.sys.dalvik.vm.lib",
/* Assuming default is */"Dalvik") as String
if ("libdvm.so" == value) {
return "Dalvik"
} else if ("libart.so" == value) {
return "ART"
} else if ("libartd.so" == value) {
return "ART debug build"
}
return value
} catch (e: IllegalAccessException) {
return "IllegalAccessException"
} catch (e: IllegalArgumentException) {
return "IllegalArgumentException"
} catch (e: InvocationTargetException) {
return "InvocationTargetException"
}
} catch (e: NoSuchMethodException) {
return "SystemProperties.get(String key, String def) method is not found"
}
} catch (e: ClassNotFoundException) {
return "SystemProperties class is not found"
}
}
/**
* 获取设备的可用内存大小,单位是M
*
* @param context 应用上下文对象context
* @return 当前内存大小
*/
fun getDeviceUsableMemory(context: Context): Long {
val am = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val mi = MemoryInfo()
am.getMemoryInfo(mi)
// 返回当前系统的可用内存
return mi.availMem / (1024 * 1024)
}
/**
* 清理后台进程与服务
* @param context 应用上下文对象context
*
* @return 被清理的数量
*/
fun gc(context: Context): Int {
val i = getDeviceUsableMemory(context)
var count = 0 // 清理掉的进程数
val am = context
.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
// 获取正在运行的service列表
val serviceList = am.getRunningServices(100)
if (serviceList != null)
for (service in serviceList) {
if (service.pid === android.os.Process.myPid())
continue
try {
android.os.Process.killProcess(service.pid)
count++
} catch (e: Exception) {
e.message
}
}
// 获取正在运行的进程列表
val processList = am.runningAppProcesses
if (processList != null)
for (process in processList) {
// 一般数值大于RunningAppProcessInfo.IMPORTANCE_SERVICE的进程都长时间没用或者空进程了
// 一般数值大于RunningAppProcessInfo.IMPORTANCE_VISIBLE的进程都是非可见进程,也就是在后台运行着
if (process.importance > RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
// pkgList 得到该进程下运行的包名
val pkgList = process.pkgList
for (pkgName in pkgList) {
Log.d("AppUtils", "======正在杀死包名:" + pkgName)
try {
am.killBackgroundProcesses(pkgName)
count++
} catch (e: Exception) { // 防止意外发生
e.message
}
}
}
}
Log.d("AppUtils", "清理了" + (getDeviceUsableMemory(context) - i) + "M内存")
return count
}
/**
* 检查某个权限是否开启
*
* @param permission
* @return true or false
*/
fun checkPermission(context: Context, permission: String): Boolean {
if (!isMOrHigher()) {
val localPackageManager = context.applicationContext.packageManager
return localPackageManager.checkPermission(permission, context.applicationContext.packageName) == PackageManager.PERMISSION_GRANTED
} else {
return context.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
}
}
| apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/base/project-structure/src/org/jetbrains/kotlin/idea/base/projectStructure/KotlinBaseProjectStructureBundle.kt | 7 | 663 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.base.projectStructure
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import org.jetbrains.annotations.PropertyKey
import org.jetbrains.kotlin.util.AbstractKotlinBundle
@NonNls
private const val BUNDLE = "messages.KotlinBaseProjectStructureBundle"
object KotlinBaseProjectStructureBundle : AbstractKotlinBundle(BUNDLE) {
@Nls
@JvmStatic
fun message(@NonNls @PropertyKey(resourceBundle = BUNDLE) key: String, vararg params: Any): String = getMessage(key, *params)
} | apache-2.0 |
ingokegel/intellij-community | plugins/kotlin/jvm-debugger/test/testData/stepping/custom/initBlocks.kt | 12 | 169 | package initBlocks
class Foo {
init {
//Breakpoint!
val a = 5
}
init {
val b = 7
}
}
fun main() {
Foo()
}
// STEP_OVER: 7 | apache-2.0 |
kelsos/mbrc | app/src/main/kotlin/com/kelsos/mbrc/utilities/RemoteViewIntentBuilder.kt | 1 | 2566 | package com.kelsos.mbrc.utilities
import android.app.PendingIntent
import android.app.PendingIntent.FLAG_UPDATE_CURRENT
import android.content.Context
import android.content.Intent
import androidx.annotation.IntDef
import com.kelsos.mbrc.ui.navigation.main.MainActivity
object RemoteViewIntentBuilder {
const val REMOTE_PLAY_PRESSED = "com.kelsos.mbrc.notification.play"
const val REMOTE_NEXT_PRESSED = "com.kelsos.mbrc.notification.next"
const val REMOTE_CLOSE_PRESSED = "com.kelsos.mbrc.notification.close"
const val REMOTE_PREVIOUS_PRESSED = "com.kelsos.mbrc.notification.previous"
const val CANCELLED_NOTIFICATION = "com.kelsos.mbrc.notification.cancel"
const val OPEN = 0
const val PLAY = 1
const val NEXT = 2
const val CLOSE = 3
const val PREVIOUS = 4
const val CANCEL = 5
fun getPendingIntent(@ButtonAction id: Int, mContext: Context): PendingIntent {
when (id) {
OPEN -> {
val notificationIntent = Intent(mContext, MainActivity::class.java)
return PendingIntent.getActivity(
mContext,
0,
notificationIntent,
FLAG_UPDATE_CURRENT
)
}
PLAY -> {
val playPressedIntent = Intent(REMOTE_PLAY_PRESSED)
return PendingIntent.getBroadcast(
mContext,
1,
playPressedIntent,
FLAG_UPDATE_CURRENT
)
}
NEXT -> {
val mediaNextButtonIntent = Intent(REMOTE_NEXT_PRESSED)
return PendingIntent.getBroadcast(
mContext,
2,
mediaNextButtonIntent,
FLAG_UPDATE_CURRENT
)
}
CLOSE -> {
val clearNotificationIntent = Intent(REMOTE_CLOSE_PRESSED)
return PendingIntent.getBroadcast(
mContext,
3,
clearNotificationIntent,
FLAG_UPDATE_CURRENT
)
}
PREVIOUS -> {
val mediaPreviousButtonIntent = Intent(REMOTE_PREVIOUS_PRESSED)
return PendingIntent.getBroadcast(
mContext,
4,
mediaPreviousButtonIntent,
FLAG_UPDATE_CURRENT
)
}
CANCEL -> {
val cancelIntent = Intent(CANCELLED_NOTIFICATION)
return PendingIntent.getBroadcast(
mContext,
4,
cancelIntent,
FLAG_UPDATE_CURRENT
)
}
else -> throw IndexOutOfBoundsException()
}
}
@IntDef(
OPEN,
PLAY,
CLOSE,
PREVIOUS,
NEXT,
CANCEL
)
@kotlin.annotation.Retention(AnnotationRetention.SOURCE)
annotation class ButtonAction
}
| gpl-3.0 |
ingokegel/intellij-community | plugins/kotlin/uast/uast-kotlin-base/src/org/jetbrains/uast/kotlin/controlStructures/KotlinUWhileExpression.kt | 4 | 953 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.uast.kotlin
import org.jetbrains.annotations.ApiStatus
import org.jetbrains.kotlin.psi.KtWhileExpression
import org.jetbrains.uast.UElement
import org.jetbrains.uast.UIdentifier
import org.jetbrains.uast.UWhileExpression
@ApiStatus.Internal
class KotlinUWhileExpression(
override val sourcePsi: KtWhileExpression,
givenParent: UElement?
) : KotlinAbstractUExpression(givenParent), UWhileExpression {
override val condition by lz {
baseResolveProviderService.baseKotlinConverter.convertOrEmpty(sourcePsi.condition, this)
}
override val body by lz {
baseResolveProviderService.baseKotlinConverter.convertOrEmpty(sourcePsi.body, this)
}
override val whileIdentifier: UIdentifier
get() = KotlinUIdentifier(null, this)
}
| apache-2.0 |
micolous/metrodroid | src/main/java/au/id/micolous/metrodroid/ui/TabPagerAdapter.kt | 1 | 2964 | /*
* TabPagerAdapter.kt
*
* Copyright (C) 2011 Eric Butler <[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/>.
*/
package au.id.micolous.metrodroid.ui
import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Parcelable
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentPagerAdapter
import androidx.fragment.app.FragmentTransaction
import androidx.viewpager.widget.ViewPager
import au.id.micolous.metrodroid.multi.Localizer
class TabPagerAdapter(private val mActivity: AppCompatActivity, private val mViewPager: ViewPager) : FragmentPagerAdapter(mActivity.supportFragmentManager) {
private val mTabs = ArrayList<TabInfo>()
private var mCurTransaction: FragmentTransaction? = null
init {
mViewPager.adapter = this
}
fun addTab(nameResource: Int, clss: Class<*>, args: Bundle?) {
val info = TabInfo(clss, args, Localizer.localizeString(nameResource))
mTabs.add(info)
notifyDataSetChanged()
}
override fun getCount(): Int = mTabs.size
override fun startUpdate(view: View) {}
override fun getItem(p0: Int): Fragment {
val info = mTabs[p0]
return Fragment.instantiate(mActivity, info.mClass.name, info.mArgs)
}
override fun getPageTitle(p0: Int): CharSequence = mTabs[p0].mName
@SuppressLint("CommitTransaction")
override fun destroyItem(view: View, i: Int, obj: Any) {
if (mCurTransaction == null) {
mCurTransaction = mActivity.supportFragmentManager.beginTransaction()
}
mCurTransaction!!.hide(obj as Fragment)
}
override fun finishUpdate(view: View) {
if (mCurTransaction != null) {
mCurTransaction?.commitAllowingStateLoss()
mCurTransaction = null
mActivity.supportFragmentManager.executePendingTransactions()
}
}
override fun isViewFromObject(view: View, obj: Any): Boolean {
return (obj as Fragment).view === view
}
override fun saveState(): Parcelable? = null
override fun restoreState(parcelable: Parcelable?, classLoader: ClassLoader?) {}
private class TabInfo internal constructor(internal val mClass: Class<*>, internal val mArgs: Bundle?, internal val mName: String)
}
| gpl-3.0 |
android/nowinandroid | feature/foryou/src/main/java/com/google/samples/apps/nowinandroid/feature/foryou/ForYouScreen.kt | 1 | 20090 | /*
* 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.
*/
package com.google.samples.apps.nowinandroid.feature.foryou
import android.app.Activity
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInVertically
import androidx.compose.animation.slideOutVertically
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.safeDrawing
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsBottomHeight
import androidx.compose.foundation.lazy.LazyListScope
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridCells.Adaptive
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridScope
import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.layout.layout
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.max
import androidx.compose.ui.unit.sp
import androidx.compose.ui.util.trace
import androidx.core.view.doOnPreDraw
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.ExperimentalLifecycleComposeApi
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import coil.compose.AsyncImage
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaFilledButton
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaOverlayLoadingWheel
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaToggleButton
import com.google.samples.apps.nowinandroid.core.designsystem.icon.NiaIcons
import com.google.samples.apps.nowinandroid.core.designsystem.theme.NiaTheme
import com.google.samples.apps.nowinandroid.core.domain.model.FollowableAuthor
import com.google.samples.apps.nowinandroid.core.domain.model.FollowableTopic
import com.google.samples.apps.nowinandroid.core.domain.model.SaveableNewsResource
import com.google.samples.apps.nowinandroid.core.model.data.previewAuthors
import com.google.samples.apps.nowinandroid.core.model.data.previewNewsResources
import com.google.samples.apps.nowinandroid.core.model.data.previewTopics
import com.google.samples.apps.nowinandroid.core.ui.DevicePreviews
import com.google.samples.apps.nowinandroid.core.ui.NewsFeedUiState
import com.google.samples.apps.nowinandroid.core.ui.TrackScrollJank
import com.google.samples.apps.nowinandroid.core.ui.newsFeed
@OptIn(ExperimentalLifecycleComposeApi::class)
@Composable
internal fun ForYouRoute(
modifier: Modifier = Modifier,
viewModel: ForYouViewModel = hiltViewModel()
) {
val onboardingUiState by viewModel.onboardingUiState.collectAsStateWithLifecycle()
val feedState by viewModel.feedState.collectAsStateWithLifecycle()
val isSyncing by viewModel.isSyncing.collectAsStateWithLifecycle()
ForYouScreen(
isSyncing = isSyncing,
onboardingUiState = onboardingUiState,
feedState = feedState,
onTopicCheckedChanged = viewModel::updateTopicSelection,
onAuthorCheckedChanged = viewModel::updateAuthorSelection,
saveFollowedTopics = viewModel::dismissOnboarding,
onNewsResourcesCheckedChanged = viewModel::updateNewsResourceSaved,
modifier = modifier
)
}
@Composable
internal fun ForYouScreen(
isSyncing: Boolean,
onboardingUiState: OnboardingUiState,
feedState: NewsFeedUiState,
onTopicCheckedChanged: (String, Boolean) -> Unit,
onAuthorCheckedChanged: (String, Boolean) -> Unit,
saveFollowedTopics: () -> Unit,
onNewsResourcesCheckedChanged: (String, Boolean) -> Unit,
modifier: Modifier = Modifier,
) {
// Workaround to call Activity.reportFullyDrawn from Jetpack Compose.
// This code should be called when the UI is ready for use
// and relates to Time To Full Display.
val onboardingLoaded =
onboardingUiState !is OnboardingUiState.Loading
val feedLoaded = feedState !is NewsFeedUiState.Loading
if (onboardingLoaded && feedLoaded) {
val localView = LocalView.current
// We use Unit to call reportFullyDrawn only on the first recomposition,
// however it will be called again if this composable goes out of scope.
// Activity.reportFullyDrawn() has its own check for this
// and is safe to call multiple times though.
LaunchedEffect(Unit) {
// We're leveraging the fact, that the current view is directly set as content of Activity.
val activity = localView.context as? Activity ?: return@LaunchedEffect
// To be sure not to call in the middle of a frame draw.
localView.doOnPreDraw { activity.reportFullyDrawn() }
}
}
val state = rememberLazyGridState()
TrackScrollJank(scrollableState = state, stateName = "forYou:feed")
LazyVerticalGrid(
columns = Adaptive(300.dp),
contentPadding = PaddingValues(16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalArrangement = Arrangement.spacedBy(24.dp),
modifier = modifier
.fillMaxSize()
.testTag("forYou:feed"),
state = state
) {
onboarding(
onboardingUiState = onboardingUiState,
onAuthorCheckedChanged = onAuthorCheckedChanged,
onTopicCheckedChanged = onTopicCheckedChanged,
saveFollowedTopics = saveFollowedTopics,
// Custom LayoutModifier to remove the enforced parent 16.dp contentPadding
// from the LazyVerticalGrid and enable edge-to-edge scrolling for this section
interestsItemModifier = Modifier.layout { measurable, constraints ->
val placeable = measurable.measure(
constraints.copy(
maxWidth = constraints.maxWidth + 32.dp.roundToPx()
)
)
layout(placeable.width, placeable.height) {
placeable.place(0, 0)
}
}
)
newsFeed(
feedState = feedState,
onNewsResourcesCheckedChanged = onNewsResourcesCheckedChanged,
)
item(span = { GridItemSpan(maxLineSpan) }) {
Column {
Spacer(modifier = Modifier.height(8.dp))
// Add space for the content to clear the "offline" snackbar.
// TODO: Check that the Scaffold handles this correctly in NiaApp
// if (isOffline) Spacer(modifier = Modifier.height(48.dp))
Spacer(Modifier.windowInsetsBottomHeight(WindowInsets.safeDrawing))
}
}
}
AnimatedVisibility(
visible = isSyncing ||
feedState is NewsFeedUiState.Loading ||
onboardingUiState is OnboardingUiState.Loading,
enter = slideInVertically(
initialOffsetY = { fullHeight -> -fullHeight },
) + fadeIn(),
exit = slideOutVertically(
targetOffsetY = { fullHeight -> -fullHeight },
) + fadeOut(),
) {
val loadingContentDescription = stringResource(id = R.string.for_you_loading)
Box(
modifier = Modifier.fillMaxWidth()
) {
NiaOverlayLoadingWheel(
modifier = Modifier.align(Alignment.Center),
contentDesc = loadingContentDescription
)
}
}
}
/**
* An extension on [LazyListScope] defining the onboarding portion of the for you screen.
* Depending on the [onboardingUiState], this might emit no items.
*
*/
private fun LazyGridScope.onboarding(
onboardingUiState: OnboardingUiState,
onAuthorCheckedChanged: (String, Boolean) -> Unit,
onTopicCheckedChanged: (String, Boolean) -> Unit,
saveFollowedTopics: () -> Unit,
interestsItemModifier: Modifier = Modifier
) {
when (onboardingUiState) {
OnboardingUiState.Loading,
OnboardingUiState.LoadFailed,
OnboardingUiState.NotShown -> Unit
is OnboardingUiState.Shown -> {
item(span = { GridItemSpan(maxLineSpan) }) {
Column(modifier = interestsItemModifier) {
Text(
text = stringResource(R.string.onboarding_guidance_title),
textAlign = TextAlign.Center,
modifier = Modifier
.fillMaxWidth()
.padding(top = 24.dp),
style = MaterialTheme.typography.titleMedium
)
Text(
text = stringResource(R.string.onboarding_guidance_subtitle),
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp, start = 16.dp, end = 16.dp),
textAlign = TextAlign.Center,
style = MaterialTheme.typography.bodyMedium
)
AuthorsCarousel(
authors = onboardingUiState.authors,
onAuthorClick = onAuthorCheckedChanged,
modifier = Modifier
.fillMaxWidth()
.padding(vertical = 8.dp)
)
TopicSelection(
onboardingUiState,
onTopicCheckedChanged,
Modifier.padding(bottom = 8.dp)
)
// Done button
Row(
horizontalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxWidth()
) {
NiaFilledButton(
onClick = saveFollowedTopics,
enabled = onboardingUiState.isDismissable,
modifier = Modifier
.padding(horizontal = 40.dp)
.width(364.dp)
) {
Text(
text = stringResource(R.string.done)
)
}
}
}
}
}
}
}
@Composable
private fun TopicSelection(
onboardingUiState: OnboardingUiState.Shown,
onTopicCheckedChanged: (String, Boolean) -> Unit,
modifier: Modifier = Modifier
) = trace("TopicSelection") {
val lazyGridState = rememberLazyGridState()
TrackScrollJank(scrollableState = lazyGridState, stateName = "forYou:TopicSelection")
LazyHorizontalGrid(
state = lazyGridState,
rows = GridCells.Fixed(3),
horizontalArrangement = Arrangement.spacedBy(12.dp),
verticalArrangement = Arrangement.spacedBy(12.dp),
contentPadding = PaddingValues(24.dp),
modifier = modifier
// LazyHorizontalGrid has to be constrained in height.
// However, we can't set a fixed height because the horizontal grid contains
// vertical text that can be rescaled.
// When the fontScale is at most 1, we know that the horizontal grid will be at most
// 240dp tall, so this is an upper bound for when the font scale is at most 1.
// When the fontScale is greater than 1, the height required by the text inside the
// horizontal grid will increase by at most the same factor, so 240sp is a valid
// upper bound for how much space we need in that case.
// The maximum of these two bounds is therefore a valid upper bound in all cases.
.heightIn(max = max(240.dp, with(LocalDensity.current) { 240.sp.toDp() }))
.fillMaxWidth()
) {
items(onboardingUiState.topics) {
SingleTopicButton(
name = it.topic.name,
topicId = it.topic.id,
imageUrl = it.topic.imageUrl,
isSelected = it.isFollowed,
onClick = onTopicCheckedChanged
)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun SingleTopicButton(
name: String,
topicId: String,
imageUrl: String,
isSelected: Boolean,
onClick: (String, Boolean) -> Unit
) = trace("SingleTopicButton") {
Surface(
modifier = Modifier
.width(312.dp)
.heightIn(min = 56.dp),
shape = RoundedCornerShape(corner = CornerSize(8.dp)),
color = MaterialTheme.colorScheme.surface,
selected = isSelected,
onClick = {
onClick(topicId, !isSelected)
}
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(start = 12.dp, end = 8.dp)
) {
TopicIcon(
imageUrl = imageUrl
)
Text(
text = name,
style = MaterialTheme.typography.titleSmall,
modifier = Modifier
.padding(horizontal = 12.dp)
.weight(1f),
color = MaterialTheme.colorScheme.onSurface
)
NiaToggleButton(
checked = isSelected,
onCheckedChange = { checked -> onClick(topicId, checked) },
icon = {
Icon(
imageVector = NiaIcons.Add,
contentDescription = name
)
},
checkedIcon = {
Icon(
imageVector = NiaIcons.Check,
contentDescription = name
)
}
)
}
}
}
@Composable
fun TopicIcon(
imageUrl: String,
modifier: Modifier = Modifier
) {
AsyncImage(
// TODO b/228077205, show loading image visual instead of static placeholder
placeholder = painterResource(R.drawable.ic_icon_placeholder),
model = imageUrl,
contentDescription = null, // decorative
colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.primary),
modifier = modifier
.padding(10.dp)
.size(32.dp)
)
}
@DevicePreviews
@Composable
fun ForYouScreenPopulatedFeed() {
BoxWithConstraints {
NiaTheme {
ForYouScreen(
isSyncing = false,
onboardingUiState = OnboardingUiState.NotShown,
feedState = NewsFeedUiState.Success(
feed = previewNewsResources.map {
SaveableNewsResource(it, false)
}
),
onTopicCheckedChanged = { _, _ -> },
onAuthorCheckedChanged = { _, _ -> },
saveFollowedTopics = {},
onNewsResourcesCheckedChanged = { _, _ -> }
)
}
}
}
@DevicePreviews
@Composable
fun ForYouScreenOfflinePopulatedFeed() {
BoxWithConstraints {
NiaTheme {
ForYouScreen(
isSyncing = false,
onboardingUiState = OnboardingUiState.NotShown,
feedState = NewsFeedUiState.Success(
feed = previewNewsResources.map {
SaveableNewsResource(it, false)
}
),
onTopicCheckedChanged = { _, _ -> },
onAuthorCheckedChanged = { _, _ -> },
saveFollowedTopics = {},
onNewsResourcesCheckedChanged = { _, _ -> }
)
}
}
}
@DevicePreviews
@Composable
fun ForYouScreenTopicSelection() {
BoxWithConstraints {
NiaTheme {
ForYouScreen(
isSyncing = false,
onboardingUiState = OnboardingUiState.Shown(
topics = previewTopics.map { FollowableTopic(it, false) },
authors = previewAuthors.map { FollowableAuthor(it, false) }
),
feedState = NewsFeedUiState.Success(
feed = previewNewsResources.map {
SaveableNewsResource(it, false)
}
),
onTopicCheckedChanged = { _, _ -> },
onAuthorCheckedChanged = { _, _ -> },
saveFollowedTopics = {},
onNewsResourcesCheckedChanged = { _, _ -> }
)
}
}
}
@DevicePreviews
@Composable
fun ForYouScreenLoading() {
BoxWithConstraints {
NiaTheme {
ForYouScreen(
isSyncing = false,
onboardingUiState = OnboardingUiState.Loading,
feedState = NewsFeedUiState.Loading,
onTopicCheckedChanged = { _, _ -> },
onAuthorCheckedChanged = { _, _ -> },
saveFollowedTopics = {},
onNewsResourcesCheckedChanged = { _, _ -> }
)
}
}
}
@DevicePreviews
@Composable
fun ForYouScreenPopulatedAndLoading() {
BoxWithConstraints {
NiaTheme {
ForYouScreen(
isSyncing = true,
onboardingUiState = OnboardingUiState.Loading,
feedState = NewsFeedUiState.Success(
feed = previewNewsResources.map {
SaveableNewsResource(it, false)
}
),
onTopicCheckedChanged = { _, _ -> },
onAuthorCheckedChanged = { _, _ -> },
saveFollowedTopics = {},
onNewsResourcesCheckedChanged = { _, _ -> }
)
}
}
}
| apache-2.0 |
squanchy-dev/squanchy-android | app/src/test/java/net/squanchy/service/firebase/FirestoreEventMapperTest.kt | 1 | 5963 | package net.squanchy.service.firebase
import com.google.common.truth.Truth.assertThat
import com.google.firebase.Timestamp
import net.squanchy.A_DATE
import net.squanchy.A_TIMEZONE
import net.squanchy.eventdetails.domain.view.ExperienceLevel
import net.squanchy.schedule.domain.view.Event
import net.squanchy.support.checksum.Checksum
import net.squanchy.support.lang.getOrThrow
import net.squanchy.support.toDate
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnit
import org.mockito.junit.MockitoRule
private const val A_VALUE = "whatever"
private const val A_CHECKSUM = 1000L
private const val FAKE_TYPE = "social"
private const val FAKE_EXPERIENCE_LEVEL = "intermediate"
class FirestoreEventMapperTest {
@Rule
@JvmField
var rule: MockitoRule = MockitoJUnit.rule()
@Mock
private lateinit var checksum: Checksum
@Before
fun before() {
`when`(checksum.getChecksumOf(A_VALUE)).thenReturn(A_CHECKSUM)
}
@Test
fun `event id should match when mapped`() {
val firestoreEvent = aFirestoreEvent(id = A_VALUE)
val event = firestoreEvent.toEvent(checksum, A_TIMEZONE)
assertThat(event.id).isEqualTo(A_VALUE)
}
@Test
fun `event start date should match when mapped`() {
val firestoreEvent = aFirestoreEvent(startTime = Timestamp(A_DATE.toDate()))
val event = firestoreEvent.toEvent(checksum, A_TIMEZONE)
assertThat(event.startTime).isEqualTo(A_DATE.withZoneSameInstant(A_TIMEZONE).toLocalDateTime())
}
@Test
fun `event end date should match when mapped`() {
val firestoreEvent = aFirestoreEvent(endTime = Timestamp(A_DATE.toDate()))
val event = firestoreEvent.toEvent(checksum, A_TIMEZONE)
assertThat(event.endTime).isEqualTo(A_DATE.withZoneSameInstant(A_TIMEZONE).toLocalDateTime())
}
@Test
fun `event title should match when mapped`() {
val firestoreEvent = aFirestoreEvent(title = A_VALUE)
val event = firestoreEvent.toEvent(checksum, A_TIMEZONE)
assertThat(event.title).isEqualTo(A_VALUE)
}
@Test
fun `event place should match when mapped`() {
val firestorePlace = aFirestorePlace()
val firestoreEvent = aFirestoreEvent(place = firestorePlace)
val event = firestoreEvent.toEvent(checksum, A_TIMEZONE)
assertThat(firestorePlace.toPlace()).isEqualTo(event.place.getOrThrow())
}
@Test
fun `event place should be empty when mapping null`() {
val firestoreEvent = aFirestoreEvent(place = null)
val event = firestoreEvent.toEvent(checksum, A_TIMEZONE)
assertThat(event.place.isEmpty()).isTrue()
}
@Test
fun `event track should match when mapped`() {
val firestoreTrack = aFirestoreTrack()
val firestoreEvent = aFirestoreEvent(track = firestoreTrack)
val event = firestoreEvent.toEvent(checksum, A_TIMEZONE)
assertThat(firestoreTrack.toTrack(checksum)).isEqualTo(event.track.getOrThrow())
}
@Test
fun `event track should be empty when mapping null`() {
val firestoreEvent = aFirestoreEvent(track = null)
val event = firestoreEvent.toEvent(checksum, A_TIMEZONE)
assertThat(event.track.isEmpty()).isTrue()
}
@Test
fun `event experience level should match when mapped`() {
val firestoreEvent = aFirestoreEvent(experienceLevel = FAKE_EXPERIENCE_LEVEL)
val event = firestoreEvent.toEvent(checksum, A_TIMEZONE)
assertThat(ExperienceLevel.tryParsingFrom(FAKE_EXPERIENCE_LEVEL)).isEqualTo(event.experienceLevel)
}
@Test
fun `event experience level should be empty when mapping null`() {
val firestoreEvent = aFirestoreEvent(experienceLevel = null)
val event = firestoreEvent.toEvent(checksum, A_TIMEZONE)
assertThat(event.experienceLevel.isEmpty()).isTrue()
}
@Test
fun `event timezone should match the parameter when mapped`() {
val firestoreEvent = aFirestoreEvent()
val event = firestoreEvent.toEvent(checksum, A_TIMEZONE)
assertThat(event.timeZone).isEqualTo(A_TIMEZONE)
}
@Test
fun `event description should match when mapped`() {
val firestoreEvent = aFirestoreEvent(description = A_VALUE)
val event = firestoreEvent.toEvent(checksum, A_TIMEZONE)
assertThat(event.description.getOrThrow()).isEqualTo(A_VALUE)
}
@Test
fun `event description should be empty when mapping null`() {
val firestoreEvent = aFirestoreEvent(description = null)
val event = firestoreEvent.toEvent(checksum, A_TIMEZONE)
assertThat(event.description.isEmpty()).isTrue()
}
@Test
fun `event type should match when mapped`() {
val firestoreEvent = aFirestoreEvent(type = FAKE_TYPE)
val event = firestoreEvent.toEvent(checksum, A_TIMEZONE)
assertThat(Event.Type.fromRawType(FAKE_TYPE)).isEqualTo(event.type)
}
@Test
fun `place floor should match when mapped`() {
val firestorePlace = aFirestorePlace()
val place = firestorePlace.toPlace()
assertThat(place.floor.getOrThrow()).isEqualTo(firestorePlace.floor)
}
@Test
fun `place floor should be empty when mapping null`() {
val firestorePlace = aFirestorePlace(floor = null)
val place = firestorePlace.toPlace()
assertThat(place.floor.isEmpty()).isTrue()
}
@Test
fun `place id should match when mapped`() {
val firestorePlace = aFirestorePlace()
val place = firestorePlace.toPlace()
assertThat(place.id).isEqualTo(firestorePlace.id)
}
@Test
fun `place name should match when mapped`() {
val firestorePlace = aFirestorePlace()
val place = firestorePlace.toPlace()
assertThat(place.name).isEqualTo(firestorePlace.name)
}
}
| apache-2.0 |
FlexSeries/FlexLib | src/main/kotlin/me/st28/flexseries/flexlib/command/argument/ArgumentParseException.kt | 1 | 1329 | /**
* Copyright 2016 Stealth2800 <http://stealthyone.com/>
* Copyright 2016 Contributors <https://github.com/FlexSeries>
*
* 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 me.st28.flexseries.flexlib.command.argument
import me.st28.flexseries.flexlib.message.Message
import me.st28.flexseries.flexlib.plugin.FlexPlugin
import kotlin.reflect.KClass
class ArgumentParseException : RuntimeException {
val errorMessage: Message
constructor(message: Message) {
errorMessage = message
}
constructor(message: String, vararg replacements: Any?) {
errorMessage = Message.getGlobal(message, *replacements)
}
constructor(plugin: KClass<out FlexPlugin>, message: String, vararg replacements: Any?) {
errorMessage = Message.get(plugin, message, *replacements)
}
}
| apache-2.0 |
iPoli/iPoli-android | app/src/main/java/io/ipoli/android/store/gem/GemStoreViewController.kt | 1 | 10943 | package io.ipoli.android.store.gem
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import com.android.billingclient.api.BillingClient
import com.android.billingclient.api.BillingClient.SkuType
import com.android.billingclient.api.BillingClient.newBuilder
import com.android.billingclient.api.BillingFlowParams
import com.android.billingclient.api.Purchase
import com.android.billingclient.api.SkuDetailsParams
import com.mikepenz.google_material_typeface_library.GoogleMaterial
import com.mikepenz.iconics.IconicsDrawable
import io.ipoli.android.Constants.Companion.GEM_PACK_TYPE_TO_GEMS
import io.ipoli.android.Constants.Companion.GEM_PACK_TYPE_TO_SKU
import io.ipoli.android.Constants.Companion.SKU_TO_GEM_PACK_TYPE
import io.ipoli.android.R
import io.ipoli.android.common.billing.BillingResponseHandler
import io.ipoli.android.common.redux.android.ReduxViewController
import io.ipoli.android.common.view.*
import io.ipoli.android.player.inventory.InventoryViewController
import io.ipoli.android.store.gem.GemStoreViewState.StateType.*
import kotlinx.android.synthetic.main.controller_gem_store.view.*
import kotlinx.android.synthetic.main.view_inventory_toolbar.view.*
import space.traversal.kapsule.required
import java.util.concurrent.atomic.AtomicInteger
/**
* Created by Venelin Valkov <[email protected]>
* on 27.12.17.
*/
class GemStoreViewController(args: Bundle? = null) :
ReduxViewController<GemStoreAction, GemStoreViewState, GemStoreReducer>(
args
) {
override val reducer = GemStoreReducer
private val billingResponseHandler by required { billingResponseHandler }
private val billingRequestExecutor by required { billingRequestExecutor }
private lateinit var billingClient: BillingClient
private val failureListener = object : BillingResponseHandler.FailureListener {
override fun onCanceledByUser() {
onBillingCanceledByUser()
}
override fun onDisconnected() {
onBillingDisconnected()
}
override fun onUnavailable(responseCode: Int) {
onBillingUnavailable()
}
override fun onError(responseCode: Int) {
onBillingError()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup,
savedViewState: Bundle?
): View {
setHasOptionsMenu(true)
val view = inflater.inflate(R.layout.controller_gem_store, container, false)
setToolbar(view.toolbar)
view.toolbarTitle.setText(R.string.gem_store)
setChildController(
view.playerGems,
InventoryViewController(showCurrencyConverter = false)
)
view.mostPopular.setCompoundDrawablesWithIntrinsicBounds(
IconicsDrawable(view.context)
.icon(GoogleMaterial.Icon.gmd_favorite)
.colorRes(R.color.md_white)
.sizeDp(24),
null, null, null
)
billingClient =
newBuilder(activity!!).setListener { responseCode, purchases ->
billingResponseHandler.handle(responseCode, {
purchases!!.forEach {
dispatch(GemStoreAction.GemPackBought(SKU_TO_GEM_PACK_TYPE[it.sku]!!))
}
consumePurchases(purchases)
}, failureListener)
}
.build()
return view
}
private fun consumePurchases(purchases: List<Purchase>?, listener: (() -> Unit)? = null) {
if (purchases == null || purchases.isEmpty()) {
listener?.invoke()
return
}
val count = AtomicInteger(0)
purchases.forEach { p ->
billingClient.execute { bc ->
bc.consumeAsync(
p.purchaseToken
) { _, _ ->
if (count.incrementAndGet() == purchases.size) {
listener?.invoke()
}
}
}
}
}
override fun onAttach(view: View) {
super.onAttach(view)
showBackButton()
billingClient.execute { bc ->
val params = SkuDetailsParams.newBuilder()
.setSkusList(GEM_PACK_TYPE_TO_SKU.values.toList())
.setType(SkuType.INAPP)
.build()
bc.querySkuDetailsAsync(params) { responseCode, skuDetailsList ->
billingResponseHandler.handle(
responseCode = responseCode,
onSuccess = {
val gemPacks = GEM_PACK_TYPE_TO_SKU.map { (k, v) ->
val sku = skuDetailsList.first { it.sku == v }
val gems = GEM_PACK_TYPE_TO_GEMS[k]!!
val titleRes = when (k) {
GemPackType.BASIC -> R.string.gem_pack_basic_title
GemPackType.SMART -> R.string.gem_pack_smart_title
GemPackType.PLATINUM -> R.string.gem_pack_platinum_title
}
val shortTitleRes = when (k) {
GemPackType.BASIC -> R.string.gem_pack_basic_title_short
GemPackType.SMART -> R.string.gem_pack_smart_title_short
GemPackType.PLATINUM -> R.string.gem_pack_platinum_title_short
}
GemPack(
stringRes(titleRes),
stringRes(shortTitleRes),
sku.price,
gems,
k
)
}
dispatch(GemStoreAction.Load(gemPacks))
},
failureListener = failureListener
)
}
}
}
private fun onBillingUnavailable() {
enableButtons()
activity?.let {
Toast.makeText(it, R.string.billing_unavailable, Toast.LENGTH_LONG).show()
}
}
private fun onBillingError() {
enableButtons()
activity?.let {
Toast.makeText(it, R.string.purchase_failed, Toast.LENGTH_LONG).show()
}
}
private fun onBillingCanceledByUser() {
enableButtons()
}
private fun onBillingDisconnected() {
enableButtons()
activity?.let {
Toast.makeText(it, R.string.billing_disconnected, Toast.LENGTH_LONG).show()
}
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
return router.handleBack()
}
return super.onOptionsItemSelected(item)
}
override fun onDetach(view: View) {
billingClient.endConnection()
super.onDetach(view)
}
override fun render(state: GemStoreViewState, view: View) {
when (state.type) {
PLAYER_CHANGED ->
if (state.isGiftPurchased)
showMostPopular(view)
GEM_PACKS_LOADED -> {
if (state.isGiftPurchased)
showMostPopular(view)
state.gemPacks.forEach {
val gp = it
when (it.type) {
GemPackType.BASIC -> {
view.basicPackPrice.text = it.price
view.basicPackTitle.text = it.title
@SuppressLint("SetTextI18n")
view.basicPackGems.text = "x ${it.gems}"
view.basicPackBuy.onDebounceClick {
disableButtons()
buyPack(gp)
}
}
GemPackType.SMART -> {
view.smartPackPrice.text = it.price
view.smartPackTitle.text = it.title
@SuppressLint("SetTextI18n")
view.smartPackGems.text = "x ${it.gems}"
view.smartPackBuy.onDebounceClick {
disableButtons()
buyPack(gp)
}
}
GemPackType.PLATINUM -> {
view.platinumPackPrice.text = it.price
view.platinumPackTitle.text = it.title
@SuppressLint("SetTextI18n")
view.platinumPackGems.text = "x ${it.gems}"
view.platinumPackBuy.onDebounceClick {
disableButtons()
buyPack(gp)
}
}
}
}
}
GEM_PACK_PURCHASED -> {
enableButtons()
Toast.makeText(view.context, R.string.gem_pack_purchased, Toast.LENGTH_LONG).show()
}
DOG_UNLOCKED -> {
showMostPopular(view)
Toast.makeText(view.context, R.string.gift_unlocked, Toast.LENGTH_LONG).show()
}
else -> {
}
}
}
private fun buyPack(gemPack: GemPack) {
val r = billingClient.queryPurchases(BillingClient.SkuType.INAPP)
billingResponseHandler.handle(r.responseCode, {
consumePurchases(r.purchasesList) {
val flowParams = BillingFlowParams.newBuilder()
.setSku(GEM_PACK_TYPE_TO_SKU[gemPack.type])
.setType(SkuType.INAPP)
.build()
billingResponseHandler.handle(
responseCode = billingClient.launchBillingFlow(activity!!, flowParams),
listener = failureListener
)
}
}, failureListener)
}
private fun enableButtons() {
view?.basicPackBuy?.enableClick()
view?.smartPackBuy?.enableClick()
view?.platinumPackBuy?.enableClick()
}
private fun disableButtons() {
view?.basicPackBuy?.disableClick()
view?.smartPackBuy?.disableClick()
view?.platinumPackBuy?.disableClick()
}
private fun showMostPopular(view: View) {
view.giftContainer.visibility = View.GONE
view.mostPopular.visibility = View.VISIBLE
}
private fun BillingClient.execute(request: (BillingClient) -> Unit) {
billingRequestExecutor.execute(this, request, failureListener)
}
} | gpl-3.0 |
JavaEden/Orchid-Core | plugins/OrchidGroovydoc/src/main/kotlin/com/eden/orchid/groovydoc/helpers/OrchidGroovydocInvoker.kt | 2 | 408 | package com.eden.orchid.groovydoc.helpers
import com.copperleaf.groovydoc.json.models.GroovydocRootdoc
import com.eden.orchid.api.options.OptionsHolder
import com.google.inject.ImplementedBy
@ImplementedBy(OrchidGroovydocInvokerImpl::class)
interface OrchidGroovydocInvoker : OptionsHolder {
fun getRootDoc(
sourceDirs: List<String>,
extraArgs: List<String>
): GroovydocRootdoc?
} | mit |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/RemoveExplicitSuperQualifierIntention.kt | 4 | 3364 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.caches.resolve.analyzeAsReplacement
import org.jetbrains.kotlin.idea.codeinsight.api.classic.intentions.SelfTargetingRangeIntention
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtSuperExpression
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForReceiver
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.error.ErrorUtils
@Suppress("DEPRECATION")
class RemoveExplicitSuperQualifierInspection : IntentionBasedInspection<KtSuperExpression>(
RemoveExplicitSuperQualifierIntention::class
), CleanupLocalInspectionTool
class RemoveExplicitSuperQualifierIntention : SelfTargetingRangeIntention<KtSuperExpression>(
KtSuperExpression::class.java,
KotlinBundle.lazyMessage("remove.explicit.supertype.qualification")
) {
override fun applicabilityRange(element: KtSuperExpression): TextRange? {
if (element.superTypeQualifier == null) return null
val qualifiedExpression = element.getQualifiedExpressionForReceiver() ?: return null
val selector = qualifiedExpression.selectorExpression ?: return null
val bindingContext = selector.analyze(BodyResolveMode.PARTIAL_WITH_CFA)
if (selector.getResolvedCall(bindingContext) == null) return null
val newQualifiedExpression = KtPsiFactory(element).createExpressionByPattern(
"$0.$1", toNonQualified(element, reformat = false), selector,
reformat = false
) as KtQualifiedExpression
val newBindingContext = newQualifiedExpression.analyzeAsReplacement(qualifiedExpression, bindingContext)
val newResolvedCall = newQualifiedExpression.selectorExpression.getResolvedCall(newBindingContext) ?: return null
if (ErrorUtils.isError(newResolvedCall.resultingDescriptor)) return null
return TextRange(element.instanceReference.endOffset, element.labelQualifier?.startOffset ?: element.endOffset)
}
override fun applyTo(element: KtSuperExpression, editor: Editor?) {
element.replace(toNonQualified(element, reformat = true))
}
private fun toNonQualified(superExpression: KtSuperExpression, reformat: Boolean): KtSuperExpression {
val factory = KtPsiFactory(superExpression)
val labelName = superExpression.getLabelNameAsName()
return (if (labelName != null)
factory.createExpressionByPattern("super@$0", labelName, reformat = reformat)
else
factory.createExpression("super")) as KtSuperExpression
}
} | apache-2.0 |
GunoH/intellij-community | plugins/evaluation-plugin/core/src/com/intellij/cce/filter/EvaluationFilterConfiguration.kt | 8 | 379 | package com.intellij.cce.filter
interface EvaluationFilterConfiguration {
interface Configurable<T> {
fun build(): EvaluationFilter
val view: T
}
val id: String
val description: String
val hasUI: Boolean
fun isLanguageSupported(languageName: String): Boolean
fun buildFromJson(json: Any?): EvaluationFilter
fun defaultFilter(): EvaluationFilter
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/base/project-model/src/org/jetbrains/kotlin/idea/projectModel/CachedArgsInfo.kt | 4 | 309 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.projectModel
interface CachedArgsInfo<T> : ArgsInfo<T, KotlinCachedCompilerArgument<*>>, CacheOriginIdentifierAware | apache-2.0 |
GunoH/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/statistics/VcsUsagesCollector.kt | 9 | 4509 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.statistics
import com.intellij.internal.statistic.beans.MetricEvent
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.internal.statistic.eventLog.events.StringEventField
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.internal.statistic.utils.getPluginInfo
import com.intellij.openapi.project.Project
import com.intellij.openapi.vcs.changes.ChangeListManager
import com.intellij.openapi.vcs.ex.ProjectLevelVcsManagerEx
import com.intellij.util.text.nullize
import com.intellij.vcsUtil.VcsUtil
class VcsUsagesCollector : ProjectUsagesCollector() {
override fun getGroup(): EventLogGroup {
return GROUP
}
override fun getMetrics(project: Project): Set<MetricEvent> {
val set = HashSet<MetricEvent>()
val vcsManager = ProjectLevelVcsManagerEx.getInstanceEx(project)
val clm = ChangeListManager.getInstance(project)
val projectBaseDir = project.basePath?.let { VcsUtil.getVirtualFile(it) }
for (vcs in vcsManager.allActiveVcss) {
val pluginInfo = getPluginInfo(vcs.javaClass)
set.add(ACTIVE_VCS.metric(pluginInfo, vcs.name))
}
for (mapping in vcsManager.directoryMappings) {
val vcsName = mapping.vcs.nullize(true)
val vcs = vcsManager.findVcsByName(vcsName)
val pluginInfo = vcs?.let { getPluginInfo(it.javaClass) }
val data = mutableListOf<EventPair<*>>()
data.add(EventFields.PluginInfo.with(pluginInfo))
data.add(IS_PROJECT_MAPPING_FIELD.with(mapping.isDefaultMapping))
data.add(VCS_FIELD_WITH_NONE.with(vcsName ?: "None"))
if (!mapping.isDefaultMapping) {
data.add(IS_BASE_DIR_FIELD.with(projectBaseDir != null &&
projectBaseDir == VcsUtil.getVirtualFile(mapping.directory)))
}
set.add(MAPPING.metric(data))
}
val defaultVcs = vcsManager.findVcsByName(vcsManager.haveDefaultMapping())
if (defaultVcs != null) {
val pluginInfo = getPluginInfo(defaultVcs.javaClass)
val explicitRoots = vcsManager.directoryMappings
.filter { it.vcs == defaultVcs.name }
.filter { it.directory.isNotEmpty() }
.map { VcsUtil.getVirtualFile(it.directory) }
.toSet()
val projectMappedRoots = vcsManager.allVcsRoots
.filter { it.vcs == defaultVcs }
.filter { !explicitRoots.contains(it.path) }
for (vcsRoot in projectMappedRoots) {
set.add(PROJECT_MAPPED_ROOTS.metric(pluginInfo, defaultVcs.name, vcsRoot.path == projectBaseDir))
}
}
set.add(MAPPED_ROOTS.metric(vcsManager.allVcsRoots.size))
set.add(CHANGELISTS.metric(clm.changeListsNumber))
set.add(UNVERSIONED_FILES.metric(clm.unversionedFilesPaths.size))
set.add(IGNORED_FILES.metric(clm.ignoredFilePaths.size))
return set
}
companion object {
private val GROUP = EventLogGroup("vcs.configuration", 3)
private val VCS_FIELD = EventFields.StringValidatedByEnum("vcs", "vcs")
private val ACTIVE_VCS = GROUP.registerEvent("active.vcs", EventFields.PluginInfo,
VCS_FIELD)
private val IS_PROJECT_MAPPING_FIELD = EventFields.Boolean("is_project_mapping")
private val IS_BASE_DIR_FIELD = EventFields.Boolean("is_base_dir")
private val VCS_FIELD_WITH_NONE = object : StringEventField("vcs") {
override val validationRule: List<String>
get() = listOf("{enum#vcs}", "{enum:None}")
}
private val MAPPING = GROUP.registerVarargEvent(
"mapping", EventFields.PluginInfo,
VCS_FIELD_WITH_NONE, IS_PROJECT_MAPPING_FIELD, IS_BASE_DIR_FIELD
)
private val PROJECT_MAPPED_ROOTS = GROUP.registerEvent(
"project.mapped.root", EventFields.PluginInfo,
VCS_FIELD, EventFields.Boolean("is_base_dir")
)
private val MAPPED_ROOTS = GROUP.registerEvent("mapped.roots", EventFields.Count)
private val CHANGELISTS = GROUP.registerEvent("changelists", EventFields.Count)
private val UNVERSIONED_FILES = GROUP.registerEvent("unversioned.files", EventFields.Count)
private val IGNORED_FILES = GROUP.registerEvent("ignored.files", EventFields.Count)
}
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/inconsistentCommentForJavaParameter/whitespace/sameName2.kt | 5 | 74 | // PROBLEM: none
fun test(j: J) {
j.foo(<caret>/* string= */"hello")
} | apache-2.0 |
cleverchap/AutoAnylysis | src/com/cc/io/XmlManager.kt | 1 | 2978 | package com.cc.io
import org.dom4j.Attribute
import org.dom4j.Document
import org.dom4j.Element
import org.dom4j.io.SAXReader
import java.io.File
/**
* 参考文章:http://blog.csdn.net/yyywyr/article/details/38359049
*/
class XmlManager {
private val SPLIT_CHAR = "@"
private val MODULE_NAME = "Module"
private val TESTCASE_NAME = "TestCase"
private val TEST_NAME = "Test"
private val mConcernNodeNameList = mutableListOf(MODULE_NAME, TESTCASE_NAME, TEST_NAME)
private val mConcernNodePropertyList = mutableListOf("name")
private var mLastModuleName = ""
private var mLastTestCaseName = ""
private var mLastTestName = ""
fun testCode() {
// 1. 创建SAXReader对象
val reader = SAXReader()
// 2. 读取文件
val file = File("D:\\Temp\\Cts_logs\\1.xml")
// 3. 转换成Document
val document : Document = reader.read(file)
// 4. 获取根节点元素对象
val root : Element = document.rootElement
// 5. 遍历
listNodes(root)
}
//遍历当前节点下的所有节点
private fun listNodes(node: Element) {
val isConcern = isConcernNode(node.name)
log(isConcern, "当前节点的名称:" + node.name)
// 5.1 首先获取当前节点的所有属性节点
val list = node.attributes() as List<Attribute>
// 5.2 遍历属性节点
for (attribute in list) {
val isConcernProperty = isConcernProperty(attribute.name)
log(isConcernProperty, "属性" + attribute.name + ":" + attribute.value)
if (isConcernProperty) {
logMajorContent(node, attribute)
}
}
// 5.3 如果当前节点内容不为空,则输出
if (node.textTrim != "") {
val isConcernProperty = isConcernProperty(node.name)
log(isConcernProperty, node.name + ":" + node.text)
}
// 5.4 同时迭代当前节点下面的所有子节点
// 5.5 使用递归
val iterator = node.elementIterator()
while (iterator.hasNext()) {
val e = iterator.next() as Element
listNodes(e)
}
}
//只处理关心结点的信息
private fun isConcernNode(nodeName: String) = nodeName in mConcernNodeNameList
private fun isConcernProperty(propertyName : String) = propertyName in mConcernNodePropertyList
private fun log(isConcern: Boolean, content: String) {
// if (isConcern) println(content)
}
private fun logMajorContent(node:Element, attribute: Attribute) {
when (node.name) {
MODULE_NAME -> mLastModuleName = attribute.value
TESTCASE_NAME -> mLastTestCaseName = attribute.value
TEST_NAME -> {
mLastTestName = attribute.value
println(mLastModuleName + SPLIT_CHAR + mLastTestCaseName + SPLIT_CHAR + mLastTestName)
}
}
}
}
| apache-2.0 |
GunoH/intellij-community | plugins/kotlin/gradle/gradle-java/src/org/jetbrains/kotlin/idea/gradleJava/testing/native/KotlinMultiplatformNativeTestMethodGradleConfigurationProducer.kt | 4 | 903 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.gradleJava.testing.native
import com.intellij.openapi.module.Module
import org.jetbrains.kotlin.idea.base.codeInsight.tooling.KotlinNativeRunConfigurationProvider
import org.jetbrains.kotlin.idea.gradleJava.run.AbstractKotlinMultiplatformTestMethodGradleConfigurationProducer
import org.jetbrains.kotlin.platform.TargetPlatform
import org.jetbrains.kotlin.platform.konan.isNative
class KotlinMultiplatformNativeTestMethodGradleConfigurationProducer
: AbstractKotlinMultiplatformTestMethodGradleConfigurationProducer(), KotlinNativeRunConfigurationProvider
{
override val isForTests: Boolean get() = true
override fun isApplicable(module: Module, platform: TargetPlatform) = platform.isNative()
} | apache-2.0 |
chiclaim/android-sample | language-kotlin/kotlin-sample/kotlin-in-action/src/new_class/SealedClassTest.kt | 1 | 1464 | package new_class
/**
* desc: sealed class 演示
*
* Created by Chiclaim on 2018/09/22
*/
/*
小结:
当我们使用when语句通常需要加else分支,如果when是判断某个复杂类型,如果该类型后面有新的子类,when语句就会走else分支
sealed class就是用来解决这个问题的。
当when判断的是sealed class,那么不需要加else默认分支,如果有新的子类,编译器会通过编译报错的方式提醒开发者添加新分支,从而保证逻辑的完整性和正确性
需要注意的是,当when判断的是sealed class,千万不要添加else分支,否则有新子类编译器也不会提醒
sealed class 在外部不能被继承,私有构造方法是私有的
*/
sealed class Expr {
class Num(val value: Int) : Expr()
class Sum(val left: Expr, val right: Expr) : Expr()
}
fun eval(e: Expr): Int =
when (e) {
is Expr.Num -> e.value
is Expr.Sum -> eval(e.left) + eval(e.right)
}
//=========================================================
open class Expr2;
class Num2(val value: Int) : Expr2()
class Sum2(val left: Expr2, val right: Expr2) : Expr2()
fun eval2(e: Expr2): Int =
when (e) {
is Num2 -> e.value
is Sum2 -> eval2(e.left) + eval2(e.right)
else -> -1
}
fun main(args: Array<String>) {
val sum = eval(Expr.Sum(Expr.Num(1), Expr.Num(2)))
println("sum = $sum")
}
| apache-2.0 |
AntonovAlexander/activecore | kernelip/cyclix/src/hw_subproc.kt | 1 | 4583 | /*
* hw_subproc.kt
*
* Created on: 05.06.2019
* Author: Alexander Antonov <[email protected]>
* License: See LICENSE file for details
*/
package cyclix
import hwast.*
class hw_subproc(var inst_name : String, var src_module: Generic, var parent_module: Generic) {
var RootResetDriver = parent_module.ulocal("gensubmod_" + inst_name + "_genrst", 0, 0, "0")
var AppResetDrivers = ArrayList<hw_var>()
var Ports = mutableMapOf<String, hw_port>()
var PortConnections = mutableMapOf<hw_port, hw_param>()
var fifo_ifs = mutableMapOf<String, hw_structvar>()
var FifoConnections = mutableMapOf<hw_structvar, hw_param>()
init {
for (port in src_module.Ports) {
Ports.put(port.name, port)
}
for (fifo in src_module.fifo_ifs) {
fifo_ifs.put(fifo.value.name, fifo.value)
}
}
fun AddResetDriver() : hw_var {
var rst_var = parent_module.ulocal(parent_module.GetGenName("genrst"), 0, 0, "0")
AppResetDrivers.add(rst_var)
return rst_var
}
fun AddResetDriver(rst_var : hw_var) : hw_var {
AppResetDrivers.add(rst_var)
return rst_var
}
fun getPortByName(name : String) : hw_port {
if (!Ports.containsKey(name)) ERROR("Port " + name + " is unknown for instance " + inst_name)
return Ports[name]!!
}
fun getFifoByName(name : String) : hw_structvar {
return fifo_ifs[name]!!
}
fun connectPort(port : hw_port, src : hw_param) {
if (!Ports.containsValue(port)) ERROR("Port " + port.name + " is unknown!")
if (PortConnections.containsKey(port)) ERROR("port " + port.name + " for instance " + inst_name
+ "cannot be connected to src " + src.GetString() +
" - it is already connected to src " + PortConnections[port]!!.GetString())
PortConnections.put(port, src)
if (src is hw_var) {
if (port.port_dir == PORT_DIR.IN) src.read_done = true
else if (port.port_dir == PORT_DIR.OUT) src.write_done = true
else {
src.read_done = true
src.write_done = true
}
}
}
fun connectPort(port : hw_port, value : Int) {
connectPort(port, hw_imm(value))
}
fun connectPort(port_name : String, src : hw_param) {
var port = getPortByName(port_name)
connectPort(port, src)
}
fun connectPort(port_name : String, value : Int) {
connectPort(port_name, hw_imm(value))
}
fun connectPortGen(port_name : String) : hw_var {
var part_var = parent_module.local(parent_module.GetGenName(port_name), getPortByName(port_name).vartype, getPortByName(port_name).defval)
connectPort(port_name, part_var)
return part_var
}
/*
fun connectFifo(fifo : hw_structvar, src : hw_param) {
if (!fifo_ifs.containsValue(fifo)) ERROR("Port " + fifo.name + " is unknown!")
if (FifoConnections.containsKey(fifo)) ERROR("port " + fifo.name + " for instance " + inst_name
+ "cannot be connected to src " + src.GetString() +
" - it is already connected to src " + FifoConnections[fifo]!!.GetString())
FifoConnections.put(fifo, src)
if (src is hw_var) {
if (fifo is hw_fifo_in) src.read_done = true
else if (fifo is hw_fifo_out) src.write_done = true
else {
src.read_done = true
src.write_done = true
}
}
}
fun connectFifo(fifo_name : String, src : hw_param) {
var fifo = getFifoByName(fifo_name)
connectFifo(fifo, src)
}
fun connectFifoGen(fifo_name : String) : hw_var {
var part_var = parent_module.local(parent_module.GetGenName(fifo_name), getFifoByName(fifo_name).vartype, getFifoByName(fifo_name).defval)
connectFifo(fifo_name, part_var)
return part_var
}
*/
fun fifo_internal_wr_unblk(fifo_name : String, wdata : hw_param) : hw_var {
return parent_module.fifo_internal_wr_unblk(this, fifo_name, wdata)
}
fun fifo_internal_rd_unblk(fifo_name : String, rdata : hw_var) : hw_var {
return parent_module.fifo_internal_rd_unblk(this, fifo_name, rdata)
}
fun fifo_internal_wr_blk(fifo_name : String, wdata : hw_param) {
parent_module.fifo_internal_wr_blk(this, fifo_name, wdata)
}
fun fifo_internal_rd_blk(fifo_name : String) : hw_var {
return parent_module.fifo_internal_rd_blk(this, fifo_name)
}
} | apache-2.0 |
oldergod/android-architecture | app/src/main/java/com/example/android/architecture/blueprints/todoapp/mvibase/MviResult.kt | 1 | 158 | package com.example.android.architecture.blueprints.todoapp.mvibase
/**
* Immutable object resulting of a processed business logic.
*/
interface MviResult
| apache-2.0 |
Novatec-Consulting-GmbH/testit-testutils | logrecorder/logrecorder-assertions/src/main/kotlin/info/novatec/testit/logrecorder/assertion/matchers/message/EndsWithMessageMatcher.kt | 1 | 999 | /*
* Copyright 2017-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 info.novatec.testit.logrecorder.assertion.matchers.message
import info.novatec.testit.logrecorder.assertion.matchers.MessageMatcher
internal class EndsWithMessageMatcher(
private val suffix: String
) : MessageMatcher {
override fun matches(actual: String): Boolean = actual.endsWith(suffix)
override fun toString(): String = """ends with ["$suffix"]"""
}
| apache-2.0 |
oldergod/android-architecture | app/src/androidTest/java/com/example/android/architecture/blueprints/todoapp/TestUtils.kt | 1 | 2921 | /*
* Copyright 2016, 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 com.example.android.architecture.blueprints.todoapp
import android.app.Activity
import android.content.pm.ActivityInfo
import android.content.res.Configuration
import android.support.annotation.IdRes
import android.support.test.InstrumentationRegistry.getInstrumentation
import android.support.test.runner.lifecycle.ActivityLifecycleMonitor
import android.support.test.runner.lifecycle.ActivityLifecycleMonitorRegistry
import android.support.test.runner.lifecycle.Stage.RESUMED
import android.support.v7.widget.Toolbar
/**
* Useful test methods common to all activities
*/
/**
* Gets an Activity in the RESUMED stage.
*
*
* This method should never be called from the Main thread. In certain situations there might
* be more than one Activities in RESUMED stage, but only one is returned.
* See [ActivityLifecycleMonitor].
*/
// The array is just to wrap the Activity and be able to access it from the Runnable.
fun getCurrentActivity(): Activity {
val resumedActivity = arrayOfNulls<Activity>(1)
getInstrumentation().runOnMainSync {
val resumedActivities =
ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(RESUMED)
if (resumedActivities.iterator().hasNext()) {
resumedActivity[0] = resumedActivities.iterator().next() as Activity
} else {
throw IllegalStateException("No Activity in stage RESUMED")
}
}
return resumedActivity[0]!!
}
private fun rotateToLandscape(activity: Activity) {
activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
}
private fun rotateToPortrait(activity: Activity) {
activity.requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT
}
fun rotateOrientation(activity: Activity) {
val currentOrientation = activity.resources.configuration.orientation
when (currentOrientation) {
Configuration.ORIENTATION_LANDSCAPE -> rotateToPortrait(activity)
Configuration.ORIENTATION_PORTRAIT -> rotateToLandscape(activity)
else -> rotateToLandscape(activity)
}
}
/**
* Returns the content description for the navigation button view in the toolbar.
*/
fun getToolbarNavigationContentDescription(
activity: Activity,
@IdRes toolbar1: Int
): String {
return activity.findViewById<Toolbar>(toolbar1).navigationContentDescription!!.toString()
}
| apache-2.0 |
inorichi/mangafeed | app/src/main/java/eu/kanade/tachiyomi/ui/setting/SettingsAppearanceController.kt | 1 | 6587 | package eu.kanade.tachiyomi.ui.setting
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.preference.PreferenceScreen
import eu.kanade.tachiyomi.R
import eu.kanade.tachiyomi.util.preference.bindTo
import eu.kanade.tachiyomi.util.preference.defaultValue
import eu.kanade.tachiyomi.util.preference.entriesRes
import eu.kanade.tachiyomi.util.preference.initThenAdd
import eu.kanade.tachiyomi.util.preference.intListPreference
import eu.kanade.tachiyomi.util.preference.listPreference
import eu.kanade.tachiyomi.util.preference.onChange
import eu.kanade.tachiyomi.util.preference.preferenceCategory
import eu.kanade.tachiyomi.util.preference.switchPreference
import eu.kanade.tachiyomi.util.preference.titleRes
import eu.kanade.tachiyomi.util.system.DeviceUtil
import eu.kanade.tachiyomi.util.system.isTablet
import eu.kanade.tachiyomi.widget.preference.ThemesPreference
import java.util.Date
import eu.kanade.tachiyomi.data.preference.PreferenceKeys as Keys
import eu.kanade.tachiyomi.data.preference.PreferenceValues as Values
class SettingsAppearanceController : SettingsController() {
private var themesPreference: ThemesPreference? = null
override fun setupPreferenceScreen(screen: PreferenceScreen) = screen.apply {
titleRes = R.string.pref_category_appearance
preferenceCategory {
titleRes = R.string.pref_category_theme
listPreference {
bindTo(preferences.themeMode())
titleRes = R.string.pref_theme_mode
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
entriesRes = arrayOf(
R.string.theme_system,
R.string.theme_light,
R.string.theme_dark
)
entryValues = arrayOf(
Values.ThemeMode.system.name,
Values.ThemeMode.light.name,
Values.ThemeMode.dark.name
)
} else {
entriesRes = arrayOf(
R.string.theme_light,
R.string.theme_dark
)
entryValues = arrayOf(
Values.ThemeMode.light.name,
Values.ThemeMode.dark.name
)
}
summary = "%s"
}
themesPreference = initThenAdd(ThemesPreference(context)) {
bindTo(preferences.appTheme())
titleRes = R.string.pref_app_theme
val appThemes = Values.AppTheme.values().filter {
val monetFilter = if (it == Values.AppTheme.MONET) {
DeviceUtil.isDynamicColorAvailable
} else {
true
}
it.titleResId != null && monetFilter
}
entries = appThemes
onChange {
activity?.let { ActivityCompat.recreate(it) }
true
}
}
switchPreference {
bindTo(preferences.themeDarkAmoled())
titleRes = R.string.pref_dark_theme_pure_black
visibleIf(preferences.themeMode()) { it != Values.ThemeMode.light }
onChange {
activity?.let { ActivityCompat.recreate(it) }
true
}
}
}
preferenceCategory {
titleRes = R.string.pref_category_navigation
if (context.isTablet()) {
intListPreference {
bindTo(preferences.sideNavIconAlignment())
titleRes = R.string.pref_side_nav_icon_alignment
entriesRes = arrayOf(
R.string.alignment_top,
R.string.alignment_center,
R.string.alignment_bottom,
)
entryValues = arrayOf("0", "1", "2")
summary = "%s"
}
} else {
switchPreference {
bindTo(preferences.hideBottomBarOnScroll())
titleRes = R.string.pref_hide_bottom_bar_on_scroll
}
}
}
preferenceCategory {
titleRes = R.string.pref_category_timestamps
intListPreference {
bindTo(preferences.relativeTime())
titleRes = R.string.pref_relative_format
val values = arrayOf("0", "2", "7")
entryValues = values
entries = values.map {
when (it) {
"0" -> context.getString(R.string.off)
"2" -> context.getString(R.string.pref_relative_time_short)
else -> context.getString(R.string.pref_relative_time_long)
}
}.toTypedArray()
summary = "%s"
}
listPreference {
key = Keys.dateFormat
titleRes = R.string.pref_date_format
entryValues = arrayOf("", "MM/dd/yy", "dd/MM/yy", "yyyy-MM-dd", "dd MMM yyyy", "MMM dd, yyyy")
val now = Date().time
entries = entryValues.map { value ->
val formattedDate = preferences.dateFormat(value.toString()).format(now)
if (value == "") {
"${context.getString(R.string.label_default)} ($formattedDate)"
} else {
"$value ($formattedDate)"
}
}.toTypedArray()
defaultValue = ""
summary = "%s"
}
}
}
override fun onSaveViewState(view: View, outState: Bundle) {
themesPreference?.let {
outState.putInt(THEMES_SCROLL_POSITION, it.lastScrollPosition ?: 0)
}
super.onSaveInstanceState(outState)
}
override fun onRestoreViewState(view: View, savedViewState: Bundle) {
super.onRestoreViewState(view, savedViewState)
themesPreference?.lastScrollPosition = savedViewState.getInt(THEMES_SCROLL_POSITION, 0)
}
override fun onDestroyView(view: View) {
super.onDestroyView(view)
themesPreference = null
}
}
private const val THEMES_SCROLL_POSITION = "themesScrollPosition"
| apache-2.0 |
google/android-fhir | contrib/barcode/src/main/java/com/google/android/fhir/datacapture/contrib/views/barcode/mlkit/md/camera/CameraSizePair.kt | 1 | 1516 | /*
* 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.fhir.datacapture.contrib.views.barcode.mlkit.md.camera
import android.hardware.Camera
import com.google.android.gms.common.images.Size
/**
* Stores a preview size and a corresponding same-aspect-ratio picture size. To avoid distorted
* preview images on some devices, the picture size must be set to a size that is the same aspect
* ratio as the preview size or the preview may end up being distorted. If the picture size is null,
* then there is no picture size with the same aspect ratio as the preview size.
*/
class CameraSizePair {
val preview: Size
val picture: Size?
constructor(previewSize: Camera.Size, pictureSize: Camera.Size?) {
preview = Size(previewSize.width, previewSize.height)
picture = pictureSize?.let { Size(it.width, it.height) }
}
constructor(previewSize: Size, pictureSize: Size?) {
preview = previewSize
picture = pictureSize
}
}
| apache-2.0 |
code-disaster/lwjgl3 | modules/lwjgl/core/src/templates/kotlin/core/linux/templates/DynamicLinkLoader.kt | 4 | 2997 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package core.linux.templates
import org.lwjgl.generator.*
val dlfcn = "DynamicLinkLoader".nativeClass(Module.CORE_LINUX, nativeSubPath = "linux") {
nativeImport("<dlfcn.h>")
documentation = "Native bindings to <dlfcn.h>."
val Modes = IntConstant(
"The {@code mode} argument to #dlopen() contains one of the following.",
"RTLD_LAZY"..0x00001,
"RTLD_NOW"..0x00002,
"RTLD_BINDING_MASK"..0x3,
"RTLD_NOLOAD"..0x00004,
"RTLD_DEEPBIND"..0x00008
).javaDocLinks + " #RTLD_GLOBAL #RTLD_LOCAL #RTLD_NODELETE"
IntConstant(
"""
If the following bit is set in the {@code mode} argument to #dlopen(), the symbols of the loaded object and its dependencies are made visible as
if the object were linked directly into the program.
""",
"RTLD_GLOBAL"..0x00100
)
IntConstant(
"""
Unix98 demands the following flag which is the inverse to #RTLD_GLOBAL. The implementation does this by default and so we can define the value
to zero.
""",
"RTLD_LOCAL".."0"
)
IntConstant(
"Do not delete object when closed.",
"RTLD_NODELETE"..0x01000
)
opaque_p(
"dlopen",
"""
Loads the dynamic library file named by the null-terminated string {@code filename} and returns an opaque "handle" for the dynamic library. If
{@code filename} is #NULL, then the returned handle is for the main program.
""",
nullable..charUTF8.const.p("filename", "the name of the dynamic library to open, or #NULL"),
int("mode", "a bitfield", Modes, LinkMode.BITFIELD)
)
charUTF8.p(
"dlerror",
"""
Returns a human readable string describing the most recent error that occurred from #dlopen(), #dlsym() or #dlclose() since
the last call to {@code dlerror()}. It returns #NULL if no errors have occurred since initialization or since it was last called.
""",
void()
)
opaque_p(
"dlsym",
"""
Takes a "handle" of a dynamic library returned by #dlopen() and the null-terminated symbol name, returning the address where that symbol is loaded
into memory. If the symbol is not found, in the specified library or any of the libraries that were automatically loaded by #dlopen() when that
library was loaded, {@code dlsym()} returns #NULL.
""",
opaque_p("handle", "the dynamic library handle"),
charASCII.const.p("name", "the symbol name")
)
int(
"dlclose",
"""
Decrements the reference count on the dynamic library handle handle. If the reference count drops to zero and no other loaded libraries use symbols in
it, then the dynamic library is unloaded.
""",
opaque_p("handle", "the dynamic library to close")
)
} | bsd-3-clause |
ClearVolume/scenery | src/main/kotlin/graphics/scenery/backends/UBO.kt | 2 | 11970 | package graphics.scenery.backends
import cleargl.GLMatrix
import cleargl.GLVector
import gnu.trove.map.hash.TIntObjectHashMap
import graphics.scenery.utils.LazyLogger
import org.joml.*
import org.lwjgl.system.MemoryUtil
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.*
import kotlin.collections.LinkedHashMap
import kotlin.math.max
/**
* UBO base class, providing API-independent uniform buffer serialisation
* functionality for both OpenGL and Vulkan.
*
* @author Ulrik Günther <[email protected]>
*/
open class UBO {
/** Name of this UBO */
var name = ""
protected var members = LinkedHashMap<String, () -> Any>()
protected var memberOffsets = HashMap<String, Int>()
protected val logger by LazyLogger()
/** Hash value of all the members, gets updated by [populate()] */
var hash: Int = 0
private set
/** Cached size of the UBO, -1 if the UBO has not been populated yet. */
var sizeCached = -1
protected set
companion object {
/** Cache for alignment data inside buffers */
internal var alignments = TIntObjectHashMap<Pair<Int, Int>>()
}
/**
* Returns the size of [element] inside an uniform buffer.
*/
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
protected fun sizeOf(element: Any): Int {
return when(element) {
is Vector2f, is Vector2i -> 2
is Vector3f, is Vector3i -> 3
is Vector4f, is Vector4i -> 4
is Matrix4f -> 4 * 4
is Float, is java.lang.Float -> 4
is Double, is java.lang.Double -> 8
is Int, is Integer -> 4
is Short, is java.lang.Short -> 2
is Boolean, is java.lang.Boolean -> 4
is Enum<*> -> 4
is FloatArray -> element.size * 4
else -> { logger.error("Don't know how to determine size of $element"); 0 }
}
}
/**
* Translates an object to an integer ID for more efficient storage in [alignments].
*/
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
protected fun Any.objectId(): Int {
return when(this) {
is GLVector -> 0
is GLMatrix -> 1
is Float, is java.lang.Float -> 2
is Double, is java.lang.Double -> 3
is Int, is Integer -> 4
is Short, is java.lang.Short -> 5
is Boolean, is java.lang.Boolean -> 6
is Enum<*> -> 7
is Vector2f -> 8
is Vector3f -> 9
is Vector4f -> 10
is Vector2i -> 11
is Vector3i -> 12
is Vector4i -> 13
is Matrix4f -> 14
is FloatArray -> 15
else -> { logger.error("Don't know how to determine object ID of $this/${this.javaClass.simpleName}"); -1 }
}
}
/**
* Returns the size occupied and alignment required for [element] inside a uniform buffer.
* Pair layout is <size, alignment>.
*/
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
fun getSizeAndAlignment(element: Any): Pair<Int, Int> {
// pack object id and size into one integer
val key = (element.objectId() shl 16) or (sizeOf(element) and 0xffff)
if(alignments.containsKey(key)) {
return alignments.get(key)
} else {
val sa = when (element) {
is Matrix4f -> Pair(4 * 4 * 4, 4 * 4)
is Vector2f, is Vector2i -> Pair(2*4, 2*4)
is Vector3f, is Vector3i -> Pair(3*4, 4*4)
is Vector4f, is Vector4i -> Pair(4*4, 4*4)
is Float -> Pair(4, 4)
is Double -> Pair(8, 8)
is Integer -> Pair(4, 4)
is Int -> Pair(4, 4)
is Short -> Pair(2, 2)
is Boolean -> Pair(4, 4)
is Enum<*> -> Pair(4, 4)
is FloatArray -> Pair(4*element.size, 4*4)
else -> {
logger.error("Unknown VulkanUBO member type: ${element.javaClass.simpleName}")
Pair(0, 0)
}
}
alignments.put(key, sa)
return sa
}
}
/**
* Returns the total size in bytes required to store the contents of this UBO in a uniform buffer.
*/
fun getSize(): Int {
val totalSize = if(sizeCached == -1) {
val size = members.map {
getSizeAndAlignment(it.value.invoke())
}.fold(0) { current_position, (first, second) ->
// next element should start at the position
// required by it's alignment
val remainder = current_position.rem(second)
val new_position = if (remainder != 0) {
current_position + second - remainder + first
} else {
current_position + first
}
new_position
}
sizeCached = size
size
} else {
sizeCached
}
return totalSize
}
/**
* Populates the [ByteBuffer] [data] with the members of this UBO, subject to the determined
* sizes and alignments. A buffer [offset] can be given, as well as a list of [elements] that
* would override the UBO's members. This routine checks if an actual buffer update is required,
* and if not, will just set the buffer to the cached position. Otherwise it will serialise all
* the members into [data].
*
* Returns true if [data] has been updated, and false if not.
*/
@Suppress("PLATFORM_CLASS_MAPPED_TO_KOTLIN")
fun populate(data: ByteBuffer, offset: Long = -1L, elements: (LinkedHashMap<String, () -> Any>)? = null): Boolean {
// no need to look further
if(members.size == 0) {
return false
}
if(offset != -1L) {
data.position(offset.toInt())
}
val originalPos = data.position()
var endPos = originalPos
val oldHash = hash
if(sizeCached > 0 && elements == null) {
// the members hash is also based on the memory address of the buffer, which is calculated at the
// end of the routine and therefore dependent on the final buffer position.
val newHash = getMembersHash(data.duplicate().order(ByteOrder.LITTLE_ENDIAN).position(originalPos + sizeCached) as ByteBuffer)
if(oldHash == newHash) {
data.position(originalPos + sizeCached)
logger.trace("UBO members of {} have not changed, {} vs {}", this, hash, newHash)
// indicates the buffer will not be updated, but only forwarded to the cached position
return false
}
}
// iterate over members, or over elements, if given
(elements ?: members).forEach {
var pos = data.position()
val value = it.value.invoke()
val (size, alignment) = getSizeAndAlignment(value)
if(logger.isTraceEnabled) {
logger.trace("Populating {} of type {} size={} alignment={}", it.key, value.javaClass.simpleName, size, alignment)
}
val memberOffset = memberOffsets[it.key]
if(memberOffset != null) {
// position in buffer is known, use it
if(logger.isTraceEnabled) {
logger.trace("{} goes to {}", it.key, memberOffset)
}
pos = (originalPos + memberOffset)
data.position(pos)
} else {
// position in buffer is not explicitly known, advance based on size
if (pos.rem(alignment) != 0) {
pos = pos + alignment - (pos.rem(alignment))
data.position(pos)
}
}
when (value) {
is Matrix4f -> value.get(data)
is Vector2i -> value.get(data)
is Vector3i -> value.get(data)
is Vector4i -> value.get(data)
is Vector2f -> value.get(data)
is Vector3f -> value.get(data)
is Vector4f -> value.get(data)
is Float -> data.asFloatBuffer().put(0, value)
is Double -> data.asDoubleBuffer().put(0, value)
is Integer -> data.asIntBuffer().put(0, value.toInt())
is Int -> data.asIntBuffer().put(0, value)
is Short -> data.asShortBuffer().put(0, value)
is Boolean -> data.asIntBuffer().put(0, value.toInt())
is Enum<*> -> data.asIntBuffer().put(0, value.ordinal)
is FloatArray -> data.asFloatBuffer().put(value)
}
data.position(pos + size)
endPos = max(pos + size, endPos)
}
data.position(endPos)
sizeCached = data.position() - originalPos
if(elements == null) {
updateHash(data)
}
logger.trace("UBO {} updated, {} -> {}", this, oldHash, hash)
// indicates the buffer has been updated
return true
}
/**
* Adds a member with [name] to this UBO. [value] is given as a lambda
* that will return the actual value when invoked. An optional [offset] can be
* given, otherwise it will be calculated automatically.
*
* Invalidates the UBO's hash if no previous member is associated with [name],
* or if a previous member already bears [name], but has another type than the
* invocation of [value].
*/
fun add(name: String, value: () -> Any, offset: Int? = null) {
val previous = members.put(name, value)
offset?.let {
memberOffsets.put(name, offset)
}
if(previous == null || previous.invoke().javaClass != value.invoke().javaClass) {
// invalidate sizes
sizeCached = -1
}
}
/**
* Adds the member only if its missing.
*/
fun addIfMissing(name: String, value: () -> Any, offset: Int? = null) {
if(!members.containsKey(name)) {
add(name, value, offset)
}
}
/**
* Returns the members of the UBO as string.
*/
fun members(): String {
return members.keys.joinToString(", ")
}
/**
* Returns the members of the UBO and their values as string.
*/
fun membersAndContent(): String {
return members.entries.joinToString { "${it.key} -> ${it.value.invoke()}" }
}
/**
* Returns the number of members of this UBO.
*/
fun memberCount(): Int {
return members.size
}
/**
* For debugging purposes. Returns the hashes of all members as string.
*/
@Suppress("unused")
internal fun perMemberHashes(): String {
return members.map { "${it.key} -> ${it.key.hashCode()} ${it.value.invoke().hashCode()}" }.joinToString("\n")
}
/**
* Returns the hash value of all current members.
*
* Takes into consideration the member's name and _invoked_ value, as well as the
* buffer's memory address to discern buffer switches the UBO is oblivious to.
*/
protected fun getMembersHash(buffer: ByteBuffer): Int {
return members.map { (it.key.hashCode() xor it.value.invoke().hashCode()).toLong() }
.fold(31L) { acc, value -> acc + (value xor (value.ushr(32)))}.toInt() + MemoryUtil.memAddress(buffer).hashCode()
}
/**
* Updates the currently stored member hash.
*/
protected fun updateHash(buffer: ByteBuffer) {
hash = getMembersHash(buffer)
}
/**
* Returns the lambda associated with member of [name], or null
* if it does not exist.
*/
fun get(name: String): (() -> Any)? {
return members[name]
}
private fun Boolean.toInt(): Int {
return if(this) { 1 } else { 0 }
}
}
| lgpl-3.0 |
code-disaster/lwjgl3 | modules/lwjgl/opengl/src/templates/kotlin/opengl/templates/ARB_shading_language_100.kt | 4 | 722 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
*/
package opengl.templates
import org.lwjgl.generator.*
import opengl.*
val ARB_shading_language_100 = "ARBShadingLanguage100".nativeClassGL("ARB_shading_language_100", postfix = ARB) {
documentation =
"""
Native bindings to the $registryLink extension.
This extension indicates that the OpenGL Shading Language is supported.
Requires ${ARB_shader_objects.link}, ${ARB_fragment_shader.link} and ${ARB_vertex_shader.link}. ${GL20.promoted}
"""
IntConstant(
"Accepted by the {@code name} parameter of GetString.",
"SHADING_LANGUAGE_VERSION_ARB"..0x8B8C
)
} | bsd-3-clause |
neva-dev/javarel-framework | communication/rest/src/main/kotlin/com/neva/javarel/communication/rest/api/RestApplication.kt | 1 | 111 | package com.neva.javarel.communication.rest.api
interface RestApplication {
fun toggle(start: Boolean)
} | apache-2.0 |
zhclwr/YunWeatherKotlin | app/src/main/java/com/victor/yunweatherkotlin/db/CityDB.kt | 1 | 208 | package com.victor.yunweatherkotlin.db
import org.litepal.crud.DataSupport
data class CityDB(var cityCode : String, var county : String, var city : String, var province : String) : DataSupport()
| apache-2.0 |
McMoonLakeDev/MoonLake | API/src/main/kotlin/com/mcmoonlake/api/chat/ChatStyle.kt | 1 | 8926 | /*
* Copyright (C) 2016-Present The MoonLake ([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/>.
*/
package com.mcmoonlake.api.chat
/**
* ## ChatStyle (聊天样式)
*
* @author lgou2w
* @since 2.0
*/
open class ChatStyle {
/** member */
private var parent: ChatStyle? = null
@JvmField internal var color: ChatColor? = null
@JvmField internal var bold: Boolean? = null
@JvmField internal var italic: Boolean? = null
@JvmField internal var underlined: Boolean? = null
@JvmField internal var strikethrough: Boolean? = null
@JvmField internal var obfuscated: Boolean? = null
@JvmField internal var clickEvent: ChatClickEvent? = null
@JvmField internal var hoverEvent: ChatHoverEvent? = null
@JvmField internal var insertion: String? = null
/** static */
companion object {
@JvmStatic
private val ROOT = object: ChatStyle() {
override fun getColor(): ChatColor?
= null
override fun getBold(): Boolean?
= false
override fun getItalic(): Boolean?
= false
override fun getStrikethrough(): Boolean?
= false
override fun getUnderlined(): Boolean?
= false
override fun getObfuscated(): Boolean?
= false
override fun getClickEvent(): ChatClickEvent?
= null
override fun getHoverEvent(): ChatHoverEvent?
= null
override fun getInsertion(): String?
= null
override fun setParent(parent: ChatStyle?): ChatStyle
= throw UnsupportedOperationException()
override fun setColor(color: ChatColor?): ChatStyle
= throw UnsupportedOperationException()
override fun setBold(bold: Boolean?): ChatStyle
= throw UnsupportedOperationException()
override fun setItalic(italic: Boolean?): ChatStyle
= throw UnsupportedOperationException()
override fun setStrikethrough(strikethrough: Boolean?): ChatStyle
= throw UnsupportedOperationException()
override fun setUnderlined(underlined: Boolean?): ChatStyle
= throw UnsupportedOperationException()
override fun setObfuscated(obfuscated: Boolean?): ChatStyle
= throw UnsupportedOperationException()
override fun setClickEvent(clickEvent: ChatClickEvent?): ChatStyle
= throw UnsupportedOperationException()
override fun setHoverEvent(hoverEvent: ChatHoverEvent?): ChatStyle
= throw UnsupportedOperationException()
override fun setInsertion(insertion: String?): ChatStyle
= throw UnsupportedOperationException()
override fun toString(): String
= "ChatStyle.ROOT"
}
}
private fun getParent(): ChatStyle
= parent ?: ROOT
/**
* @see [ChatColor]
*/
open fun getColor(): ChatColor?
= color ?: getParent().getColor()
/**
* @see [ChatColor.BOLD]
*/
open fun getBold(): Boolean?
= bold ?: getParent().getBold()
/**
* @see [ChatColor.ITALIC]
*/
open fun getItalic(): Boolean?
= italic ?: getParent().getItalic()
/**
* @see [ChatColor.STRIKETHROUGH]
*/
open fun getStrikethrough(): Boolean?
= strikethrough ?: getParent().getStrikethrough()
/**
* @see [ChatColor.UNDERLINE]
*/
open fun getUnderlined(): Boolean?
= underlined ?: getParent().getUnderlined()
/**
* @see [ChatColor.OBFUSCATED]
*/
open fun getObfuscated(): Boolean?
= obfuscated ?: getParent().getObfuscated()
/**
* @see [ChatClickEvent]
*/
open fun getClickEvent(): ChatClickEvent?
= clickEvent ?: getParent().getClickEvent()
/**
* @see [ChatHoverEvent]
*/
open fun getHoverEvent(): ChatHoverEvent?
= hoverEvent ?: getParent().getHoverEvent()
open fun getInsertion(): String?
= insertion ?: getParent().getInsertion()
open fun setParent(parent: ChatStyle?): ChatStyle
{ this.parent = parent; return this; }
/**
* @see [ChatColor]
*/
open fun setColor(color: ChatColor?): ChatStyle
{ this.color = color; return this; }
/**
* @see [ChatColor.BOLD]
*/
open fun setBold(bold: Boolean?): ChatStyle
{ this.bold = bold; return this; }
/**
* @see [ChatColor.ITALIC]
*/
open fun setItalic(italic: Boolean?): ChatStyle
{ this.italic = italic; return this; }
/**
* @see [ChatColor.STRIKETHROUGH]
*/
open fun setStrikethrough(strikethrough: Boolean?): ChatStyle
{ this.strikethrough = strikethrough; return this; }
/**
* @see [ChatColor.UNDERLINE]
*/
open fun setUnderlined(underlined: Boolean?): ChatStyle
{ this.underlined = underlined; return this; }
/**
* @see [ChatColor.OBFUSCATED]
*/
open fun setObfuscated(obfuscated: Boolean?): ChatStyle
{ this.obfuscated = obfuscated; return this; }
/**
* @see [ChatClickEvent]
*/
open fun setClickEvent(clickEvent: ChatClickEvent?): ChatStyle
{ this.clickEvent = clickEvent; return this; }
/**
* @see [ChatHoverEvent]
*/
open fun setHoverEvent(hoverEvent: ChatHoverEvent?): ChatStyle
{ this.hoverEvent = hoverEvent; return this; }
open fun setInsertion(insertion: String?): ChatStyle
{ this.insertion = insertion; return this; }
/**
* * Get this chat style is empty.
* * 获取此聊天样式是否为空.
*/
fun isEmpty(): Boolean
= color == null && bold == null && italic == null && strikethrough == null && underlined == null && obfuscated == null && clickEvent == null && hoverEvent == null && insertion == null
/**
* * Shallow a clone of this chat style object.
* * 浅克隆一份此聊天样式的对象.
*/
fun clone(): ChatStyle {
val copy = ChatStyle()
copy.color = color
copy.bold = bold
copy.italic = italic
copy.strikethrough = strikethrough
copy.underlined = underlined
copy.obfuscated = obfuscated
copy.clickEvent = clickEvent
copy.hoverEvent = hoverEvent
copy.insertion = insertion
return copy
}
override fun equals(other: Any?): Boolean {
if(other === this)
return true
if(other is ChatStyle) {
if(parent != other.parent) return false
if(color != other.color) return false
if(bold != other.bold) return false
if(italic != other.italic) return false
if(underlined != other.underlined) return false
if(strikethrough != other.strikethrough) return false
if(obfuscated != other.obfuscated) return false
if(clickEvent != other.clickEvent) return false
if(hoverEvent != other.hoverEvent) return false
if(insertion != other.insertion) return false
return true
}
return false
}
override fun hashCode(): Int {
var result = color?.hashCode() ?: 0
result = 31 * result + (bold?.hashCode() ?: 0)
result = 31 * result + (italic?.hashCode() ?: 0)
result = 31 * result + (underlined?.hashCode() ?: 0)
result = 31 * result + (strikethrough?.hashCode() ?: 0)
result = 31 * result + (obfuscated?.hashCode() ?: 0)
result = 31 * result + (clickEvent?.hashCode() ?: 0)
result = 31 * result + (hoverEvent?.hashCode() ?: 0)
result = 31 * result + (insertion?.hashCode() ?: 0)
return result
}
override fun toString(): String {
return "ChatStyle(hasParent=${parent != null}, color=$color, bold=$bold, italic=$italic, underlined=$underlined, strikethrough=$strikethrough, obfuscated=$obfuscated, clickEvent=$clickEvent, hoverEvent=$hoverEvent, insertion=$insertion)"
}
}
| gpl-3.0 |
google/ground-android | ground/src/test/java/com/google/android/ground/ui/mapcontainer/LocationOfInterestDataTypeSelectorDialogFragmentTest.kt | 1 | 2979 | /*
* Copyright 2022 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.google.android.ground.ui.mapcontainer
import android.os.Looper
import android.view.View
import android.widget.ListView
import com.google.android.ground.BaseHiltTest
import com.google.android.ground.MainActivity
import com.google.android.ground.R
import com.google.android.ground.ui.home.mapcontainer.LocationOfInterestDataTypeSelectorDialogFragment
import com.google.android.ground.ui.surveyselector.SurveySelectorDialogFragment
import com.google.common.truth.Truth.assertThat
import dagger.hilt.android.testing.HiltAndroidTest
import java8.util.function.Consumer
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows.shadowOf
@HiltAndroidTest
@RunWith(RobolectricTestRunner::class)
class LocationOfInterestDataTypeSelectorDialogFragmentTest : BaseHiltTest() {
private lateinit var dialogFragment: LocationOfInterestDataTypeSelectorDialogFragment
private lateinit var onSelectLoiDataType: Consumer<Int>
private var selectedPosition = -1
@Before
override fun setUp() {
super.setUp()
selectedPosition = -1
onSelectLoiDataType = Consumer { integer: Int -> selectedPosition = integer }
setUpFragment()
}
private fun setUpFragment() {
val activityController = Robolectric.buildActivity(MainActivity::class.java)
val activity = activityController.setup().get()
dialogFragment = LocationOfInterestDataTypeSelectorDialogFragment(onSelectLoiDataType)
dialogFragment.showNow(
activity.supportFragmentManager,
SurveySelectorDialogFragment::class.java.simpleName
)
shadowOf(Looper.getMainLooper()).idle()
}
@Test
fun show_dialogIsShown() {
val listView = dialogFragment.dialog!!.currentFocus as ListView
assertThat(listView.visibility).isEqualTo(View.VISIBLE)
assertThat(listView.findViewById<View>(R.id.survey_name)?.visibility).isEqualTo(View.VISIBLE)
}
@Test
fun show_dataTypeSelected_correctDataTypeIsPassed() {
val listView = dialogFragment.dialog!!.currentFocus as ListView
val positionToSelect = 1
shadowOf(listView).performItemClick(positionToSelect)
shadowOf(Looper.getMainLooper()).idle()
// Verify Dialog is dismissed
assertThat(dialogFragment.dialog).isNull()
assertThat(selectedPosition).isEqualTo(1)
}
}
| apache-2.0 |
dhis2/dhis2-android-sdk | core/src/main/java/org/hisp/dhis/android/core/category/CategoryOptionComboService.kt | 1 | 3526 | /*
* Copyright (c) 2004-2022, University of Oslo
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* Neither the name of the HISP project nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.hisp.dhis.android.core.category
import dagger.Reusable
import io.reactivex.Single
import java.util.Date
import javax.inject.Inject
@Reusable
class CategoryOptionComboService @Inject constructor(
private val categoryOptionRepository: CategoryOptionCollectionRepository
) {
fun blockingHasAccess(categoryOptionComboUid: String, date: Date?, orgUnitUid: String? = null): Boolean {
val categoryOptions = categoryOptionRepository
.byCategoryOptionComboUid(categoryOptionComboUid)
.blockingGet()
return blockingIsAssignedToOrgUnit(categoryOptionComboUid, orgUnitUid) &&
blockingHasWriteAccess(categoryOptions) &&
isInOptionRange(categoryOptions, date)
}
fun blockingHasWriteAccess(
categoryOptions: List<CategoryOption>,
): Boolean {
return categoryOptions.none { it.access().data().write() == false }
}
fun blockingIsAssignedToOrgUnit(
categoryOptionComboUid: String,
orgUnitUid: String?
): Boolean {
return orgUnitUid?.let {
val categoryOptions = categoryOptionRepository
.byCategoryOptionComboUid(categoryOptionComboUid)
.withOrganisationUnits()
.blockingGet()
categoryOptions.all { categoryOption ->
categoryOption.organisationUnits()?.any {
it.uid() == orgUnitUid
} ?: true
}
} ?: true
}
fun hasAccess(categoryOptionComboUid: String, date: Date?): Single<Boolean> {
return Single.fromCallable { blockingHasAccess(categoryOptionComboUid, date) }
}
fun isInOptionRange(options: List<CategoryOption>, date: Date?): Boolean {
return date?.let {
options.all { option ->
option.startDate()?.before(date) ?: true && option.endDate()?.after(date) ?: true
}
} ?: true
}
}
| bsd-3-clause |
mikepenz/FastAdapter | app/src/main/java/com/mikepenz/fastadapter/app/model/ModelIconItem.kt | 1 | 1996 | package com.mikepenz.fastadapter.app.model
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.mikepenz.fastadapter.app.R
import com.mikepenz.fastadapter.app.utils.getThemeColor
import com.mikepenz.fastadapter.items.ModelAbstractItem
import com.mikepenz.iconics.IconicsDrawable
import com.mikepenz.iconics.utils.colorInt
import com.mikepenz.iconics.view.IconicsImageView
/**
* Created by mikepenz on 28.12.15.
*/
open class ModelIconItem(icon: IconModel) : ModelAbstractItem<IconModel, ModelIconItem.ViewHolder>(icon) {
/**
* defines the type defining this item. must be unique. preferably an id
*
* @return the type
*/
override val type: Int
get() = R.id.fastadapter_model_icon_item_id
/**
* defines the layout which will be used for this item in the list
*
* @return the layout for this item
*/
override val layoutRes: Int
get() = R.layout.icon_item
/**
* binds the data of this item onto the viewHolder
*
* @param holder the viewHolder of this item
*/
override fun bindView(holder: ViewHolder, payloads: List<Any>) {
super.bindView(holder, payloads)
//define our data for the view
holder.image.icon = IconicsDrawable(holder.image.context, model.icon).apply {
colorInt = holder.view.context.getThemeColor(R.attr.colorOnSurface)
}
holder.name.text = model.icon.name
}
override fun unbindView(holder: ViewHolder) {
super.unbindView(holder)
holder.image.setImageDrawable(null)
holder.name.text = null
}
override fun getViewHolder(v: View): ViewHolder {
return ViewHolder(v)
}
/**
* our ViewHolder
*/
class ViewHolder(val view: View) : RecyclerView.ViewHolder(view) {
var name: TextView = view.findViewById(R.id.name)
var image: IconicsImageView = view.findViewById(R.id.icon)
}
}
| apache-2.0 |
dahlstrom-g/intellij-community | plugins/kotlin/idea/tests/testData/inspectionsLocal/collections/convertCallChainIntoSequence/termination/find.kt | 9 | 110 | // WITH_STDLIB
fun test(list: List<Int>) {
val find: Int? = list.<caret>filter { it > 1 }.find { true }
} | apache-2.0 |
dahlstrom-g/intellij-community | platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/frame/CallFrameView.kt | 12 | 4189 | // Copyright 2000-2018 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 org.jetbrains.debugger.frame
import com.intellij.icons.AllIcons
import com.intellij.openapi.util.NlsSafe
import com.intellij.ui.ColoredTextContainer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.xdebugger.XDebuggerBundle
import com.intellij.xdebugger.evaluation.XDebuggerEvaluator
import com.intellij.xdebugger.frame.XCompositeNode
import com.intellij.xdebugger.frame.XStackFrame
import com.intellij.xdebugger.frame.XValueChildrenList
import org.jetbrains.concurrency.Promise
import org.jetbrains.debugger.*
// isInLibraryContent call could be costly, so we compute it only once (our customizePresentation called on each repaint)
class CallFrameView @JvmOverloads constructor(val callFrame: CallFrame,
override val viewSupport: DebuggerViewSupport,
val script: Script? = null,
sourceInfo: SourceInfo? = null,
isInLibraryContent: Boolean? = null,
override val vm: Vm? = null,
val methodReturnValue: Variable? = null) : XStackFrame(), VariableContext {
private val sourceInfo = sourceInfo ?: viewSupport.getSourceInfo(script, callFrame)
private val isInLibraryContent: Boolean = isInLibraryContent ?: (this.sourceInfo != null && viewSupport.isInLibraryContent(this.sourceInfo, script))
private var evaluator: XDebuggerEvaluator? = null
override fun getEqualityObject(): Any = callFrame.equalityObject
override fun computeChildren(node: XCompositeNode) {
node.setAlreadySorted(true)
methodReturnValue?.let {
val list = XValueChildrenList.singleton(VariableView(methodReturnValue, this))
node.addChildren(list, false)
}
createAndAddScopeList(node, callFrame.variableScopes, this, callFrame)
}
override val evaluateContext: EvaluateContext
get() = callFrame.evaluateContext
override fun watchableAsEvaluationExpression(): Boolean = true
override val memberFilter: Promise<MemberFilter>
get() = viewSupport.getMemberFilter(this)
fun getMemberFilter(scope: Scope): Promise<MemberFilter> = createVariableContext(scope, this, callFrame).memberFilter
override fun getEvaluator(): XDebuggerEvaluator? {
if (evaluator == null) {
evaluator = viewSupport.createFrameEvaluator(this)
}
return evaluator
}
override fun getSourcePosition(): SourceInfo? = sourceInfo
override fun customizePresentation(component: ColoredTextContainer) {
if (sourceInfo == null) {
val scriptName = if (script == null) XDebuggerBundle.message("stack.frame.function.unknown") else script.url.trimParameters().toDecodedForm()
val line = callFrame.line
component.append(if (line == -1) scriptName else "$scriptName:$line", SimpleTextAttributes.ERROR_ATTRIBUTES)
return
}
val fileName = sourceInfo.file.name
val line = sourceInfo.line + 1
val textAttributes =
if (isInLibraryContent || callFrame.isFromAsyncStack) SimpleTextAttributes.GRAYED_ATTRIBUTES
else SimpleTextAttributes.REGULAR_ATTRIBUTES
@NlsSafe val functionName = sourceInfo.functionName
if (functionName == null || (functionName.isEmpty() && callFrame.hasOnlyGlobalScope)) {
if (fileName.startsWith("index.")) {
sourceInfo.file.parent?.let {
component.append("${it.name}/", textAttributes)
}
}
component.append("$fileName:$line", textAttributes)
}
else {
if (functionName.isEmpty()) {
component.append(XDebuggerBundle.message("stack.frame.function.name.anonymous"), if (isInLibraryContent) SimpleTextAttributes.GRAYED_ITALIC_ATTRIBUTES else SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES)
}
else {
component.append(functionName, textAttributes)
}
component.append("(), $fileName:$line", textAttributes)
}
component.setIcon(AllIcons.Debugger.Frame)
}
} | apache-2.0 |
dahlstrom-g/intellij-community | plugins/editorconfig/src/org/editorconfig/language/codeinsight/inspections/EditorConfigCharClassRedundancyInspection.kt | 7 | 1114 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.editorconfig.language.codeinsight.inspections
import com.intellij.codeInspection.LocalInspectionTool
import com.intellij.codeInspection.ProblemsHolder
import org.editorconfig.language.codeinsight.quickfixes.EditorConfigConvertToPlainPatternQuickFix
import org.editorconfig.language.messages.EditorConfigBundle
import org.editorconfig.language.psi.EditorConfigCharClass
import org.editorconfig.language.psi.EditorConfigVisitor
class EditorConfigCharClassRedundancyInspection : LocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) = object : EditorConfigVisitor() {
override fun visitCharClass(charClass: EditorConfigCharClass) {
if (charClass.charClassExclamation != null) return
if (charClass.charClassLetterList.size != 1) return
val message = EditorConfigBundle["inspection.charclass.redundant.message"]
holder.registerProblem(charClass, message, EditorConfigConvertToPlainPatternQuickFix())
}
}
}
| apache-2.0 |
github/codeql | java/ql/test/kotlin/library-tests/generic-type-bounds/test.kt | 1 | 280 | class Test<T : Number, S : T, R> {
fun <Q : Number> f() { }
}
class MultipleBounds<P> where P : List<String>, P : Set<String> { }
class RecursiveBound<T : RecursiveBound<T>> { }
class MutualRecursiveBound<T : MutualRecursiveBound<T, S>, S : MutualRecursiveBound<T, S>> { }
| mit |
awsdocs/aws-doc-sdk-examples | kotlin/usecases/serverless_rds/src/main/kotlin/com/example/demo/DemoApplication.kt | 1 | 3077 | /*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.example.demo
import kotlinx.coroutines.runBlocking
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import java.io.IOException
@SpringBootApplication
open class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
@CrossOrigin(origins = ["*"])
@RestController
@RequestMapping("api/")
class MessageResource {
// Add a new item.
@PostMapping("/add")
fun addItems(@RequestBody payLoad: Map<String, Any>): String = runBlocking {
val injectWorkService = InjectWorkService()
val nameVal = "user"
val guideVal = payLoad.get("guide").toString()
val descriptionVal = payLoad.get("description").toString()
val statusVal = payLoad.get("status").toString()
// Create a Work Item object.
val myWork = WorkItem()
myWork.guide = guideVal
myWork.description = descriptionVal
myWork.status = statusVal
myWork.name = nameVal
val id = injectWorkService.injestNewSubmission(myWork)
return@runBlocking "Item $id added successfully!"
}
// Retrieve items.
@GetMapping("items/{state}")
fun getItems(@PathVariable state: String): MutableList<WorkItem> = runBlocking {
val retrieveItems = RetrieveItems()
val list: MutableList<WorkItem>
val name = "user"
if (state.compareTo("archive") == 0) {
list = retrieveItems.getItemsDataSQL(name, 1)
} else {
list = retrieveItems.getItemsDataSQL(name, 0)
}
return@runBlocking list
}
// Flip an item from Active to Archive.
@PutMapping("mod/{id}")
fun modUser(@PathVariable id: String): String = runBlocking {
val retrieveItems = RetrieveItems()
retrieveItems.flipItemArchive(id)
return@runBlocking id
}
// Send a report through Amazon SES.
@PutMapping("report/{email}")
fun sendReport(@PathVariable email: String): String = runBlocking {
val retrieveItems = RetrieveItems()
val nameVal = "user"
val sendMsg = SendMessage()
val xml = retrieveItems.getItemsDataSQLReport(nameVal, 0)
try {
sendMsg.send(email, xml)
} catch (e: IOException) {
e.stackTrace
}
return@runBlocking "Report was sent"
}
}
| apache-2.0 |
gamerson/liferay-blade-samples | gradle/apps/kotlin-portlet/src/main/kotlin/com/liferay/blade/samples/portlet/kotlin/KotlinGreeterPortlet.kt | 1 | 2038 | /**
* Copyright 2000-present Liferay, 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 com.liferay.blade.samples.portlet.kotlin
import com.liferay.blade.samples.portlet.kotlin.constants.KotlinGreeterPortletKeys
import com.liferay.portal.kernel.portlet.bridges.mvc.MVCPortlet
import java.io.IOException
import javax.portlet.Portlet
import javax.portlet.PortletException
import javax.portlet.RenderRequest
import javax.portlet.RenderResponse
import org.osgi.service.component.annotations.Component
/**
* @author Liferay
*/
@Component(
immediate = true,
property = arrayOf(
"com.liferay.portlet.css-class-wrapper=portlet-greeter",
"com.liferay.portlet.display-category=category.sample",
"com.liferay.portlet.instanceable=true",
"javax.portlet.display-name=Kotlin Greeter Portlet",
"javax.portlet.init-param.template-path=/",
"javax.portlet.init-param.view-template=/view.jsp",
"javax.portlet.name=" + KotlinGreeterPortletKeys.KotlinGreeterPortlet,
"javax.portlet.security-role-ref=power-user,user"
),
service = arrayOf(Portlet::class)
)
class KotlinGreeterPortlet : MVCPortlet() {
@Throws(IOException::class, PortletException::class)
override fun doView(
renderRequest: RenderRequest, renderResponse: RenderResponse) {
val greeting: String? = renderRequest.getAttribute(KotlinGreeterPortletKeys.GreeterMessage) as String?
if (greeting == null) {
renderRequest.setAttribute(KotlinGreeterPortletKeys.GreeterMessage, "")
}
super.doView(renderRequest, renderResponse)
}
} | apache-2.0 |
gorrotowi/Nothing | Android/Nothing/app/src/main/java/com/gorro/nothing/NothingMessagingService.kt | 1 | 817 | package com.gorro.nothing
import android.util.Log
import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
private val TAG = NothingMessagingService::class.java.simpleName
class NothingMessagingService : FirebaseMessagingService() {
override fun onMessageReceived(remoteMessage: RemoteMessage) {
super.onMessageReceived(remoteMessage)
Log.d(TAG, "${remoteMessage.from}")
remoteMessage.notification?.let {
Log.e(TAG, "${it.title}")
Log.e(TAG, "${it.body}")
Log.e(TAG, "${it.tag}")
Log.e(TAG, "${remoteMessage.data}")
remoteMessage.data.map { some ->
Log.e(TAG, "${some.key} ${some.value}")
}
//TODO show alert
}
}
}
| apache-2.0 |
zanata/zanata-platform | server/services/src/test/java/org/zanata/email/multipart.kt | 1 | 986 | package org.zanata.email
import org.assertj.core.api.Assertions
import javax.mail.Multipart
import javax.mail.internet.MimeMessage
/**
* @author Sean Flanigan <a href="mailto:[email protected]">[email protected]</a>
*/
internal data class MultipartContents(val text: String, val html: String)
internal fun extractMultipart(message: MimeMessage): MultipartContents {
val multipart = message.content as Multipart
// one for html, one for text
Assertions.assertThat(multipart.count).isEqualTo(2)
// Text should appear first (because HTML is the preferred format)
val textPart = multipart.getBodyPart(0)
Assertions.assertThat(textPart.dataHandler.contentType).isEqualTo(
"text/plain; charset=UTF-8")
val htmlPart = multipart.getBodyPart(1)
Assertions.assertThat(htmlPart.dataHandler.contentType).isEqualTo(
"text/html; charset=UTF-8")
return MultipartContents(textPart.content as String, htmlPart.content as String)
}
| lgpl-2.1 |
orauyeu/SimYukkuri | subprojects/simyukkuri/src/main/kotlin/simyukkuri/gameobject/yukkuri/statistic/statistics/Pregnancy.kt | 1 | 473 | package simyukkuri.gameobject.yukkuri.statistic.statistics
import simyukkuri.gameobject.yukkuri.statistic.YukkuriStats
/** ゆっくりの妊娠のインターフェース */
interface Pregnancy {
/** 妊娠しているか. */
val isPregnant: Boolean
/** 産気づいているか. */
val isInTravail: Boolean
/** お腹の中にいる子供のコレクション */
val babiesInWomb: MutableSet<YukkuriStats>
fun update()
}
| apache-2.0 |
gmariotti/kotlin-koans | util/src/koansTestUtil.kt | 2 | 338 | package koans.util
fun String.toMessage() = "The function '$this' is implemented incorrectly"
fun String.toMessageInEquals() = toMessage().inEquals()
fun String.inEquals() = this + ":" + if (mode == Mode.WEB_DEMO) " " else "<br><br>"
private enum class Mode { WEB_DEMO, EDUCATIONAL_PLUGIN }
private val mode = Mode.EDUCATIONAL_PLUGIN
| mit |
akhbulatov/wordkeeper | app/src/main/java/com/akhbulatov/wordkeeper/domain/global/models/Word.kt | 1 | 463 | package com.akhbulatov.wordkeeper.domain.global.models
data class Word(
val id: Long = 0,
val name: String,
val translation: String,
val datetime: Long,
val category: String
) {
enum class SortMode {
NAME,
LAST_MODIFIED;
companion object {
fun toEnumSortMode(sortMode: Int): SortMode = when (sortMode) {
0 -> NAME
else -> LAST_MODIFIED
}
}
}
}
| apache-2.0 |
paplorinc/intellij-community | platform/platform-impl/src/com/intellij/ui/layout/ShowcaseUiDslAction.kt | 1 | 1055 | // Copyright 2000-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 com.intellij.ui.layout
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.util.Disposer
import com.intellij.ui.components.dialog
import com.intellij.ui.tabs.JBTabsFactory
import com.intellij.ui.tabs.TabInfo
// not easy to replicate the same LaF outside of IDEA app, so, to be sure, showcase available as an IDE action
internal class ShowcaseUiDslAction : DumbAwareAction() {
override fun actionPerformed(e: AnActionEvent) {
val disposable = Disposer.newDisposable()
val tabs = JBTabsFactory.createEditorTabs(e.project, disposable)
tabs.presentation.setAlphabeticalMode(false)
tabs.addTab(TabInfo(secondColumnSmallerPanel()).setText("Second Column Smaller"))
val dialog = dialog("UI DSL Showcase", tabs.component)
Disposer.register(dialog.disposable, disposable)
dialog.showAndGet()
}
}
| apache-2.0 |
google/intellij-community | python/src/com/jetbrains/python/testing/AbstractPythonTestRunConfiguration.kt | 3 | 4549 | // Copyright 2000-2018 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 com.jetbrains.python.testing
import com.intellij.execution.Location
import com.intellij.execution.configurations.ConfigurationFactory
import com.intellij.execution.configurations.RuntimeConfigurationException
import com.intellij.execution.configurations.RuntimeConfigurationWarning
import com.intellij.execution.target.TargetEnvironmentRequest
import com.intellij.execution.target.value.TargetEnvironmentFunction
import com.intellij.execution.target.value.constant
import com.intellij.execution.target.value.getTargetEnvironmentValueForLocalPath
import com.intellij.execution.target.value.joinToStringFunction
import com.intellij.execution.testframework.AbstractTestProxy
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.project.Project
import com.intellij.psi.util.PsiTreeUtil
import com.jetbrains.python.PyBundle
import com.jetbrains.python.packaging.PyPackageManager
import com.jetbrains.python.psi.PyClass
import com.jetbrains.python.psi.PyFunction
import com.jetbrains.python.run.AbstractPythonRunConfiguration
/**
* Parent of all test configurations
*
* @author Ilya.Kazakevich
*/
abstract class AbstractPythonTestRunConfiguration<T : AbstractPythonTestRunConfiguration<T>>
@JvmOverloads
protected constructor(project: Project, factory: ConfigurationFactory, val requiredPackage: String? = null) :
AbstractPythonRunConfiguration<T>(project, factory) {
/**
* Create test spec (string to be passed to runner, probably glued with [TEST_NAME_PARTS_SPLITTER])
*
* *To be deprecated. The part of the legacy implementation based on [com.intellij.execution.configurations.GeneralCommandLine].*
*
* @param location test location as reported by runner
* @param failedTest failed test
* @return string spec or null if spec calculation is impossible
*/
open fun getTestSpec(location: Location<*>, failedTest: AbstractTestProxy): String? {
val element = location.psiElement
var pyClass = PsiTreeUtil.getParentOfType(element, PyClass::class.java, false)
if (location is PyPsiLocationWithFixedClass) {
pyClass = location.fixedClass
}
val pyFunction = PsiTreeUtil.getParentOfType(element, PyFunction::class.java, false)
val virtualFile = location.virtualFile
if (virtualFile != null) {
var path = virtualFile.canonicalPath
if (pyClass != null) {
path += TEST_NAME_PARTS_SPLITTER + pyClass.name
}
if (pyFunction != null) {
path += TEST_NAME_PARTS_SPLITTER + pyFunction.name
}
return path
}
return null
}
open fun getTestSpec(request: TargetEnvironmentRequest,
location: Location<*>,
failedTest: AbstractTestProxy): TargetEnvironmentFunction<String>? {
val element = location.psiElement
var pyClass = PsiTreeUtil.getParentOfType(element, PyClass::class.java, false)
if (location is PyPsiLocationWithFixedClass) {
pyClass = location.fixedClass
}
val pyFunction = PsiTreeUtil.getParentOfType(element, PyFunction::class.java, false)
val virtualFile = location.virtualFile
return virtualFile?.canonicalPath?.let { localPath ->
val targetPath = request.getTargetEnvironmentValueForLocalPath(localPath)
(listOf(targetPath) + listOfNotNull(pyClass?.name, pyFunction?.name).map(::constant))
.joinToStringFunction(separator = TEST_NAME_PARTS_SPLITTER)
}
}
@Throws(RuntimeConfigurationException::class)
override fun checkConfiguration() {
super.checkConfiguration()
if (requiredPackage != null && !isFrameworkInstalled()) {
throw RuntimeConfigurationWarning(
PyBundle.message("runcfg.testing.no.test.framework", requiredPackage))
}
}
/**
* Check if framework is available on SDK
*/
fun isFrameworkInstalled(): Boolean {
val sdk = sdk
if (sdk == null) {
// No SDK -- no tests
logger<AbstractPythonRunConfiguration<*>>().warn("SDK is null")
return false
}
val requiredPackage = this.requiredPackage ?: return true // Installed by default
return PyPackageManager.getInstance(sdk).packages?.firstOrNull { it.name == requiredPackage } != null
}
companion object {
/**
* When passing path to test to runners, you should join parts with this char.
* I.e.: file.py::PyClassTest::test_method
*/
protected const val TEST_NAME_PARTS_SPLITTER = "::"
}
} | apache-2.0 |
aahlenst/spring-boot | spring-boot-project/spring-boot-docs/src/main/kotlin/org/springframework/boot/docs/features/testing/springbootapplications/autoconfiguredspringdatamongodb/MyDataMongoDbTests.kt | 10 | 1031 | /*
* Copyright 2012-2022 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.boot.docs.features.testing.springbootapplications.autoconfiguredspringdatamongodb
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest
import org.springframework.data.mongodb.core.MongoTemplate
@DataMongoTest
class MyDataMongoDbTests(@Autowired val mongoTemplate: MongoTemplate) {
// ...
}
| apache-2.0 |
google/intellij-community | plugins/kotlin/code-insight/intentions-k2/src/org/jetbrains/kotlin/idea/k2/codeinsight/intentions/AddNameToArgumentIntention.kt | 3 | 3762 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.k2.codeinsight.intentions
import com.intellij.codeInsight.intention.LowPriorityAction
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.calls.KtFunctionCall
import org.jetbrains.kotlin.analysis.api.calls.singleFunctionCallOrNull
import org.jetbrains.kotlin.analysis.api.calls.symbol
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.base.projectStructure.languageVersionSettings
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.AbstractKotlinApplicatorBasedIntention
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.inputProvider
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.AddArgumentNamesApplicators
import org.jetbrains.kotlin.idea.codeinsights.impl.base.applicators.ApplicabilityRanges
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtCallElement
import org.jetbrains.kotlin.psi.KtContainerNode
import org.jetbrains.kotlin.psi.KtValueArgument
import org.jetbrains.kotlin.psi.KtValueArgumentList
internal class AddNameToArgumentIntention :
AbstractKotlinApplicatorBasedIntention<KtValueArgument, AddArgumentNamesApplicators.SingleArgumentInput>(KtValueArgument::class),
LowPriorityAction {
override fun getApplicator() = AddArgumentNamesApplicators.singleArgumentApplicator
override fun getApplicabilityRange() = ApplicabilityRanges.VALUE_ARGUMENT_EXCLUDING_LAMBDA
override fun getInputProvider() = inputProvider { element: KtValueArgument ->
val argumentList = element.parent as? KtValueArgumentList ?: return@inputProvider null
val shouldBeLastUnnamed =
!element.languageVersionSettings.supportsFeature(LanguageFeature.MixedNamedArgumentsInTheirOwnPosition)
if (shouldBeLastUnnamed && element != argumentList.arguments.last { !it.isNamed() }) return@inputProvider null
val callElement = argumentList.parent as? KtCallElement ?: return@inputProvider null
val resolvedCall = callElement.resolveCall().singleFunctionCallOrNull() ?: return@inputProvider null
if (!resolvedCall.symbol.hasStableParameterNames) {
return@inputProvider null
}
getArgumentNameIfCanBeUsedForCalls(element, resolvedCall)?.let(AddArgumentNamesApplicators::SingleArgumentInput)
}
override fun skipProcessingFurtherElementsAfter(element: PsiElement) = element is KtValueArgumentList ||
element is KtContainerNode || super.skipProcessingFurtherElementsAfter(element)
}
fun KtAnalysisSession.getArgumentNameIfCanBeUsedForCalls(argument: KtValueArgument, resolvedCall: KtFunctionCall<*>): Name? {
val valueParameterSymbol = resolvedCall.argumentMapping[argument.getArgumentExpression()]?.symbol ?: return null
if (valueParameterSymbol.isVararg) {
if (argument.languageVersionSettings.supportsFeature(LanguageFeature.ProhibitAssigningSingleElementsToVarargsInNamedForm) &&
!argument.isSpread
) {
return null
}
// We can only add the parameter name for an argument for a vararg parameter if it's the ONLY argument for the parameter. E.g.,
//
// fun foo(vararg i: Int) {}
//
// foo(1, 2) // Can NOT add `i = ` to either argument
// foo(1) // Can change to `i = 1`
val varargArgumentCount = resolvedCall.argumentMapping.values.count { it.symbol == valueParameterSymbol }
if (varargArgumentCount != 1) {
return null
}
}
return valueParameterSymbol.name
} | apache-2.0 |
apache/isis | incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/builder/LayoutBuilder.kt | 2 | 1300 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.causeway.client.kroviz.ui.builder
import io.kvision.panel.VPanel
import org.apache.causeway.client.kroviz.to.TObject
import org.apache.causeway.client.kroviz.to.bs3.Grid
class LayoutBuilder {
fun create(grid: Grid, tObject: TObject, dsp: RoDisplay): VPanel {
val panel = VPanel()
for (rl in grid.rows) {
val cpt = RowBuilder().create(rl, tObject, dsp)
panel.add(cpt)
}
return panel
}
}
| apache-2.0 |
cd1/motofretado | app/src/main/java/com/gmail/cristiandeives/motofretado/http/ModelListener.kt | 1 | 151 | package com.gmail.cristiandeives.motofretado.http
internal interface ModelListener<in T> {
fun onSuccess(data: T)
fun onError(ex: Exception)
} | gpl-3.0 |
Atsky/haskell-idea-plugin | plugin/src/org/jetbrains/haskell/vfs/TarGzArchive.kt | 1 | 915 | package org.jetbrains.haskell.vfs
import java.io.File
import java.io.BufferedInputStream
import java.io.InputStream
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream
import java.io.FileInputStream
import java.util.ArrayList
/**
* Created by atsky on 12/12/14.
*/
class TarGzArchive(val file : File) {
val filesList : List<String>
init {
val bin = BufferedInputStream(FileInputStream(file))
val gzIn = GzipCompressorInputStream(bin)
val tarArchiveInputStream = TarArchiveInputStream(gzIn)
var file = ArrayList<String>()
while (true) {
val entry = tarArchiveInputStream.nextTarEntry
if (entry == null) {
break
}
file.add(entry.name)
}
filesList = file
bin.close()
}
} | apache-2.0 |
youdonghai/intellij-community | platform/platform-impl/src/com/intellij/ui/NotificationActions.kt | 1 | 1438 | /*
* 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.ui
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.wm.IdeFrame
/**
* @author Alexander Lobas
*/
abstract class NotificationAction : AnAction() {
override fun update(e: AnActionEvent) {
val layout = getBalloonLayout(e)
e.presentation.isEnabled = layout != null && layout.balloonCount > 0
}
protected fun getBalloonLayout(e: AnActionEvent) = e.getData(IdeFrame.KEY)?.balloonLayout as BalloonLayoutImpl?
}
class CloseFirstNotificationAction : NotificationAction() {
override fun actionPerformed(e: AnActionEvent) {
getBalloonLayout(e)?.closeFirst()
}
}
class CloseAllNotificationsAction : NotificationAction() {
override fun actionPerformed(e: AnActionEvent) {
getBalloonLayout(e)?.closeAll()
}
} | apache-2.0 |
youdonghai/intellij-community | platform/configuration-store-impl/testSrc/ModuleStoreRenameTest.kt | 1 | 5057 | package com.intellij.configurationStore
import com.intellij.ProjectTopics
import com.intellij.ide.highlighter.ModuleFileType
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.components.StoragePathMacros
import com.intellij.openapi.components.stateStore
import com.intellij.openapi.module.Module
import com.intellij.openapi.project.ModuleListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.project.modifyModules
import com.intellij.testFramework.*
import com.intellij.util.Function
import com.intellij.util.SmartList
import com.intellij.util.io.systemIndependentPath
import org.assertj.core.api.Assertions.assertThat
import org.junit.ClassRule
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExternalResource
import java.nio.file.Path
import java.nio.file.Paths
import java.util.*
import kotlin.properties.Delegates
internal class ModuleStoreRenameTest {
companion object {
@JvmField
@ClassRule val projectRule = ProjectRule()
private val Module.storage: FileBasedStorage
get() = (stateStore.stateStorageManager as StateStorageManagerImpl).getCachedFileStorages(listOf(StoragePathMacros.MODULE_FILE)).first()
}
var module: Module by Delegates.notNull()
// we test fireModuleRenamedByVfsEvent
private val oldModuleNames = SmartList<String>()
private val tempDirManager = TemporaryDirectory()
private val ruleChain = RuleChain(
tempDirManager,
object : ExternalResource() {
override fun before() {
runInEdtAndWait {
module = projectRule.createModule(tempDirManager.newPath(refreshVfs = true).resolve("m.iml"))
}
module.messageBus.connect().subscribe(ProjectTopics.MODULES, object : ModuleListener {
override fun modulesRenamed(project: Project, modules: MutableList<Module>, oldNameProvider: Function<Module, String>) {
assertThat(modules).containsOnly(module)
oldModuleNames.add(oldNameProvider.`fun`(module))
}
})
}
// should be invoked after project tearDown
override fun after() {
(ApplicationManager.getApplication().stateStore.stateStorageManager as StateStorageManagerImpl).getVirtualFileTracker()!!.remove {
if (it.storageManager.componentManager == module) {
throw AssertionError("Storage manager is not disposed, module $module, storage $it")
}
false
}
}
},
DisposeModulesRule(projectRule)
)
@Rule fun getChain() = ruleChain
// project structure
@Test fun `rename module using model`() {
runInEdtAndWait { module.saveStore() }
val storage = module.storage
val oldFile = storage.file
assertThat(oldFile).isRegularFile()
val oldName = module.name
val newName = "foo"
runInEdtAndWait { projectRule.project.modifyModules { renameModule(module, newName) } }
assertRename(newName, oldFile)
assertThat(oldModuleNames).containsOnly(oldName)
}
// project view
@Test fun `rename module using rename virtual file`() {
runInEdtAndWait { module.saveStore() }
val storage = module.storage
val oldFile = storage.file
assertThat(oldFile).isRegularFile()
val oldName = module.name
val newName = "foo"
runInEdtAndWait { runWriteAction { LocalFileSystem.getInstance().refreshAndFindFileByPath(oldFile.systemIndependentPath)!!.rename(null, "$newName${ModuleFileType.DOT_DEFAULT_EXTENSION}") } }
assertRename(newName, oldFile)
assertThat(oldModuleNames).containsOnly(oldName)
}
// we cannot test external rename yet, because it is not supported - ModuleImpl doesn't support delete and create events (in case of external change we don't get move event, but get "delete old" and "create new")
private fun assertRename(newName: String, oldFile: Path) {
val newFile = module.storage.file
assertThat(newFile.fileName.toString()).isEqualTo("$newName${ModuleFileType.DOT_DEFAULT_EXTENSION}")
assertThat(oldFile)
.doesNotExist()
.isNotEqualTo(newFile)
assertThat(newFile).isRegularFile()
// ensure that macro value updated
assertThat(module.stateStore.stateStorageManager.expandMacros(StoragePathMacros.MODULE_FILE)).isEqualTo(newFile.systemIndependentPath)
}
@Test fun `rename module parent virtual dir`() {
runInEdtAndWait { module.saveStore() }
val storage = module.storage
val oldFile = storage.file
val parentVirtualDir = storage.virtualFile!!.parent
runInEdtAndWait { runWriteAction { parentVirtualDir.rename(null, UUID.randomUUID().toString()) } }
val newFile = Paths.get(parentVirtualDir.path, "${module.name}${ModuleFileType.DOT_DEFAULT_EXTENSION}")
try {
assertThat(newFile).isRegularFile()
assertRename(module.name, oldFile)
assertThat(oldModuleNames).isEmpty()
}
finally {
runInEdtAndWait { runWriteAction { parentVirtualDir.delete(this) } }
}
}
} | apache-2.0 |
NeatoRobotics/neato-sdk-android | Neato-SDK/neato-sdk-android/src/main/java/com/neatorobotics/sdk/android/robotservices/housecleaning/HouseCleaningBasic3Service.kt | 1 | 711 | /*
* Copyright (c) 2019.
* Neato Robotics Inc.
*/
package com.neatorobotics.sdk.android.robotservices.housecleaning
class HouseCleaningBasic3Service : HouseCleaningService() {
override val isMultipleZonesCleaningSupported: Boolean
get() = false
override val isEcoModeSupported: Boolean
get() = true
override val isTurboModeSupported: Boolean
get() = true
override val isExtraCareModeSupported: Boolean
get() = true
override val isCleaningAreaSupported: Boolean
get() = false
override val isCleaningFrequencySupported: Boolean
get() = false
companion object {
private const val TAG = "HouseCleaningBasic3"
}
}
| mit |
nathanj/ogsdroid | app/src/main/java/com/ogs/Challenge.kt | 1 | 4569 | package com.ogs
import org.json.JSONException
import org.json.JSONObject
class Challenge : Comparable<Challenge> {
var challengeId: Int = 0
var name: String = ""
var username: String = ""
var ranked: Boolean = false
var rank: Int = 0
var minRank: Int = 0
var maxRank: Int = 0
var handicap: Int = 0
var timePerMove: Int = 0
var width: Int = 0
var height: Int = 0
var timeControlParameters: JSONObject? = null
constructor(id: Int) {
challengeId = id
}
constructor(obj: JSONObject) {
try {
challengeId = obj.getInt("challenge_id")
username = obj.getString("username")
name = obj.getString("name")
timePerMove = obj.getInt("time_per_move")
ranked = obj.getBoolean("ranked")
rank = obj.getInt("rank")
minRank = obj.getInt("min_rank")
maxRank = obj.getInt("max_rank")
handicap = obj.getInt("handicap")
width = obj.getInt("width")
height = obj.getInt("height")
timeControlParameters = obj.getJSONObject("time_control_parameters")
} catch (e: JSONException) {
e.printStackTrace()
}
}
private fun rankToString(rank: Int): String {
if (rank < 30)
return String.format("%d Kyu", 30 - rank)
else
return String.format("%d Dan", rank - 30 + 1)
}
override fun toString(): String {
val handicapStr = if (handicap == -1)
"Auto Handicap"
else if (handicap == 0)
"No Handicap"
else
String.format("%d Stones", handicap)
return String.format("%s - %dx%d - %s (%s) - %s - %s - %s",
name, width, height, username, rankToString(rank),
if (ranked) "Ranked" else "Casual",
handicapStr,
formatTime())
}
fun prettyTime(time: Int): String {
if (time > 24 * 3600)
return (time / 24 / 3600).toString() + "d"
else if (time > 3600)
return (time / 3600).toString() + "h"
else if (time > 60)
return (time / 60).toString() + "m"
return time.toString() + "s"
}
fun formatTime(): String {
try {
val tcp = timeControlParameters
if (tcp != null) {
val control = tcp.getString("time_control")
if (control == "byoyomi") {
val periodTime = tcp.getInt("period_time")
val mainTime = tcp.getInt("main_time")
val periods = tcp.getInt("periods")
return "${prettyTime(mainTime)} + ${prettyTime(periodTime)} x $periods"
} else if (control == "fischer") {
val initialTime = tcp.getInt("initial_time")
val maxTime = tcp.getInt("max_time")
val increment = tcp.getInt("time_increment")
return "${prettyTime(initialTime)} + ${prettyTime(increment)} up to ${prettyTime(maxTime)}"
} else if (control == "canadian") {
val periodTime = tcp.getInt("period_time")
val mainTime = tcp.getInt("main_time")
val stonesPerPeriod = tcp.getInt("stones_per_period")
return "${prettyTime(mainTime)} + ${prettyTime(periodTime)} per $stonesPerPeriod stones"
} else if (control == "absolute") {
val totalTime = tcp.getInt("total_time")
return prettyTime(totalTime)
} else if (control == "simple") {
val perMove = tcp.getInt("per_move")
return prettyTime(perMove)
} else {
System.err.println("error: control = $control tcp=$tcp")
}
}
} catch (ex: JSONException) {
// nothing, move along
}
return prettyTime(timePerMove) + " / move"
}
override fun equals(other: Any?): Boolean {
if (other is Challenge)
return other.challengeId == challengeId
else
return false
}
fun canAccept(myRanking: Int): Boolean {
return myRanking >= minRank && myRanking <= maxRank && (!ranked || Math.abs(myRanking - rank) <= 9)
}
override fun compareTo(other: Challenge): Int {
if (other.timePerMove == timePerMove)
return rank - other.rank
return timePerMove - other.timePerMove
}
}
| mit |
mrebollob/RestaurantBalance | app/src/test/java/com/mrebollob/m2p/domain/CreateCreditCardTest.kt | 2 | 2749 | /*
* Copyright (c) 2017. Manuel Rebollo Báez
*
* 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.mrebollob.m2p.domain
import com.mrebollob.m2p.domain.datasources.DbDataSource
import com.mrebollob.m2p.domain.exceptions.InvalidCreditCardException
import com.mrebollob.m2p.domain.executor.PostExecutionThread
import com.mrebollob.m2p.domain.executor.ThreadExecutor
import com.mrebollob.m2p.domain.interactor.CreateCreditCard
import com.mrebollob.m2p.utils.mock
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.ExpectedException
import org.mockito.Mockito
class CreateCreditCardTest {
@Rule @JvmField var expectedException = ExpectedException.none()
private lateinit var createCreditCard: CreateCreditCard
private val mockDbDataSource: DbDataSource = mock()
private val mockThreadExecutor: ThreadExecutor = mock()
private val mockPostExecutionThread: PostExecutionThread = mock()
@Before
fun setUp() {
createCreditCard = CreateCreditCard(mockDbDataSource, mockThreadExecutor, mockPostExecutionThread)
}
@Test
fun shouldCreateACreditCard() {
val number = "4222222222222222"
val expDate = "08/21"
createCreditCard.buildInteractorObservable(
CreateCreditCard.Params.newCreditCard(number, expDate))
Mockito.verify(mockDbDataSource).createCreditCard(number, expDate)
Mockito.verifyNoMoreInteractions(mockDbDataSource)
Mockito.verifyZeroInteractions(mockPostExecutionThread)
Mockito.verifyZeroInteractions(mockThreadExecutor)
}
@Test
fun shouldFailWithEmptyNumber() {
val number = ""
val expDate = "08/21"
expectedException.expect(InvalidCreditCardException::class.java)
createCreditCard.buildInteractorObservable(
CreateCreditCard.Params.newCreditCard(number, expDate))
}
@Test
fun shouldFailWithEmptyExpDate() {
val number = "4222222222222222"
val expDate = ""
expectedException.expect(InvalidCreditCardException::class.java)
createCreditCard.buildInteractorObservable(
CreateCreditCard.Params.newCreditCard(number, expDate))
}
} | apache-2.0 |
DmytroTroynikov/aemtools | lang/src/test/kotlin/com/aemtools/lang/clientlib/parser/CdParserTest.kt | 1 | 651 | package com.aemtools.lang.clientlib.parser
import com.aemtools.lang.clientlib.CdParserDefinition
import com.aemtools.test.parser.BaseParserTest
/**
* @author Dmytro_Troynikov
*/
class CdParserTest
: BaseParserTest(
"com/aemtools/lang/clientlib/parser/fixtures",
"in",
CdParserDefinition()
) {
fun testInclude() = doTest()
fun testComplex1() = doTest()
fun testCommentBaseInclude() = doTest()
fun testBaseEmpty() = doTest()
fun testBaseInclude() = doTest()
fun testBaseCommentInclude() = doTest()
fun testRelativeInclude1() = doTest()
fun testRelativeInclude2() = doTest()
fun testRelativeInclude3() = doTest()
}
| gpl-3.0 |
allotria/intellij-community | platform/platform-impl/src/com/intellij/diagnostic/JetBrainsAccountDialog.kt | 1 | 2964 | // Copyright 2000-2020 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 com.intellij.diagnostic
import com.intellij.credentialStore.CredentialAttributes
import com.intellij.credentialStore.Credentials
import com.intellij.credentialStore.RememberCheckBoxState
import com.intellij.ide.BrowserUtil
import com.intellij.ide.passwordSafe.PasswordSafe
import com.intellij.openapi.project.Project
import com.intellij.ui.UIBundle
import com.intellij.ui.components.CheckBox
import com.intellij.ui.components.dialog
import com.intellij.ui.layout.*
import com.intellij.util.io.encodeUrlQueryParameter
import com.intellij.util.text.nullize
import java.awt.Component
import javax.swing.JPasswordField
import javax.swing.JTextField
@JvmOverloads
fun askJBAccountCredentials(parent: Component, project: Project?, authFailed: Boolean = false): Credentials? {
val credentials = ErrorReportConfigurable.getCredentials()
val remember = if (credentials?.userName == null) PasswordSafe.instance.isRememberPasswordByDefault // EA credentials were never stored
else !credentials.password.isNullOrEmpty() // a password was stored already
val prompt = if (authFailed) DiagnosticBundle.message("error.report.auth.failed")
else DiagnosticBundle.message("error.report.auth.prompt")
val userField = JTextField(credentials?.userName)
val passwordField = JPasswordField(credentials?.getPasswordAsString())
val rememberCheckBox = CheckBox(UIBundle.message("auth.remember.cb"), remember)
val panel = panel {
noteRow(prompt)
row(DiagnosticBundle.message("error.report.auth.user")) { userField(growPolicy = GrowPolicy.SHORT_TEXT) }
row(DiagnosticBundle.message("error.report.auth.pass")) { passwordField() }
row {
rememberCheckBox()
right {
link(DiagnosticBundle.message("error.report.auth.restore")) {
val userName = userField.text.trim().encodeUrlQueryParameter()
BrowserUtil.browse("https://account.jetbrains.com/forgot-password?username=$userName")
}
}
}
noteRow(DiagnosticBundle.message("error.report.auth.enlist", "https://account.jetbrains.com/login?signup"))
}
val dialog = dialog(
title = DiagnosticBundle.message("error.report.auth.title"),
panel = panel,
focusedComponent = if (credentials?.userName == null) userField else passwordField,
project = project,
parent = if (parent.isShowing) parent else null)
if (!dialog.showAndGet()) {
return null
}
val userName = userField.text.nullize(true)
val password = passwordField.password
val passwordToRemember = if (rememberCheckBox.isSelected) password else null
RememberCheckBoxState.update(rememberCheckBox)
PasswordSafe.instance.set(CredentialAttributes(ErrorReportConfigurable.SERVICE_NAME, userName), Credentials(userName, passwordToRemember))
return Credentials(userName, password)
}
| apache-2.0 |
allotria/intellij-community | python/python-grazie/src/com/intellij/grazie/ide/language/python/PythonGrammarCheckingStrategy.kt | 2 | 2049 | // Copyright 2000-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 com.intellij.grazie.ide.language.python
import com.intellij.grazie.grammar.strategy.BaseGrammarCheckingStrategy
import com.intellij.grazie.grammar.strategy.GrammarCheckingStrategy
import com.intellij.grazie.grammar.strategy.StrategyUtils
import com.intellij.grazie.grammar.strategy.impl.RuleGroup
import com.intellij.psi.PsiElement
import com.intellij.psi.impl.source.tree.LeafPsiElement
import com.intellij.psi.impl.source.tree.PsiCommentImpl
import com.intellij.psi.util.elementType
import com.jetbrains.python.PyTokenTypes
import com.jetbrains.python.PyTokenTypes.FSTRING_TEXT
import com.jetbrains.python.psi.PyFormattedStringElement
import com.jetbrains.python.psi.PyStringLiteralExpression
internal class PythonGrammarCheckingStrategy : BaseGrammarCheckingStrategy {
override fun isMyContextRoot(element: PsiElement) = element is PsiCommentImpl || element.elementType in PyTokenTypes.STRING_NODES
override fun getContextRootTextDomain(root: PsiElement) = when (root.elementType) {
PyTokenTypes.DOCSTRING -> GrammarCheckingStrategy.TextDomain.DOCS
PyTokenTypes.END_OF_LINE_COMMENT -> GrammarCheckingStrategy.TextDomain.COMMENTS
in PyTokenTypes.STRING_NODES -> GrammarCheckingStrategy.TextDomain.LITERALS
else -> GrammarCheckingStrategy.TextDomain.NON_TEXT
}
override fun isAbsorb(element: PsiElement): Boolean {
if (element.parent is PyFormattedStringElement) {
return element !is LeafPsiElement || element.elementType != FSTRING_TEXT
}
return false
}
override fun getIgnoredRuleGroup(root: PsiElement, child: PsiElement) = if (root is PyStringLiteralExpression) {
RuleGroup.LITERALS
}
else null
override fun getStealthyRanges(root: PsiElement, text: CharSequence) = when (root) {
is PsiCommentImpl -> StrategyUtils.indentIndexes(text, setOf(' ', '\t', '#'))
else -> StrategyUtils.indentIndexes(text, setOf(' ', '\t'))
}
}
| apache-2.0 |
allotria/intellij-community | java/java-impl/src/com/intellij/refactoring/extractMethod/newImpl/inplace/LegacyMethodExtractor.kt | 1 | 2841 | // Copyright 2000-2021 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 com.intellij.refactoring.extractMethod.newImpl.inplace
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiMethodCallExpression
import com.intellij.psi.search.searches.MethodReferencesSearch
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.refactoring.extractMethod.ExtractMethodHandler
import com.intellij.refactoring.extractMethod.ExtractMethodProcessor
import com.intellij.refactoring.util.duplicates.DuplicatesImpl
class LegacyMethodExtractor: InplaceExtractMethodProvider {
var processor: ExtractMethodProcessor? = null
override fun extract(targetClass: PsiClass, elements: List<PsiElement>, methodName: String, makeStatic: Boolean): Pair<PsiMethod, PsiMethodCallExpression> {
val project = targetClass.project
val processor = ExtractMethodHandler.getProcessor(project, elements.toTypedArray(), targetClass.containingFile, false)
processor ?: throw IllegalStateException("Failed to create processor for selected elements")
processor.prepare()
processor.prepareVariablesAndName()
processor.methodName = methodName
processor.targetClass = targetClass
processor.isStatic = makeStatic
processor.prepareNullability()
ExtractMethodHandler.extractMethod(project, processor)
val method = processor.extractedMethod
val call = findSingleMethodCall(method)!!
this.processor = processor
return Pair(method, call)
}
override fun extractInDialog(targetClass: PsiClass, elements: List<PsiElement>, methodName: String, makeStatic: Boolean) {
val project = targetClass.project
val file = targetClass.containingFile
val processor = ExtractMethodHandler.getProcessor(project, elements.toTypedArray(), file, false)
if (processor != null) {
ExtractMethodHandler.invokeOnElements(project, processor, file, false)
}
}
override fun postprocess(editor: Editor, method: PsiMethod) {
val handler = processor ?: return
val project = editor.project ?: return
val methodCall = findSingleMethodCall(method) ?: return
handler.extractedMethod = method
handler.methodCall = methodCall
handler.methodName = method.name
handler.parametrizedDuplicates?.apply {
setParametrizedMethod(method)
setParametrizedCall(methodCall)
}
DuplicatesImpl.processDuplicates(handler, project, editor)
}
private fun findSingleMethodCall(method: PsiMethod): PsiMethodCallExpression? {
val reference = MethodReferencesSearch.search(method).single().element
return PsiTreeUtil.getParentOfType(reference, PsiMethodCallExpression::class.java, false)
}
} | apache-2.0 |
codebrothers/PhraseTool | src/main/kotlin/phraseTool/process/io/BinaryFormat.kt | 1 | 197 | package phraseTool.process.io
val refByteLength = 3 // Byte length of a reference ( 1 control char + uint16 offset )
val refByte = 0x1B // Control char to use for reference
| mit |
Kotlin/kotlinx.coroutines | kotlinx-coroutines-core/jvm/src/internal/FastServiceLoader.kt | 1 | 6915 | /*
* Copyright 2016-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license.
*/
package kotlinx.coroutines.internal
import java.io.*
import java.net.*
import java.util.*
import java.util.jar.*
import java.util.zip.*
import kotlin.collections.ArrayList
/**
* Don't use JvmField here to enable R8 optimizations via "assumenosideeffects"
*/
internal val ANDROID_DETECTED = runCatching { Class.forName("android.os.Build") }.isSuccess
/**
* A simplified version of [ServiceLoader].
* FastServiceLoader locates and instantiates all service providers named in configuration
* files placed in the resource directory <tt>META-INF/services</tt>.
*
* The main difference between this class and classic service loader is in skipping
* verification JARs. A verification requires reading the whole JAR (and it causes problems and ANRs on Android devices)
* and prevents only trivial checksum issues. See #878.
*
* If any error occurs during loading, it fallbacks to [ServiceLoader], mostly to prevent R8 issues.
*/
internal object FastServiceLoader {
private const val PREFIX: String = "META-INF/services/"
/**
* This method attempts to load [MainDispatcherFactory] in Android-friendly way.
*
* If we are not on Android, this method fallbacks to a regular service loading,
* else we attempt to do `Class.forName` lookup for
* `AndroidDispatcherFactory` and `TestMainDispatcherFactory`.
* If lookups are successful, we return resultinAg instances because we know that
* `MainDispatcherFactory` API is internal and this is the only possible classes of `MainDispatcherFactory` Service on Android.
*
* Such intricate dance is required to avoid calls to `ServiceLoader.load` for multiple reasons:
* 1) It eliminates disk lookup on potentially slow devices on the Main thread.
* 2) Various Android toolchain versions by various vendors don't tend to handle ServiceLoader calls properly.
* Sometimes META-INF is removed from the resulting APK, sometimes class names are mangled, etc.
* While it is not the problem of `kotlinx.coroutines`, it significantly worsens user experience, thus we are workarounding it.
* Examples of such issues are #932, #1072, #1557, #1567
*
* We also use SL for [CoroutineExceptionHandler], but we do not experience the same problems and CEH is a public API
* that may already be injected vis SL, so we are not using the same technique for it.
*/
internal fun loadMainDispatcherFactory(): List<MainDispatcherFactory> {
val clz = MainDispatcherFactory::class.java
if (!ANDROID_DETECTED) {
return load(clz, clz.classLoader)
}
return try {
val result = ArrayList<MainDispatcherFactory>(2)
createInstanceOf(clz, "kotlinx.coroutines.android.AndroidDispatcherFactory")?.apply { result.add(this) }
createInstanceOf(clz, "kotlinx.coroutines.test.internal.TestMainDispatcherFactory")?.apply { result.add(this) }
result
} catch (e: Throwable) {
// Fallback to the regular SL in case of any unexpected exception
load(clz, clz.classLoader)
}
}
/*
* This method is inline to have a direct Class.forName("string literal") in the byte code to avoid weird interactions with ProGuard/R8.
*/
@Suppress("NOTHING_TO_INLINE")
private inline fun createInstanceOf(
baseClass: Class<MainDispatcherFactory>,
serviceClass: String
): MainDispatcherFactory? {
return try {
val clz = Class.forName(serviceClass, true, baseClass.classLoader)
baseClass.cast(clz.getDeclaredConstructor().newInstance())
} catch (e: ClassNotFoundException) { // Do not fail if TestMainDispatcherFactory is not found
null
}
}
private fun <S> load(service: Class<S>, loader: ClassLoader): List<S> {
return try {
loadProviders(service, loader)
} catch (e: Throwable) {
// Fallback to default service loader
ServiceLoader.load(service, loader).toList()
}
}
// Visible for tests
internal fun <S> loadProviders(service: Class<S>, loader: ClassLoader): List<S> {
val fullServiceName = PREFIX + service.name
// Filter out situations when both JAR and regular files are in the classpath (e.g. IDEA)
val urls = loader.getResources(fullServiceName)
val providers = urls.toList().flatMap { parse(it) }.toSet()
require(providers.isNotEmpty()) { "No providers were loaded with FastServiceLoader" }
return providers.map { getProviderInstance(it, loader, service) }
}
private fun <S> getProviderInstance(name: String, loader: ClassLoader, service: Class<S>): S {
val clazz = Class.forName(name, false, loader)
require(service.isAssignableFrom(clazz)) { "Expected service of class $service, but found $clazz" }
return service.cast(clazz.getDeclaredConstructor().newInstance())
}
private fun parse(url: URL): List<String> {
val path = url.toString()
// Fast-path for JARs
if (path.startsWith("jar")) {
val pathToJar = path.substringAfter("jar:file:").substringBefore('!')
val entry = path.substringAfter("!/")
// mind the verify = false flag!
(JarFile(pathToJar, false)).use { file ->
BufferedReader(InputStreamReader(file.getInputStream(ZipEntry(entry)), "UTF-8")).use { r ->
return parseFile(r)
}
}
}
// Regular path for everything else
return BufferedReader(InputStreamReader(url.openStream())).use { reader ->
parseFile(reader)
}
}
// JarFile does no implement Closesable on Java 1.6
private inline fun <R> JarFile.use(block: (JarFile) -> R): R {
var cause: Throwable? = null
try {
return block(this)
} catch (e: Throwable) {
cause = e
throw e
} finally {
try {
close()
} catch (closeException: Throwable) {
if (cause === null) throw closeException
cause.addSuppressed(closeException)
throw cause
}
}
}
private fun parseFile(r: BufferedReader): List<String> {
val names = mutableSetOf<String>()
while (true) {
val line = r.readLine() ?: break
val serviceName = line.substringBefore("#").trim()
require(serviceName.all { it == '.' || Character.isJavaIdentifierPart(it) }) { "Illegal service provider class name: $serviceName" }
if (serviceName.isNotEmpty()) {
names.add(serviceName)
}
}
return names.toList()
}
}
| apache-2.0 |
JetBrains/teamcity-dnx-plugin | plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/dotcover/ImportDataServiceMessageTest.kt | 1 | 1232 | package jetbrains.buildServer.dotnet.test.dotcover
import jetbrains.buildServer.agent.Path
import jetbrains.buildServer.dotcover.ImportDataServiceMessage
import org.testng.Assert
import org.testng.annotations.DataProvider
import org.testng.annotations.Test
class ImportDataServiceMessageTest {
@DataProvider(name = "serviceMessageCases")
fun serviceMessageCases(): Array<Array<Any>> {
return arrayOf(
arrayOf("dotcover", Path("dotCoverHome"), "##teamcity[importData type='dotNetCoverage' tool='dotcover' path='dotCoverHome']"),
arrayOf("dotCover", Path("dotCover Home"), "##teamcity[importData type='dotNetCoverage' tool='dotCover' path='dotCover Home']"),
arrayOf("", Path(""), "##teamcity[importData type='dotNetCoverage' tool='' path='']"))
}
@Test(dataProvider = "serviceMessageCases")
fun shouldProduceServiceMessage(coverageToolName: String, artifactPath: Path, expectedMessage: String) {
// Given
val serviceMessage = ImportDataServiceMessage(coverageToolName, artifactPath)
// When
val actualMessage = serviceMessage.toString()
// Then
Assert.assertEquals(actualMessage, expectedMessage)
}
} | apache-2.0 |
genonbeta/TrebleShot | core/src/main/java/com/genonbeta/android/framework/util/ElapsedTime.kt | 1 | 1767 | /*
* Copyright (C) 2021 Veli Tasalı
*
* 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 com.genonbeta.android.framework.util
/**
* created by: Veli
* date: 6.02.2018 12:27
*/
class ElapsedTime(
var time: Long,
val years: Long,
val months: Long,
val days: Long,
val hours: Long,
val minutes: Long,
val seconds: Long,
) {
class Calculator(var time: Long) {
fun crop(summonBy: Long): Long {
var result: Long = 0
if (time > summonBy) {
result = summonBy / summonBy
time -= result * summonBy
}
return result
}
}
companion object {
fun from(time: Long): ElapsedTime {
val calculator = Calculator(time / 1000)
return ElapsedTime(
time,
calculator.crop(62208000),
calculator.crop(2592000),
calculator.crop(86400),
calculator.crop(3600),
calculator.crop(60),
calculator.time
)
}
}
}
| gpl-2.0 |
zdary/intellij-community | platform/vcs-log/impl/src/com/intellij/vcs/log/history/VcsLogFileHistoryProviderImpl.kt | 3 | 8322 | // Copyright 2000-2021 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 com.intellij.vcs.log.history
import com.google.common.util.concurrent.SettableFuture
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vcs.FilePath
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.ui.content.TabGroupId
import com.intellij.vcs.log.*
import com.intellij.vcs.log.data.VcsLogData
import com.intellij.vcs.log.data.VcsLogStorage
import com.intellij.vcs.log.impl.*
import com.intellij.vcs.log.statistics.VcsLogUsageTriggerCollector
import com.intellij.vcs.log.ui.MainVcsLogUi
import com.intellij.vcs.log.ui.VcsLogUiEx
import com.intellij.vcs.log.ui.table.GraphTableModel
import com.intellij.vcs.log.util.VcsLogUtil
import com.intellij.vcs.log.util.VcsLogUtil.jumpToRow
import com.intellij.vcs.log.visible.VisiblePack
import com.intellij.vcs.log.visible.filters.VcsLogFilterObject
import com.intellij.vcs.log.visible.filters.matches
import com.intellij.vcsUtil.VcsUtil
import java.util.function.Function
fun isNewHistoryEnabled() = Registry.`is`("vcs.new.history")
class VcsLogFileHistoryProviderImpl : VcsLogFileHistoryProvider {
private val tabGroupId: TabGroupId = TabGroupId("History", VcsBundle.messagePointer("file.history.tab.name"), false)
override fun canShowFileHistory(project: Project, paths: Collection<FilePath>, revisionNumber: String?): Boolean {
if (!isNewHistoryEnabled()) return false
val dataManager = VcsProjectLog.getInstance(project).dataManager ?: return false
if (paths.size == 1) {
return canShowSingleFileHistory(project, dataManager, paths.single(), revisionNumber != null)
}
return revisionNumber == null && createPathsFilter(project, dataManager, paths) != null
}
private fun canShowSingleFileHistory(project: Project, dataManager: VcsLogData, path: FilePath, isRevisionHistory: Boolean): Boolean {
val root = VcsLogUtil.getActualRoot(project, path) ?: return false
return dataManager.index.isIndexingEnabled(root) ||
canShowHistoryInLog(dataManager, getCorrectedPath(project, path, root, isRevisionHistory), root)
}
override fun showFileHistory(project: Project, paths: Collection<FilePath>, revisionNumber: String?) {
val hash = revisionNumber?.let { HashImpl.build(it) }
val root = VcsLogUtil.getActualRoot(project, paths.first())!!
triggerFileHistoryUsage(project, paths, hash)
val logManager = VcsProjectLog.getInstance(project).logManager!!
val historyUiConsumer = { ui: VcsLogUiEx, firstTime: Boolean ->
if (hash != null) {
ui.jumpToNearestCommit(logManager.dataManager.storage, hash, root, true)
}
else if (firstTime) {
jumpToRow(ui, 0, true)
}
}
if (paths.size == 1) {
val correctedPath = getCorrectedPath(project, paths.single(), root, revisionNumber != null)
if (!canShowHistoryInLog(logManager.dataManager, correctedPath, root)) {
findOrOpenHistory(project, logManager, root, correctedPath, hash, historyUiConsumer)
return
}
}
findOrOpenFolderHistory(project, createHashFilter(hash, root), createPathsFilter(project, logManager.dataManager, paths)!!,
historyUiConsumer)
}
private fun canShowHistoryInLog(dataManager: VcsLogData,
correctedPath: FilePath,
root: VirtualFile): Boolean {
if (!correctedPath.isDirectory) {
return false
}
val logProvider = dataManager.logProviders[root] ?: return false
return VcsLogProperties.SUPPORTS_LOG_DIRECTORY_HISTORY.getOrDefault(logProvider)
}
private fun triggerFileHistoryUsage(project: Project, paths: Collection<FilePath>, hash: Hash?) {
VcsLogUsageTriggerCollector.triggerUsage(VcsLogUsageTriggerCollector.VcsLogEvent.HISTORY_SHOWN, { data ->
val kind = if (paths.size > 1) "multiple" else if (paths.first().isDirectory) "folder" else "file"
data.addData("kind", kind).addData("has_revision", hash != null)
}, project)
}
private fun findOrOpenHistory(project: Project, logManager: VcsLogManager,
root: VirtualFile, path: FilePath, hash: Hash?,
consumer: (VcsLogUiEx, Boolean) -> Unit) {
var fileHistoryUi = VcsLogContentUtil.findAndSelect(project, FileHistoryUi::class.java) { ui -> ui.matches(path, hash) }
val firstTime = fileHistoryUi == null
if (firstTime) {
val suffix = if (hash != null) " (" + hash.toShortString() + ")" else ""
fileHistoryUi = VcsLogContentUtil.openLogTab(project, logManager, tabGroupId, Function { path.name + suffix },
FileHistoryUiFactory(path, root, hash), true)
}
consumer(fileHistoryUi!!, firstTime)
}
private fun findOrOpenFolderHistory(project: Project, hashFilter: VcsLogFilter, pathsFilter: VcsLogFilter,
consumer: (VcsLogUiEx, Boolean) -> Unit) {
var ui = VcsLogContentUtil.findAndSelect(project, MainVcsLogUi::class.java) { logUi ->
matches(logUi.filterUi.filters, pathsFilter, hashFilter)
}
val firstTime = ui == null
if (firstTime) {
val filters = VcsLogFilterObject.collection(pathsFilter, hashFilter)
ui = VcsProjectLog.getInstance(project).openLogTab(filters) ?: return
ui.properties.set(MainVcsLogUiProperties.SHOW_ONLY_AFFECTED_CHANGES, true)
}
consumer(ui!!, firstTime)
}
private fun createPathsFilter(project: Project, dataManager: VcsLogData, paths: Collection<FilePath>): VcsLogFilter? {
val forRootFilter = mutableSetOf<VirtualFile>()
val forPathsFilter = mutableListOf<FilePath>()
for (path in paths) {
val root = VcsLogUtil.getActualRoot(project, path)
if (root == null) return null
if (!dataManager.roots.contains(root) ||
!VcsLogProperties.SUPPORTS_LOG_DIRECTORY_HISTORY.getOrDefault(dataManager.getLogProvider(root))) return null
val correctedPath = getCorrectedPath(project, path, root, false)
if (!correctedPath.isDirectory) return null
if (path.virtualFile == root) {
forRootFilter.add(root)
}
else {
forPathsFilter.add(correctedPath)
}
if (forPathsFilter.isNotEmpty() && forRootFilter.isNotEmpty()) return null
}
if (forPathsFilter.isNotEmpty()) return VcsLogFilterObject.fromPaths(forPathsFilter)
return VcsLogFilterObject.fromRoots(forRootFilter)
}
private fun createHashFilter(hash: Hash?, root: VirtualFile): VcsLogFilter {
if (hash == null) {
return VcsLogFilterObject.fromBranch(VcsLogUtil.HEAD)
}
return VcsLogFilterObject.fromCommit(CommitId(hash, root))
}
private fun matches(filters: VcsLogFilterCollection, pathsFilter: VcsLogFilter, hashFilter: VcsLogFilter): Boolean {
if (!filters.matches(hashFilter.key, pathsFilter.key)) {
return false
}
return filters.get(pathsFilter.key) == pathsFilter && filters.get(hashFilter.key) == hashFilter
}
private fun getCorrectedPath(project: Project, path: FilePath, root: VirtualFile,
isRevisionHistory: Boolean): FilePath {
var correctedPath = path
if (root != VcsUtil.getVcsRootFor(project, correctedPath) && correctedPath.isDirectory) {
correctedPath = VcsUtil.getFilePath(correctedPath.path, false)
}
if (!isRevisionHistory) {
return VcsUtil.getLastCommitPath(project, correctedPath)
}
return correctedPath
}
}
private fun VcsLogUiEx.jumpToNearestCommit(storage: VcsLogStorage, hash: Hash, root: VirtualFile, silently: Boolean) {
jumpTo(hash, { visiblePack: VisiblePack, h: Hash? ->
if (!storage.containsCommit(CommitId(h!!, root))) return@jumpTo GraphTableModel.COMMIT_NOT_FOUND
val commitIndex: Int = storage.getCommitIndex(h, root)
var rowIndex = visiblePack.visibleGraph.getVisibleRowIndex(commitIndex)
if (rowIndex == null) {
rowIndex = findVisibleAncestorRow(commitIndex, visiblePack)
}
rowIndex ?: GraphTableModel.COMMIT_DOES_NOT_MATCH
}, SettableFuture.create(), silently, true)
}
| apache-2.0 |
io53/Android_RuuvitagScanner | app/src/main/java/com/ruuvi/station/settings/ui/AppSettingsBackgroundScanViewModel.kt | 1 | 2030 | package com.ruuvi.station.settings.ui
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import android.os.Build
import com.ruuvi.station.R
import com.ruuvi.station.app.preferences.Preferences
import com.ruuvi.station.util.BackgroundScanModes
class AppSettingsBackgroundScanViewModel (private val preferences: Preferences): ViewModel() {
private val scanMode = MutableLiveData<BackgroundScanModes>()
private val interval = MutableLiveData<Int>()
init {
scanMode.value = preferences.backgroundScanMode
interval.value = preferences.backgroundScanInterval
}
fun observeScanMode(): LiveData<BackgroundScanModes> = scanMode
fun observeInterval(): LiveData<Int> = interval
fun setBackgroundMode(mode: BackgroundScanModes){
preferences.backgroundScanMode = mode
}
fun setBackgroundScanInterval(newInterval: Int) {
preferences.backgroundScanInterval = newInterval
}
fun getPossibleScanModes() = listOf(
BackgroundScanModes.DISABLED,
BackgroundScanModes.BACKGROUND
)
fun getBatteryOptimizationMessageId(): Int {
val deviceManufacturer = Build.MANUFACTURER.toUpperCase()
val deviceApi = Build.VERSION.SDK_INT
return when (deviceManufacturer) {
SAMSUNG_MANUFACTURER ->
if (deviceApi <= Build.VERSION_CODES.M) {
R.string.background_scan_samsung23_instructions
} else {
R.string.background_scan_samsung_instructions
}
XIAOMI_MANUFACTURER -> R.string.background_scan_xiaomi_instructions
HUAWEI_MANUFACTURER -> R.string.background_scan_huawei_instructions
else -> R.string.background_scan_common_instructions
}
}
companion object {
const val SAMSUNG_MANUFACTURER = "SAMSUNG"
const val XIAOMI_MANUFACTURER = "XIAOMI"
const val HUAWEI_MANUFACTURER = "HUAWEI"
}
} | mit |
leafclick/intellij-community | platform/projectModel-impl/src/com/intellij/openapi/components/impl/stores/ModuleStore.kt | 1 | 812 | /*
* 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.openapi.components.impl.stores
import org.jetbrains.annotations.SystemIndependent
interface ModuleStore : IComponentStore {
fun setPath(path: @SystemIndependent String, isNew: Boolean)
} | apache-2.0 |
faceofcat/Tesla-Core-Lib | src/main/kotlin/net/ndrei/teslacorelib/items/TeslaBattery.kt | 1 | 6504 | package net.ndrei.teslacorelib.items
import cofh.redstoneflux.api.IEnergyContainerItem
import com.mojang.realmsclient.gui.ChatFormatting
import net.minecraft.client.util.ITooltipFlag
import net.minecraft.creativetab.CreativeTabs
import net.minecraft.item.ItemStack
import net.minecraft.nbt.NBTTagCompound
import net.minecraft.util.EnumFacing
import net.minecraft.util.NonNullList
import net.minecraft.util.ResourceLocation
import net.minecraft.world.World
import net.minecraftforge.common.capabilities.Capability
import net.minecraftforge.common.capabilities.ICapabilityProvider
import net.minecraftforge.common.util.Constants
import net.minecraftforge.common.util.INBTSerializable
import net.minecraftforge.energy.CapabilityEnergy
import net.minecraftforge.energy.EnergyStorage
import net.minecraftforge.fml.common.Optional
import net.minecraftforge.fml.relauncher.Side
import net.minecraftforge.fml.relauncher.SideOnly
import net.ndrei.teslacorelib.annotations.AutoRegisterItem
import net.ndrei.teslacorelib.compatibility.RFPowerProxy
import net.ndrei.teslacorelib.config.TeslaCoreLibConfig
/**
* Created by CF on 2017-06-27.
*/
@AutoRegisterItem(TeslaCoreLibConfig.REGISTER_BATTERY)
@Optional.Interface(iface = "cofh.redstoneflux.api.IEnergyContainerItem", modid = RFPowerProxy.MODID, striprefs = true)
object TeslaBattery
: CoreItem("battery"), IEnergyContainerItem {
init {
super
.setHasSubtypes(true)
.addPropertyOverride(ResourceLocation("power"), { stack, _, _ ->
val energy = stack.getCapability(CapabilityEnergy.ENERGY, null)
if (energy == null) {
0.0f
} else {
val thing = Math.round(energy.energyStored.toDouble() / energy.maxEnergyStored.toDouble() * 6)
Math.max(0, Math.min(6, thing)).toFloat()
}
})
}
override fun initCapabilities(stack: ItemStack?, nbt: NBTTagCompound?): ICapabilityProvider? {
return object: ICapabilityProvider, INBTSerializable<NBTTagCompound> {
private var storage = EnergyStorage(10000, 100, 100)
@Suppress("UNCHECKED_CAST")
override fun <T : Any?> getCapability(capability: Capability<T>, facing: EnumFacing?): T?
= if (capability == CapabilityEnergy.ENERGY) (this.storage as? T) else null
override fun hasCapability(capability: Capability<*>, facing: EnumFacing?)
= capability == CapabilityEnergy.ENERGY
override fun deserializeNBT(nbt: NBTTagCompound?) {
val capacity = if ((nbt != null) && nbt.hasKey("capacity", Constants.NBT.TAG_INT))
nbt.getInteger("capacity")
else 10000
val stored = if ((nbt != null) && nbt.hasKey("stored", Constants.NBT.TAG_INT))
nbt.getInteger("stored")
else 0
val inputRate = /*if ((nbt != null) && nbt.hasKey("input_rate", Constants.NBT.TAG_INT))
nbt.getInteger("input_rate")
else*/ 100
val outputRate = /*if ((nbt != null) && nbt.hasKey("output_rate", Constants.NBT.TAG_INT))
nbt.getInteger("output_rate")
else*/ 100
this.storage = EnergyStorage(capacity, inputRate, outputRate, stored)
}
override fun serializeNBT(): NBTTagCompound {
return NBTTagCompound().also {
it.setInteger("capacity", this.storage.maxEnergyStored)
it.setInteger("stored", this.storage.energyStored)
// it.setInteger("input_rate", 100)
// it.setInteger("output_rate", 100)
}
}
}
}
override fun getItemStackLimit(stack: ItemStack?): Int {
val energy = stack?.getCapability(CapabilityEnergy.ENERGY, null)
return if ((energy == null) || (energy.energyStored == 0)) 16 else 1
}
@SideOnly(Side.CLIENT)
override fun addInformation(stack: ItemStack?, worldIn: World?, tooltip: MutableList<String>?, flagIn: ITooltipFlag?) {
val energy = stack?.getCapability(CapabilityEnergy.ENERGY, null)
if (energy != null) {
if (energy.energyStored > 0) {
tooltip!!.add(ChatFormatting.AQUA.toString() + "Power: " + energy.energyStored + ChatFormatting.RESET + " of " + ChatFormatting.AQUA + energy.maxEnergyStored)
} else {
tooltip!!.add(ChatFormatting.RED.toString() + "EMPTY!")
}
}
super.addInformation(stack, worldIn, tooltip, flagIn)
}
@SideOnly(Side.CLIENT)
override fun getSubItems(tab: CreativeTabs, subItems: NonNullList<ItemStack>) {
if (this.isInCreativeTab(tab)) {
subItems.add(ItemStack(this))
val full = ItemStack(this)
val energy = full.getCapability(CapabilityEnergy.ENERGY, null)
if (energy != null) {
var cycle = 0
while(energy.canReceive() && (energy.maxEnergyStored > energy.energyStored) && (cycle++ < 100)) {
energy.receiveEnergy(energy.maxEnergyStored - energy.energyStored, false)
}
}
subItems.add(full)
}
}
//#region IEnergyContainerItem members
@Optional.Method(modid = RFPowerProxy.MODID)
override fun getMaxEnergyStored(container: ItemStack?): Int {
val energy = container?.getCapability(CapabilityEnergy.ENERGY, null) ?: return 0
return energy.maxEnergyStored
}
@Optional.Method(modid = RFPowerProxy.MODID)
override fun getEnergyStored(container: ItemStack?): Int {
val energy = container?.getCapability(CapabilityEnergy.ENERGY, null) ?: return 0
return energy.energyStored
}
@Optional.Method(modid = RFPowerProxy.MODID)
override fun extractEnergy(container: ItemStack?, maxExtract: Int, simulate: Boolean): Int {
val energy = container?.getCapability(CapabilityEnergy.ENERGY, null) ?: return 0
return energy.extractEnergy(maxExtract, simulate)
}
@Optional.Method(modid = RFPowerProxy.MODID)
override fun receiveEnergy(container: ItemStack?, maxReceive: Int, simulate: Boolean): Int {
val energy = container?.getCapability(CapabilityEnergy.ENERGY, null) ?: return 0
return energy.receiveEnergy(maxReceive, simulate)
}
//#endregion
}
| mit |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/statics/anonymousInitializerInClassObject.kt | 5 | 157 | class Foo {
companion object {
val bar: String
init {
bar = "OK"
}
}
}
fun box(): String {
return Foo.bar
} | apache-2.0 |
MGaetan89/Kolumbus | app/src/main/kotlin/io/kolumbus/demo/model/Product.kt | 1 | 292 | package io.kolumbus.demo.model
import io.realm.RealmList
import io.realm.RealmObject
import io.realm.annotations.PrimaryKey
open class Product : RealmObject() {
open var description = ""
@PrimaryKey
open var id = 0
open var name = ""
open var categories: RealmList<Category>? = null
}
| apache-2.0 |
AndroidX/androidx | compose/material/material/src/commonMain/kotlin/androidx/compose/material/Colors.kt | 3 | 13326 | /*
* Copyright 2019 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.material
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ReadOnlyComposable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.runtime.structuralEqualityPolicy
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.takeOrElse
/**
* <a href="https://material.io/design/color/the-color-system.html" class="external" target="_blank">Material Design color system</a>.
*
* The Material Design color system can help you create a color theme that reflects your brand or
* style.
*
* 
*
* To create a light set of colors using the baseline values, use [lightColors]
* To create a dark set of colors using the baseline values, use [darkColors]
*
* @property primary The primary color is the color displayed most frequently across your app’s
* screens and components.
* @property primaryVariant The primary variant color is used to distinguish two elements of the
* app using the primary color, such as the top app bar and the system bar.
* @property secondary The secondary color provides more ways to accent and distinguish your
* product. Secondary colors are best for:
* - Floating action buttons
* - Selection controls, like checkboxes and radio buttons
* - Highlighting selected text
* - Links and headlines
* @property secondaryVariant The secondary variant color is used to distinguish two elements of the
* app using the secondary color.
* @property background The background color appears behind scrollable content.
* @property surface The surface color is used on surfaces of components, such as cards, sheets and
* menus.
* @property error The error color is used to indicate error within components, such as text fields.
* @property onPrimary Color used for text and icons displayed on top of the primary color.
* @property onSecondary Color used for text and icons displayed on top of the secondary color.
* @property onBackground Color used for text and icons displayed on top of the background color.
* @property onSurface Color used for text and icons displayed on top of the surface color.
* @property onError Color used for text and icons displayed on top of the error color.
* @property isLight Whether this Colors is considered as a 'light' or 'dark' set of colors. This
* affects default behavior for some components: for example, in a light theme a [TopAppBar] will
* use [primary] by default for its background color, when in a dark theme it will use [surface].
*/
@Stable
class Colors(
primary: Color,
primaryVariant: Color,
secondary: Color,
secondaryVariant: Color,
background: Color,
surface: Color,
error: Color,
onPrimary: Color,
onSecondary: Color,
onBackground: Color,
onSurface: Color,
onError: Color,
isLight: Boolean
) {
var primary by mutableStateOf(primary, structuralEqualityPolicy())
internal set
var primaryVariant by mutableStateOf(primaryVariant, structuralEqualityPolicy())
internal set
var secondary by mutableStateOf(secondary, structuralEqualityPolicy())
internal set
var secondaryVariant by mutableStateOf(secondaryVariant, structuralEqualityPolicy())
internal set
var background by mutableStateOf(background, structuralEqualityPolicy())
internal set
var surface by mutableStateOf(surface, structuralEqualityPolicy())
internal set
var error by mutableStateOf(error, structuralEqualityPolicy())
internal set
var onPrimary by mutableStateOf(onPrimary, structuralEqualityPolicy())
internal set
var onSecondary by mutableStateOf(onSecondary, structuralEqualityPolicy())
internal set
var onBackground by mutableStateOf(onBackground, structuralEqualityPolicy())
internal set
var onSurface by mutableStateOf(onSurface, structuralEqualityPolicy())
internal set
var onError by mutableStateOf(onError, structuralEqualityPolicy())
internal set
var isLight by mutableStateOf(isLight, structuralEqualityPolicy())
internal set
/**
* Returns a copy of this Colors, optionally overriding some of the values.
*/
fun copy(
primary: Color = this.primary,
primaryVariant: Color = this.primaryVariant,
secondary: Color = this.secondary,
secondaryVariant: Color = this.secondaryVariant,
background: Color = this.background,
surface: Color = this.surface,
error: Color = this.error,
onPrimary: Color = this.onPrimary,
onSecondary: Color = this.onSecondary,
onBackground: Color = this.onBackground,
onSurface: Color = this.onSurface,
onError: Color = this.onError,
isLight: Boolean = this.isLight
): Colors = Colors(
primary,
primaryVariant,
secondary,
secondaryVariant,
background,
surface,
error,
onPrimary,
onSecondary,
onBackground,
onSurface,
onError,
isLight
)
override fun toString(): String {
return "Colors(" +
"primary=$primary, " +
"primaryVariant=$primaryVariant, " +
"secondary=$secondary, " +
"secondaryVariant=$secondaryVariant, " +
"background=$background, " +
"surface=$surface, " +
"error=$error, " +
"onPrimary=$onPrimary, " +
"onSecondary=$onSecondary, " +
"onBackground=$onBackground, " +
"onSurface=$onSurface, " +
"onError=$onError, " +
"isLight=$isLight" +
")"
}
}
/**
* Creates a complete color definition for the
* [Material color specification](https://material.io/design/color/the-color-system.html#color-theme-creation)
* using the default light theme values.
*
* @see darkColors
*/
fun lightColors(
primary: Color = Color(0xFF6200EE),
primaryVariant: Color = Color(0xFF3700B3),
secondary: Color = Color(0xFF03DAC6),
secondaryVariant: Color = Color(0xFF018786),
background: Color = Color.White,
surface: Color = Color.White,
error: Color = Color(0xFFB00020),
onPrimary: Color = Color.White,
onSecondary: Color = Color.Black,
onBackground: Color = Color.Black,
onSurface: Color = Color.Black,
onError: Color = Color.White
): Colors = Colors(
primary,
primaryVariant,
secondary,
secondaryVariant,
background,
surface,
error,
onPrimary,
onSecondary,
onBackground,
onSurface,
onError,
true
)
/**
* Creates a complete color definition for the
* [Material color specification](https://material.io/design/color/the-color-system.html#color-theme-creation)
* using the default dark theme values.
*
* Note: [secondaryVariant] is typically the same as [secondary] in dark theme since contrast
* levels are higher, and hence there is less need for a separate secondary color.
*
* @see lightColors
*/
fun darkColors(
primary: Color = Color(0xFFBB86FC),
primaryVariant: Color = Color(0xFF3700B3),
secondary: Color = Color(0xFF03DAC6),
secondaryVariant: Color = secondary,
background: Color = Color(0xFF121212),
surface: Color = Color(0xFF121212),
error: Color = Color(0xFFCF6679),
onPrimary: Color = Color.Black,
onSecondary: Color = Color.Black,
onBackground: Color = Color.White,
onSurface: Color = Color.White,
onError: Color = Color.Black
): Colors = Colors(
primary,
primaryVariant,
secondary,
secondaryVariant,
background,
surface,
error,
onPrimary,
onSecondary,
onBackground,
onSurface,
onError,
false
)
/**
* primarySurface represents the background color of components that are [Colors.primary]
* in light theme, and [Colors.surface] in dark theme, such as [androidx.compose.material.TabRow]
* and [androidx.compose.material.TopAppBar]. This is to reduce brightness of large surfaces in dark
* theme, aiding contrast and readability. See
* [Dark Theme](https://material.io/design/color/dark-theme.html#custom-application).
*
* @return [Colors.primary] if in light theme, else [Colors.surface]
*/
val Colors.primarySurface: Color get() = if (isLight) primary else surface
/**
* The Material color system contains pairs of colors that are typically used for the background
* and content color inside a component. For example, a [Button] typically uses `primary` for its
* background, and `onPrimary` for the color of its content (usually text or iconography).
*
* This function tries to match the provided [backgroundColor] to a 'background' color in this
* [Colors], and then will return the corresponding color used for content. For example, when
* [backgroundColor] is [Colors.primary], this will return [Colors.onPrimary].
*
* If [backgroundColor] does not match a background color in the theme, this will return
* [Color.Unspecified].
*
* @return the matching content color for [backgroundColor]. If [backgroundColor] is not present in
* the theme's [Colors], then returns [Color.Unspecified].
*
* @see contentColorFor
*/
fun Colors.contentColorFor(backgroundColor: Color): Color {
return when (backgroundColor) {
primary -> onPrimary
primaryVariant -> onPrimary
secondary -> onSecondary
secondaryVariant -> onSecondary
background -> onBackground
surface -> onSurface
error -> onError
else -> Color.Unspecified
}
}
/**
* The Material color system contains pairs of colors that are typically used for the background
* and content color inside a component. For example, a [Button] typically uses `primary` for its
* background, and `onPrimary` for the color of its content (usually text or iconography).
*
* This function tries to match the provided [backgroundColor] to a 'background' color in this
* [Colors], and then will return the corresponding color used for content. For example, when
* [backgroundColor] is [Colors.primary], this will return [Colors.onPrimary].
*
* If [backgroundColor] does not match a background color in the theme, this will return
* the current value of [LocalContentColor] as a best-effort color.
*
* @return the matching content color for [backgroundColor]. If [backgroundColor] is not present in
* the theme's [Colors], then returns the current value of [LocalContentColor].
*
* @see Colors.contentColorFor
*/
@Composable
@ReadOnlyComposable
fun contentColorFor(backgroundColor: Color) =
MaterialTheme.colors.contentColorFor(backgroundColor).takeOrElse { LocalContentColor.current }
/**
* Updates the internal values of the given [Colors] with values from the [other] [Colors]. This
* allows efficiently updating a subset of [Colors], without recomposing every composable that
* consumes values from [LocalColors].
*
* Because [Colors] is very wide-reaching, and used by many expensive composables in the
* hierarchy, providing a new value to [LocalColors] causes every composable consuming
* [LocalColors] to recompose, which is prohibitively expensive in cases such as animating one
* color in the theme. Instead, [Colors] is internally backed by [mutableStateOf], and this
* function mutates the internal state of [this] to match values in [other]. This means that any
* changes will mutate the internal state of [this], and only cause composables that are reading
* the specific changed value to recompose.
*/
internal fun Colors.updateColorsFrom(other: Colors) {
primary = other.primary
primaryVariant = other.primaryVariant
secondary = other.secondary
secondaryVariant = other.secondaryVariant
background = other.background
surface = other.surface
error = other.error
onPrimary = other.onPrimary
onSecondary = other.onSecondary
onBackground = other.onBackground
onSurface = other.onSurface
onError = other.onError
isLight = other.isLight
}
/**
* CompositionLocal used to pass [Colors] down the tree.
*
* Setting the value here is typically done as part of [MaterialTheme], which will
* automatically handle efficiently updating any changed colors without causing unnecessary
* recompositions, using [Colors.updateColorsFrom].
* To retrieve the current value of this CompositionLocal, use [MaterialTheme.colors].
*/
internal val LocalColors = staticCompositionLocalOf { lightColors() }
| apache-2.0 |
hannesa2/owncloud-android | owncloudData/src/main/java/com/owncloud/android/data/sharing/shares/datasources/mapper/RemoteShareMapper.kt | 2 | 2746 | /**
* ownCloud Android client application
*
* @author David González Verdugo
* Copyright (C) 2020 ownCloud GmbH.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* 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.owncloud.android.data.sharing.shares.datasources.mapper
import com.owncloud.android.domain.mappers.RemoteMapper
import com.owncloud.android.domain.sharing.shares.model.OCShare
import com.owncloud.android.domain.sharing.shares.model.ShareType
import com.owncloud.android.lib.resources.shares.RemoteShare
import com.owncloud.android.lib.resources.shares.ShareType as RemoteShareType
class RemoteShareMapper : RemoteMapper<OCShare, RemoteShare> {
override fun toModel(remote: RemoteShare?): OCShare? =
remote?.let {
OCShare(
shareType = ShareType.fromValue(remote.shareType!!.value)!!,
shareWith = remote.shareWith,
path = remote.path,
permissions = remote.permissions,
sharedDate = remote.sharedDate,
expirationDate = remote.expirationDate,
token = remote.token,
sharedWithDisplayName = remote.sharedWithDisplayName,
sharedWithAdditionalInfo = remote.sharedWithAdditionalInfo,
isFolder = remote.isFolder,
remoteId = remote.id,
name = remote.name,
shareLink = remote.shareLink
)
}
override fun toRemote(model: OCShare?): RemoteShare? =
model?.let {
RemoteShare(
id = model.remoteId,
shareWith = model.shareWith!!,
path = model.path,
token = model.token!!,
sharedWithDisplayName = model.sharedWithDisplayName!!,
sharedWithAdditionalInfo = model.sharedWithAdditionalInfo!!,
name = model.name!!,
shareLink = model.shareLink!!,
shareType = RemoteShareType.fromValue(model.shareType.value),
permissions = model.permissions,
sharedDate = model.sharedDate,
expirationDate = model.expirationDate,
isFolder = model.isFolder,
)
}
}
| gpl-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/findWithStructuralGrouping/kotlinPropertyUsages.0.kt | 1 | 498 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtProperty
// GROUPING_RULES: org.jetbrains.kotlin.idea.findUsages.KotlinDeclarationGroupingRule
// OPTIONS: usages
// FIR_IGNORE
package server
open class A<T> {
open var <caret>foo: T = TODO()
}
open class B : A<String>() {
override var foo: String
get() {
println("get")
return super<A>.foo
}
set(value: String) {
println("set:" + value)
super<A>.foo = value
}
}
| apache-2.0 |
mglukhikh/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/ResolveUtil.kt | 1 | 6262 | // Copyright 2000-2018 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.
@file:Suppress("LoopToCallChain")
package org.jetbrains.plugins.groovy.lang.resolve
import com.intellij.openapi.util.Key
import com.intellij.psi.*
import com.intellij.psi.scope.ElementClassHint
import com.intellij.psi.scope.ElementClassHint.DeclarationKind
import com.intellij.psi.scope.NameHint
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.psi.util.CachedValueProvider.Result
import com.intellij.psi.util.CachedValuesManager.getCachedValue
import org.jetbrains.plugins.groovy.lang.psi.GroovyFileBase
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotation
import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrStatement
import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement
import org.jetbrains.plugins.groovy.lang.psi.api.util.GrStatementOwner
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.DefaultConstructor
import org.jetbrains.plugins.groovy.lang.psi.util.skipSameTypeParents
import org.jetbrains.plugins.groovy.lang.resolve.processors.DynamicMembersHint
import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolveKind
import org.jetbrains.plugins.groovy.lang.resolve.processors.GroovyResolverProcessor
@JvmField
val NON_CODE = Key.create<Boolean?>("groovy.process.non.code.members")
fun initialState(processNonCodeMembers: Boolean) = ResolveState.initial().put(NON_CODE, processNonCodeMembers)
fun ResolveState.processNonCodeMembers(): Boolean = get(NON_CODE).let { it == null || it }
fun treeWalkUp(place: PsiElement, processor: PsiScopeProcessor, state: ResolveState): Boolean {
return ResolveUtil.treeWalkUp(place, place, processor, state)
}
fun GrStatementOwner.processStatements(lastParent: PsiElement?, processor: (GrStatement) -> Boolean): Boolean {
var run = if (lastParent == null) lastChild else lastParent.prevSibling
while (run != null) {
if (run is GrStatement && !processor(run)) return false
run = run.prevSibling
}
return true
}
fun GrStatementOwner.processLocals(processor: PsiScopeProcessor, state: ResolveState, lastParent: PsiElement?, place: PsiElement): Boolean {
return !processor.shouldProcessLocals() || processStatements(lastParent) {
it.processDeclarations(processor, state, null, place)
}
}
fun PsiScopeProcessor.checkName(name: String, state: ResolveState): Boolean {
val expectedName = getName(state) ?: return true
return expectedName == name
}
fun PsiScopeProcessor.getName(state: ResolveState): String? = getHint(NameHint.KEY)?.getName(state)
fun shouldProcessDynamicMethods(processor: PsiScopeProcessor): Boolean {
return processor.getHint(DynamicMembersHint.KEY)?.shouldProcessMethods() ?: false
}
fun PsiScopeProcessor.shouldProcessDynamicProperties(): Boolean {
return getHint(DynamicMembersHint.KEY)?.shouldProcessProperties() ?: false
}
fun PsiScopeProcessor.shouldProcessLocals(): Boolean = shouldProcess(GroovyResolveKind.VARIABLE)
fun PsiScopeProcessor.shouldProcessFields(): Boolean = shouldProcess(GroovyResolveKind.FIELD)
fun PsiScopeProcessor.shouldProcessMethods(): Boolean {
return ResolveUtil.shouldProcessMethods(getHint(ElementClassHint.KEY))
}
fun PsiScopeProcessor.shouldProcessClasses(): Boolean {
return ResolveUtil.shouldProcessClasses(getHint(ElementClassHint.KEY))
}
fun PsiScopeProcessor.shouldProcessMembers(): Boolean {
val hint = getHint(ElementClassHint.KEY) ?: return true
return hint.shouldProcess(DeclarationKind.CLASS) ||
hint.shouldProcess(DeclarationKind.FIELD) ||
hint.shouldProcess(DeclarationKind.METHOD)
}
fun PsiScopeProcessor.shouldProcessTypeParameters(): Boolean {
if (shouldProcessClasses()) return true
val groovyKindHint = getHint(GroovyResolveKind.HINT_KEY) ?: return true
return groovyKindHint.shouldProcess(GroovyResolveKind.TYPE_PARAMETER)
}
fun PsiScopeProcessor.shouldProcessProperties(): Boolean {
return this is GroovyResolverProcessor && isPropertyResolve
}
fun PsiScopeProcessor.shouldProcessPackages(): Boolean = shouldProcess(GroovyResolveKind.PACKAGE)
private fun PsiScopeProcessor.shouldProcess(kind: GroovyResolveKind): Boolean {
val resolveKindHint = getHint(GroovyResolveKind.HINT_KEY)
if (resolveKindHint != null) return resolveKindHint.shouldProcess(kind)
val elementClassHint = getHint(ElementClassHint.KEY) ?: return true
return kind.declarationKinds.any(elementClassHint::shouldProcess)
}
fun wrapClassType(type: PsiType, context: PsiElement) = TypesUtil.createJavaLangClassType(type, context.project, context.resolveScope)
fun getDefaultConstructor(clazz: PsiClass): PsiMethod {
return getCachedValue(clazz) {
Result.create(DefaultConstructor(clazz), clazz)
}
}
fun GroovyFileBase.processClassesInFile(processor: PsiScopeProcessor, state: ResolveState): Boolean {
if (!processor.shouldProcessClasses()) return true
val scriptClass = scriptClass
if (scriptClass != null && !ResolveUtil.processElement(processor, scriptClass, state)) return false
for (definition in typeDefinitions) {
if (!ResolveUtil.processElement(processor, definition, state)) return false
}
return true
}
fun GroovyFileBase.processClassesInPackage(processor: PsiScopeProcessor, state: ResolveState, place: PsiElement = this): Boolean {
if (!processor.shouldProcessClasses()) return true
val aPackage = JavaPsiFacade.getInstance(project).findPackage(packageName) ?: return true
return aPackage.processDeclarations(PackageSkippingProcessor(processor), state, null, place)
}
val PsiScopeProcessor.annotationHint: AnnotationHint? get() = getHint(AnnotationHint.HINT_KEY)
fun PsiScopeProcessor.isAnnotationResolve(): Boolean {
val hint = annotationHint ?: return false
return hint.isAnnotationResolve
}
fun PsiScopeProcessor.isNonAnnotationResolve(): Boolean {
val hint = annotationHint ?: return false
return !hint.isAnnotationResolve
}
fun GrCodeReferenceElement.isAnnotationReference(): Boolean {
val (possibleAnnotation, _) = skipSameTypeParents()
return possibleAnnotation is GrAnnotation
}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/convertLambdaToReference/unitWithOverloadedFunctions.kt | 9 | 230 | // IS_APPLICABLE: false
class Random {
fun nextInt(): Int {
return 42
}
fun nextInt(bound: Int): Int {
return 42
}
}
fun main() {
val random: (Int) -> Unit = {<caret> Random().nextInt(it) }
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/completion/tests/testData/handlers/charFilter/NamedParameter2.kt | 13 | 105 | fun foo(xxx: Int, yyy: Int)
fun test() {
foo(xxx = 10, <caret>)
}
// ELEMENT: "yyy ="
// CHAR: ' '
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/intentions/replaceUnderscoreWithParameterName/conflict.kt | 9 | 196 | // WITH_STDLIB
// AFTER-WARNING: Variable 'first' is never used
// AFTER-WARNING: Variable 'first1' is never used
fun foo(pair: Pair<Int, Int>) {
val (<caret>_, _) = pair
val first = 42
} | apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/j2k/new/tests/testData/copyPaste/OpenPublicFunctionToTopLevel.expected.kt | 13 | 11 | fun x() {}
| apache-2.0 |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/testData/findUsages/kotlin/companionObject/simple.0.kt | 3 | 157 | // PSI_ELEMENT: org.jetbrains.kotlin.psi.KtObjectDeclaration
// OPTIONS: usages
class Foo {
companion <caret>object {
fun f() {
}
}
} | apache-2.0 |
jotomo/AndroidAPS | app/src/main/java/info/nightscout/androidaps/plugins/profile/local/LocalProfilePlugin.kt | 1 | 12936 | package info.nightscout.androidaps.plugins.profile.local
import androidx.fragment.app.FragmentActivity
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.Constants
import info.nightscout.androidaps.R
import info.nightscout.androidaps.data.Profile
import info.nightscout.androidaps.events.EventProfileStoreChanged
import info.nightscout.androidaps.interfaces.*
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.general.nsclient.NSUpload
import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.DecimalFormatter
import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.utils.resources.ResourceHelper
import info.nightscout.androidaps.utils.sharedPreferences.SP
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
import kotlin.collections.ArrayList
@Singleton
class LocalProfilePlugin @Inject constructor(
injector: HasAndroidInjector,
aapsLogger: AAPSLogger,
private val rxBus: RxBusWrapper,
resourceHelper: ResourceHelper,
private val sp: SP,
private val profileFunction: ProfileFunction,
private val nsUpload: NSUpload
) : PluginBase(PluginDescription()
.mainType(PluginType.PROFILE)
.fragmentClass(LocalProfileFragment::class.java.name)
.enableByDefault(true)
.pluginIcon(R.drawable.ic_local_profile)
.pluginName(R.string.localprofile)
.shortName(R.string.localprofile_shortname)
.description(R.string.description_profile_local)
.setDefault(),
aapsLogger, resourceHelper, injector
), ProfileInterface {
private var rawProfile: ProfileStore? = null
private val defaultArray = "[{\"time\":\"00:00\",\"timeAsSeconds\":0,\"value\":0}]"
override fun onStart() {
super.onStart()
loadSettings()
}
class SingleProfile {
internal var name: String? = null
internal var mgdl: Boolean = false
internal var dia: Double = Constants.defaultDIA
internal var ic: JSONArray? = null
internal var isf: JSONArray? = null
internal var basal: JSONArray? = null
internal var targetLow: JSONArray? = null
internal var targetHigh: JSONArray? = null
fun deepClone(): SingleProfile {
val sp = SingleProfile()
sp.name = name
sp.mgdl = mgdl
sp.dia = dia
sp.ic = JSONArray(ic.toString())
sp.isf = JSONArray(isf.toString())
sp.basal = JSONArray(basal.toString())
sp.targetLow = JSONArray(targetLow.toString())
sp.targetHigh = JSONArray(targetHigh.toString())
return sp
}
}
var isEdited: Boolean = false
var profiles: ArrayList<SingleProfile> = ArrayList()
var numOfProfiles = 0
internal var currentProfileIndex = 0
fun currentProfile(): SingleProfile? = if (numOfProfiles > 0) profiles[currentProfileIndex] else null
@Synchronized
fun isValidEditState(): Boolean {
return createProfileStore().getDefaultProfile()?.isValid(resourceHelper.gs(R.string.localprofile), false)
?: false
}
@Synchronized
fun storeSettings(activity: FragmentActivity? = null) {
for (i in 0 until numOfProfiles) {
profiles[i].run {
val localProfileNumbered = Constants.LOCAL_PROFILE + "_" + i + "_"
sp.putString(localProfileNumbered + "name", name!!)
sp.putBoolean(localProfileNumbered + "mgdl", mgdl)
sp.putDouble(localProfileNumbered + "dia", dia)
sp.putString(localProfileNumbered + "ic", ic.toString())
sp.putString(localProfileNumbered + "isf", isf.toString())
sp.putString(localProfileNumbered + "basal", basal.toString())
sp.putString(localProfileNumbered + "targetlow", targetLow.toString())
sp.putString(localProfileNumbered + "targethigh", targetHigh.toString())
}
}
sp.putInt(Constants.LOCAL_PROFILE + "_profiles", numOfProfiles)
createAndStoreConvertedProfile()
isEdited = false
aapsLogger.debug(LTag.PROFILE, "Storing settings: " + rawProfile?.data.toString())
rxBus.send(EventProfileStoreChanged())
var namesOK = true
profiles.forEach {
val name = it.name ?: "."
if (name.contains(".")) namesOK = false
}
if (namesOK)
rawProfile?.let { nsUpload.uploadProfileStore(it.data) }
else
activity?.let {
OKDialog.show(it, "", resourceHelper.gs(R.string.profilenamecontainsdot))
}
}
@Synchronized
fun loadSettings() {
numOfProfiles = sp.getInt(Constants.LOCAL_PROFILE + "_profiles", 0)
profiles.clear()
// numOfProfiles = max(numOfProfiles, 1) // create at least one default profile if none exists
for (i in 0 until numOfProfiles) {
val p = SingleProfile()
val localProfileNumbered = Constants.LOCAL_PROFILE + "_" + i + "_"
p.name = sp.getString(localProfileNumbered + "name", Constants.LOCAL_PROFILE + i)
if (isExistingName(p.name)) continue
p.mgdl = sp.getBoolean(localProfileNumbered + "mgdl", false)
p.dia = sp.getDouble(localProfileNumbered + "dia", Constants.defaultDIA)
try {
p.ic = JSONArray(sp.getString(localProfileNumbered + "ic", defaultArray))
} catch (e1: JSONException) {
try {
p.ic = JSONArray(defaultArray)
} catch (ignored: JSONException) {
}
aapsLogger.error("Exception", e1)
}
try {
p.isf = JSONArray(sp.getString(localProfileNumbered + "isf", defaultArray))
} catch (e1: JSONException) {
try {
p.isf = JSONArray(defaultArray)
} catch (ignored: JSONException) {
}
aapsLogger.error("Exception", e1)
}
try {
p.basal = JSONArray(sp.getString(localProfileNumbered + "basal", defaultArray))
} catch (e1: JSONException) {
try {
p.basal = JSONArray(defaultArray)
} catch (ignored: JSONException) {
}
aapsLogger.error("Exception", e1)
}
try {
p.targetLow = JSONArray(sp.getString(localProfileNumbered + "targetlow", defaultArray))
} catch (e1: JSONException) {
try {
p.targetLow = JSONArray(defaultArray)
} catch (ignored: JSONException) {
}
aapsLogger.error("Exception", e1)
}
try {
p.targetHigh = JSONArray(sp.getString(localProfileNumbered + "targethigh", defaultArray))
} catch (e1: JSONException) {
try {
p.targetHigh = JSONArray(defaultArray)
} catch (ignored: JSONException) {
}
aapsLogger.error("Exception", e1)
}
profiles.add(p)
}
isEdited = false
numOfProfiles = profiles.size
createAndStoreConvertedProfile()
}
fun copyFrom(profile: Profile, newName: String): SingleProfile {
var verifiedName = newName
if (rawProfile?.getSpecificProfile(newName) != null) {
verifiedName += " " + DateUtil.now().toString()
}
val sp = SingleProfile()
sp.name = verifiedName
sp.mgdl = profile.units == Constants.MGDL
sp.dia = profile.dia
sp.ic = JSONArray(profile.data.getJSONArray("carbratio").toString())
sp.isf = JSONArray(profile.data.getJSONArray("sens").toString())
sp.basal = JSONArray(profile.data.getJSONArray("basal").toString())
sp.targetLow = JSONArray(profile.data.getJSONArray("target_low").toString())
sp.targetHigh = JSONArray(profile.data.getJSONArray("target_high").toString())
return sp
}
private fun isExistingName(name: String?): Boolean {
for (p in profiles) {
if (p.name == name) return true
}
return false
}
/*
{
"_id": "576264a12771b7500d7ad184",
"startDate": "2016-06-16T08:35:00.000Z",
"defaultProfile": "Default",
"store": {
"Default": {
"dia": "3",
"carbratio": [{
"time": "00:00",
"value": "30"
}],
"carbs_hr": "20",
"delay": "20",
"sens": [{
"time": "00:00",
"value": "100"
}],
"timezone": "UTC",
"basal": [{
"time": "00:00",
"value": "0.1"
}],
"target_low": [{
"time": "00:00",
"value": "0"
}],
"target_high": [{
"time": "00:00",
"value": "0"
}],
"startDate": "1970-01-01T00:00:00.000Z",
"units": "mmol"
}
},
"created_at": "2016-06-16T08:34:41.256Z"
}
*/
private fun createAndStoreConvertedProfile() {
rawProfile = createProfileStore()
}
fun addNewProfile() {
var free = 0
for (i in 1..10000) {
if (rawProfile?.getSpecificProfile(Constants.LOCAL_PROFILE + i) == null) {
free = i
break
}
}
val p = SingleProfile()
p.name = Constants.LOCAL_PROFILE + free
p.mgdl = profileFunction.getUnits() == Constants.MGDL
p.dia = Constants.defaultDIA
p.ic = JSONArray(defaultArray)
p.isf = JSONArray(defaultArray)
p.basal = JSONArray(defaultArray)
p.targetLow = JSONArray(defaultArray)
p.targetHigh = JSONArray(defaultArray)
profiles.add(p)
currentProfileIndex = profiles.size - 1
numOfProfiles++
createAndStoreConvertedProfile()
storeSettings()
}
fun cloneProfile() {
val p = profiles[currentProfileIndex].deepClone()
p.name = p.name + " copy"
profiles.add(p)
currentProfileIndex = profiles.size - 1
numOfProfiles++
createAndStoreConvertedProfile()
storeSettings()
isEdited = false
}
fun addProfile(p: SingleProfile) {
profiles.add(p)
currentProfileIndex = profiles.size - 1
numOfProfiles++
createAndStoreConvertedProfile()
storeSettings()
isEdited = false
}
fun removeCurrentProfile() {
profiles.removeAt(currentProfileIndex)
numOfProfiles--
if (profiles.size == 0) addNewProfile()
currentProfileIndex = 0
createAndStoreConvertedProfile()
storeSettings()
isEdited = false
}
fun createProfileStore(): ProfileStore {
val json = JSONObject()
val store = JSONObject()
try {
for (i in 0 until numOfProfiles) {
profiles[i].run {
val profile = JSONObject()
profile.put("dia", dia)
profile.put("carbratio", ic)
profile.put("sens", isf)
profile.put("basal", basal)
profile.put("target_low", targetLow)
profile.put("target_high", targetHigh)
profile.put("units", if (mgdl) Constants.MGDL else Constants.MMOL)
profile.put("timezone", TimeZone.getDefault().id)
store.put(name, profile)
}
}
if (numOfProfiles > 0) json.put("defaultProfile", currentProfile()?.name)
json.put("startDate", DateUtil.toISOAsUTC(DateUtil.now()))
json.put("store", store)
} catch (e: JSONException) {
aapsLogger.error("Unhandled exception", e)
}
return ProfileStore(injector, json)
}
override fun getProfile(): ProfileStore? {
return rawProfile
}
override fun getProfileName(): String {
return DecimalFormatter.to2Decimal(rawProfile?.getDefaultProfile()?.percentageBasalSum()
?: 0.0) + "U "
}
}
| agpl-3.0 |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.