path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
compose/foundation/foundation/src/test/kotlin/androidx/compose/foundation/text2/input/TextEditFilterTest.kt
androidx
256,589,781
false
null
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.text2.input import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.ui.text.input.KeyboardType import com.google.common.truth.Truth.assertThat import org.junit.Test @OptIn(ExperimentalFoundationApi::class) class TextEditFilterTest { @Test fun chainedFilters_areEqual() { val filter1 = TextEditFilter { _, _ -> // Noop } val filter2 = TextEditFilter { _, _ -> // Noop } val chain1 = filter1.then( filter2, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email) ) val chain2 = filter1.then( filter2, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email) ) assertThat(chain1).isEqualTo(chain2) } @Test fun chainedFilters_areNotEqual_whenKeyboardOptionsDifferent() { val filter1 = TextEditFilter { _, _ -> // Noop } val filter2 = TextEditFilter { _, _ -> // Noop } val chain1 = filter1.then( filter2, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email) ) val chain2 = filter1.then( filter2, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password) ) assertThat(chain1).isNotEqualTo(chain2) } @Test fun chainedFilters_areNotEqual_whenFiltersAreDifferent() { val filter1 = TextEditFilter { _, _ -> // Noop } val filter2 = TextEditFilter { _, _ -> // Noop } val filter3 = TextEditFilter { _, _ -> // Noop } val chain1 = filter1.then(filter2) val chain2 = filter1.then(filter3) assertThat(chain1).isNotEqualTo(chain2) } }
20
Kotlin
819
4,682
9ddc33236c8976556d20e1a9432b66280e307547
2,556
androidx
Apache License 2.0
src/main/kotlin/demos/AldousBroderDemo.kt
andeemarks
568,036,348
false
{"Kotlin": 44224}
package demos import DistanceGrid import ImageMazePainter import algos.AldousBroder import com.github.ajalt.mordant.rendering.AnsiLevel import com.github.ajalt.mordant.rendering.TextColors import com.github.ajalt.mordant.rendering.TextStyle import com.github.ajalt.mordant.terminal.Terminal class AldousBroderDemo(private val style: TextStyle = TextColors.white) : Demoable { private val t = Terminal(AnsiLevel.TRUECOLOR) override fun run() { repeat(5) { i -> t.println("Aldous Broder iteration $i...") buildMaze(i) } } private fun buildMaze(mazeIterationNumber: Int) { val tree = AldousBroder() val distanceGrid = DistanceGrid(10, 10) val grid = tree.on(distanceGrid) as DistanceGrid val middleCell = distanceGrid.at(5, 5) grid.distances = middleCell.distances() ImageMazePainter(grid).paint("aldous-broder-${mazeIterationNumber}.svg") } } fun main() { AldousBroderDemo().run() }
0
Kotlin
0
0
8284b3e65e4783c22b99b76eb99cee01ff0439ed
999
mazes-kotlin
MIT License
browser-kotlin/src/jsMain/kotlin/web/svg/SVGSwitchElement.kt
karakum-team
393,199,102
false
null
// Automatically generated - do not modify! package web.svg sealed external class SVGSwitchElement : SVGGraphicsElement
0
Kotlin
6
22
00321b7e81352bc3d7243dd6631e1fb178f528c8
126
types-kotlin
Apache License 2.0
vocabularies/generator/src/main/kotlin/net/subroh0508/otonashi/vocabulary/generator/internal/HttpClient.kt
subroh0508
175,314,339
false
null
package net.subroh0508.otonashi.vocabulary.generator.internal import okhttp3.OkHttpClient import okhttp3.Request internal object HttpClient { private val client = OkHttpClient() fun fetch(url: String): String { val request = Request.Builder() .url(url) .build() return client.newCall(request).execute().body()?.string() ?: throw IllegalStateException("Empty body") } }
1
Kotlin
0
10
bbf62cd0f24ec8b8133e144ec8d1bf04f55dcd8a
424
otonashi
MIT License
app/src/main/java/com/nadafeteih/bookstore/viewModel/savedBook/SavedBookViewModel.kt
NadaFeteiha
590,720,352
false
{"Kotlin": 70843}
package com.nadafeteih.bookstore.viewModel.savedBook import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.nadafeteih.bookstore.useCase.GetSavedBooksUseCase import com.nadafeteih.bookstore.useCase.SaveBookUseCase import com.nadafeteih.bookstore.viewModel.home.BookUIState import com.nadafeteih.bookstore.viewModel.home.BooksUIState import com.nadafeteih.bookstore.viewModel.home.toEntity import com.nadafeteih.bookstore.viewModel.home.toUIState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class SavedBookViewModel @Inject constructor( private val saveBook: SaveBookUseCase, private val getSavedBooks: GetSavedBooksUseCase ) : ViewModel() { private val _uiState = MutableStateFlow(BooksUIState()) val uiState = _uiState.asStateFlow() init { viewModelScope.launch { try { getSavedBooks().collect { books -> _uiState.update { it.copy(books = books.toUIState()) } } }catch (t:Throwable){ } } } fun onClickSave(book: BookUIState) { viewModelScope.launch { saveBook(book.toEntity(),true) _uiState.update { it.copy(books = _uiState.value.books .map {if (it.id == book.id) { it.copy(isSaved = !book.isSaved) } else { it } } ) } } } }
1
Kotlin
2
7
3758e5543d5053271777c073ecbcec5636c92934
1,617
BookStore
Apache License 2.0
src/commonMain/kotlin/app/thelema/shader/node/GLSLVec2Literal.kt
zeganstyl
275,550,896
false
null
/* * Copyright 2020-2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package app.thelema.shader.node import app.thelema.math.IVec2 import app.thelema.math.Vec2 /** @author zeganstyl */ class GLSLVec2Literal: GLSLLiteralBase() { override var inlineCode: String get() = asVec2() set(_) {} override val type: String get() = GLSLType.Vec2 override val componentName: String get() = "GLSLVec2Literal" var value: IVec2 = Vec2() set(value) { field.set(value) } override fun asFloat(): String = str(value.x) override fun asVec2(): String = "vec2(${str(value.x)}, ${str(value.y)})" override fun asVec3(): String = "vec3(${str(value.x)}, ${str(value.y)}, 0.0)" override fun asVec4(): String = "vec4(${str(value.x)}, ${str(value.y)}, 0.0, 1.0)" }
3
Kotlin
5
61
8e2943b6d2de3376ce338025b58ff31c14097caf
1,340
thelema-engine
Apache License 2.0
fuzzer/src/test/resources/compilerTestData/codegen/box/reflection/mapping/extensionProperty.kt
ItsLastDay
102,885,402
false
null
import kotlin.reflect.jvm.* import kotlin.test.assertEquals class K(var value: Long) var K.ext: Double get() = value.toDouble() set(value) { this.value = value.toLong() } fun box(): String { val p = K::ext val getter = p.javaGetter!! val setter = p.javaSetter!! assertEquals(getter, Class.forName("ExtensionPropertyKt").getMethod("getExt", K::class.java)) assertEquals(setter, Class.forName("ExtensionPropertyKt").getMethod("setExt", K::class.java, Double::class.java)) val k = K(42L) assert(getter.invoke(null, k) == 42.0) { "Fail k getter" } setter.invoke(null, k, -239.0) assert(getter.invoke(null, k) == -239.0) { "Fail k setter" } return "OK" }
2
Kotlin
0
6
56f50fc307709443bb0c53972d0c239e709ce8f2
717
KotlinFuzzer
MIT License
rd-kt/rd-framework/src/test/kotlin/com/jetbrains/rd/framework/test/cases/contexts/ContextWithExtTest.kt
JetBrains
107,686,809
false
null
package com.jetbrains.rd.framework.test.cases.contexts import com.jetbrains.rd.framework.RdContext import com.jetbrains.rd.framework.test.util.RdFrameworkTestBase import demo.demoModel import demo.extModel import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource class ContextWithExtTest : RdFrameworkTestBase() { @ParameterizedTest @ValueSource(booleans = [true, false]) fun testExtPreserveContextOnLateConnect(useHeavyContext: Boolean) { println("useHeavyContext: $useHeavyContext") val context = if(useHeavyContext) ContextsTest.TestKeyHeavy else ContextsTest.TestKeyLight clientProtocol.serializers.register(RdContext.marshallerFor(context)) serverProtocol.contexts.registerContext(context) val serverModel = serverProtocol.demoModel val clientModel = clientProtocol.demoModel val serverExt = serverModel.extModel val fireValues = listOf("a", "b", "c") setWireAutoFlush(false) fireValues.forEach { context.updateValue(it).use { serverExt.checker.fire(Unit) } } var numReceives = 0 val receivedContexts = mutableSetOf<String>() val clientExt = clientModel.extModel clientExt.checker.advise(clientLifetime) { numReceives++ receivedContexts.add(context.value ?: "null") } setWireAutoFlush(true) assertEquals(3, numReceives) assertEquals(fireValues.toSet(), receivedContexts) } }
36
null
53
384
cbf1373f7a764d0aeccee3146c814a69cea34ae7
1,630
rd
Apache License 2.0
privacy-config/privacy-config-impl/src/main/java/com/duckduckgo/privacy/config/impl/features/useragent/RealUserAgent.kt
duckduckgo
78,869,127
false
null
/* * Copyright (c) 2022 DuckDuckGo * * 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.duckduckgo.privacy.config.impl.features.useragent import com.duckduckgo.app.global.UriString import com.duckduckgo.di.scopes.AppScope import com.duckduckgo.privacy.config.api.UnprotectedTemporary import com.duckduckgo.privacy.config.api.UserAgent import com.duckduckgo.privacy.config.store.features.useragent.UserAgentRepository import com.squareup.anvil.annotations.ContributesBinding import javax.inject.Inject @ContributesBinding(AppScope::class) class RealUserAgent @Inject constructor( private val userAgentRepository: UserAgentRepository, private val unprotectedTemporary: UnprotectedTemporary ) : UserAgent { override fun isAnApplicationException(url: String): Boolean { return userAgentRepository.omitApplicationExceptions.any { UriString.sameOrSubdomain(url, it.domain) } } override fun isAVersionException(url: String): Boolean { return userAgentRepository.omitVersionExceptions.any { UriString.sameOrSubdomain(url, it.domain) } } override fun isADefaultException(url: String): Boolean { return unprotectedTemporary.isAnException(url) || userAgentRepository.defaultExceptions.any { UriString.sameOrSubdomain(url, it.domain) } } }
49
null
847
3,198
be3bcd0ff64a25d9732b72a618c27accce467a5a
1,812
Android
Apache License 2.0
app/src/main/java/com/arturkowalczyk300/cryptocurrencyprices/model/Repository.kt
arturkowalczyk300
488,542,310
false
{"Kotlin": 136239}
package com.arturkowalczyk300.cryptocurrencyprices.model import android.app.Application import android.util.Log import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.Observer import com.arturkowalczyk300.cryptocurrencyprices.model.room.* import com.arturkowalczyk300.cryptocurrencyprices.model.webAccess.CryptocurrencyPricesWebService import kotlinx.coroutines.runBlocking import java.util.* import javax.inject.Inject class Repository @Inject constructor( private val application: Application, private val webService: CryptocurrencyPricesWebService, private val database: CryptocurrencyPricesDatabase, ) { private var _chartDataObserved = false private var _cryptocurrencyChartData = MutableLiveData<InfoWithinTimeRangeEntity?>() private val cryptocurrencyChartData: LiveData<InfoWithinTimeRangeEntity?> = _cryptocurrencyChartData private var _lastChartDataFromDaoRef: LiveData<List<InfoWithinTimeRangeEntity>>? = null private var _lastChartDataFromDaoObserver: Observer<List<InfoWithinTimeRangeEntity>?>? = null private fun addCryptocurrency(entity: CryptocurrencyEntity) { runBlocking { database!!.userDao()!!.addCryptocurrency(entity) } } fun getAllCryptocurrencies(): LiveData<List<CryptocurrencyEntity>> { return database!!.userDao()!!.getAllCryptocurrencies() } private suspend fun deleteAllCryptocurrencies() { database!!.userDao()!!.deleteAllCryptocurrencies() } fun getAllCryptocurrenciesPrices(): LiveData<List<PriceEntity>> { return database!!.userDao().getAllCryptocurrenciesPrices() } private suspend fun deleteAllCryptocurrenciesPrices() { database!!.userDao().deleteAllCryptocurrenciesPrices() } private suspend fun deletePricesOfGivenCryptocurrency(cryptocurrencyId: String) { database!!.userDao().deletePricesOfGivenCryptocurrency(cryptocurrencyId) } private suspend fun addCryptocurrencyPrice(entity: PriceEntity) { database!!.userDao()!!.deletePricesOfGivenCryptocurrency(entity.cryptocurrencyId) database!!.userDao()!!.addCryptocurrencyPrice(entity) } private suspend fun addCryptocurrencyInfoWithinTimeRange(entity: InfoWithinTimeRangeEntity) { if (entity.daysCount > 0) database!!.userDao()!!.deleteAllCryptocurrenciesInfoInGivenDaysCount( entity.cryptocurrencyId, entity.daysCount ) database!!.userDao()!!.addCryptocurrencyInfoWithinTimeRange(entity) } fun getAllCryptocurrenciesInfo(): LiveData<List<InfoWithinTimeRangeEntity>> { return database!!.userDao()!!.getAllCryptocurrenciesInfoWithinTimeRange() } fun getCryptocurrencyChartData( cryptocurrencyId: String? = null, daysCount: Int? = null, ): LiveData<InfoWithinTimeRangeEntity?> { if (cryptocurrencyId != null && daysCount != null ) { //update data, if parameters are given val observer: androidx.lifecycle.Observer<List<InfoWithinTimeRangeEntity>?> = object : androidx.lifecycle.Observer<List<InfoWithinTimeRangeEntity>?> { override fun onChanged(currenciesChartData: List<InfoWithinTimeRangeEntity>?) { if (currenciesChartData != null) { _cryptocurrencyChartData.value = currenciesChartData .filter { it.cryptocurrencyId == cryptocurrencyId && it.daysCount == daysCount } .maxByOrNull { it.updateDate.time } } } } _lastChartDataFromDaoObserver?.let { removeChartDataObserver(_lastChartDataFromDaoObserver!!) } _lastChartDataFromDaoRef = database!!.userDao()!! .getInfoOfCryptocurrencyWithinTimeRange( cryptocurrencyId, daysCount ).also { it.observeForever(observer) _lastChartDataFromDaoObserver = observer } } return cryptocurrencyChartData } private fun removeChartDataObserver(observer: Observer<List<InfoWithinTimeRangeEntity>?>) { if (_lastChartDataFromDaoRef != null && _lastChartDataFromDaoRef!!.hasActiveObservers()) _lastChartDataFromDaoRef!!.removeObserver(observer) } private suspend fun deleteAllCryptocurrenciesInfo() { database!!.userDao()!!.deleteAllCryptocurrenciesInfo() } private suspend fun deleteCryptocurrencyInfoContainsGivenDay( cryptocurrencyId: String, unixTimeDay: Long, ) { database!!.userDao()!!.deleteCryptocurrencyInfoContainsGivenDay( cryptocurrencyId, unixTimeDay ) } suspend fun updatePriceData( currencySymbol: String, vs_currency: String, archival: Boolean = false, archivalDate: Date? = null, ) { if (!archival || archivalDate != null) { val liveData = when (archival) { true -> webService.requestArchivalPriceData(currencySymbol, archivalDate!!) else -> webService.requestActualPriceData(currencySymbol, vs_currency) } if (!liveData.hasActiveObservers()) liveData.observeForever { response -> if (response?.actualPrice != null) //value check { runBlocking { addCryptocurrencyPrice( PriceEntity( index = 0, //auto-increment, no need to specify manually cryptocurrencyId = response.currencySymbol, price = response.actualPrice!!.toDouble(), date = Date(response.date.time * 1000), ) ) } } } } } suspend fun updateCryptocurrenciesList() { val liveData = webService.requestCryptocurrenciesList() if (!liveData.hasActiveObservers()) liveData.observeForever() { response -> runBlocking { deleteAllCryptocurrencies() } response.forEach { row -> this.addCryptocurrency( CryptocurrencyEntity( market_cap_rank = row.market_cap_rank, cryptocurrencyId = row.id, name = row.id, symbol = row.symbol, marketCap = row.market_cap, currentPrice = row.current_price, updateDate = Date() ) ) } } } suspend fun updateCryptocurrenciesInfoWithinDateRange( currencySymbol: String, vs_currency: String, unixtimeFrom: Long, unixTimeTo: Long, ) { val liveData = webService.requestPriceHistoryForDateRange( currencySymbol, vs_currency, unixtimeFrom, unixTimeTo ) if (!liveData.hasActiveObservers()) liveData.observeForever { response -> if (response != null && response?.archivalPrices?.isNotEmpty() != null) { val list: List<ParameterAtTime> = response.archivalPrices!!.map { ParameterAtTime( it[0].toLong(), it[1] ) } val prices = ParametersAtTime(list) val totalVolume = ParametersAtTime( response.totalVolumes!!.map { ParameterAtTime( it[0].toLong(), it[1] ) }) val marketCaps = ParametersAtTime( response.marketCaps!!.map { ParameterAtTime( it[0].toLong(), it[1] ) }) runBlocking { addCryptocurrencyInfoWithinTimeRange( InfoWithinTimeRangeEntity( index = 0, //auto-increment, no need to specify manually cryptocurrencyId = response.currencySymbol, timeRangeFrom = response.unixtimeFrom, timeRangeTo = response.unixTimeTo, daysCount = (((response.unixTimeTo - response.unixtimeFrom) / 3600 / 24).toInt()), prices = prices, market_caps = marketCaps, total_volumes = totalVolume, updateDate = Date() ) ) } } } } fun getApiErrorCodeLiveData() = webService.mldErrorCode fun addPriceAlert(entity: PriceAlertEntity) { runBlocking { database!!.userDao().addPriceAlert(entity).also { } } } fun deletePriceAlert(entity: PriceAlertEntity) { runBlocking { database!!.userDao().deletePriceAlert(entity) } } fun deleteAllPriceAlerts() { runBlocking { database!!.userDao().deleteAllPricesAlerts() } } fun getPricesAlerts(): LiveData<List<PriceAlertEntity>> { return database!!.userDao().getPricesAlerts() } fun getActualPriceOfCryptocurrencySynchronously( cryptocurrencySymbol: String, vs_currency: String, ): Float { return webService.getActualPriceOfCryptocurrencySynchronously( cryptocurrencySymbol, vs_currency ) } }
3
Kotlin
1
4
21b78750311a6163eeb1bc33dfc03eec47005249
10,475
android-cryptocurrency-prices
Apache License 2.0
app/src/main/java/com/flowfoundation/wallet/page/walletrestore/WalletRestoreActivity.kt
Outblock
692,942,645
false
{"Kotlin": 2425609, "Java": 104150}
package com.flowfoundation.wallet.page.walletrestore import android.content.Context import android.content.Intent import android.os.Bundle import android.view.MenuItem import androidx.lifecycle.ViewModelProvider import com.flowfoundation.wallet.base.activity.BaseActivity import com.flowfoundation.wallet.databinding.ActivityRestoreWalletBinding import com.flowfoundation.wallet.page.walletrestore.model.WalletRestoreContentModel import com.flowfoundation.wallet.page.walletrestore.presenter.WalletRestoreContentPresenter class WalletRestoreActivity : BaseActivity() { private lateinit var binding: ActivityRestoreWalletBinding private lateinit var contentPresenter: WalletRestoreContentPresenter private lateinit var viewModel: WalletRestoreViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityRestoreWalletBinding.inflate(layoutInflater) setContentView(binding.root) contentPresenter = WalletRestoreContentPresenter(this, binding) viewModel = ViewModelProvider(this)[WalletRestoreViewModel::class.java].apply { onStepChangeLiveData.observe(this@WalletRestoreActivity) { contentPresenter.bind( WalletRestoreContentModel(changeStep = it) ) } } setupToolbar() } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> finish() else -> super.onOptionsItemSelected(item) } return true } private fun setupToolbar() { setSupportActionBar(binding.toolbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) title = "" } companion object { fun launch(context: Context) { context.startActivity(Intent(context, WalletRestoreActivity::class.java)) } } }
93
Kotlin
5
0
6ecc281292b80741d976c738b67da0c3384323c7
1,997
FRW-Android
Apache License 2.0
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/BrandTwilio.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup public val OutlineGroup.BrandTwilio: ImageVector get() { if (_brandTwilio != null) { return _brandTwilio!! } _brandTwilio = Builder(name = "BrandTwilio", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(21.0f, 12.0f) arcToRelative(9.0f, 9.0f, 0.0f, true, true, -18.0f, 0.0f) arcToRelative(9.0f, 9.0f, 0.0f, false, true, 18.0f, 0.0f) close() } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.0f, 9.0f) moveToRelative(-1.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, 2.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, -2.0f, 0.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(15.0f, 9.0f) moveToRelative(-1.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, 2.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, -2.0f, 0.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(15.0f, 15.0f) moveToRelative(-1.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, 2.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, -2.0f, 0.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(9.0f, 15.0f) moveToRelative(-1.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, 2.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, false, -2.0f, 0.0f) } } .build() return _brandTwilio!! } private var _brandTwilio: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
3,695
compose-icon-collections
MIT License
src/main/kotlin/com/blr19c/falowp/bot/system/plugin/event/EventManager.kt
falowp-bot
736,172,318
false
{"Kotlin": 229423, "HTML": 3910}
package com.blr19c.falowp.bot.system.plugin.event import com.blr19c.falowp.bot.system.Log import com.blr19c.falowp.bot.system.api.BotApi import com.blr19c.falowp.bot.system.listener.events.HelpEvent import com.blr19c.falowp.bot.system.listener.hooks.EventPluginExecutionHook import com.blr19c.falowp.bot.system.plugin.EventPluginRegister import com.blr19c.falowp.bot.system.plugin.Plugin import com.blr19c.falowp.bot.system.plugin.PluginInfo import com.blr19c.falowp.bot.system.plugin.hook.withPluginHook import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.launch import java.util.concurrent.ConcurrentHashMap import kotlin.reflect.KClass /** * 事件类插件管理 */ object EventManager : Log { private val executor = CoroutineScope(Dispatchers.Default + SupervisorJob()) private val eventPlugins = ConcurrentHashMap<KClass<out Plugin.Listener.Event>, List<EventPluginRegister<out Plugin.Listener.Event>>>() fun configure(pluginList: List<PluginInfo>) { registerHelp(pluginList) log().info("加载的事件监听器数量:{}", eventPlugins.values.sumOf { it.size }) } /** * 注册事件 */ fun <T : Plugin.Listener.Event> registerEvent(pluginRegister: EventPluginRegister<T>) { eventPlugins.compute(pluginRegister.listener) { _, v -> v?.let { it + listOf(pluginRegister) } ?: listOf(pluginRegister) } } /** * 处理事件 */ suspend fun <T : Plugin.Listener.Event> publishEvent(botApi: BotApi, event: T) { eventPlugins[event::class]?.forEach { executor.launch { withPluginHook(botApi, EventPluginExecutionHook(event, it)) { it.publish(botApi, event) } } } } /** * 帮助事件注册 */ private fun registerHelp(pluginList: List<PluginInfo>) { registerEvent(EventPluginRegister(HelpEvent::class, PluginHelp(pluginList), PluginHelp::class)) } }
0
Kotlin
0
6
4dfb4620ce2ef529bcf27bc1b719587eb668b56e
2,024
falowp-bot-system
Apache License 2.0
presentation/src/main/kotlin/io/petros/github/presentation/feature/ViewExtensions.kt
ParaskP7
140,927,471
false
{"Kotlin": 118109}
package io.petros.github.presentation.feature import android.support.annotation.ColorRes import android.support.annotation.LayoutRes import android.view.View import android.view.ViewGroup import io.petros.github.data.getColorCompat fun ViewGroup.inflate(@LayoutRes resource: Int): View { return View.inflate(context, resource, this) } fun View.setBackgroundColorCompat(@ColorRes resource: Int) { setBackgroundColor(context.getColorCompat(resource)) }
0
Kotlin
1
9
ad9c53165db32af9ca08e4ae3ca4ea9b30e24d2e
462
sample-code-github
Apache License 2.0
backend/src/main/kotlin/daniil/backend/api/impl/ChannelApiImpl.kt
Yellowtyler
704,670,810
false
null
package daniil.backend.api.impl import daniil.backend.api.ChannelApi import daniil.backend.dto.channel.* import daniil.backend.service.ChannelService import org.springframework.beans.factory.annotation.Autowired import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.security.core.Authentication import org.springframework.web.bind.annotation.* import java.util.* @RestController @RequestMapping("api/channel") class ChannelApiImpl( @Autowired private val channelService: ChannelService ): ChannelApi { @GetMapping("{id}") override fun getChannel(@PathVariable id: UUID, auth: Authentication): ResponseEntity<ChannelDto> { return ResponseEntity.ok(channelService.getChannel(id, auth)) } @GetMapping("/all") override fun getChannels(@RequestBody req: GetChannelsRequest, auth: Authentication): ResponseEntity<GetChannelsResponse> { return ResponseEntity.ok(channelService.getChannels(req, auth)) } @ResponseStatus(HttpStatus.OK) @PostMapping("/subscribe") override fun subscribe(@RequestBody req: SubscribeChannelRequest, auth: Authentication) { channelService.subscribe(req, auth) } @ResponseStatus(HttpStatus.OK) @PutMapping override fun editChannel(@RequestBody req: EditChannelRequest, auth: Authentication) { channelService.editChannel(req, auth) } @ResponseStatus(HttpStatus.OK) @PostMapping("/block") override fun blockChannel(@RequestBody req: BlockChannelRequest, auth: Authentication) { channelService.blockChannel(req, auth) } @ResponseStatus(HttpStatus.NO_CONTENT) @DeleteMapping("/{id}") override fun deleteChannel(@PathVariable id: UUID, auth: Authentication) { channelService.deleteChannel(id, auth) } }
0
null
0
1
e4fcc14a0f221f27270d2e1ff66e0941e81ff5b9
1,828
mytube
Apache License 2.0
src/main/kotlin/indi/midreamsheep/app/tre/ui/page/mainpage/MainPage.kt
Simple-Markdown
744,897,915
false
{"Kotlin": 264030, "Java": 62889}
package indi.midreamsheep.app.tre.ui.page.mainpage import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.outlined.Settings import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.dp import indi.midreamsheep.app.tre.context.mainpage.TREMainPageContext import indi.midreamsheep.app.tre.service.language.TRELanguageResource import indi.midreamsheep.app.tre.ui.page.mainpage.history.recentUsed import indi.midreamsheep.app.tre.ui.page.settingpage.SettingWindow @Composable fun mainPage() { val context = TREMainPageContext() Column( modifier = Modifier .fillMaxSize() .padding(23.dp) ) { /*标题*/ Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { Image( painter = painterResource("book.svg"), contentDescription = "book" ) Text( text = "TextRenderEngine 2024", modifier = Modifier.padding(5.dp), style = MaterialTheme.typography.h5, fontWeight = FontWeight.Bold ) } Row { leftScreen( modifier = Modifier.weight(1.8f), context = context ) Spacer(modifier = Modifier.width(20.dp)) rightScreen( modifier = Modifier.weight(1f), context = context ) } } } @Composable fun leftScreen( modifier: Modifier, context: TREMainPageContext ) { Column( modifier ) { Text( text = TRELanguageResource.getLanguage("RecentUsed", "Recent Used"), modifier = Modifier.padding(5.dp), style = MaterialTheme.typography.h6, fontWeight = FontWeight.Bold ) //最近使用 Box( modifier = Modifier.fillMaxSize().background(Color(0xFFFAFAFA)) ) { recentUsed() } } } @Composable fun rightScreen( modifier: Modifier, context: TREMainPageContext ) { Column( modifier ) { Text( text = TRELanguageResource.getLanguage("Start", "start"), modifier = Modifier.padding(5.dp), style = MaterialTheme.typography.h6, fontWeight = FontWeight.Bold ) //按钮组 LazyColumn( modifier = Modifier.weight(1f) ) { for (button in context.mainPageButtonViewModel.getButtons()) { item { Row( modifier = Modifier .padding(bottom = 5.dp) .fillMaxWidth() .background(Color(0xFFEEEBEB)) .clickable { button.onClick(context) } .padding(5.dp), verticalAlignment = Alignment.CenterVertically ) { Image( button.icon, contentDescription = button.buttonName, modifier = Modifier.size(40.dp) ) Spacer(modifier = Modifier.width(10.dp)) Column { Text( text = button.buttonName, style = MaterialTheme.typography.body1 ) Spacer(Modifier.weight(1f)) Text( text = button.description, style = MaterialTheme.typography.body2, color = Color.Gray ) } } } } } Row( horizontalArrangement = Arrangement.End, verticalAlignment = Alignment.CenterVertically, modifier = Modifier.fillMaxWidth() ) { IconButton( onClick = { SettingWindow().register() }, modifier = Modifier.size(30.dp) ) { Icon( imageVector = Icons.Outlined.Settings, contentDescription = "setting", modifier = Modifier.fillMaxSize(), tint = Color.Gray ) } } } }
0
Kotlin
0
3
f0c575f55da4e535bf4b99b0b67474d7f9c9e4da
5,242
SMarkdown
Apache License 2.0
subprojects/android-test/ui-testing-core/src/main/kotlin/com/avito/android/test/page_object/SimpleScreen.kt
avito-tech
230,265,582
false
null
package com.avito.android.test.page_object import androidx.annotation.CallSuper import androidx.test.espresso.matcher.ViewMatchers import androidx.test.espresso.matcher.ViewMatchers.withId import com.avito.android.screen.BaseScreenChecks import com.avito.android.screen.Screen import com.avito.android.test.InteractionContext import com.avito.android.test.SimpleInteractionContext public abstract class SimpleScreen : PageObject(), Screen { override val interactionContext: InteractionContext by lazy { SimpleInteractionContext(ViewMatchers.isRoot()) { if (checks.checkOnEachScreenInteraction) { checks.isScreenOpened() } } } override val checks: com.avito.android.screen.ScreenChecks = SimpleScreenChecks(screen = this, checkOnEachScreenInteraction = false) public val rootElement: ViewElement by lazy { // rootId property is initialized after rootElement property element(withId(rootId)) } public open class SimpleScreenChecks<T : SimpleScreen>( screen: T, override val checkOnEachScreenInteraction: Boolean = false ) : BaseScreenChecks<T>(screen) { @CallSuper override fun screenOpenedCheck() { if (screen.rootId != Screen.UNKNOWN_ROOT_ID) { screen.rootElement.checks.exists() screen.rootElement.checks.isDisplayed() } } } }
10
null
50
414
bc94abf5cbac32ac249a653457644a83b4b715bb
1,443
avito-android
MIT License
feature/add-record/src/main/kotlin/com/kevlina/budgetplus/feature/add/record/ui/BookSelector.kt
kevinguitar
517,537,183
false
null
package com.kevlina.budgetplus.feature.add.record.ui import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.ArrowDropDown import androidx.compose.material.icons.rounded.Check import androidx.compose.material.icons.rounded.Lock import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.unit.DpOffset import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.kevlina.budgetplus.core.common.R import com.kevlina.budgetplus.core.common.nav.AddDest import com.kevlina.budgetplus.core.common.nav.Navigator import com.kevlina.budgetplus.core.theme.LocalAppColors import com.kevlina.budgetplus.core.ui.DropdownDivider import com.kevlina.budgetplus.core.ui.DropdownItem import com.kevlina.budgetplus.core.ui.DropdownMenu import com.kevlina.budgetplus.core.ui.FontSize import com.kevlina.budgetplus.core.ui.Icon import com.kevlina.budgetplus.core.ui.InputDialog import com.kevlina.budgetplus.core.ui.Text import com.kevlina.budgetplus.core.ui.rippleClick import com.kevlina.budgetplus.feature.add.record.BookSelectorViewModel import com.kevlina.budgetplus.feature.add.record.CreateBookBtnState @Composable fun BookSelector(navigator: Navigator) { val viewModel = hiltViewModel<BookSelectorViewModel>() val bookState by viewModel.book.collectAsStateWithLifecycle() val booksState by viewModel.books.collectAsStateWithLifecycle() val createBookBtnState by viewModel.createBookBtnState.collectAsStateWithLifecycle() var isSelectorShown by remember { mutableStateOf(false) } var isBookCreationDialogShown by remember { mutableStateOf(false) } Box(modifier = Modifier.fillMaxWidth()) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .rippleClick( color = LocalAppColors.current.light, onClick = { isSelectorShown = true } ) .padding(vertical = 8.dp) ) { Text( text = bookState?.name.orEmpty(), fontSize = FontSize.Header, fontWeight = FontWeight.SemiBold, color = LocalAppColors.current.light ) Icon( imageVector = Icons.Rounded.ArrowDropDown, contentDescription = stringResource(id = R.string.book_selection), tint = LocalAppColors.current.light ) } DropdownMenu( expanded = isSelectorShown, onDismissRequest = { isSelectorShown = false }, offset = DpOffset(0.dp, 8.dp), modifier = Modifier.heightIn(max = 300.dp) ) { booksState.orEmpty().forEach { book -> DropdownItem(onClick = { viewModel.selectBook(book) isSelectorShown = false }) { Row(verticalAlignment = Alignment.CenterVertically) { Text( text = book.name, color = LocalAppColors.current.dark, fontSize = FontSize.SemiLarge ) if (bookState?.id == book.id) { Icon( imageVector = Icons.Rounded.Check, contentDescription = null, tint = LocalAppColors.current.dark, modifier = Modifier.padding(horizontal = 4.dp) ) } } } } DropdownDivider() DropdownItem( name = stringResource(id = R.string.menu_create_book), icon = if (createBookBtnState != CreateBookBtnState.Enabled) { Icons.Rounded.Lock } else { null }, onClick = { when (createBookBtnState) { CreateBookBtnState.Enabled -> isBookCreationDialogShown = true CreateBookBtnState.NeedPremium -> navigator.navigate(AddDest.UnlockPremium.route) CreateBookBtnState.ReachedMax -> viewModel.showReachedMaxMessage() } isSelectorShown = false } ) } } if (isBookCreationDialogShown) { InputDialog( buttonText = stringResource(id = R.string.cta_create), title = stringResource(id = R.string.book_name_title), placeholder = stringResource(id = R.string.book_name_placeholder), onButtonClicked = viewModel::createBook, onDismiss = { isBookCreationDialogShown = false } ) } }
2
null
0
9
9c964e063efdf797f84f58fcc3e8b17da75f8309
5,571
budgetplus-android
MIT License
core/domain/src/main/kotlin/com/wansenai/dto/basic/AddOrUpdateCustomerDTO.kt
wansenai
605,630,517
false
null
/* * Copyright 2023-2033 WanSen AI Team, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance * with the License. A copy of the License is located at * * http://opensource.wansenai.com/apache2.0/ * * or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES * OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package com.wansensoft.dto.basic import com.wansensoft.NoArg import java.math.BigDecimal @NoArg data class AddOrUpdateCustomerDTO( val id: Long?, var customerName: String, var contact: String?, var phoneNumber: String?, var email: String?, var firstQuarterAccountReceivable: BigDecimal?, var secondQuarterAccountReceivable: BigDecimal?, var thirdQuarterAccountReceivable: BigDecimal?, var fourthQuarterAccountReceivable: BigDecimal?, var totalAccountReceivable: BigDecimal?, var address: String?, var taxNumber: String?, var bankName: String?, var accountNumber: String?, var taxRate: BigDecimal?, var status: Int?, var remark: String?, var sort: Int?, )
37
null
4
66
7cb630645f167eaadf20939df034a319b7132665
1,320
eairp
Apache License 2.0
app/src/main/java/com/davemorrissey/labs/subscaleview/sample/extension/views/FreehandView.kt
davemorrissey
109,281,052
false
null
package com.davemorrissey.labs.subscaleview.sample.extension.views import android.content.Context import android.graphics.* import android.graphics.Paint.Cap import android.graphics.Paint.Style import android.util.AttributeSet import android.view.MotionEvent import android.view.View import android.view.View.OnTouchListener import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView class FreehandView @JvmOverloads constructor(context: Context, attr: AttributeSet? = null) : SubsamplingScaleImageView(context, attr), OnTouchListener { private val paint = Paint() private val vPath = Path() private val vPoint = PointF() private var vPrev = PointF() private var vPrevious: PointF? = null private var sStart: PointF? = null private var drawing = false private var strokeWidth: Int = 0 private val sPoints: MutableList<PointF> = mutableListOf() init { initialise() } private fun initialise() { setOnTouchListener(this) val density = resources.displayMetrics.densityDpi.toFloat() strokeWidth = (density / 60f).toInt() } override fun onTouch(view: View, motionEvent: MotionEvent): Boolean { return false } override fun onTouchEvent(event: MotionEvent): Boolean { if (sPoints.isNotEmpty() && !drawing) { return super.onTouchEvent(event) } var consumed = false val touchCount = event.pointerCount when (event.actionMasked) { MotionEvent.ACTION_DOWN -> if (event.actionIndex == 0) { sStart = viewToSourceCoord(event.x, event.y) vPrevious = PointF(event.x, event.y) } else { sStart = null vPrevious = null } MotionEvent.ACTION_MOVE -> { val sCurrentF = viewToSourceCoord(event.x, event.y) if (sCurrentF != null) { val sCurrent = PointF(sCurrentF.x, sCurrentF.y) val sStart = this.sStart val vPrevious = this.vPrevious if (touchCount == 1 && sStart != null && vPrevious != null) { val vDX = Math.abs(event.x - vPrevious.x) val vDY = Math.abs(event.y - vPrevious.y) if (vDX >= strokeWidth || vDY >= strokeWidth) { if (sPoints.isEmpty()) { sPoints.add(sStart) } sPoints.add(sCurrent) vPrevious.x = event.x vPrevious.y = event.y drawing = true } consumed = true invalidate() } else if (touchCount == 1) { // Consume all one touch drags to prevent odd panning effects handled by the superclass. consumed = true } } } MotionEvent.ACTION_UP, MotionEvent.ACTION_POINTER_UP -> { invalidate() drawing = false vPrevious = null sStart = null } } // Use parent to handle pinch and two-finger pan. return consumed || super.onTouchEvent(event) } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) // Don't draw anything before image is ready. if (!isReady) { return } paint.isAntiAlias = true if (sPoints.size >= 2) { vPath.reset() sourceToViewCoord(sPoints[0].x, sPoints[0].y, vPrev) vPath.moveTo(vPrev.x, vPrev.y) for (i in 1 until sPoints.size) { sourceToViewCoord(sPoints[i].x, sPoints[i].y, vPoint) vPath.quadTo(vPrev.x, vPrev.y, (vPoint.x + vPrev.x) / 2, (vPoint.y + vPrev.y) / 2) vPrev = vPoint } paint.style = Style.STROKE paint.strokeCap = Cap.ROUND paint.strokeWidth = (strokeWidth * 2).toFloat() paint.color = Color.BLACK canvas.drawPath(vPath, paint) paint.strokeWidth = strokeWidth.toFloat() paint.color = Color.argb(255, 38, 166, 154) canvas.drawPath(vPath, paint) } } fun reset() { this.sPoints.clear() invalidate() } }
0
Kotlin
8
35
53e3c2343cf62c114d53c814898d98e8edf602b7
4,508
ssiv-kotlin-sample
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsaccreditedprogrammesapi/client/oasysApi/model/OasysBehaviour.kt
ministryofjustice
615,402,552
false
{"Kotlin": 555496, "Shell": 9504, "Dockerfile": 1415}
package uk.gov.justice.digital.hmpps.hmppsaccreditedprogrammesapi.client.oasysApi.model import com.fasterxml.jackson.annotation.JsonIgnoreProperties @JsonIgnoreProperties(ignoreUnknown = true) data class OasysBehaviour( val temperControl: String?, val problemSolvingSkills: String?, val awarenessOfConsequences: String?, val achieveGoals: String?, val understandsViewsOfOthers: String?, val concreteAbstractThinking: String?, val sexualPreOccupation: String?, val offenceRelatedSexualInterests: String?, val aggressiveControllingBehavour: String?, val impulsivity: String?, )
0
Kotlin
0
0
b29d1cc17bacb1313cf5e5994624e00588041443
598
hmpps-accredited-programmes-api
MIT License
vector/src/withvoip/java/im/vector/app/features/call/conference/JitsiService.kt
tchapgouv
340,329,238
false
null
/* * Copyright (c) 2021 New Vector Ltd * * 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 im.vector.app.features.call.conference import im.vector.app.R import im.vector.app.core.network.await import im.vector.app.core.resources.StringProvider import im.vector.app.core.utils.ensureProtocol import im.vector.app.core.utils.toBase32String import im.vector.app.features.call.conference.jwt.JitsiJWTFactory import im.vector.app.features.displayname.getBestName import im.vector.app.features.raw.wellknown.getElementWellknown import im.vector.app.features.settings.VectorLocale import im.vector.app.features.themes.ThemeProvider import okhttp3.Request import org.jitsi.meet.sdk.JitsiMeetUserInfo import org.matrix.android.sdk.api.extensions.tryOrNull import org.matrix.android.sdk.api.raw.RawService import org.matrix.android.sdk.api.session.Session import org.matrix.android.sdk.api.session.widgets.model.Widget import org.matrix.android.sdk.api.session.widgets.model.WidgetType import org.matrix.android.sdk.api.util.MatrixJsonParser import org.matrix.android.sdk.api.util.appendParamToUrl import org.matrix.android.sdk.api.util.toMatrixItem import java.net.URL import java.util.UUID import javax.inject.Inject class JitsiService @Inject constructor( private val session: Session, private val rawService: RawService, private val stringProvider: StringProvider, private val themeProvider: ThemeProvider, private val jitsiJWTFactory: JitsiJWTFactory) { companion object { const val JITSI_OPEN_ID_TOKEN_JWT_AUTH = "openidtoken-jwt" } private val jitsiWidgetDataFactory by lazy { JitsiWidgetDataFactory(stringProvider.getString(R.string.preferred_jitsi_domain)) { widget -> session.widgetService().getWidgetComputedUrl(widget, themeProvider.isLightTheme()) } } suspend fun createJitsiWidget(roomId: String, withVideo: Boolean): Widget { // Build data for a jitsi widget val widgetId: String = WidgetType.Jitsi.preferred + "_" + session.myUserId + "_" + System.currentTimeMillis() val preferredJitsiDomain = tryOrNull { rawService.getElementWellknown(session.sessionParams) ?.jitsiServer ?.preferredDomain } val jitsiDomain = preferredJitsiDomain ?: stringProvider.getString(R.string.preferred_jitsi_domain) val jitsiAuth = getJitsiAuth(jitsiDomain) val confId = createConferenceId(roomId, jitsiAuth) // We use the default element wrapper for this widget // https://github.com/vector-im/element-web/blob/develop/docs/jitsi-dev.md // https://github.com/matrix-org/matrix-react-sdk/blob/develop/src/utils/WidgetUtils.ts#L469 val url = buildString { append("https://app.element.io/jitsi.html") appendParamToUrl("confId", confId) append("#conferenceDomain=\$domain") append("&conferenceId=\$conferenceId") append("&isAudioOnly=\$isAudioOnly") append("&displayName=\$matrix_display_name") append("&avatarUrl=\$matrix_avatar_url") append("&userId=\$matrix_user_id") append("&roomId=\$matrix_room_id") append("&theme=\$theme") if (jitsiAuth != null) { append("&auth=$jitsiAuth") } } val widgetEventContent = mapOf( "url" to url, "type" to WidgetType.Jitsi.legacy, "data" to JitsiWidgetData(jitsiDomain, confId, !withVideo, jitsiAuth), "creatorUserId" to session.myUserId, "id" to widgetId, "name" to "jitsi" ) return session.widgetService().createRoomWidget(roomId, widgetId, widgetEventContent) } suspend fun joinConference(roomId: String, jitsiWidget: Widget, enableVideo: Boolean): JitsiCallViewEvents.JoinConference { val me = session.getRoomMember(session.myUserId, roomId)?.toMatrixItem() val userDisplayName = me?.getBestName() val userAvatar = me?.avatarUrl?.let { session.contentUrlResolver().resolveFullSize(it) } val userInfo = JitsiMeetUserInfo().apply { this.displayName = userDisplayName this.avatar = userAvatar?.let { URL(it) } } val roomName = session.getRoomSummary(roomId)?.displayName val widgetData = jitsiWidgetDataFactory.create(jitsiWidget) val token = if (widgetData.isOpenIdJWTAuthenticationRequired()) { getOpenIdJWTToken(roomId, widgetData.domain, userDisplayName ?: session.myUserId, userAvatar ?: "") } else { null } return JitsiCallViewEvents.JoinConference( enableVideo = enableVideo, jitsiUrl = widgetData.domain.ensureProtocol(), subject = roomName ?: "", confId = widgetData.confId, userInfo = userInfo, token = token ) } fun extractJitsiWidgetData(widget: Widget): JitsiWidgetData? { return tryOrNull { jitsiWidgetDataFactory.create(widget) } } private fun JitsiWidgetData.isOpenIdJWTAuthenticationRequired(): Boolean { return auth == JITSI_OPEN_ID_TOKEN_JWT_AUTH } private suspend fun getOpenIdJWTToken(roomId: String, domain: String, userDisplayName: String, userAvatar: String): String { val openIdToken = session.openIdService().getOpenIdToken() return jitsiJWTFactory.create( openIdToken = openIdToken, jitsiServerDomain = domain, roomId = roomId, userAvatarUrl = userAvatar, userDisplayName = userDisplayName ) } private fun createConferenceId(roomId: String, jitsiAuth: String?): String { return if (jitsiAuth == JITSI_OPEN_ID_TOKEN_JWT_AUTH) { // Create conference ID from room ID // For compatibility with Jitsi, use base32 without padding. // More details here: // https://github.com/matrix-org/prosody-mod-auth-matrix-user-verification roomId.toBase32String(padding = false) } else { // Create a random enough jitsi conference id // Note: the jitsi server automatically creates conference when the conference // id does not exist yet var widgetSessionId = UUID.randomUUID().toString() if (widgetSessionId.length > 8) { widgetSessionId = widgetSessionId.substring(0, 7) } roomId.substring(1, roomId.indexOf(":") - 1) + widgetSessionId.lowercase(VectorLocale.applicationLocale) } } private suspend fun getJitsiAuth(jitsiDomain: String): String? { val request = Request.Builder().url("$jitsiDomain/.well-known/element/jitsi".ensureProtocol()).build() return tryOrNull { val response = session.getOkHttpClient().newCall(request).await() val json = response.body?.string() ?: return null MatrixJsonParser.getMoshi().adapter(JitsiWellKnown::class.java).fromJson(json)?.auth } } }
91
null
6
9
a2c060c687b0aa69af681138c5788d6933d19860
7,739
tchap-android
Apache License 2.0
app/src/main/kotlin/com/machinerychorus/lifeprogresswallpaper/LifeWallpaper.kt
ethanmdavidson
417,362,838
false
{"Kotlin": 30873}
package com.machinerychorus.lifeprogresswallpaper import android.app.WallpaperColors import android.content.SharedPreferences import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.os.Build import android.service.wallpaper.WallpaperService import android.view.SurfaceHolder import android.widget.Toast import androidx.annotation.RequiresApi import androidx.core.content.ContextCompat import androidx.preference.PreferenceManager import java.text.SimpleDateFormat import java.time.DateTimeException import java.time.Duration import java.time.Instant import java.time.temporal.ChronoUnit import java.util.Locale import kotlin.time.toKotlinDuration const val DEFAULT_EXPECTANCY_YEARS = "85" const val DEFAULT_NUM_DECIMALS = "4" const val DEFAULT_STATUS_BAR_HEIGHT = 100 const val DAYS_IN_YEAR = 365.2425 const val DAYS_IN_YEAR_WITHOUT_LEAPS = 365 const val HOURS_IN_DAY = 24 const val DAYS_IN_WEEK = 7 const val PROGRESS_LABEL_MARGIN = 10f class LifeWallpaper : WallpaperService() { override fun onCreateEngine(): Engine { return WallpaperEngine() } @Suppress("TooManyFunctions") // eh, whatever private inner class WallpaperEngine : Engine(), SharedPreferences.OnSharedPreferenceChangeListener { private var lastDrawTime: Long = 0 init { setOffsetNotificationsEnabled(false) PreferenceManager.getDefaultSharedPreferences(applicationContext) .registerOnSharedPreferenceChangeListener(this) } override fun onDestroy() { //remove preference listener PreferenceManager.getDefaultSharedPreferences(applicationContext) .unregisterOnSharedPreferenceChangeListener(this) } override fun onSurfaceCreated(holder: SurfaceHolder) { super.onSurfaceCreated(holder) prepAndDraw() } override fun onSurfaceDestroyed(holder: SurfaceHolder) { super.onSurfaceDestroyed(holder) } override fun onSurfaceRedrawNeeded(holder: SurfaceHolder) { prepAndDraw() } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, s: String) { prepAndDraw() } override fun onVisibilityChanged(visible: Boolean) { //only check the time between draws here, because in all other events we want //it to redraw every time if (visible && System.currentTimeMillis() - lastDrawTime > MIN_TIME_BETWEEN_DRAWS_MS) { prepAndDraw() } } fun prepAndDraw() { var canvas: Canvas? = null try { canvas = surfaceHolder.lockCanvas() canvas?.drawFrame() lastDrawTime = System.currentTimeMillis() } finally { if (canvas != null) { surfaceHolder.unlockCanvasAndPost(canvas) } } } @Suppress("LongMethod", // I guess I should refactor this, but don't feel like it right now "CyclomaticComplexMethod",) // yikes, I really need to refactor this fun Canvas.drawFrame() { val pref = PreferenceManager.getDefaultSharedPreferences(applicationContext) val birthdate = DATE_FORMATTER.parse( pref.getString(getString(R.string.birthdateKey), DEFAULT_DATE)!! )!!.toInstant() val yearsPref = pref.getString(getString(R.string.expectancyKey), DEFAULT_EXPECTANCY_YEARS)!! val expectancyYears = Duration.of((yearsPref.toLong() * DAYS_IN_YEAR).toLong(), ChronoUnit.DAYS) val hoursAlive = ChronoUnit.HOURS.between(birthdate, Instant.now()) val deathDate = try { birthdate.plus(expectancyYears) } catch (e: DateTimeException){ // This error handling isn't very elegant, but I think that's okay in this // scenario. The max Instant is the year 1,000,000,000 (a billion) so no // user should hit this unless they're just messing around anyway. I thought // about just not catching the exception, but decided against that because // it would clutter up the app reporting, and crashing is not a good look. println("Error calculating deathDate: ${e.message}") Toast.makeText(applicationContext, "LifeProgressWallpaper Error: (birthDate + expectancy) exceeds max instant", Toast.LENGTH_LONG).show() return } val hoursExpectancy = ChronoUnit.HOURS.between(birthdate, deathDate) val percentDead = hoursAlive.toFloat() / hoursExpectancy.toFloat() //get screen width/height from surface because getDesiredMinimumWidth()/Height() // doesn't always return the correct values (e.g. 1280x800 tablet returned 1920x1280) val screenWidth = surfaceHolder.surfaceFrame.right val screenHeight = surfaceHolder.surfaceFrame.bottom val paint = Paint() // Draw background color across whole screen paint.style = Paint.Style.FILL paint.color = getBackgroundColor(pref) this.drawRect(0f, 0f, screenWidth.toFloat(), screenHeight.toFloat(), paint) // Draw foreground color across part of screen corresponding to progress val reverse = pref.getBoolean(getString(R.string.reverseKey), false) paint.color = getForegroundColor(pref) var top = (screenHeight - (screenHeight * percentDead).toInt()).toFloat() var bottom = screenHeight.toFloat() if (reverse) { bottom = top top = 0f } this.drawRect( 0f, top, screenWidth.toFloat(), bottom, paint ) // Draw progress text at edge of progress bar paint.textSize = pref.getString(getString(R.string.progressFontSizeKey), "240")!!.toFloat() val progressType = pref.getString(getString(R.string.progressUnitsKey), "Percentage") ?: "Percentage" val decimals = pref.getString(getString(R.string.decimalsKey), DEFAULT_NUM_DECIMALS) ?: DEFAULT_NUM_DECIMALS var progressLabel = "" // this code is gross :/ when (progressType) { "Percentage" -> { val progress = if (!reverse) { percentDead * @Suppress("MagicNumber") 100f } else { (1 - percentDead) * @Suppress("MagicNumber") 100f } progressLabel = String.format(Locale.US, "%." + decimals + "f%%", progress) } "Duration" -> { val progress = if (!reverse) { Duration.ofHours(hoursAlive) } else { Duration.ofHours(hoursExpectancy - hoursAlive) } progress.toKotlinDuration().toComponents { totalDays: Long, hours: Int, _: Int, _: Int, _: Int -> // not attempting to account for leap years here because it just // looked wrong (e.g. year wouldn't roll over until 366 days). // We ignore minutes and seconds because the wallpaper only // refreshes every hour anyway val years = (totalDays / DAYS_IN_YEAR_WITHOUT_LEAPS).toInt() val days = (totalDays % DAYS_IN_YEAR_WITHOUT_LEAPS).toInt() progressLabel = "${years}Y ${days}D ${hours}H" } } "Weeks" -> { val progress = if (!reverse) { hoursAlive.toFloat() / HOURS_IN_DAY / DAYS_IN_WEEK } else { (hoursExpectancy - hoursAlive).toFloat() / HOURS_IN_DAY / DAYS_IN_WEEK } progressLabel = String.format(Locale.US, "%." + decimals + "f", progress) } "Days" -> { val progress = if (!reverse) { hoursAlive.toFloat() / HOURS_IN_DAY } else { (hoursExpectancy - hoursAlive).toFloat() / HOURS_IN_DAY } progressLabel = String.format(Locale.US, "%." + decimals + "f", progress) } "Hours" -> { progressLabel = if (!reverse) { hoursAlive.toString() } else { (hoursExpectancy - hoursAlive).toString() } } "None" -> { progressLabel = "" } } var textBaseline = (screenHeight - (screenHeight * percentDead) - PROGRESS_LABEL_MARGIN) if (reverse) { textBaseline -= paint.fontMetrics.ascent } this.drawText( progressLabel, PROGRESS_LABEL_MARGIN, textBaseline, paint ) //draw goals text if (reverse) { paint.color = getBackgroundColor(pref) } val statusBarHeight = pref.getInt( getString(R.string.statusBarHeightKey), DEFAULT_STATUS_BAR_HEIGHT ) paint.textSize = pref.getString(getString(R.string.goalsFontSizeKey), "75")!!.toFloat() val goals = pref.getString(getString(R.string.goalsKey), "")!!.split("\n").toTypedArray() var lineNumber = 0 val goalsFontHeight = paint.fontMetrics.descent - paint.fontMetrics.ascent for (line in goals) { val textWidth = paint.measureText(line) this.drawText( line, (screenWidth - textWidth) / 2, statusBarHeight - paint.fontMetrics.top + lineNumber * goalsFontHeight, paint ) lineNumber += 1 } } private fun getBackgroundColor(pref: SharedPreferences): Int { return pref.getInt( getString(R.string.bgColorKey), ContextCompat.getColor( applicationContext, R.color.wholesomeTeal ) ) } private fun getForegroundColor(pref: SharedPreferences): Int { return pref.getInt( getString(R.string.fgColorKey), ContextCompat.getColor( applicationContext, R.color.blackAsMySOUUUUUUUULLLL ) ) } @RequiresApi(Build.VERSION_CODES.O_MR1) override fun onComputeColors(): WallpaperColors { val pref = PreferenceManager.getDefaultSharedPreferences(applicationContext) val primary = getBackgroundColor(pref) val secondary = getForegroundColor(pref) return WallpaperColors(Color.valueOf(primary), Color.valueOf(secondary), null) } } companion object { //only draw every hour, in order to keep battery usage down. //Users would be able to see it move every 10 minutes with like 6 digits precision //so it might be cool to have it increase draw rate as precision increases private const val MIN_TIME_BETWEEN_DRAWS_MS = 3600000 val DATE_FORMATTER = SimpleDateFormat("yyyy-MM-dd", Locale.ROOT) const val DEFAULT_DATE = "1994-05-31" } }
2
Kotlin
3
13
5a5647615b23848f3ba4154f2579b45d3b722e65
9,493
DeathProgress
The Unlicense
src/jsMain/kotlin/com/severett/planetxcompose/js/Main.kt
severn-everett
640,801,543
false
{"Kotlin": 82527, "CSS": 23454, "HTML": 683}
package com.severett.planetxcompose.js import com.severett.planetxcompose.js.ui.components.AppContent import org.jetbrains.compose.web.renderComposable fun main() { renderComposable(rootElementId = "root") { AppContent() } }
0
Kotlin
0
0
2175bdb9ab634826abb561c71f902c5bd4577b92
243
PlanetXCompose
Apache License 2.0
shared/src/commonTest/kotlin/me/saket/press/shared/db/BaseDatabaeTest.kt
saket
201,701,386
false
null
package me.saket.press.shared.db import com.squareup.sqldelight.db.SqlDriver import me.saket.press.PressDatabase import me.saket.press.shared.sync.createJson import kotlin.test.AfterTest expect fun inMemorySqlDriver(): SqlDriver /** * Creates an in-memory database and closes it before and after each test. * This class exists because JUnit rules aren't a thing (yet) in Kotlin tests. * * The name of this class is not a typo. */ abstract class BaseDatabaeTest { private val sqlDriver: SqlDriver = inMemorySqlDriver() protected open val database: PressDatabase = createPressDatabase(sqlDriver, createJson()) @AfterTest fun closeDb() { sqlDriver.close() } }
13
null
110
1,849
5f64350ec51402f3e6aeff145cbc35438780a03c
680
press
Apache License 2.0
app/src/main/java/com/steleot/jetpackcompose/playground/datastore/SettingsProtoSerializer.kt
Vivecstel
338,792,534
false
{"Kotlin": 1538487}
package com.steleot.jetpackcompose.playground.datastore import androidx.datastore.core.Serializer import com.google.protobuf.InvalidProtocolBufferException import com.steleot.jetpackcompose.playground.BuildConfig import com.steleot.jetpackcompose.playground.theme.ColorPalette import timber.log.Timber import java.io.InputStream import java.io.OutputStream @Suppress("BlockingMethodInNonBlockingContext") object SettingsProtoSerializer : Serializer<SettingsProto> { override val defaultValue: SettingsProto get() = SettingsProto.getDefaultInstance() .toBuilder() .setAnalyticsEnabled(!BuildConfig.DEBUG) .setCrashlyticsEnabled(!BuildConfig.DEBUG) .setColorPalette(ColorPalette.DEEP_PURPLE.name) .build() override suspend fun readFrom(input: InputStream): SettingsProto { return try { SettingsProto.parseFrom(input) } catch (e: InvalidProtocolBufferException) { Timber.e(e) defaultValue } } override suspend fun writeTo(t: SettingsProto, output: OutputStream) { t.writeTo(output) } }
2
Kotlin
46
346
0161d9c7bf2eee53270ba2227a61d71ba8292ad0
1,144
Jetpack-Compose-Playground
Apache License 2.0
4_swing.main.kts
hexagontk
788,570,576
false
{"Kotlin": 9147, "Java": 1970, "HTML": 1548}
#!/usr/bin/env kotlin /* * 4. SWING INTERFACES */ @file:DependsOn("com.formdev:flatlaf:3.4.1") import com.formdev.flatlaf.FlatDarculaLaf import java.io.File import java.nio.file.Path import java.nio.file.Paths import javax.swing.* import javax.swing.WindowConstants.EXIT_ON_CLOSE /* * To display Swing applications, you have to disable the headless mode */ System.setProperty("java.awt.headless", "false") UIManager.setLookAndFeel(FlatDarculaLaf()) val currentPath: Path = Paths.get("").toRealPath() val displayedFiles: Array<File> = currentPath.toFile().listFiles() ?: emptyArray() JFrame("Mini Directory Browser").apply { add( JScrollPane( JList( DefaultListModel<String>().apply { addAll(displayedFiles.map(File::getName)) } ) ) ) defaultCloseOperation = EXIT_ON_CLOSE isVisible = true pack() } /* * If you don't want to print anything as the script's result, return Unit. If not, last evaluated * expression will also be printed (in this case, JFrame's toString) */ Unit
0
Kotlin
0
2
d56f39589313e04db681bf013ed4a372186d10df
1,103
kotlin_as_if_it_was_python
MIT License
app/src/main/java/an/maguste/android/archsamples/ui/mvvm/MVVMFragment.kt
AnnGal
309,823,069
false
null
package an.maguste.android.archsamples.ui.mvvm import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.lifecycle.ViewModelProvider import an.maguste.android.archsamples.R import android.widget.Toast import kotlinx.android.synthetic.main.fragment_mvvm.* class MVVMFragment : Fragment() { private var mvvmViewModel = MVVMViewModel() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { //mvvmViewModel = ViewModelProvider(this).get(MVVMViewModel::class.java) mvvmViewModel.state.observe( viewLifecycleOwner, Observer<ModelState> {state -> when (state) { is ModelState.LoginSucessState -> { //Toast.makeText() } is ModelState.SendingState -> { // } is ModelState.ErrorState<*> -> { when (state.message) { is Int -> Toast.makeText(requireContext(), getString(state.message as Int), Toast.LENGTH_SHORT).show() is String -> Toast.makeText(requireContext(), state.message, Toast.LENGTH_SHORT).show() } // } is ModelState.InitializeState -> { // } } }) return inflater.inflate(R.layout.fragment_mvvm, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) btnLogin.setOnClickListener { mvvmViewModel.login(textLogin.text.toString(), textPassword.text.toString()) //Toast.makeText(requireContext(), "PressButton", Toast.LENGTH_SHORT).show() } } }
0
Kotlin
0
0
331e6b2428f273cc9b2a6dfd9a9a3588acf49d5f
2,119
ArchitectureSample
Apache License 2.0
kite-core/src/test/java/jp/co/cyberagent/kite/core/KiteMemoScopeTest.kt
cats-oss
262,991,077
false
null
package jp.co.cyberagent.kite.core import io.kotest.assertions.throwables.shouldNotThrowAny import io.kotest.assertions.throwables.shouldThrow import io.kotest.core.spec.style.StringSpec import io.kotest.matchers.shouldBe import jp.co.cyberagent.kite.testcommon.memoize import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext class KiteMemoScopeTest : StringSpec({ val kite by memoize { TestKiteDslScope() } "Create memo in main thread should success" { shouldNotThrowAny { kite.memo { 0 } } } "Create memo in background thread should throw exception" { withContext(Dispatchers.IO) { shouldThrow<IllegalStateException> { kite.memo { 0 } } } } "Memo should compute immediately" { val state = kite.state { 1 } val memo = kite.memo { state.value + 2 } memo.value shouldBe 3 } "Memo should recompute when any dependent state changed" { val state1 = kite.state { "A" } val state2 = kite.state { 1 } val memo = kite.memo { state1.value + state2.value } memo.value shouldBe "A1" state1.value = "B" memo.value shouldBe "B1" state2.value = 2 memo.value shouldBe "B2" } "Memo should recompute when nested dependent state changed" { val state = kite.state { 1 } val memo1 = kite.memo { state.value } val memo2 = kite.memo { memo1.value } memo2.value shouldBe 1 state.value = 2 memo2.value shouldBe 2 state.value = 3 memo2.value shouldBe 3 } })
0
Kotlin
1
20
d47da96072d5a964de854cc94c8ca4369fd97dca
1,476
kite
Apache License 2.0
modules/wasm-binary/src/commonMain/kotlin/tree/instructions/SimdLoadInstruction.kt
wasmium
761,480,110
false
{"Kotlin": 352107, "JavaScript": 200}
package org.wasmium.wasm.binary.tree.instructions import org.wasmium.wasm.binary.tree.Opcode import org.wasmium.wasm.binary.visitors.FunctionBodyVisitor public class SimdLoadInstruction( public override val opcode: Opcode, public override val alignment: UInt, public override val offset: UInt, ) : AlignOffsetInstruction { override fun accept(functionBodyVisitor: FunctionBodyVisitor) { functionBodyVisitor.visitSimdLoadInstruction(opcode, alignment, offset) } }
0
Kotlin
0
1
f7ddef76630278616d221e7c8251adf0f11b9587
493
wasmium-wasm-binary
Apache License 2.0
app/src/main/java/uz/javokhirjambulov/tmdbclient/data/repository/artist/datasourceImpl/ArtistLocalDataSourceImpl.kt
JavokhirJambulov
834,870,015
false
{"Kotlin": 70299}
package uz.javokhirjambulov.tmdbclient.data.repository.artist.datasourceImpl import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import uz.javokhirjambulov.tmdbclient.data.db.ArtistDao import uz.javokhirjambulov.tmdbclient.data.model.artist.Artist import uz.javokhirjambulov.tmdbclient.data.repository.artist.datasource.ArtistLocalDataSource class ArtistLocalDataSourceImpl(private val artistDao: ArtistDao): ArtistLocalDataSource { override suspend fun getArtistFromDB(): List<Artist> { return artistDao.getArtists() } override suspend fun saveArtistToDB(artists: List<Artist>) { CoroutineScope(Dispatchers.IO).launch { artistDao.saveArtists(artists) } } override suspend fun clearAll() { CoroutineScope(Dispatchers.IO).launch { artistDao.deleteAllArtists() } } }
0
Kotlin
0
0
5f9cd63aa962627932eb622935b5f7f44039110a
916
TMDB_App
MIT License
app/src/main/java/com/lucianbc/receiptscan/presentation/receipt/ReceiptFragment.kt
lucianbc
183,749,890
false
null
package com.lucianbc.receiptscan.presentation.receipt import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.lifecycle.Observer import androidx.recyclerview.widget.LinearLayoutManager import com.lucianbc.receiptscan.R import com.lucianbc.receiptscan.base.BaseFragment import com.lucianbc.receiptscan.databinding.FragmentReceiptBinding import kotlinx.android.synthetic.main.fragment_receipt.* class ReceiptFragment : BaseFragment<ReceiptViewModel>(ReceiptViewModel::class.java) { private val itemsAdapter = ItemsAdapter() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { initParentViewModel() return setupBinding(inflater, container)?.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setupAdapter() observe(viewModel) } private fun setupBinding( inflater: LayoutInflater, container: ViewGroup? ): FragmentReceiptBinding? { val binding = DataBindingUtil.inflate<FragmentReceiptBinding>( inflater, R.layout.fragment_receipt, container, false ) binding.viewModel = viewModel binding.lifecycleOwner = this return binding } private fun setupAdapter() { receiptItems.apply { layoutManager = LinearLayoutManager(activity) adapter = itemsAdapter } } private fun observe(viewModel: ReceiptViewModel) { viewModel.apply { products.observe(viewLifecycleOwner, Observer { it?.let { itemsAdapter.submitList(it) } }) } } }
13
null
1
2
05950c87f2eda6f53f886e340459aa13cdbdd621
1,880
ReceiptScan
Apache License 2.0
compiler/frontend/src/org/jetbrains/kotlin/psi/synthetics/SyntheticClassOrObjectDescriptor.kt
gigliovale
89,726,097
false
null
/* * Copyright 2010-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.psi.synthetics import com.intellij.psi.PsiElement import org.jetbrains.kotlin.descriptors.* import org.jetbrains.kotlin.descriptors.annotations.Annotations import org.jetbrains.kotlin.descriptors.impl.ClassDescriptorBase import org.jetbrains.kotlin.name.Name import org.jetbrains.kotlin.psi.* import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingContextUtils import org.jetbrains.kotlin.resolve.DescriptorFactory import org.jetbrains.kotlin.resolve.DescriptorUtils import org.jetbrains.kotlin.resolve.lazy.LazyClassContext import org.jetbrains.kotlin.resolve.lazy.data.KtClassLikeInfo import org.jetbrains.kotlin.resolve.lazy.declarations.ClassMemberDeclarationProvider import org.jetbrains.kotlin.resolve.lazy.descriptors.ClassResolutionScopesSupport import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyClassMemberScope import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter import org.jetbrains.kotlin.resolve.scopes.LexicalScope import org.jetbrains.kotlin.resolve.scopes.MemberScope import org.jetbrains.kotlin.storage.StorageManager import org.jetbrains.kotlin.types.AbstractClassTypeConstructor import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeConstructor /* * This class introduces all attributes that are needed for synthetic classes/object so far. * This list may grow in the future, adding more constructor parameters. * This class has its own synthetic declaration inside. */ class SyntheticClassOrObjectDescriptor( c: LazyClassContext, parentClassOrObject: KtPureClassOrObject, containingDeclaration: DeclarationDescriptor, name: Name, source: SourceElement, outerScope: LexicalScope, private val modality: Modality, private val visibility: Visibility, private val kind: ClassKind, private val isCompanionObject: Boolean ) : ClassDescriptorBase(c.storageManager, containingDeclaration, name, source, false), ClassDescriptorWithResolutionScopes { val syntheticDeclaration: KtPureClassOrObject = SyntheticDeclaration(parentClassOrObject, name.asString()) private val thisDescriptor: SyntheticClassOrObjectDescriptor get() = this // code readability private val typeConstructor = SyntheticTypeConstructor(c.storageManager) private val resolutionScopesSupport = ClassResolutionScopesSupport(thisDescriptor, c.storageManager, { outerScope }) private val syntheticSupertypes = mutableListOf<KotlinType>().apply { c.syntheticResolveExtension.addSyntheticSupertypes(thisDescriptor, this) } private val unsubstitutedMemberScope = LazyClassMemberScope(c, SyntheticClassMemberDeclarationProvider(syntheticDeclaration), this, c.trace) private val unsubstitutedPrimaryConstructor = createUnsubstitutedPrimaryConstructor() override val annotations: Annotations get() = Annotations.EMPTY override fun getModality() = modality override fun getVisibility() = visibility override fun getKind() = kind override fun isCompanionObject() = isCompanionObject override fun isInner() = false override fun isData() = false override fun isHeader() = false override fun isImpl() = false override fun getCompanionObjectDescriptor() = null override fun getTypeConstructor(): TypeConstructor = typeConstructor override fun getUnsubstitutedPrimaryConstructor() = unsubstitutedPrimaryConstructor override fun getConstructors() = listOf(unsubstitutedPrimaryConstructor) override fun getDeclaredTypeParameters() = emptyList<TypeParameterDescriptor>() override fun getStaticScope() = MemberScope.Empty override fun getUnsubstitutedMemberScope() = unsubstitutedMemberScope override fun getSealedSubclasses() = emptyList<ClassDescriptor>() init { assert(modality != Modality.SEALED) { "Implement getSealedSubclasses() for this class: ${this::class.java}" } } override fun getDeclaredCallableMembers(): List<CallableMemberDescriptor> = DescriptorUtils.getAllDescriptors(unsubstitutedMemberScope).filterIsInstance<CallableMemberDescriptor>().filter { it.kind != CallableMemberDescriptor.Kind.FAKE_OVERRIDE } override fun getScopeForClassHeaderResolution(): LexicalScope = resolutionScopesSupport.scopeForClassHeaderResolution() override fun getScopeForConstructorHeaderResolution(): LexicalScope = resolutionScopesSupport.scopeForConstructorHeaderResolution() override fun getScopeForCompanionObjectHeaderResolution(): LexicalScope = resolutionScopesSupport.scopeForCompanionObjectHeaderResolution() override fun getScopeForMemberDeclarationResolution(): LexicalScope = resolutionScopesSupport.scopeForMemberDeclarationResolution() override fun getScopeForStaticMemberDeclarationResolution(): LexicalScope = resolutionScopesSupport.scopeForStaticMemberDeclarationResolution() override fun getScopeForInitializerResolution(): LexicalScope = throw UnsupportedOperationException("Not supported for synthetic class or object") override fun toString(): String = "synthetic class " + name.toString() + " in " + containingDeclaration private fun createUnsubstitutedPrimaryConstructor(): ClassConstructorDescriptor { val constructor = DescriptorFactory.createPrimaryConstructorForObject(thisDescriptor, source) constructor.returnType = getDefaultType() return constructor } private inner class SyntheticTypeConstructor(storageManager: StorageManager) : AbstractClassTypeConstructor(storageManager) { override fun getParameters(): List<TypeParameterDescriptor> = emptyList() override fun isFinal(): Boolean = true override fun isDenotable(): Boolean = true override fun getDeclarationDescriptor(): ClassifierDescriptor = thisDescriptor override fun computeSupertypes(): Collection<KotlinType> = syntheticSupertypes override val supertypeLoopChecker: SupertypeLoopChecker = SupertypeLoopChecker.EMPTY } private class SyntheticClassMemberDeclarationProvider( override val correspondingClassOrObject: KtPureClassOrObject ) : ClassMemberDeclarationProvider { override val ownerInfo: KtClassLikeInfo? = null override fun getDeclarations(kindFilter: DescriptorKindFilter, nameFilter: (Name) -> Boolean): List<KtDeclaration> = emptyList() override fun getFunctionDeclarations(name: Name): Collection<KtNamedFunction> = emptyList() override fun getPropertyDeclarations(name: Name): Collection<KtProperty> = emptyList() override fun getClassOrObjectDeclarations(name: Name): Collection<KtClassLikeInfo> = emptyList() override fun getTypeAliasDeclarations(name: Name): Collection<KtTypeAlias> = emptyList() } internal inner class SyntheticDeclaration( private val _parent: KtPureElement, private val _name: String ) : KtPureClassOrObject { fun descriptor() = thisDescriptor override fun getName(): String? = _name override fun isLocal(): Boolean = false override fun getDeclarations(): List<KtDeclaration> = emptyList() override fun getSuperTypeListEntries(): List<KtSuperTypeListEntry> = emptyList() override fun getCompanionObjects(): List<KtObjectDeclaration> = emptyList() override fun hasExplicitPrimaryConstructor(): Boolean = false override fun hasPrimaryConstructor(): Boolean = false override fun getPrimaryConstructor(): KtPrimaryConstructor? = null override fun getPrimaryConstructorModifierList(): KtModifierList? = null override fun getPrimaryConstructorParameters(): List<KtParameter> = emptyList() override fun getSecondaryConstructors(): List<KtSecondaryConstructor> = emptyList() override fun getPsiOrParent() = _parent.psiOrParent override fun getParent() = _parent.psiOrParent override fun getContainingKtFile() = _parent.containingKtFile } } fun KtPureElement.findClassDescriptor(bindingContext: BindingContext): ClassDescriptor = when (this) { is PsiElement -> BindingContextUtils.getNotNull(bindingContext, BindingContext.CLASS, this) is SyntheticClassOrObjectDescriptor.SyntheticDeclaration -> descriptor() else -> throw IllegalArgumentException("$this shall be PsiElement or SyntheticClassOrObjectDescriptor.SyntheticDeclaration") }
1
null
4
6
ce145c015d6461c840050934f2200dbc11cb3d92
9,034
kotlin
Apache License 2.0
src/main/kotlin/io/kadena/pact/intellij/language/psi/PactFile.kt
lukeribchester
513,030,883
false
{"Kotlin": 24714, "Lex": 4062}
package io.kadena.pact.intellij.language.psi import com.intellij.extapi.psi.PsiFileBase import com.intellij.openapi.fileTypes.FileType import com.intellij.psi.FileViewProvider import io.kadena.pact.intellij.PactFileType import io.kadena.pact.intellij.PactLanguage import org.jetbrains.annotations.NotNull class PactFile constructor(@NotNull viewProvider: FileViewProvider) : PsiFileBase(viewProvider, PactLanguage.INSTANCE) { @NotNull override fun getFileType(): FileType { return PactFileType.INSTANCE; } override fun toString(): String { return "Pact File"; } }
2
Kotlin
0
2
4e2812c4605e8fef49ce4beacdf366b0b95dfea5
603
pact-intellij
MIT License
app/src/main/java/cl/panmu/stroller/TabbedMainActivity.kt
LeandroPintoT
648,867,137
false
{"Kotlin": 89058}
package cl.panmu.stroller import android.app.AlertDialog import android.content.res.ColorStateList import android.os.Bundle import android.util.Log import android.view.View import android.widget.Button import android.widget.TableLayout import android.widget.Toast import androidx.activity.viewModels import androidx.appcompat.app.AppCompatActivity import androidx.viewpager2.widget.ViewPager2 import cl.panmu.stroller.databinding.ActivityTabbedMainBinding import cl.panmu.stroller.ui.fragments.AudioFragment import cl.panmu.stroller.ui.fragments.ChatFragment import cl.panmu.stroller.ui.fragments.EscenasFragment import cl.panmu.stroller.ui.fragments.EstadoFragment import cl.panmu.stroller.ui.fragments.FuentesFragment import cl.panmu.stroller.ui.fragments.UtilidadesFragment import cl.panmu.stroller.ui.main.PageViewModel import cl.panmu.stroller.ui.main.PagerAdapter import com.google.android.material.tabs.TabLayout import com.google.android.material.tabs.TabLayoutMediator import org.json.JSONObject import java.io.File import java.time.LocalDateTime import java.time.ZoneOffset class TabbedMainActivity : AppCompatActivity() { //lateinit var mainHandler: Handler private lateinit var binding: ActivityTabbedMainBinding private val viewModel: PageViewModel by viewModels() private var alto: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityTabbedMainBinding.inflate(layoutInflater) setContentView(binding.root) val pagerAdapter = PagerAdapter(supportFragmentManager, lifecycle) val viewPager: ViewPager2 = binding.viewPager viewPager.offscreenPageLimit = 4 pagerAdapter.addFragment(EstadoFragment(), resources.getString(R.string.fragment_title_estado)) pagerAdapter.addFragment(EscenasFragment(), resources.getString(R.string.fragment_title_escenas)) pagerAdapter.addFragment(UtilidadesFragment(), resources.getString(R.string.fragment_title_utilidades)) pagerAdapter.addFragment(FuentesFragment(), resources.getString(R.string.fragment_title_fuentes)) pagerAdapter.addFragment(AudioFragment(), resources.getString(R.string.fragment_title_audio)) pagerAdapter.addFragment(ChatFragment(), resources.getString(R.string.fragment_title_chat)) viewPager.adapter = pagerAdapter val tabs: TabLayout = binding.tabs tabs.addOnTabSelectedListener(TabSelectedListener(this, viewModel)) TabLayoutMediator(tabs, viewPager) { tab, position -> tab.text = pagerAdapter.getFragmentTitle(position) }.attach() val userlogged = File(filesDir, "userlogged.cfg") if (userlogged.exists() && userlogged.readLines().isNotEmpty()) { val jsonObs = JSONObject(userlogged.readLines().first()) viewModel.username(jsonObs.get("user").toString()) } val btnToggleReplay = findViewById<Button>(R.id.btnToggleReplay) val btnGetReplay = findViewById<Button>(R.id.btnGetReplay) btnToggleReplay.setOnClickListener { viewModel.obsController.value?.toggleReplayBuffer { if (!it.isSuccessful) runOnUiThread { btnToggleReplay.text = resources.getString(R.string.btn_iniciar_buffer) btnGetReplay.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.dark_ocean_blue, null)) btnGetReplay.isEnabled = false AlertDialog .Builder(this) .setTitle(R.string.alerta_titulo_buffer) .setMessage(R.string.alerta_msg_buffer) .setPositiveButton(R.string.alerta_btn_pos_conexion_error) { _, _ -> } .show() } } } btnGetReplay.setOnClickListener { viewModel.obsController.value?.getReplayBufferStatus { if (it.isSuccessful && it.outputActive) { viewModel.obsController.value?.saveReplayBuffer { saveRes -> if (saveRes.isSuccessful) { viewModel.obsController.value?.getLastReplayBufferReplay {res -> if (res.isSuccessful) runOnUiThread { Toast.makeText(this, resources.getString(R.string.toast_msg_pos_guardar_clip), Toast.LENGTH_SHORT).show() } } } } } else { runOnUiThread { Toast.makeText(this, resources.getString(R.string.toast_msg_neg_guardar_clip), Toast.LENGTH_SHORT).show() } } } } viewModel.isConnected.observe(this) { isConnected -> val btnsLayout: TableLayout = findViewById(R.id.tableLayoutBtnsStream) runOnUiThread { if (isConnected) { btnsLayout.visibility = View.VISIBLE btnsLayout.layoutParams.height = alto } else { alto = btnsLayout.layoutParams.height btnsLayout.visibility = View.INVISIBLE btnsLayout.layoutParams.height = 1 } } viewModel.obsController.value?.getReplayBufferStatus { if (it.isSuccessful) { btnToggleReplay.text = resources.getString(if(it.outputActive) R.string.btn_detener_buffer else R.string.btn_iniciar_buffer) btnGetReplay.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.ocean_blue, null)) btnGetReplay.isEnabled = true } else { btnToggleReplay.text = resources.getString(R.string.btn_iniciar_buffer) btnGetReplay.backgroundTintList = ColorStateList.valueOf(resources.getColor(R.color.dark_ocean_blue, null)) btnGetReplay.isEnabled = false } } } viewModel.isStreaming.observe(this) { isStreaming -> val btnStream: Button = findViewById(R.id.btnStream) // actualiza boton stream runOnUiThread { btnStream.setText(if (isStreaming) R.string.btn_detener_transmision else R.string.btn_iniciar_transmision) // Setea la funcion usada dependiendo del estado de la transmision btnStream.setOnClickListener( if (isStreaming) { { AlertDialog .Builder(this) .setTitle(R.string.alerta_titulo_emision) .setMessage(R.string.alerta_msg_emision_final) .setPositiveButton(R.string.alerta_btn_pos_emision_final) { _, _ -> viewModel.obsController.value?.stopStream { if (it.isSuccessful) runOnUiThread { viewModel.isStreaming(false) } else Toast.makeText(this, resources.getText(R.string.toast_msg_neg_detener_emision), Toast.LENGTH_LONG).show() } } .setNegativeButton(R.string.alerta_btn_neg_emision_final) { _, _ -> } .show() } } else { { AlertDialog .Builder(this) .setTitle(R.string.alerta_titulo_emision) .setMessage(R.string.alerta_msg_emision_inicio) .setPositiveButton(R.string.alerta_btn_pos_emision_inicio) { _, _ -> viewModel.obsController.value?.startStream { if (it.isSuccessful) { runOnUiThread { viewModel.isStreaming(true) viewModel.timeStream(LocalDateTime.now(ZoneOffset.UTC)) } } else Toast.makeText(this, resources.getText(R.string.toast_msg_neg_iniciar_emision), Toast.LENGTH_LONG).show() } } .setNegativeButton(R.string.alerta_btn_neg_emision_inicio) { _, _ -> } .show() } } ) } } viewModel.isRecording.observe(this) { isRecording -> // actualiza boton record val btnRecord: Button = findViewById(R.id.btnRecord) runOnUiThread { btnRecord.setText(if (isRecording) R.string.btn_detener_grabacion else R.string.btn_iniciar_grabacion) // si esta desconectado, hace el startForResult, si no, desconecta y recarga btnRecord.setOnClickListener( if (isRecording) { { AlertDialog .Builder(this) .setTitle(R.string.alerta_titulo_grabacion) .setMessage(R.string.alerta_msg_grabacion_final) .setPositiveButton(R.string.alerta_btn_pos_grabacion_final) { _, _ -> viewModel.obsController.value?.stopRecord { if (it.isSuccessful) runOnUiThread { viewModel.isRecording(false) } else Toast.makeText(this, resources.getText(R.string.toast_msg_neg_detener_grabacion), Toast.LENGTH_LONG).show() } } .setNegativeButton(R.string.alerta_btn_neg_grabacion_final) { _, _ -> } .show() } } else { { AlertDialog .Builder(this) .setTitle(R.string.alerta_titulo_grabacion) .setMessage(R.string.alerta_msg_grabacion_inicio) .setPositiveButton(R.string.alerta_btn_pos_grabacion_inicio) { _, _ -> viewModel.obsController.value?.startRecord { if (it.isSuccessful) { runOnUiThread { viewModel.isRecording(true) viewModel.timeRecord(LocalDateTime.now(ZoneOffset.UTC)) } } else Toast.makeText(this, resources.getText(R.string.toast_msg_neg_iniciar_grabacion), Toast.LENGTH_LONG).show() } } .setNegativeButton(R.string.alerta_btn_neg_grabacion_inicio) { _, _ -> } .show() } } ) } } } } class TabSelectedListener(private val ctx: TabbedMainActivity, private val viewModel: PageViewModel) : TabLayout.OnTabSelectedListener { private var alto: Int = 0 override fun onTabSelected(tab: TabLayout.Tab?) { if (tab?.text == "Chat") { ctx.runOnUiThread { val btnsLayout: TableLayout = ctx.findViewById(R.id.tableLayoutBtnsStream) btnsLayout.visibility = View.INVISIBLE alto = btnsLayout.layoutParams.height btnsLayout.layoutParams.height = 1 } } } override fun onTabUnselected(tab: TabLayout.Tab?) { if (tab?.text == "Chat") { if (viewModel.isConnected.value != null && viewModel.isConnected.value!!) { val btnsLayout: TableLayout = ctx.findViewById(R.id.tableLayoutBtnsStream) ctx.runOnUiThread { btnsLayout.visibility = View.VISIBLE btnsLayout.layoutParams.height = alto } } } } override fun onTabReselected(tab: TabLayout.Tab?) { Log.d("TABSEL", "onTabReselected: " + tab?.text) } }
0
Kotlin
0
0
efdd76cdc986845ab4c825c455735970e366711b
12,897
Stroller
Apache License 2.0
ui/common/src/iosMain/kotlin/ly/david/musicsearch/ui/common/topappbar/TopAppBarWithFilter.ios.kt
lydavid
458,021,427
false
null
package ly.david.musicsearch.ui.common.topappbar import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.TopAppBarScrollBehavior import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import ly.david.musicsearch.core.models.network.MusicBrainzEntity import ly.david.musicsearch.ui.common.topappbar.OverflowMenuScope import ly.david.musicsearch.ui.common.topappbar.TopAppBarWithFilterInternal /** * [ScrollableTopAppBar] with filtering. */ @OptIn(ExperimentalMaterial3Api::class) @Composable actual fun TopAppBarWithFilter( modifier: Modifier, onBack: () -> Unit, showBackButton: Boolean, entity: MusicBrainzEntity?, title: String, subtitle: String, scrollBehavior: TopAppBarScrollBehavior?, overflowDropdownMenuItems: @Composable (OverflowMenuScope.() -> Unit)?, subtitleDropdownMenuItems: @Composable (OverflowMenuScope.() -> Unit)?, showFilterIcon: Boolean, filterText: String, onFilterTextChange: (String) -> Unit, additionalActions: @Composable () -> Unit, additionalBar: @Composable () -> Unit, ) { var isFilterMode by rememberSaveable { mutableStateOf(false) } TopAppBarWithFilterInternal( modifier = modifier, onBack = onBack, showBackButton = showBackButton, entity = entity, title = title, subtitle = subtitle, scrollBehavior = scrollBehavior, overflowDropdownMenuItems = overflowDropdownMenuItems, subtitleDropdownMenuItems = subtitleDropdownMenuItems, showFilterIcon = showFilterIcon, filterText = filterText, onFilterTextChange = onFilterTextChange, isFilterMode = isFilterMode, onFilterModeChange = { isFilterMode = it }, additionalActions = additionalActions, additionalBar = additionalBar, ) }
119
null
0
22
94228bfad5473e3a3d86c1f3b8273689df7a4421
2,058
MusicSearch
Apache License 2.0
src/test/kotlin/io/vlang/lang/completion/ChanInitCompletionTest.kt
vlang
754,996,747
false
null
package io.vlang.lang.completion class ChanInitCompletionTest : CompletionTestBase() { fun `test fields`() = checkEquals( """ module main fn main() { ch := chan int{/*caret*/} } """.trimIndent(), 0, "cap" ) fun `test second field`() = checkEquals( """ module main fn main() { ch := chan int{cap: 100/*caret*/} } """.trimIndent(), 0, ) fun `test field value`() = checkIncludes( """ module main fn main() { ch := chan int{cap: /*caret*/} } """.trimIndent(), 0, "unsafe", ) }
4
null
5
33
5b05a7b1f71ef8dcd7f26425a756259081fe5122
702
intellij-v
MIT License
src/main/java/com/wald/mainject/inject/extension/impl/DefaultDependencyDescriptionResolver.kt
Waldemared
338,810,220
false
null
package com.wald.mainject.inject.extension.impl import com.wald.mainject.inject.DependencyDescriptor import com.wald.mainject.inject.DependencyInfo import com.wald.mainject.inject.extension.DependencyDescriptorResolver import com.wald.mainject.inject.qualify.qualifier import com.wald.mainject.inject.qualify.qualifiers import kotlin.reflect.KParameter /** * @author vkosolapov * @since */ class DefaultDependencyDescriptionResolver : DependencyDescriptorResolver { override fun resolve(callableParameter: KParameter) = with(callableParameter) { DependencyInfo(type, qualifiers.toSet(), isOptional) } }
1
null
1
1
eb8ea2dc2697f1d96636cceb1e97ca044b2fd89f
624
mainject-core
MIT License
server/src/main/kotlin/kotlinbars/server/Main.kt
jamesward
350,496,939
false
null
/* * Copyright 2020 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 kotlinbars.server import kotlinbars.common.Bar import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.json.Json import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.data.repository.kotlin.CoroutineCrudRepository import org.springframework.http.HttpStatus import org.springframework.http.ResponseEntity import org.springframework.http.codec.ServerCodecConfigurer import org.springframework.http.codec.json.KotlinSerializationJsonDecoder import org.springframework.web.bind.annotation.* import org.springframework.web.reactive.config.WebFluxConfigurer import java.net.URI import java.util.* interface BarRepo : CoroutineCrudRepository<Bar, Long> @SpringBootApplication @RestController class WebApp(val barRepo: BarRepo) { @GetMapping("/api/bars") suspend fun getBars() = run { barRepo.findAll() } @PostMapping("/api/bars") suspend fun addBar(@RequestBody bar: Bar) = run { barRepo.save(bar) ResponseEntity<Unit>(HttpStatus.NO_CONTENT) } @DeleteMapping("/api/bars/{id}") suspend fun deleteBar(@PathVariable id: Long) = run { barRepo.deleteById(id) ResponseEntity<Unit>(HttpStatus.OK) } } @Configuration(proxyBeanMethods = false) class JsonConfig { @ExperimentalSerializationApi @Bean fun kotlinSerializationJsonDecoder() = KotlinSerializationJsonDecoder(Json { explicitNulls = false }) @Bean fun webConfig(decoder: KotlinSerializationJsonDecoder): WebFluxConfigurer { return object : WebFluxConfigurer { override fun configureHttpMessageCodecs(configurer: ServerCodecConfigurer) { super.configureHttpMessageCodecs(configurer) configurer.defaultCodecs().kotlinSerializationJsonDecoder(decoder) } } } } fun main(args: Array<String>) { val props = Properties() System.getenv()["DATABASE_URL"]?.let { val dbUri = URI(it) props["spring.r2dbc.url"] = "r2dbc:postgresql://" + dbUri.host + dbUri.path props["spring.r2dbc.username"] = dbUri.userInfo.split(":")[0] props["spring.r2dbc.password"] = dbUri.userInfo.split(":")[1] } runApplication<WebApp>(*args) { setDefaultProperties(props) } }
2
null
5
47
8d5443a7f72f1ba10ec2ad171a5dfe193b3e7be4
3,073
kotlin-bars
Apache License 2.0
features/app-widgets/src/main/java/app/ss/widgets/glance/WidgetLoading.kt
Adventech
65,243,816
false
{"Kotlin": 1669895, "Java": 17228, "CSS": 9010, "JavaScript": 7718, "HTML": 2229, "Shell": 544}
package app.ss.widgets.glance import androidx.compose.runtime.Composable import androidx.glance.GlanceModifier import androidx.glance.GlanceTheme import androidx.glance.appwidget.CircularProgressIndicator import androidx.glance.layout.Alignment import androidx.glance.layout.Box import androidx.glance.layout.fillMaxSize @Composable internal fun WidgetLoading(modifier: GlanceModifier = GlanceModifier) { Box(modifier = modifier.fillMaxSize(), contentAlignment = Alignment.Center) { CircularProgressIndicator( modifier = GlanceModifier, color = GlanceTheme.colors.primary ) } }
2
Kotlin
49
171
2cc105ea76c7fdf979b0b6ee1098f413c1aa009d
628
sabbath-school-android
MIT License
androidApp/src/androidTest/java/com/gplay/app/feature/home/HomeViewTest.kt
lukma
529,747,563
false
{"Kotlin": 140900, "Swift": 26911}
package com.gplay.app.feature.home import androidx.compose.ui.test.* import androidx.compose.ui.test.junit4.createComposeRule import androidx.core.text.HtmlCompat import androidx.paging.compose.collectAsLazyPagingItems import com.gplay.app.ui.GPlayScaffold import com.gplay.app.ui.theme.GPlayTheme import com.gplay.app.util.TestSamples import com.gplay.core.domain.article.usecase.GetArticlesUseCase import io.mockk.coEvery import io.mockk.mockk import kotlinx.coroutines.flow.flow import org.junit.Rule import org.junit.Test class HomeViewTest { private val getArticlesUseCase: GetArticlesUseCase = mockk() private lateinit var viewModel: HomeViewModel @get:Rule val composeTestRule = createComposeRule() private fun launchView() { viewModel = HomeViewModel(getArticlesUseCase) composeTestRule.setContent { GPlayTheme { GPlayScaffold { val pagingItems = viewModel.paging.collectAsLazyPagingItems() HomeView( pagingItems = pagingItems, ) } } } } @Test fun perform_get_articles_got_value() { // given coEvery { getArticlesUseCase(any()) } returns flow { emit(TestSamples.articlePagingResult()) } // when launchView() // then val parentMatcher = hasParent(hasTestTag("ArticleItem")) TestSamples.articlePagingResult().items.subList(0, 1).forEach { composeTestRule.onNode(parentMatcher and hasText(it.title)) .assertIsDisplayed() val plainContent = HtmlCompat.fromHtml(it.content, HtmlCompat.FROM_HTML_MODE_LEGACY) .toString() composeTestRule.onNode(parentMatcher and hasTextExactly(plainContent)) .assertIsDisplayed() } } @Test fun perform_get_articles_got_failure() { // given coEvery { getArticlesUseCase(any()) } returns flow { throw TestSamples.error } // when launchView() // then val parentMatcher = hasParent(hasTestTag("ErrorView")) composeTestRule.onNode(parentMatcher and hasText(TestSamples.error.message.orEmpty())) .assertIsDisplayed() } }
0
Kotlin
0
1
06828523a53ce3e35963fd1536264e3110b8cfed
2,288
sample-kmm
Apache License 2.0
lib_mangax/src/main/kotlin/com/crow/mangax/copymanga/glide/AppOnGlideProgressListener.kt
crowforkotlin
610,636,509
false
{"Kotlin": 988386, "CMake": 2776, "C++": 2732, "Makefile": 1968}
package com.crow.mangax.copymanga.glide fun interface AppOnGlideProgressListener { fun doOnProgress(url: String, isComplete: Boolean, percentage: Int, bytesRead: Long, totalBytes: Long) }
13
Kotlin
7
250
6589a636788baff27760da5f47b61eeefb52abf0
192
CopyMangaX
Apache License 2.0
app/src/main/java/ru/rshbdigital/farmhub/core/api/model/NWCounter.kt
MaksimZotov
720,237,303
false
{"Kotlin": 4780}
package ru.rshbdigital.farmhub.core.api.model data class NWCounter( val count: Int? = null )
0
Kotlin
0
0
9d84d35989f288c30980dffa6e3fc62cd2fc6cdf
97
FarmHub
MIT License
compose/ui/ui-graphics/src/androidMain/kotlin/androidx/compose/ui/graphics/layer/LayerManager.android.kt
androidx
256,589,781
false
{"Kotlin": 102794437, "Java": 64412412, "C++": 9138104, "AIDL": 617598, "Python": 310931, "Shell": 189529, "TypeScript": 40586, "HTML": 35176, "Groovy": 27482, "ANTLR": 26700, "Svelte": 20307, "CMake": 18033, "C": 16982, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
/* * Copyright 2024 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.ui.graphics.layer import android.graphics.PixelFormat import android.media.ImageReader import android.os.Build import android.os.Looper import android.os.Message import android.view.Surface import androidx.annotation.RequiresApi import androidx.collection.ScatterSet import androidx.collection.mutableScatterSetOf import androidx.compose.ui.graphics.CanvasHolder import androidx.core.os.HandlerCompat /** * Class responsible for managing the layer lifecycle to support * persisting of displaylist content. HWUI aggressively releases resources * from a displaylist if it is not used to render a single frame from a HardwareRenderer * instance */ internal class LayerManager(val canvasHolder: CanvasHolder) { private val layerSet = mutableScatterSetOf<GraphicsLayer>() /** * Create a placeholder ImageReader instance that we will use to issue a single draw call * for each GraphicsLayer. This placeholder draw will increase the ref count of each * RenderNode instance within HWUI therefore persisting it across frames as there is * another internal CanvasContext instance owned by the internal HwuiContext instance of * a Surface */ private var imageReader: ImageReader? = null private val handler = HandlerCompat.createAsync(Looper.getMainLooper()) { persistLayers(layerSet) true } fun persist(layer: GraphicsLayer) { layerSet.add(layer) if (!handler.hasMessages(0)) { // we don't run persistLayers() synchronously in order to do less work as there // might be a lot of new layers created during one frame. however we also want // to execute it as soon as possible to be able to persist the layers before // they discard their content. it is possible that there is some other work // scheduled on the main thread which is going to change what layers are drawn. // we use sendMessageAtFrontOfQueue() in order to be executed before that. handler.sendMessageAtFrontOfQueue(Message.obtain()) } } fun release(layer: GraphicsLayer) { if (layerSet.remove(layer)) { layer.discardDisplayList() } } private fun persistLayers(layers: ScatterSet<GraphicsLayer>) { /** * Create a placeholder ImageReader instance that we will use to issue a single draw call * for each GraphicsLayer. This placeholder draw will increase the ref count of each * RenderNode instance within HWUI therefore persisting it across frames as there is * another internal CanvasContext instance owned by the internal HwuiContext instance of * a Surface. This is only necessary for Android M and above. */ val requiredOsVersion = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M // On Robolectric even Surface#lockHardwareCanvas is not hardware accelerated and // drawing render nodes are not supported. Additionally robolectric mistakenly flags // surfaces as not being released even though the owning ImageReader does release the // surface in ImageReader#close // See b/340578758 val shouldPersistLayers = requiredOsVersion && layers.isNotEmpty() && !isRobolectric if (shouldPersistLayers) { val reader = imageReader ?: ImageReader.newInstance( 1, 1, PixelFormat.RGBA_8888, 1 ).apply { // We don't care about the result, but release the buffer back to the queue // for subsequent renders to ensure the RenderThread is free as much as possible setOnImageAvailableListener({ it?.acquireLatestImage()?.close() }, handler) }.also { imageReader = it } val surface = reader.surface val canvas = LockHardwareCanvasHelper.lockHardwareCanvas(surface) canvasHolder.drawInto(canvas) { canvas.save() canvas.clipRect(0, 0, 1, 1) layers.forEach { layer -> layer.drawForPersistence(this) } canvas.restore() } surface.unlockCanvasAndPost(canvas) } } fun destroy() { imageReader?.close() imageReader = null } /** * Discards the corresponding ImageReader used to increment the ref count of each layer * and persists the current layer list creating a new ImageReader. This is useful in scenarios * where HWUI releases graphics resources in response to onTrimMemory often when the application * is backgrounded */ fun updateLayerPersistence() { destroy() persistLayers(layerSet) } companion object { private val isRobolectric = Build.FINGERPRINT.lowercase() == "robolectric" } } @RequiresApi(Build.VERSION_CODES.M) private object LockHardwareCanvasHelper { @androidx.annotation.DoNotInline fun lockHardwareCanvas(surface: Surface): android.graphics.Canvas = surface.lockHardwareCanvas() }
28
Kotlin
937
5,108
89ec14e39cf771106a8719337062572717cbad31
5,730
androidx
Apache License 2.0
src/test/kotlin/solutions/constantTime/iteration6/RegionTaxCalculatorTest.kt
daniel-rusu
669,564,782
false
{"Kotlin": 70190}
package solutions.constantTime.iteration5 import dataModel.base.TaxBracket import org.junit.jupiter.api.Test import sampleData.SampleTaxBrackets import solutions.TaxCalculatorValidator import utilities.TaxBracketGenerator import kotlin.random.Random class MinBracketTaxCalculatorTest { @Test fun `produces the same tax amounts as the well-tested LinearTaxCalculator`() { ensureMatchesResultsOfLinearTaxCalculator(forBrackets = SampleTaxBrackets.texasTaxBrackets, random = Random) } @Test fun `produces the same tax amounts as the well-tested LinearTaxCalculator with random brackets`() { val seed = Random.nextLong() val random = Random(seed) println("Seed: $seed") // to be able to reproduce when encountering a failure repeat(100) { val numBrackets = random.nextInt(1, 100) val lowerBoundDollarsOfHighestBracket = when (numBrackets) { 1 -> 0 else -> random.nextInt(numBrackets - 1, numBrackets * 100) } val taxBrackets = TaxBracketGenerator.generateTaxBrackets( numBrackets, lowerBoundDollarsOfHighestBracket, random ) ensureMatchesResultsOfLinearTaxCalculator(forBrackets = taxBrackets, random = random) } } private fun ensureMatchesResultsOfLinearTaxCalculator(forBrackets: List<TaxBracket>, random: Random) { TaxCalculatorValidator.ensureProducesSameResultsAsLinearTaxCalculator( MinBracketTaxCalculator(forBrackets), forBrackets, random, ) } }
0
Kotlin
0
1
f5f63e1eeb3b3fe137d99b2c94bd50f5016167d0
1,639
tax-calculator
MIT License
app/src/main/java/com/example/textingapplication/SmsListener.kt
travispavletich
206,397,717
false
null
package com.example.textingapplication import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.net.Uri import android.os.Bundle import android.telephony.SmsMessage import android.util.Log import java.lang.Exception class SmsListener : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { //TODO("not implemented") //To change body of created functions use File | Settings | File Templates. Log.d("Receive SMS", "Got a message") if (intent?.action == "android.provider.Telephony.SMS_RECEIVED") { val bundle = intent.extras var msgs: Array<SmsMessage>? = null var msg_from: String? = null if (bundle != null) { val intentExtras: Bundle? = intent.extras try { val pdus: Array<Any> = bundle.get("pdus") as Array<Any> msgs = Array(pdus.size) { val format = intentExtras?.getString("format") SmsMessage.createFromPdu(pdus[it] as ByteArray, format) } var body = "" val sender = if (msgs.isNotEmpty()) msgs[0].originatingAddress else "" val timestamp = msgs[0].timestampMillis val date = MessageHandler.timestampToDate(timestamp) for (msg in msgs) { body += msg.messageBody } val uri = Uri.parse("content://sms") val cursor = context?.contentResolver?.query(uri, null , null, null, null) var conversation_id = 0 cursor?.use { if (it.moveToFirst()) { val person = it.getString(it.getColumnIndex("address")) val messageTimestamp = it.getLong(it.getColumnIndex("date")) val convoId = it.getInt(it.getColumnIndex("thread_id")) // if (person == sender && messageTimestamp == timestamp) { if (person == sender) { conversation_id = convoId } } } if (sender != null) { val message = Message(sender, false, body, conversation_id, date, timestamp) Log.d("NewMessage", "$message") ServerMessaging.sendNewMessage(context!!, message) } else { Log.d("NewMessage", "Sender is null") } } catch (e: Exception) { Log.d("Exception caught", e.message) } } } } }
0
Kotlin
0
0
88cbfd0cd24686c2757062d67ff1eef04bf5295b
2,880
TextingAndroidApp
MIT License
platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsProjectLogErrorHandler.kt
ingokegel
72,937,917
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.vcs.log.impl import com.google.common.collect.EnumMultiset import com.intellij.openapi.diagnostic.thisLogger import com.intellij.util.concurrency.annotations.RequiresEdt import com.intellij.vcs.log.data.VcsLogStorageImpl import com.intellij.vcs.log.data.index.VcsLogBigRepositoriesList import com.intellij.vcs.log.data.index.VcsLogPersistentIndex import com.intellij.vcs.log.util.StorageId import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.withContext internal class VcsProjectLogErrorHandler(private val projectLog: VcsProjectLog) { private val countBySource = EnumMultiset.create(VcsLogErrorHandler.Source::class.java) @RequiresEdt fun recreateOnError(source: VcsLogErrorHandler.Source, t: Throwable) { if (projectLog.isDisposing) return val logManager = projectLog.logManager ?: return countBySource.add(source) val count = countBySource.count(source) if (source == VcsLogErrorHandler.Source.Index) { if (count > DISABLE_INDEX_COUNT) { val rootsForIndexing = VcsLogPersistentIndex.getRootsForIndexing(logManager.dataManager.logProviders) thisLogger().error("Disabling indexing for ${rootsForIndexing.map { it.name }} due to corruption " + "(count=$count).", t) rootsForIndexing.forEach { VcsLogBigRepositoriesList.getInstance().addRepository(it) } projectLog.recreateLog(logManager, true) return } } val invalidateCaches = count % INVALIDATE_CACHES_COUNT == 0 if (invalidateCaches) { thisLogger().error("Invalidating Vcs Log caches after $source corruption (count=$count).", t) } else { thisLogger().debug("Recreating Vcs Log after $source corruption (count=$count).", t) } projectLog.recreateLog(logManager, invalidateCaches) } } private const val INVALIDATE_CACHES_COUNT = 5 private const val DISABLE_INDEX_COUNT = 2 * INVALIDATE_CACHES_COUNT internal fun VcsLogManager.storageIds(): List<StorageId> { return linkedSetOf((dataManager.index as? VcsLogPersistentIndex)?.indexStorageId, (dataManager.storage as? VcsLogStorageImpl)?.refsStorageId, (dataManager.storage as? VcsLogStorageImpl)?.hashesStorageId).filterNotNull() } internal fun VcsProjectLog.invalidateCaches(logManager: VcsLogManager): Job = recreateLog(logManager = logManager, invalidateCaches = true) private fun VcsProjectLog.recreateLog(logManager: VcsLogManager, invalidateCaches: Boolean): Job { val storageIds = logManager.storageIds() thisLogger().assertTrue(storageIds.isNotEmpty()) return runOnDisposedLog { if (invalidateCaches) { for (storageId in storageIds) { try { val deleted = withContext(Dispatchers.IO) { storageId.cleanupAllStorageFiles() } if (deleted) { thisLogger().info("Deleted ${storageId.storagePath}") } else { thisLogger().error("Could not delete ${storageId.storagePath}") } } catch (t: Throwable) { thisLogger().error(t) } } } } }
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
3,260
intellij-community
Apache License 2.0
sqllin-driver/src/linuxMain/kotlin/com/ctrip/sqllin/driver/platform/UtilsLinux.kt
ctripcorp
570,015,389
false
null
package com.ctrip.sqllin.driver.platform import kotlinx.cinterop.ByteVar import kotlinx.cinterop.CPointer import kotlinx.cinterop.toKString /** * The tools with Linux implementation * @author yqiao */ internal actual fun bytesToString(bv: CPointer<ByteVar>): String = bv.toKString() internal actual inline val separatorChar: Char get() = '/'
1
C
5
154
0c15e7e49ec75ae403b0e213c6205a0bc1d92013
352
SQLlin
Apache License 2.0
src/main/java/com/github/ai/autokpass/presentation/ui/root/RootViewModel.kt
aivanovski
473,610,974
false
{"Kotlin": 288569}
package com.github.ai.autokpass.presentation.ui.root import androidx.compose.ui.Alignment import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import androidx.compose.ui.window.WindowPlacement import androidx.compose.ui.window.WindowPosition import androidx.compose.ui.window.WindowState import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow class RootViewModel { private val _windowState = MutableStateFlow(newWindowState(width = 1000.dp, height = 600.dp)) val windowState: StateFlow<WindowState> = _windowState fun updateWindowSize(width: Dp? = null, height: Dp? = null) { val currentWidth = _windowState.value.size.width val currentHeight = _windowState.value.size.height if (currentWidth == width && currentHeight == height) { return } val w = width ?: currentWidth val h = height ?: currentHeight _windowState.value = newWindowState(width = w, height = h) } private fun newWindowState(width: Dp, height: Dp): WindowState { return WindowState( placement = WindowPlacement.Floating, isMinimized = false, position = WindowPosition(Alignment.BottomCenter), size = DpSize(width, height) ) } }
1
Kotlin
0
1
4f9d3bebbde84056b8d721dae71aca15932d0b5c
1,346
autokpass
Apache License 2.0
src/main/kotlin/it/czerwinski/intellij/common/ui/ErrorLogTreeModel.kt
sczerwinski
283,832,623
false
null
/* * Copyright 2020-2021 <NAME> * * 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 it.czerwinski.intellij.wavefront.editor.ui import javax.swing.tree.DefaultMutableTreeNode import javax.swing.tree.DefaultTreeModel class ErrorLogTreeModel : DefaultTreeModel(DefaultMutableTreeNode()), ErrorLog { private val rootNode: DefaultMutableTreeNode get() = root as DefaultMutableTreeNode override fun addError(entry: ErrorLog.Entry) { for (node in rootNode.children()) { if ((node as? DefaultMutableTreeNode)?.userObject == entry.headline) return } rootNode.add( DefaultMutableTreeNode(entry.headline).apply { add(DefaultMutableTreeNode(entry.stackTrace, false)) } ) reload() } override fun clearErrors() { rootNode.removeAllChildren() reload() } }
27
null
1
9
ca6ee47083cdca9b52cd2a59994d12a4a10033eb
1,394
wavefront-obj-intellij-plugin
Apache License 2.0
lib/src/main/java/net/imoya/android/preference/util/TimePeriodPreferenceUtil.kt
IceImo-P
392,544,118
false
null
/* * Copyright (C) 2022 IceImo-P * * 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 net.imoya.android.preference.util import android.content.SharedPreferences import net.imoya.android.preference.PreferenceLog import net.imoya.android.preference.model.TimePeriod /** * [TimePeriod] 設定値関連ユーティリティ */ @Suppress("unused") object TimePeriodPreferenceUtil { /** * 指定の [SharedPreferences] より、[TimePeriod]を取得して返します。 * * @param sharedPreferences [SharedPreferences] * @param key 設定値のキー * @return 設定値が存在し読み取りに成功した場合は [TimePeriod], その他の場合は null */ @JvmStatic fun getTimePeriod(sharedPreferences: SharedPreferences, key: String): TimePeriod? { PreferenceLog.v(TAG, "getTimePeriod: start.") val stored = sharedPreferences.getString(key, null) return if (stored != null) { try { TimePeriod.parse(stored) } catch (ex: Exception) { null } } else null } /** * 指定の時刻が、指定の * [SharedPreferences] に保存された設定値の時間範囲に含まれているか否かを返します。 * 時間範囲は設定値の両端の時刻を含みます。 * * @param sharedPreferences [SharedPreferences] * @param key Preference の Key を表す文字列。 * @param hourOfDay 時刻の時(0-23) * @param minute 時刻の分(0-59) * @return 正常な設定値が存在し、且つ指定の時刻が範囲に含まれている場合は true, それ以外の場合は false */ @JvmStatic fun isInPeriod( sharedPreferences: SharedPreferences, key: String, hourOfDay: Int, minute: Int ): Boolean { val value = getTimePeriod(sharedPreferences, key) return value?.isInPeriod(hourOfDay, minute, 0) ?: false } /** * Tag for log */ private const val TAG = "TimePeriodPrefUtil" }
0
Kotlin
0
0
77d4a8374389e7c67d857762c3626526f8418b98
2,265
ImoyaAndroidPreferenceLib
Apache License 2.0
src/main/java/com/denisbelobrotski/eye_tracking_library/algorithm/EyeTracker.kt
DenisBelobrotski
354,017,403
false
null
package by.swiftdrachen.eye_tracking_library.algorithm import by.swiftdrachen.eye_tracking_library.abstraction.IEyeProcessor import by.swiftdrachen.eye_tracking_library.abstraction.IEyeTrackerConfig import by.swiftdrachen.eye_tracking_library.abstraction.IRectDetector import by.swiftdrachen.eye_tracking_library.cv_util.DrawUtils import by.swiftdrachen.eye_tracking_library.cv_util.OpenCvUtils import by.swiftdrachen.eye_tracking_library.exception.EyeTrackerNotPreparedException import by.swiftdrachen.eye_tracking_library.util.SessionFileManager import org.opencv.core.Mat import org.opencv.core.Point import org.opencv.core.Rect import org.opencv.core.Scalar import org.opencv.imgproc.Imgproc class EyeTracker(val config: IEyeTrackerConfig) { private val processingImage = Mat() private val faceDetector: IRectDetector = config.faceDetector private val eyeDetector: IRectDetector = config.eyeDetector private val eyeProcessor: IEyeProcessor = config.eyeProcessor private val sessionFileManager: SessionFileManager? = config.sessionFileManager private var detectedFaceRect: Rect? = null private var detectedLeftEyeRect: Rect? = null private var detectedRightEyeRect: Rect? = null private var leftEyeGazeDirectionIndex: Int = DEFAULT_GAZE_DIRECTION_INDEX private var rightEyeGazeDirectionIndex: Int = DEFAULT_GAZE_DIRECTION_INDEX var sourceImage: Mat? = null val lastDetectedFaceRect: Rect? get() = detectedFaceRect val lastDetectedLeftEyeRect: Rect? get() = detectedLeftEyeRect val lastDetectedRightEyeRect: Rect? get() = detectedRightEyeRect val leftEyeBestGazeDirectionIndex: Int get() = leftEyeGazeDirectionIndex val rightEyeBestGazeDirectionIndex: Int get() = rightEyeGazeDirectionIndex fun detect() { sessionFileManager?.addLog("EyeTracker - detection started") checkAvailability() val sourceImage = this.sourceImage!! sessionFileManager?.saveMat(sourceImage, "source_image", true) sessionFileManager?.addLog("EyeTracker - source image saved", true) if (config.grayscaleEnabled) { Imgproc.cvtColor(sourceImage, processingImage, Imgproc.COLOR_RGB2GRAY, 1) sessionFileManager?.addLog("EyeTracker - RGB to GRAY done") sessionFileManager?.saveMat(processingImage, "gray_image", true) sessionFileManager?.addLog("EyeTracker - gray image saved", true) } if (config.histogramEqualizationEnabled) { Imgproc.equalizeHist(processingImage, processingImage) sessionFileManager?.addLog("EyeTracker - image histogram equalized") sessionFileManager?.saveMat(processingImage, "hist_equalized_image", true) sessionFileManager?.addLog("EyeTracker - histogram equalized image saved", true) } faceDetector.processingImage = processingImage faceDetector.detect() sessionFileManager?.addLog("EyeTracker - face detection done") val faceRects = faceDetector.detectedRects detectedFaceRect = getBestFace(faceRects) detectedFaceRect?.let { faceRect -> val sourceFaceRoi = sourceImage.submat(faceRect) val processingFaceRoi = processingImage.submat(faceRect) sessionFileManager?.addLog("EyeTracker - face submats taken") sessionFileManager?.saveMat(processingFaceRoi, "detected_face", true) sessionFileManager?.addLog("EyeTracker - detected face saved", true) eyeDetector.processingImage = processingFaceRoi eyeDetector.detect() sessionFileManager?.addLog("EyeTracker - eye detection done") tryDrawFaceRect(sourceImage, faceRect) val eyeRects = eyeDetector.detectedRects val eyes = getBestEyes(eyeRects, sourceFaceRoi) detectedLeftEyeRect = eyes.first detectedRightEyeRect = eyes.second leftEyeGazeDirectionIndex = DEFAULT_GAZE_DIRECTION_INDEX rightEyeGazeDirectionIndex = DEFAULT_GAZE_DIRECTION_INDEX detectedLeftEyeRect?.let { leftEyeRect -> processEye(leftEyeRect, eyeProcessor, sourceFaceRoi, processingFaceRoi, true) leftEyeGazeDirectionIndex = getBestDirectionIndex(config.gazeDirections, eyeProcessor, leftEyeRect) } detectedRightEyeRect?.let { rightEyeRect -> processEye(rightEyeRect, eyeProcessor, sourceFaceRoi, processingFaceRoi, false) rightEyeGazeDirectionIndex = getBestDirectionIndex(config.gazeDirections, eyeProcessor, rightEyeRect) } } sessionFileManager?.addLog("EyeTracker - detection done") } private fun checkAvailability() { val exceptionReason = isDetectionAvailable() if (exceptionReason != null) { throw EyeTrackerNotPreparedException(exceptionReason) } } private fun isDetectionAvailable(): String? { if (sourceImage == null) { return "Target image not set" } return null } private fun getBestFace(faceRects: List<Rect>): Rect? { val rectsCount = faceRects.count() if (rectsCount == 0) { return null } var relevantFaceRect = faceRects[0] var maxArea = relevantFaceRect.area() for (index in 1 until rectsCount) { val currentRect = faceRects[index] val currentArea = currentRect.area() if (currentArea > maxArea) { maxArea = currentArea relevantFaceRect = currentRect } } return relevantFaceRect } private fun getBestEyes(eyeRects: List<Rect>, faceMat: Mat): Pair<Rect?, Rect?> { val rectsCount = eyeRects.count() if (rectsCount == 0) { return Pair(null, null) } var leftEye: Rect? = null var rightEye: Rect? = null val faceCenter = OpenCvUtils.getMatCenter(faceMat) for (index in 0 until rectsCount) { val eyeRect = eyeRects[index] val eyeCenter = OpenCvUtils.getRectCenter(eyeRect) if (eyeCenter.y > faceCenter.y) { continue } if (leftEye == null && eyeCenter.x < faceCenter.x) { leftEye = eyeRect continue } if (rightEye == null && eyeCenter.x > faceCenter.x) { rightEye = eyeRect continue } } return if (!config.mirrorEyes) { Pair(leftEye, rightEye) } else { Pair(rightEye, leftEye) } } private fun processEye( eyeRect: Rect, eyeProcessor: IEyeProcessor, sourceFaceRoi: Mat, processingFaceRoi: Mat, left: Boolean) { val sourceEyeRoi = sourceFaceRoi.submat(eyeRect) val processingEyeRoi = processingFaceRoi.submat(eyeRect) sessionFileManager?.addLog("EyeTracker - eye submats taken") val eyeName = if (left) "left" else "right" sessionFileManager?.saveMat(processingEyeRoi, "detected_eye_$eyeName", true) sessionFileManager?.addLog("EyeTracker - detected eye saved ($eyeName)", true) eyeProcessor.sourceImage = sourceEyeRoi eyeProcessor.process() sessionFileManager?.addLog("EyeTracker - eye processed") tryDrawEyeRect(sourceFaceRoi, eyeRect, left) tryDrawEyeMarkers(sourceEyeRoi, eyeProcessor) } private fun getBestDirectionIndex( directions: Array<Point>, eyeProcessor: IEyeProcessor, eyeRect: Rect): Int { val directionsCount = directions.count() if (directionsCount == 0) { return DEFAULT_GAZE_DIRECTION_INDEX } val diff = OpenCvUtils.getDifference( eyeProcessor.detectedPupilCenter, eyeProcessor.detectedEyeCenter) val diffLength = OpenCvUtils.getLength(diff) val halfMaxLength = OpenCvUtils.getLength(Point(eyeRect.width.toDouble(), eyeRect.height.toDouble())) * 0.5 val lengthFactor = (diffLength / halfMaxLength * 100).toInt() val minCenterFactor = config.gazeCenterDirectionOffset if (lengthFactor < minCenterFactor) { return CENTER_GAZE_DIRECTION_INDEX } var maxDotProductIndex = 0 var maxDotProduct = directions[maxDotProductIndex].dot(diff) for (index in 1 until directionsCount) { val direction = directions[index] val dotProduct = direction.dot(diff) if (dotProduct > maxDotProduct) { maxDotProduct = dotProduct maxDotProductIndex = index } } return maxDotProductIndex } private fun tryDrawFaceRect(sourceImage: Mat, faceRect: Rect) { if (config.drawDebugFaceRects) { val thickness = DrawUtils.getLineThicknessForMat(sourceImage, 100, 1) val lineType = Imgproc.LINE_8 Imgproc.rectangle(sourceImage, faceRect, faceRectColor, thickness, lineType) } } private fun tryDrawEyeRect(sourceFaceRoi: Mat, eyeRect: Rect, left: Boolean) { if (config.drawDebugEyeRects) { val color = if (left) leftEyeRectColor else rightEyeRectColor val thickness = DrawUtils.getLineThicknessForMat(sourceFaceRoi, 100, 1) val lineType = Imgproc.LINE_8 Imgproc.rectangle(sourceFaceRoi, eyeRect, color, thickness, lineType) } } private fun tryDrawEyeMarkers(sourceEyeRoi: Mat, eyeProcessor: IEyeProcessor) { if (config.drawDebugEyeMarkers) { val markerSize = DrawUtils.getMarkerSizeForMat(sourceEyeRoi, 20, 2) val thickness = DrawUtils.getLineThicknessForMat(sourceEyeRoi, 30, 1) val lineType = Imgproc.LINE_8 val roiCenter = OpenCvUtils.getMatCenter(sourceEyeRoi) Imgproc.drawMarker( sourceEyeRoi, roiCenter, eyeRoiCenterColor, Imgproc.MARKER_DIAMOND, markerSize, thickness, lineType) Imgproc.drawMarker( sourceEyeRoi, eyeProcessor.detectedEyeCenter, eyeCenterColor, Imgproc.MARKER_DIAMOND, markerSize, thickness, lineType) Imgproc.drawMarker( sourceEyeRoi, eyeProcessor.detectedPupilCenter, pupilCenterColor, Imgproc.MARKER_DIAMOND, markerSize, thickness, lineType) sessionFileManager?.addLog("EyeTracker - debug markers drawn") } } companion object { private val faceRectColor = Scalar(0.0, 255.0, 0.0, 255.0) private val leftEyeRectColor = Scalar(255.0, 0.0, 255.0, 255.0) private val rightEyeRectColor = Scalar(0.0, 255.0, 255.0, 255.0) private val eyeRoiCenterColor = Scalar(255.0, 255.0, 0.0, 255.0) private val eyeCenterColor = Scalar(0.0, 255.0, 0.0, 255.0) private val pupilCenterColor = Scalar(255.0, 0.0, 0.0, 255.0) const val DEFAULT_GAZE_DIRECTION_INDEX = Int.MIN_VALUE const val CENTER_GAZE_DIRECTION_INDEX = -1 } }
0
null
0
1
7f7654914023a0f572abb79274081475edb724c5
11,291
eye-tracking-library
MIT License
core/src/main/kotlin/org/tenkiv/kuantify/fs/hardware/channel/FSDigitalOutput.kt
Tenkiv
183,814,098
false
null
/* * Copyright 2019 Tenkiv, Inc. * * 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 org.tenkiv.kuantify.fs.hardware.channel import kotlinx.coroutines.channels.* import kotlinx.serialization.json.* import org.tenkiv.coral.* import org.tenkiv.kuantify.* import org.tenkiv.kuantify.fs.gate.* import org.tenkiv.kuantify.fs.hardware.device.* import org.tenkiv.kuantify.fs.networking.* import org.tenkiv.kuantify.fs.networking.configuration.* import org.tenkiv.kuantify.gate.* import org.tenkiv.kuantify.gate.control.output.* import org.tenkiv.kuantify.hardware.channel.* import org.tenkiv.kuantify.hardware.device.* import org.tenkiv.kuantify.hardware.outputs.* import org.tenkiv.kuantify.lib.* import org.tenkiv.kuantify.networking.configuration.* import tec.units.indriya.* import javax.measure.quantity.* @Suppress("LeakingThis") public abstract class LocalDigitalOutput<out D> : DigitalOutput<D>, NetworkBoundSide<String>, NetworkBoundCombined where D : LocalDevice, D : DigitalOutputDevice { private val thisAsBinaryStateController = SimpleBinaryStateController(this) private val thisAsPwmController = SimplePwmController(this) private val thisAsFrequencyController = SimpleFrequencyController(this) private val _isTransceiving: InitializedUpdatable<Boolean> = Updatable(false) public override val isTransceiving: InitializedTrackable<Boolean> get() = _isTransceiving private val _updateBroadcaster = ConflatedBroadcastChannel<ValueInstant<DigitalValue>>() public override val updateBroadcaster: ConflatedBroadcastChannel<out ValueInstant<DigitalValue>> get() = _updateBroadcaster init { onAnyTransceivingChange { _isTransceiving.value = it } } public override fun asBinaryStateController(): BinaryStateOutput = thisAsBinaryStateController public override fun asPwmController(avgFrequency: ComparableQuantity<Frequency>): QuantityOutput<Dimensionless> { this.avgFrequency.set(avgFrequency) return thisAsPwmController } public override fun asFrequencyController(avgFrequency: ComparableQuantity<Frequency>): QuantityOutput<Frequency> { this.avgFrequency.set(avgFrequency) return thisAsFrequencyController } public override fun combinedRouting(routing: CombinedNetworkRouting) { routing.addToThisPath { digitalGateRouting(this@LocalDigitalOutput) } } public override fun sideRouting(routing: SideNetworkRouting<String>) { routing.addToThisPath { digitalGateIsTransceivingLocal(isTransceivingBinaryState, RC.IS_TRANSCEIVING_BIN_STATE) digitalGateIsTransceivingLocal(isTransceivingPwm, RC.IS_TRANSCEIVING_PWM) digitalGateIsTransceivingLocal(isTransceivingFrequency, RC.IS_TRANSCEIVING_FREQUENCY) bind<ValueInstant<DigitalValue>>(RC.VALUE) { serializeMessage { Json.stringify(ValueInstantSerializer(DigitalValue.serializer()), it) } receive { val setting = Json.parse(ValueInstantSerializer(DigitalValue.serializer()), it) val (value, _) = setting when (value) { is DigitalValue.BinaryState -> setOutputState(value.state) is DigitalValue.Percentage -> pulseWidthModulate(value.percent) is DigitalValue.Frequency -> sustainTransitionFrequency(value.frequency) } _updateBroadcaster.send(setting) } setLocalUpdateChannel(updateBroadcaster.openSubscription()) withUpdateChannel { send() } } } } } @Suppress("LeakingThis") public abstract class FSRemoteDigitalOutput<out D> : DigitalOutput<D>, NetworkBoundSide<String>, NetworkBoundCombined where D : DigitalOutputDevice, D : FSRemoteDevice { private val thisAsBinaryStateController = SimpleBinaryStateController(this) private val thisAsPwmController = SimplePwmController(this) private val thisAsFrequencyController = SimpleFrequencyController(this) private val _updateBroadcaster = ConflatedBroadcastChannel<ValueInstant<DigitalValue>>() public override val updateBroadcaster: ConflatedBroadcastChannel<out ValueInstant<DigitalValue>> get() = _updateBroadcaster private val _binaryStateBroadcaster = ConflatedBroadcastChannel<BinaryStateMeasurement>() public override val binaryStateBroadcaster: ConflatedBroadcastChannel<out BinaryStateMeasurement> get() = _binaryStateBroadcaster private val _pwmBroadcaster = ConflatedBroadcastChannel<QuantityMeasurement<Dimensionless>>() override val pwmBroadcaster: ConflatedBroadcastChannel<out QuantityMeasurement<Dimensionless>> get() = _pwmBroadcaster private val _transitionFrequencyBroadcaster = ConflatedBroadcastChannel<QuantityMeasurement<Frequency>>() public override val transitionFrequencyBroadcaster: ConflatedBroadcastChannel<out QuantityMeasurement<Frequency>> get() = _transitionFrequencyBroadcaster private val _isTransceiving = Updatable(false) public override val isTransceiving: InitializedTrackable<Boolean> get() = _isTransceiving private val _isTransceivingBinaryState = Updatable(false) public override val isTransceivingBinaryState: InitializedTrackable<Boolean> get() = _isTransceivingBinaryState private val _isTransceivingPwm = Updatable(false) public override val isTransceivingPwm: InitializedTrackable<Boolean> get() = _isTransceivingPwm private val _isTransceivingFrequency = Updatable(false) public override val isTransceivingFrequency: InitializedTrackable<Boolean> get() = _isTransceivingFrequency init { onAnyTransceivingChange { _isTransceiving.value = it } } public override fun asBinaryStateController(): BinaryStateOutput = thisAsBinaryStateController public override fun asPwmController(avgFrequency: ComparableQuantity<Frequency>): QuantityOutput<Dimensionless> { this.avgFrequency.set(avgFrequency) return thisAsPwmController } public override fun asFrequencyController(avgFrequency: ComparableQuantity<Frequency>): QuantityOutput<Frequency> { this.avgFrequency.set(avgFrequency) return thisAsFrequencyController } public override fun combinedRouting(routing: CombinedNetworkRouting) { routing.addToThisPath { digitalGateRouting(this@FSRemoteDigitalOutput) } } public override fun sideRouting(routing: SideNetworkRouting<String>) { routing.addToThisPath { digitalGateIsTransceivingRemote(_isTransceivingBinaryState, RC.IS_TRANSCEIVING_BIN_STATE) digitalGateIsTransceivingRemote(_isTransceivingPwm, RC.IS_TRANSCEIVING_PWM) digitalGateIsTransceivingRemote(_isTransceivingFrequency, RC.IS_TRANSCEIVING_FREQUENCY) bind<ValueInstant<DigitalValue>>(RC.VALUE) { serializeMessage { Json.stringify(ValueInstantSerializer(DigitalValue.serializer()), it) } receive { val setting = Json.parse(ValueInstantSerializer(DigitalValue.serializer()), it) val (value, instant) = setting when (value) { is DigitalValue.BinaryState -> _binaryStateBroadcaster.send(value.state at instant) is DigitalValue.Percentage -> _pwmBroadcaster.send(value.percent at instant) is DigitalValue.Frequency -> _transitionFrequencyBroadcaster.send(value.frequency at instant) } _updateBroadcaster.send(setting) } setLocalUpdateChannel(updateBroadcaster.openSubscription()) withUpdateChannel { send() } } } } }
0
Kotlin
0
4
cc774f93c7d47f84c4e22aeb032e48451478beb8
9,115
kuantify
MIT License
modules/core/arrow-instances-data/src/main/kotlin/arrow/instances/eithert.kt
raosuj
157,551,397
true
{"Kotlin": 1365489, "CSS": 118712, "HTML": 10089, "JavaScript": 8493, "Java": 4465, "Shell": 3043}
package arrow.instances import arrow.Kind import arrow.core.* import arrow.data.EitherT import arrow.data.EitherTOf import arrow.data.EitherTPartialOf import arrow.data.fix import arrow.typeclasses.* interface EitherTFunctorInstance<F, L> : Functor<EitherTPartialOf<F, L>> { fun FF(): Functor<F> override fun <A, B> Kind<EitherTPartialOf<F, L>, A>.map(f: (A) -> B): EitherT<F, L, B> = fix().map(FF(), { f(it) }) } interface EitherTApplicativeInstance<F, L> : EitherTFunctorInstance<F, L>, Applicative<EitherTPartialOf<F, L>> { fun MF(): Monad<F> override fun <A> just(a: A): EitherT<F, L, A> = EitherT.just(MF(), a) override fun <A, B> Kind<EitherTPartialOf<F, L>, A>.map(f: (A) -> B): EitherT<F, L, B> = fix().map(MF(), { f(it) }) override fun <A, B> Kind<EitherTPartialOf<F, L>, A>.ap(ff: Kind<EitherTPartialOf<F, L>, (A) -> B>): EitherT<F, L, B> = fix().ap(MF(), ff) } interface EitherTMonadInstance<F, L> : EitherTApplicativeInstance<F, L>, Monad<EitherTPartialOf<F, L>> { override fun <A, B> Kind<EitherTPartialOf<F, L>, A>.map(f: (A) -> B): EitherT<F, L, B> = fix().map(MF(), { f(it) }) override fun <A, B> Kind<EitherTPartialOf<F, L>, A>.ap(ff: Kind<EitherTPartialOf<F, L>, (A) -> B>): EitherT<F, L, B> = fix().ap(MF(), ff) override fun <A, B> Kind<EitherTPartialOf<F, L>, A>.flatMap(f: (A) -> Kind<EitherTPartialOf<F, L>, B>): EitherT<F, L, B> = fix().flatMap(MF(), { f(it).fix() }) override fun <A, B> tailRecM(a: A, f: (A) -> EitherTOf<F, L, Either<A, B>>): EitherT<F, L, B> = EitherT.tailRecM(MF(), a, f) } interface EitherTApplicativeErrorInstance<F, L> : EitherTApplicativeInstance<F, L>, ApplicativeError<EitherTPartialOf<F, L>, L> { override fun <A> Kind<EitherTPartialOf<F, L>, A>.handleErrorWith(f: (L) -> Kind<EitherTPartialOf<F, L>, A>): EitherT<F, L, A> = MF().run { EitherT(fix().value.flatMap({ when (it) { is Either.Left -> f(it.a).fix().value is Either.Right -> just(it) } })) } override fun <A> raiseError(e: L): EitherT<F, L, A> = EitherT(MF().just(Left(e))) } interface EitherTMonadErrorInstance<F, L> : EitherTApplicativeErrorInstance<F, L>, EitherTMonadInstance<F, L>, MonadError<EitherTPartialOf<F, L>, L> interface EitherTFoldableInstance<F, L> : Foldable<EitherTPartialOf<F, L>> { fun FFF(): Foldable<F> override fun <B, C> Kind<EitherTPartialOf<F, L>, B>.foldLeft(b: C, f: (C, B) -> C): C = fix().foldLeft(FFF(), b, f) override fun <B, C> Kind<EitherTPartialOf<F, L>, B>.foldRight(lb: Eval<C>, f: (B, Eval<C>) -> Eval<C>): Eval<C> = fix().foldRight(FFF(), lb, f) } interface EitherTTraverseInstance<F, L> : EitherTFunctorInstance<F, L>, EitherTFoldableInstance<F, L>, Traverse<EitherTPartialOf<F, L>> { fun TF(): Traverse<F> override fun <A, B> Kind<EitherTPartialOf<F, L>, A>.map(f: (A) -> B): EitherT<F, L, B> = fix().map(TF(), { f(it) }) override fun <G, B, C> Kind<EitherTPartialOf<F, L>, B>.traverse(AP: Applicative<G>, f: (B) -> Kind<G, C>): Kind<G, EitherT<F, L, C>> = fix().traverse(TF(), AP, f) } interface EitherTSemigroupKInstance<F, L> : SemigroupK<EitherTPartialOf<F, L>> { fun MF(): Monad<F> override fun <A> Kind<EitherTPartialOf<F, L>, A>.combineK(y: Kind<EitherTPartialOf<F, L>, A>): EitherT<F, L, A> = fix().combineK(MF(), y) } fun <F, A, B, C> EitherTOf<F, A, B>.foldLeft(FF: Foldable<F>, b: C, f: (C, B) -> C): C = FF.compose(Either.foldable<A>()).foldLC(fix().value, b, f) fun <F, A, B, C> EitherTOf<F, A, B>.foldRight(FF: Foldable<F>, lb: Eval<C>, f: (B, Eval<C>) -> Eval<C>): Eval<C> = FF.compose(Either.foldable<A>()).run { fix().value.foldRC(lb, f) } fun <F, A, B, G, C> EitherTOf<F, A, B>.traverse(FF: Traverse<F>, GA: Applicative<G>, f: (B) -> Kind<G, C>): Kind<G, EitherT<F, A, C>> { val fa: Kind<G, Kind<Nested<F, EitherPartialOf<A>>, C>> = ComposedTraverse(FF, Either.traverse(), Either.monad<A>()).traverseC(fix().value, f, GA) return GA.run { fa.map({ EitherT(FF.run { it.unnest().map({ it.fix() }) }) }) } } fun <F, G, A, B> EitherTOf<F, A, Kind<G, B>>.sequence(FF: Traverse<F>, GA: Applicative<G>): Kind<G, EitherT<F, A, B>> = traverse(FF, GA, ::identity) fun <F, L> EitherT.Companion.functor(FF: Functor<F>): Functor<EitherTPartialOf<F, L>> = object : EitherTFunctorInstance<F, L> { override fun FF(): Functor<F> = FF } fun <F, L> EitherT.Companion.applicative(MF: Monad<F>): Applicative<EitherTPartialOf<F, L>> = object : EitherTApplicativeInstance<F, L> { override fun FF(): Functor<F> = MF override fun MF(): Monad<F> = MF } fun <F, L> EitherT.Companion.monad(MF: Monad<F>): Monad<EitherTPartialOf<F, L>> = object : EitherTMonadInstance<F, L> { override fun FF(): Functor<F> = MF override fun MF(): Monad<F> = MF } fun <F, L> EitherT.Companion.applicativeError(MF: Monad<F>): ApplicativeError<EitherTPartialOf<F, L>, L> = object : EitherTApplicativeErrorInstance<F, L> { override fun FF(): Functor<F> = MF override fun MF(): Monad<F> = MF } fun <F, L> EitherT.Companion.monadError(MF: Monad<F>): MonadError<EitherTPartialOf<F, L>, L> = object : EitherTMonadErrorInstance<F, L> { override fun FF(): Functor<F> = MF override fun MF(): Monad<F> = MF } fun <F, A> EitherT.Companion.traverse(FF: Traverse<F>): Traverse<EitherTPartialOf<F, A>> = object : EitherTTraverseInstance<F, A> { override fun FF(): Functor<F> = FF override fun FFF(): Foldable<F> = FF override fun TF(): Traverse<F> = FF } fun <F, A> EitherT.Companion.foldable(FF: Traverse<F>): Foldable<EitherTPartialOf<F, A>> = object : EitherTFoldableInstance<F, A> { override fun FFF(): Foldable<F> = FF } fun <F, L> EitherT.Companion.semigroupK(MF: Monad<F>): SemigroupK<EitherTPartialOf<F, L>> = object : EitherTSemigroupKInstance<F, L> { override fun MF(): Monad<F> = MF } class EitherTContext<F, E>(val MF: Monad<F>) : EitherTMonadErrorInstance<F, E>, EitherTSemigroupKInstance<F, E> { override fun FF(): Functor<F> = MF override fun MF(): Monad<F> = MF } class EitherTContextPartiallyApplied<F, E>(val MF: Monad<F>) { infix fun <A> extensions(f: EitherTContext<F, E>.() -> A): A = f(EitherTContext(MF)) } fun <F, E> ForEitherT(MF: Monad<F>): EitherTContextPartiallyApplied<F, E> = EitherTContextPartiallyApplied(MF)
0
Kotlin
0
0
b911e960173bf21dcaab04dd702457e718158c36
6,310
arrow
Apache License 2.0
app/src/main/java/com/santimattius/paging/MainActivity.kt
santimattius
295,560,177
false
null
package com.santimattius.paging import android.os.Bundle import androidx.activity.compose.setContent import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.ExperimentalFoundationApi import coil.annotation.ExperimentalCoilApi import com.santimattius.paging.ui.screen.HomeRoute @ExperimentalCoilApi @ExperimentalFoundationApi class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { PagingApplication { HomeRoute() } } } }
0
Kotlin
0
4
75083390066ad4850d94bb7f3e6af5e19511407c
610
android-sample-paging
Apache License 2.0
src/main/kotlin/main.kt
junron
207,942,044
false
null
package main import http.download import http.downloadMediaFiles import http.getVideoData import io.ktor.client.HttpClient import kotlinx.coroutines.runBlocking import main.util.getM3U8FileByFormat import main.util.parseResolutions import main.util.parseStreamUrl import me.tongfei.progressbar.ProgressBarBuilder import me.tongfei.progressbar.ProgressBarStyle import util.secondsToString import java.io.File import java.util.* fun main() { print("Enter toggle URL: ") val reader = Scanner(System.`in`) val url = reader.nextLine()!!.trim() val client = HttpClient() runBlocking { val (mediaName, _, mediaDuration, files) = getVideoData(url, client) println("Processing video: $mediaName") println("Runtime: $mediaDuration seconds (${secondsToString(mediaDuration.toInt())})") val m3Url = files.getM3U8FileByFormat("HLS_Web")?.url ?: return@runBlocking println("M3U8 file with suitable format not found") val resolutionData = download(m3Url, client) val resolutions = parseResolutions(resolutionData) if (resolutions.isEmpty()) { println("No resolutions found.") return@runBlocking } println("Select resolution: ") resolutions.forEachIndexed { i, v -> println("[${i + 1}]: $v") } print("Enter choice [1 to ${resolutions.size}]: ") val resolutionChoice = reader.nextInt() println("You chose: ${resolutions[resolutionChoice - 1].first}") val streamUrl = resolutions[resolutionChoice - 1].second val outputDirectory = File("output-$mediaName") if (!outputDirectory.exists()) { outputDirectory.mkdir() } val tsFiles = parseStreamUrl(download(streamUrl, client)) val pb = ProgressBarBuilder().setInitialMax(tsFiles.size.toLong()).setUpdateIntervalMillis(10).setStyle(ProgressBarStyle.ASCII).build() downloadMediaFiles(tsFiles, client, outputDirectory) { current, max -> pb.step() if (current == max) pb.close() } client.close() } }
0
Kotlin
0
1
2cc40936e8567e9a587f7d6c4f86efd21d47b955
1,980
toggle-download
MIT License
apollo/apollo-appsync/src/main/java/com/amplifyframework/apollo/appsync/AppSyncAuthorizer.kt
aws-amplify
177,009,933
false
{"Java": 5271326, "Kotlin": 3564857, "Shell": 28043, "Groovy": 11755, "Python": 3681, "Ruby": 1874}
/* * Copyright 2024 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amplifyframework.apollo.appsync import com.apollographql.apollo.api.ApolloRequest import com.apollographql.apollo.api.http.HttpRequest /** * Interface for classes that provide different types of authorization for AppSync. AppSync supports various auth * modes, including API Key, Cognito User Pools, OIDC, Lambda-based authorization, and IAM policies. Implementations * of this interface can be used to provide the specific headers and payloads needed for the auth mode being used. */ interface AppSyncAuthorizer { /** * Return the headers to append to HTTP requests (e.g. mutations and queries) * @param request The HttpRequest being sent * @return A map of header names to values */ suspend fun getHttpAuthorizationHeaders(request: HttpRequest): Map<String, String> /** * Return the headers to append to the web socket connection request when establishing a subscription. * @param endpoint The [AppSyncEndpoint] for this subscription * @return A map of header names to values */ suspend fun getWebsocketConnectionHeaders(endpoint: AppSyncEndpoint): Map<String, String> /** * Return the payload value to append to each message sent over the websocket. * @param endpoint The [AppSyncEndpoint] for this subscription * @param request The [ApolloRequest] being sent * @return A map of header names to values */ suspend fun getWebSocketSubscriptionPayload( endpoint: AppSyncEndpoint, request: ApolloRequest<*> ): Map<String, String> }
105
Java
115
245
14c71f38f052a964b96d7abaff6e157bd21a64d8
2,141
amplify-android
Apache License 2.0
MyPayTemplate/app/src/main/java/br/uea/transirie/mypay/mypaytemplate2/ui/home/Venda/SelecaoProdutosActivity.kt
gldnjmat17
438,400,051
false
{"Kotlin": 501915}
package br.uea.transirie.mypay.mypaytemplate2.ui.home.Venda import android.app.AlertDialog import android.app.SearchManager import android.content.Context import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.Gravity import android.view.Menu import android.widget.EditText import android.widget.Toast import androidx.appcompat.widget.SearchView import androidx.core.content.ContextCompat import androidx.recyclerview.widget.LinearLayoutManager import br.uea.transirie.mypay.mypaytemplate2.R import br.uea.transirie.mypay.mypaytemplate2.adapters.SelecaoProdutoAdapter import br.uea.transirie.mypay.mypaytemplate2.model.Estoque import br.uea.transirie.mypay.mypaytemplate2.model.ItemVenda import br.uea.transirie.mypay.mypaytemplate2.repository.room.AppDatabase import br.uea.transirie.mypay.mypaytemplate2.repository.sqlite.PREF_DATA_NAME import br.uea.transirie.mypay.mypaytemplate2.ui.home.Estoque.ManterEstoqueViewModel import br.uea.transirie.mypay.mypaytemplate2.utils.AppPreferences import kotlinx.android.synthetic.main.activity_selecao_produtos.* import org.jetbrains.anko.doAsync import org.jetbrains.anko.uiThread import java.text.DecimalFormat class SelecaoProdutosActivity : AppCompatActivity() { private lateinit var cpfGerente:String private lateinit var adapter:SelecaoProdutoAdapter private lateinit var cadastros:List<ItemVenda> private lateinit var produtos:MutableList<Estoque> private var subTotal:Float = 0f private var df = DecimalFormat("0.00") override fun onCreateOptionsMenu(menu: Menu?): Boolean { val inflater = menuInflater inflater.inflate(R.menu.menu_procurar,menu) val manager = getSystemService(Context.SEARCH_SERVICE) as SearchManager val searchItem = menu?.findItem(R.id.id_search_brinde) val searchView = searchItem?.actionView as SearchView val editText = searchView.findViewById<EditText>(R.id.search_src_text) editText.setTextColor(ContextCompat.getColor(this, R.color.white)) editText.setHintTextColor(ContextCompat.getColor(this, R.color.search_color)) editText.hint = "Pesquisar..." searchView.setSearchableInfo(manager.getSearchableInfo(componentName)) searchView.setOnQueryTextListener(object : SearchView.OnQueryTextListener { override fun onQueryTextChange(query: String?): Boolean { if (query != null) { searchDataBase(query) } return true } override fun onQueryTextSubmit(query: String?): Boolean { if (query != null) { searchDataBase(query) } return true } }) return super.onCreateOptionsMenu(menu) } private fun searchDataBase(query:String){ if (query.isEmpty()){ adapter.swapData(cadastros) }else{ val listaProduto = produtos.filter { it.descricao.toUpperCase().contains(query.toUpperCase()) } var x = 0 val tamanho = listaProduto.size val listaItem:MutableList<ItemVenda> = mutableListOf() while (x<tamanho){ val item = cadastros.filter { it.codigoBarras == listaProduto[x].codigoBarras } listaItem.add(item[0]) adapter.swapData(listaItem) x +=1 } } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_selecao_produtos) //resgata o usuário que está logado val preference = getSharedPreferences(PREF_DATA_NAME, MODE_PRIVATE) cpfGerente = AppPreferences.getCPFGerente(this) val toast = Toast.makeText(this@SelecaoProdutosActivity,"Adicione produtos ao carrinho", Toast.LENGTH_SHORT) toast.setGravity(Gravity.BOTTOM,0,170) btCarrinho.setOnClickListener { toast.cancel() doAsync { val viewModel = ManterItemVendaViewModel(AppDatabase.getDatabase(this@SelecaoProdutosActivity)) val lista = viewModel.getAllItemVenda().filter { it.gerenteCPF == cpfGerente && it.quantidade > 0 } uiThread { if (lista.isEmpty()){ toast.show() }else{ val clienteJson = preference.getString("clienteEscolhido","") if (clienteJson.isNullOrEmpty()){ val builder:AlertDialog.Builder = AlertDialog.Builder(this@SelecaoProdutosActivity) builder.setMessage("Você gostaria de vincular essa compra a um cliente?") builder.setPositiveButton("VINCULAR"){dialog,_-> startActivity(Intent(this@SelecaoProdutosActivity,SelecionarClienteActivity::class.java)) dialog.dismiss() } builder.setNegativeButton("NÃO"){dialog,_-> startActivity(Intent(this@SelecaoProdutosActivity,CarrinhoVendaActivity::class.java)) dialog.dismiss() } builder.show() }else{ startActivity(Intent(this@SelecaoProdutosActivity,CarrinhoVendaActivity::class.java)) } } } } } val toolbar = findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbarS) setSupportActionBar(toolbar) toolbarS.setNavigationOnClickListener { doAsync { val viewModelItem = ManterItemVendaViewModel(AppDatabase.getDatabase(this@SelecaoProdutosActivity)) cadastros = viewModelItem.getAllItemVenda().filter { it.gerenteCPF == cpfGerente } as MutableList cadastros.forEach { itemVenda -> itemVenda.quantidade = 0 itemVenda.subTotalItem = 0f viewModelItem.updateItemVenda(itemVenda) } uiThread { val sharedEditor = preference.edit() sharedEditor.putString("descontoVenda","0") sharedEditor.putString("clienteEscolhido","") sharedEditor.apply() } } finish() } doAsync { val viewModelItem = ManterItemVendaViewModel(AppDatabase.getDatabase(this@SelecaoProdutosActivity)) cadastros = viewModelItem.getAllItemVenda().filter { it.gerenteCPF == cpfGerente } as MutableList val viewModelProduto = ManterEstoqueViewModel(AppDatabase.getDatabase(this@SelecaoProdutosActivity)) produtos = viewModelProduto.getAllEstoque().filter { it.gerenteCPF == cpfGerente } as MutableList gerarTotal() uiThread { adapter = SelecaoProdutoAdapter( this@SelecaoProdutosActivity, mutableListOf(), produtos, ::onMais, ::onMenos ) recyclerViewSelecao.adapter = adapter recyclerViewSelecao.layoutManager = LinearLayoutManager(this@SelecaoProdutosActivity) adapter.swapData(cadastros) } } } private fun onMenos(item:ItemVenda){ item.quantidade = item.quantidade - 1 val produto = produtos.filter { it.codigoBarras == item.codigoBarras }[0] item.subTotalItem = item.quantidade * produto.valorVenda doAsync { val viewModelItemVenda = ManterItemVendaViewModel(AppDatabase.getDatabase(this@SelecaoProdutosActivity)) viewModelItemVenda.updateItemVenda(item) gerarTotal() } } private fun onMais(item: ItemVenda){ item.quantidade = item.quantidade + 1 val produto = produtos.filter { it.codigoBarras == item.codigoBarras }[0] item.subTotalItem = item.quantidade*produto.valorVenda doAsync { val viewModelItemVenda = ManterItemVendaViewModel(AppDatabase.getDatabase(this@SelecaoProdutosActivity)) viewModelItemVenda.updateItemVenda(item) gerarTotal() } } private fun gerarTotal(){ doAsync { val viewModel = ManterItemVendaViewModel(AppDatabase.getDatabase(this@SelecaoProdutosActivity)) val lista = viewModel.getAllItemVenda().filter { it.gerenteCPF == cpfGerente && it.quantidade > 0 } val quantidade = lista.size var x = 0 subTotal = 0f while (x < lista.size){ subTotal += lista[x].subTotalItem x += 1 } uiThread { if (lista.isEmpty()){ val preference = getSharedPreferences(PREF_DATA_NAME, MODE_PRIVATE) val sharedEditor = preference.edit() sharedEditor.putString("descontoVenda","0") sharedEditor.putString("clienteEscolhido","") sharedEditor.apply() } txtSubtotal.text = "R$ ${df.format(subTotal).replace(".",",")}" if (quantidade == 1){ txtIntes.text = "$quantidade item adicionado" }else{ txtIntes.text = "$quantidade itens adicionados" } } } } }
0
Kotlin
0
0
bef2b21101aee9c8f985498532385eee18cb0e05
9,930
MyPets---Aplicativo
MIT License
atomicfu-gradle-plugin/src/test/kotlin/kotlinx/atomicfu/plugin/gradle/test/JsProjectTest.kt
Kotlin
99,576,820
false
null
package kotlinx.atomicfu.plugin.gradle.test import kotlinx.atomicfu.plugin.gradle.internal.* import kotlinx.atomicfu.plugin.gradle.internal.BaseKotlinScope import org.junit.Test class JsProjectTest : BaseKotlinGradleTest("js-simple") { private fun BaseKotlinScope.createProject() { buildGradleKts { resolve("projects/js-simple/js-simple.gradle.kts") } settingsGradleKts { resolve("projects/js-simple/settings.gradle.kts") } dir("src/main/kotlin") {} kotlin("IntArithmetic.kt", "main") { resolve("projects/js-simple/src/main/kotlin/IntArithmetic.kt") } dir("src/test/kotlin") {} kotlin("ArithmeticTest.kt", "test") { resolve("projects/js-simple/src/test/kotlin/ArithmeticTest.kt") } } @Test fun testPlugin() { val runner = test { createProject() runner { arguments.add(":build") } } val tasksToCheck = arrayOf( ":compileKotlinJs", ":transformJsMainAtomicfu", ":compileTestKotlinJs", ":transformJsTestAtomicfu" ) runner.build().apply { tasksToCheck.forEach { assertTaskSuccess(it) } } // check that task outcomes are cached for the second build runner.build().apply { tasksToCheck.forEach { assertTaskUpToDate(it) } } checkJsCompilationClasspath() } }
38
Kotlin
47
573
b40401ea459cf5cbc616e20d5b30281ad072dd72
1,560
kotlinx.atomicfu
Apache License 2.0
luakt-extension/src/main/kotlin/com/github/only52607/luakt/extension/LuaValueExtensions.kt
only52607
269,326,871
false
null
@file:Suppress("UNUSED") package com.github.only52607.luakt.extension import org.luaj.vm2.* val LuaValue.nullable: LuaValue? get() = if (isnil()) null else this val LuaValue.tableValue: LuaTable get() = checktable() val LuaValue.tableValueOrNull: LuaTable? get() = if (istable()) checktable() else null val LuaValue.functionValue: LuaFunction get() = checkfunction() val LuaValue.functionValueOrNull: LuaFunction? get() = if (isfunction()) checkfunction() else null val LuaValue.closureValue: LuaClosure get() = checkclosure() val LuaValue.closureValueOrNull: LuaClosure? get() = if (isclosure()) checkclosure() else null val LuaValue.threadValue: LuaThread get() = checkthread() val LuaValue.threadValueOrNull: LuaThread? get() = if (isthread()) checkthread() else null val LuaValue.globalsValue: Globals get() = checkglobals() val LuaValue.booleanValue: Boolean get() = checkboolean() val LuaValue.booleanValueOrNull: Boolean? get() = if (isboolean()) checkboolean() else null val LuaValue.intValue: Int get() = checkint() val LuaValue.intValueOrNull: Int? get() = if (isint()) checkint() else null val LuaValue.longValue: Long get() = checklong() val LuaValue.longValueOrNull: Long? get() = if (islong()) checklong() else null val LuaValue.doubleValue: Double get() = checkdouble() val LuaValue.doubleValueOrNull: Double? get() = if (isnumber()) checkdouble() else null val LuaValue.stringValue: String get() = checkjstring() val LuaValue.stringValueOrNull: String? get() = if (isstring()) checkjstring() else null val LuaValue.userdataValue: Any get() = checkuserdata() val LuaValue.userdataValueOrNull: Any? get() = if (isuserdata()) checkuserdata() else null val Int.luaValue: LuaValue get() = LuaValue.valueOf(this) val Long.luaValue: LuaValue get() = if (this >= Int.MIN_VALUE && this <= Int.MAX_VALUE) LuaValue.valueOf(this.toInt()) else LuaValue.valueOf( this.toDouble() ) val Boolean.luaValue: LuaValue get() = LuaValue.valueOf(this) val String.luaValue: LuaValue get() = LuaValue.valueOf(this) val Double.luaValue: LuaValue get() = LuaValue.valueOf(this) val ByteArray.luaValue: LuaValue get() = LuaValue.valueOf(this) val Array<LuaValue>.luaListValue: LuaTable get() = LuaValue.listOf(this) inline fun buildLuaTable(builder: LuaValue.() -> Unit): LuaTable = LuaTable().apply(builder).tableValue fun luaTableOf(vararg pairs: Pair<LuaValue, LuaValue>) = buildLuaTable { pairs.forEach { (k, v) -> this@buildLuaTable.set(k, v) } } fun luaTableOfStringKeys(vararg pairs: Pair<String, LuaValue>) = buildLuaTable { pairs.forEach { (k, v) -> this@buildLuaTable.set(k, v) } } // getters // setters // invokers // collection operators fun LuaValue.forEach(process: (key: LuaValue, value: LuaValue) -> Unit) { var k: LuaValue = LuaValue.NIL while (true) { val n = next(k) k = n.arg1() if (k.isnil()) break val v = n.arg(2) process(k, v) } } fun LuaValue.applyFrom(luaTable: LuaTable) { luaTable.forEach { key, value -> set(key, value) } } // metatables var LuaValue.metatable: LuaValue? get() = getmetatable() set(value) { setmetatable(value) }
1
null
5
18
1ebf17bf9fc0b28c5ba292b4abe85451d9ad4848
3,341
luakt
MIT License
core/src/main/kotlin/net/olegg/aoc/utils/Vector4D.kt
0legg
110,665,187
false
null
package net.olegg.aoc.utils import kotlin.math.abs data class Vector4D( var x: Int = 0, var y: Int = 0, var z: Int = 0, var w: Int = 0, ) { operator fun plus(other: Vector4D) = Vector4D(x + other.x, y + other.y, z + other.z, w + other.w) operator fun plusAssign(other: Vector4D) = run { x += other.x y += other.y z += other.z w += other.w } operator fun minus(other: Vector4D) = Vector4D(x - other.x, y - other.y, z - other.z, w - other.w) operator fun minusAssign(other: Vector4D) = run { x -= other.x y -= other.y z -= other.z w -= other.w } operator fun unaryMinus() = Vector4D(-x, -y, -z, -w) operator fun times(other: Int) = Vector4D(x * other, y * other, z * other, w * other) operator fun timesAssign(other: Int) = run { x *= other y *= other z *= other w *= other } operator fun times(other: Vector4D) = x * other.x + y * other.y + z * other.z + w * other.w operator fun div(other: Int) = Vector4D(x / other, y / other, z / other, w / other) operator fun divAssign(other: Int) = run { x /= other y /= other z /= other w /= other } fun length2() = x * x + y * y + z * z + w * w fun manhattan() = abs(x) + abs(y) + abs(z) + abs(w) fun toList() = listOf(x, y, w, z) fun volume() = abs(x * y * w * z) }
0
null
1
8
3006775fc2d1da3b12303029b9f35d2793c912df
1,317
adventofcode
MIT License
app/src/main/java/com/pri/architecture_boilerplate/util/Extensions.kt
priyanka-rani
218,155,486
false
null
package com.pri.architecture_boilerplate.util import android.annotation.SuppressLint import android.text.Editable import android.text.TextUtils import android.text.TextWatcher import android.view.View import android.widget.* import com.google.android.material.textfield.TextInputLayout import com.pri.architecture_boilerplate.R /** * Created by Priyanka on 2019-06-09. */ fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) { this.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { } override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) { afterTextChanged.invoke(p0.toString()) } override fun afterTextChanged(editable: Editable?) { } }) } fun List<View>.isValid(): Boolean { var isValid = true this.reversed().forEach { if (!it.isValid()) isValid = false } return isValid } fun View.isValid(): Boolean { val valid = if (this.visibility == View.VISIBLE) { when (this) { is TextInputLayout -> { when { this.editText?.text?.isBlank() == true -> { this.error = this.context.getString(R.string.empty_field) false } else -> this.error.isNullOrBlank() } } is RadioGroup -> if (this.checkedRadioButtonId != -1) true else { val lastChildPos = this.childCount - 1 (this.getChildAt(lastChildPos) as RadioButton).error = "Please select option" false } is Spinner -> if (this.selectedItem != null && !TextUtils.isEmpty(this.selectedItem.toString())) true else { (this.selectedView as TextView).error = "Please ${this.adapter.getItem(0)}" false } is ImageView -> { this.drawable != null } else -> false } } else { true } if (!valid) this.requestFocus() return valid } fun String?.userNameError() = when { MobileValidator.validate(this) || EmailValidator.validate(this) -> null android.util.Patterns.PHONE.matcher(this).matches() -> R.string.error_invalid_mobile else -> R.string.error_invalid_email }
1
null
1
1
18a74203aebf027e66254925663023aefb6b685b
2,444
architecture_dagger_binding_pri
Apache License 2.0
plugins/maven/testFramework/src/com/intellij/maven/testFramework/MavenTestCase.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.maven.testFramework import com.intellij.diagnostic.ThreadDumper import com.intellij.execution.wsl.WSLDistribution import com.intellij.execution.wsl.WslDistributionManager import com.intellij.ide.DataManager import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.application.* import com.intellij.openapi.command.WriteCommandAction import com.intellij.openapi.module.Module import com.intellij.openapi.module.ModuleManager.Companion.getInstance import com.intellij.openapi.module.ModuleType import com.intellij.openapi.module.StdModuleTypes import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.progress.runBlockingMaybeCancellable import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.openapi.projectRoots.JavaSdk import com.intellij.openapi.projectRoots.ProjectJdkTable import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.roots.ex.ProjectRootManagerEx import com.intellij.openapi.util.Disposer import com.intellij.openapi.util.SystemInfo import com.intellij.openapi.util.ThrowableComputable import com.intellij.openapi.util.io.FileUtil import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.platform.testFramework.core.FileComparisonFailedError import com.intellij.testFramework.* import com.intellij.testFramework.TemporaryDirectory.Companion.generateTemporaryPath import com.intellij.testFramework.fixtures.IdeaProjectTestFixture import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory import com.intellij.util.ExceptionUtil import com.intellij.util.ThrowableRunnable import com.intellij.util.containers.CollectionFactory import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.intellij.lang.annotations.Language import org.jetbrains.annotations.NonNls import org.jetbrains.idea.maven.indices.MavenIndicesManager import org.jetbrains.idea.maven.project.* import org.jetbrains.idea.maven.server.MavenServerConnector import org.jetbrains.idea.maven.server.MavenServerConnectorImpl import org.jetbrains.idea.maven.server.MavenServerManager import org.jetbrains.idea.maven.server.RemotePathTransformerFactory import org.jetbrains.idea.maven.utils.MavenLog import org.jetbrains.idea.maven.utils.MavenProgressIndicator import org.jetbrains.idea.maven.utils.MavenProgressIndicator.MavenProgressTracker import org.jetbrains.idea.maven.utils.MavenUtil import org.junit.AssumptionViolatedException import java.awt.HeadlessException import java.io.File import java.io.IOException import java.nio.charset.StandardCharsets import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.util.* import java.util.concurrent.TimeUnit abstract class MavenTestCase : UsefulTestCase() { protected var mavenProgressIndicator: MavenProgressIndicator? = null private set private var myWSLDistribution: WSLDistribution? = null private var myPathTransformer: RemotePathTransformerFactory.Transformer? = null private var ourTempDir: File? = null private var myTestFixture: IdeaProjectTestFixture? = null private var myProject: Project? = null private var myDir: File? = null private var myProjectRoot: VirtualFile? = null private var myProjectPom: VirtualFile? = null private val myAllPoms: MutableList<VirtualFile> = ArrayList() val pathTransformer: RemotePathTransformerFactory.Transformer get() = myPathTransformer!! var testFixture: IdeaProjectTestFixture get() = myTestFixture!! set(testFixture) { myTestFixture = testFixture } fun setTestFixtureNull() { myTestFixture = null } val project: Project get() = myProject!! val dir: File get() = myDir!! val projectRoot: VirtualFile get() = myProjectRoot!! var projectPom: VirtualFile get() = myProjectPom!! set(projectPom) { myProjectPom = projectPom } val allPoms: List<VirtualFile> get() = myAllPoms fun addPom(pom: VirtualFile) { myAllPoms.add(pom) } @Throws(Exception::class) override fun setUp() { assumeThisTestCanBeReusedForPreimport() super.setUp() setUpFixtures() myProject = myTestFixture!!.project myPathTransformer = RemotePathTransformerFactory.createForProject(project) setupWsl() ensureTempDirCreated() myDir = File(ourTempDir, getTestName(false)) FileUtil.ensureExists(myDir!!) mavenProgressIndicator = MavenProgressIndicator(project, EmptyProgressIndicator(ModalityState.nonModal()), null) MavenWorkspaceSettingsComponent.getInstance(project).loadState(MavenWorkspacePersistedSettings()) val home = testMavenHome if (home != null) { mavenGeneralSettings.mavenHomeType = MavenInSpecificPath(home) } mavenGeneralSettings.isAlwaysUpdateSnapshots = true MavenUtil.cleanAllRunnables() EdtTestUtil.runInEdtAndWait<IOException> { restoreSettingsFile() try { WriteAction.run<Exception> { this.setUpInWriteAction() } } catch (e: Throwable) { try { tearDown() } catch (e1: Exception) { e1.printStackTrace() } throw RuntimeException(e) } } } protected fun assumeThisTestCanBeReusedForPreimport() { assumeTestCanBeReusedForPreimport(this.javaClass, name) } private fun setupWsl() { val wslMsId = System.getProperty("wsl.distribution.name") if (wslMsId == null) return val distributions = WslDistributionManager.getInstance().installedDistributions if (distributions.isEmpty()) throw IllegalStateException("no WSL distributions configured!") myWSLDistribution = distributions.firstOrNull { it.msId == wslMsId } ?: throw IllegalStateException("Distribution $wslMsId was not found") var jdkPath = System.getProperty("wsl.jdk.path") if (jdkPath == null) { jdkPath = "/usr/lib/jvm/java-11-openjdk-amd64" } val wslSdk = getWslSdk(myWSLDistribution!!.getWindowsPath(jdkPath)) WriteAction.runAndWait<RuntimeException> { ProjectRootManagerEx.getInstanceEx(myProject).projectSdk = wslSdk } assertTrue(File(myWSLDistribution!!.getWindowsPath(myWSLDistribution!!.userHome!!)).isDirectory) } protected fun waitForMavenUtilRunnablesComplete() { PlatformTestUtil.waitWithEventsDispatching( { "Waiting for MavenUtils runnables completed" + MavenUtil.getUncompletedRunnables() }, { MavenUtil.noUncompletedRunnables() }, 15) } @Throws(Throwable::class) override fun runBare(testRunnable: ThrowableRunnable<Throwable>) { LoggedErrorProcessor.executeWith<Throwable>(object : LoggedErrorProcessor() { override fun processError(category: String, message: String, details: Array<String>, t: Throwable?): Set<Action> { val intercept = t != null && ((t.message ?: "").contains("The network name cannot be found") && message.contains("Couldn't read shelf information") || "JDK annotations not found" == t.message && "#com.intellij.openapi.projectRoots.impl.JavaSdkImpl" == category) return if (intercept) Action.NONE else Action.ALL } }) { super.runBare(testRunnable) } } private fun getWslSdk(jdkPath: String): Sdk { val sdk = ProjectJdkTable.getInstance().allJdks.find { jdkPath == it.homePath }!! val jdkTable = ProjectJdkTable.getInstance() for (existingSdk in jdkTable.allJdks) { if (existingSdk === sdk) return sdk } val newSdk = JavaSdk.getInstance().createJdk("Wsl JDK For Tests", jdkPath) WriteAction.runAndWait<RuntimeException> { jdkTable.addJdk(newSdk, testRootDisposable) } return newSdk } @Throws(Exception::class) override fun tearDown() { val basePath = myProject!!.basePath RunAll( ThrowableRunnable { val mavenProgressTracker = myProject!!.getServiceIfCreated(MavenProgressTracker::class.java) mavenProgressTracker?.assertProgressTasksCompleted() }, ThrowableRunnable { MavenServerManager.getInstance().closeAllConnectorsAndWait() }, ThrowableRunnable { tearDownEmbedders() }, ThrowableRunnable { checkAllMavenConnectorsDisposed() }, ThrowableRunnable { myProject = null }, ThrowableRunnable { val defaultProject = ProjectManager.getInstance().defaultProject val mavenIndicesManager = defaultProject.getServiceIfCreated(MavenIndicesManager::class.java) if (mavenIndicesManager != null) { Disposer.dispose(mavenIndicesManager) } }, ThrowableRunnable { doTearDownFixtures() }, ThrowableRunnable { deleteDirOnTearDown(myDir) }, ThrowableRunnable { if (myWSLDistribution != null && basePath != null) { deleteDirOnTearDown(File(basePath)) } }, ThrowableRunnable { super.tearDown() } ).run() } private fun doTearDownFixtures() { if (ApplicationManager.getApplication().isDispatchThread) { EdtTestUtil.runInEdtAndWait<Exception> { tearDownFixtures() } } else { runBlockingMaybeCancellable { withContext(Dispatchers.EDT) { tearDownFixtures() } } } } private fun tearDownEmbedders() { val manager = MavenProjectsManager.getInstanceIfCreated(myProject!!) if (manager == null) return manager.embeddersManager.releaseInTests() } @Throws(IOException::class) private fun ensureTempDirCreated() { if (ourTempDir != null) return ourTempDir = if (myWSLDistribution == null) { File(FileUtil.getTempDirectory(), "mavenTests") } else { File(myWSLDistribution!!.getWindowsPath("/tmp"), "mavenTests") } FileUtil.delete(ourTempDir!!) FileUtil.ensureExists(ourTempDir!!) } @Throws(Exception::class) protected open fun setUpFixtures() { val wslMsId = System.getProperty("wsl.distribution.name") val isDirectoryBasedProject = useDirectoryBasedProjectFormat() if (wslMsId != null) { val path = generateTemporaryPath(FileUtil.sanitizeFileName(name, false), Paths.get( "\\\\wsl$\\$wslMsId\\tmp")) myTestFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(name, path, isDirectoryBasedProject).fixture } else { myTestFixture = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(name, isDirectoryBasedProject).fixture } myTestFixture!!.setUp() } protected open fun useDirectoryBasedProjectFormat(): Boolean { return false } @Throws(Exception::class) protected open fun setUpInWriteAction() { val projectDir = File(myDir, "project") projectDir.mkdirs() myProjectRoot = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(projectDir) } @Throws(Exception::class) protected open fun tearDownFixtures() { try { myTestFixture!!.tearDown() } finally { myTestFixture = null } } @Throws(Throwable::class) override fun runTestRunnable(testRunnable: ThrowableRunnable<Throwable>) { try { super.runTestRunnable(testRunnable) } catch (throwable: Throwable) { if (ExceptionUtil.causedBy(throwable, HeadlessException::class.java)) { printIgnoredMessage("Doesn't work in Headless environment") } throw throwable } } protected val mavenGeneralSettings: MavenGeneralSettings get() = MavenProjectsManager.getInstance(myProject!!).generalSettings protected val mavenImporterSettings: MavenImportingSettings get() = MavenProjectsManager.getInstance(myProject!!).importingSettings protected var repositoryPath: String? get() { val path = repositoryFile.path return FileUtil.toSystemIndependentName(path) } protected set(path) { mavenGeneralSettings.setLocalRepository(path) } protected val repositoryFile: File get() = mavenGeneralSettings.effectiveLocalRepository protected val projectPath: String get() = myProjectRoot!!.path protected val parentPath: String get() = myProjectRoot!!.parent.path protected fun pathFromBasedir(relPath: String): String { return pathFromBasedir(myProjectRoot, relPath) } @Throws(IOException::class) protected fun createSettingsXml(innerContent: String): VirtualFile { val content = createSettingsXmlContent(innerContent) val path = Path.of(myDir!!.path, "settings.xml") Files.writeString(path, content) mavenGeneralSettings.setUserSettingsFile(path.toString()) return LocalFileSystem.getInstance().refreshAndFindFileByNioFile(path)!! } @Throws(IOException::class) protected fun updateSettingsXml(content: String): VirtualFile { return updateSettingsXmlFully(createSettingsXmlContent(content)) } @Throws(IOException::class) protected fun updateSettingsXmlFully(@Language("XML") content: @NonNls String?): VirtualFile { val ioFile = File(myDir, "settings.xml") ioFile.createNewFile() val f = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(ioFile) setFileContent(f, content, true) mavenGeneralSettings.setUserSettingsFile(f!!.path) return f } @Throws(IOException::class) protected fun restoreSettingsFile() { updateSettingsXml("") } protected fun createModule(name: String, type: ModuleType<*>): Module { try { return WriteCommandAction.writeCommandAction(myProject).compute<Module, IOException> { val f = createProjectSubFile("$name/$name.iml") val module = getInstance(myProject!!).newModule(f.path, type.id) PsiTestUtil.addContentRoot(module, f.parent) module } } catch (e: IOException) { throw RuntimeException(e) } } protected fun createModule(name: String): Module = createModule(name, StdModuleTypes.JAVA) protected fun createProjectPom(@Language(value = "XML", prefix = "<project>", suffix = "</project>") xml: String): VirtualFile { return createPomFile(myProjectRoot, xml).also { myProjectPom = it } } protected fun createModulePom(relativePath: String, @Language(value = "XML", prefix = "<project>", suffix = "</project>") xml: String?): VirtualFile { return createPomFile(createProjectSubDir(relativePath), xml) } protected fun createPomFile(dir: VirtualFile?, @Language(value = "XML", prefix = "<project>", suffix = "</project>") xml: String?): VirtualFile { return createPomFile(dir, "pom.xml", xml) } protected fun createPomFile(dir: VirtualFile?, fileName: String? = "pom.xml", @Language(value = "XML", prefix = "<project>", suffix = "</project>") xml: String?): VirtualFile { val pomName = fileName ?: "pom.xml" var f = dir!!.findChild(pomName) if (f == null) { try { f = WriteAction.computeAndWait<VirtualFile, IOException> { dir.createChildData(null, pomName) } } catch (e: IOException) { throw RuntimeException(e) } myAllPoms.add(f) } setPomContent(f, xml) return f!! } protected fun createProfilesXmlOldStyle(xml: String): VirtualFile { return createProfilesFile(myProjectRoot, xml, true) } protected fun createProfilesXmlOldStyle(relativePath: String, xml: String): VirtualFile { return createProfilesFile(createProjectSubDir(relativePath), xml, true) } protected fun createProfilesXml(xml: String): VirtualFile { return createProfilesFile(myProjectRoot, xml, false) } protected fun createProfilesXml(relativePath: String, xml: String): VirtualFile { return createProfilesFile(createProjectSubDir(relativePath), xml, false) } protected fun createFullProfilesXml(content: String): VirtualFile { return createProfilesFile(myProjectRoot, content) } protected fun createFullProfilesXml(relativePath: String, content: String): VirtualFile { return createProfilesFile(createProjectSubDir(relativePath), content) } @Throws(IOException::class) protected fun deleteProfilesXml() { WriteCommandAction.writeCommandAction(myProject).run<IOException> { val f = myProjectRoot!!.findChild("profiles.xml") f?.delete(this) } } protected fun createProjectSubDirs(vararg relativePaths: String) { for (path in relativePaths) { createProjectSubDir(path) } } protected fun createProjectSubDir(relativePath: String): VirtualFile { val f = File(projectPath, relativePath) f.mkdirs() return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f)!! } @Throws(IOException::class) protected fun createProjectSubFile(relativePath: String): VirtualFile { val f = File(projectPath, relativePath) f.parentFile.mkdirs() f.createNewFile() return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(f)!! } @Throws(IOException::class) protected fun createProjectSubFile(relativePath: String, content: String): VirtualFile { val file = createProjectSubFile(relativePath) setFileContent(file, content, false) return file } protected fun ignore(): Boolean { //printIgnoredMessage(null); return false } protected fun hasMavenInstallation(): Boolean { val result = testMavenHome != null if (!result) printIgnoredMessage("Maven installation not found") return result } private fun printIgnoredMessage(message: String?) { var toPrint = "Ignored" if (message != null) { toPrint += ", because $message" } toPrint += ": " + javaClass.simpleName + "." + name println(toPrint) } protected fun <R, E : Throwable?> runWriteAction(computable: ThrowableComputable<R, E>): R { return WriteCommandAction.writeCommandAction(myProject).compute(computable) } protected fun <E : Throwable?> runWriteAction(runnable: ThrowableRunnable<E>) { WriteCommandAction.writeCommandAction(myProject).run(runnable) } protected fun createTestDataContext(pomFile: VirtualFile): DataContext { val defaultContext = DataManager.getInstance().dataContext return DataContext { dataId: String? -> if (CommonDataKeys.PROJECT.`is`(dataId)) { return@DataContext myProject } if (CommonDataKeys.VIRTUAL_FILE_ARRAY.`is`(dataId)) { return@DataContext arrayOf<VirtualFile>(pomFile) } defaultContext.getData(dataId!!) } } protected val MAVEN_COMPILER_PROPERTIES: String = """ <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>11</maven.compiler.source> <maven.compiler.target>11</maven.compiler.target> </properties> """.trimIndent() private fun checkAllMavenConnectorsDisposed() { val connectors = MavenServerManager.getInstance().getAllConnectors() if (!connectors.isEmpty()) { MavenLog.LOG.warn("Connectors not empty, printing thread dump") MavenLog.LOG.warn("===============================================") MavenLog.LOG.warn(ThreadDumper.getThreadDumpInfo(ThreadDumper.getThreadInfos(), false).rawDump) MavenLog.LOG.warn("===============================================") fail("all maven connectors should be disposed but got $connectors") } } protected fun deleteDirOnTearDown(dir: File?) { FileUtil.delete(dir!!) // cannot use reliably the result of the com.intellij.openapi.util.io.FileUtil.delete() method // because com.intellij.openapi.util.io.FileUtilRt.deleteRecursivelyNIO() does not honor this contract if (dir.exists()) { System.err.println("Cannot delete $dir") //printDirectoryContent(myDir); dir.deleteOnExit() } } private fun printDirectoryContent(dir: File) { val files = dir.listFiles() if (files == null) return for (file in files) { println(file.absolutePath) if (file.isDirectory) { printDirectoryContent(file) } } } protected val root: String get() { if (SystemInfo.isWindows) return "c:" return "" } protected val envVar: String get() { if (SystemInfo.isWindows) { return "TEMP" } else if (SystemInfo.isLinux) return "HOME" return "TMPDIR" } protected fun pathFromBasedir(root: VirtualFile?, relPath: String): String { return FileUtil.toSystemIndependentName(root!!.path + "/" + relPath) } private fun createSettingsXmlContent(content: String): String { return "<settings>" + content + "</settings>\r\n" } private fun createProfilesFile(dir: VirtualFile?, xml: String, oldStyle: Boolean): VirtualFile { return createProfilesFile(dir, createValidProfiles(xml, oldStyle)) } private fun createProfilesFile(dir: VirtualFile?, content: String): VirtualFile { var f = dir!!.findChild("profiles.xml") if (f == null) { try { f = WriteAction.computeAndWait<VirtualFile, IOException> { dir.createChildData(null, "profiles.xml") } } catch (e: IOException) { throw RuntimeException(e) } } setFileContent(f, content, true) return f!! } @Language("XML") private fun createValidProfiles(@Language("XML") xml: String, oldStyle: Boolean): String { if (oldStyle) { return "<?xml version=\"1.0\"?>" + "<profiles>" + xml + "</profiles>" } return "<?xml version=\"1.0\"?>" + "<profilesXml>" + "<profiles>" + xml + "</profiles>" + "</profilesXml>" } protected fun setPomContent(file: VirtualFile?, @Language(value = "XML", prefix = "<project>", suffix = "</project>") xml: String?) { setFileContent(file, createPomXml(xml), true) } protected fun setFileContent(file: VirtualFile?, content: String?, advanceStamps: Boolean) { try { WriteAction.runAndWait<IOException> { doSetFileContent(file!!, content!!, advanceStamps) } } catch (e: IOException) { throw RuntimeException(e) } } protected suspend fun setPomContentAsync(file: VirtualFile, @Language(value = "XML", prefix = "<project>", suffix = "</project>") xml: String) { setFileContentAsync(file, createPomXml(xml), true) } protected suspend fun setFileContentAsync(file: VirtualFile, content: String, advanceStamps: Boolean) { writeAction { doSetFileContent(file, content, advanceStamps) } } private fun doSetFileContent(file: VirtualFile, content: String, advanceStamps: Boolean) { val bytes = content.toByteArray(StandardCharsets.UTF_8) val newModificationStamp = if (advanceStamps) -1 else file.modificationStamp val newTimeStamp = if (advanceStamps) file.timeStamp + 4000 else file.timeStamp MavenLog.LOG.debug("Set file content, modification stamp $newModificationStamp, time stamp $newTimeStamp, file $file") file.setBinaryContent(bytes, newModificationStamp, newTimeStamp) } protected fun <T> assertOrderedElementsAreEqual(actual: Collection<T>, expected: List<T>) { val s = "\nexpected: $expected\nactual: $actual" assertEquals(s, expected.size, actual.size) val actualList: List<T> = ArrayList(actual) for (i in expected.indices) { val expectedElement = expected[i] val actualElement = actualList[i] assertEquals(s, expectedElement, actualElement) } } protected fun <T> assertOrderedElementsAreEqual(actual: Collection<T>, vararg expected: T) { assertOrderedElementsAreEqual(actual, expected.toList()) } protected fun <T> assertUnorderedElementsAreEqual(actual: Collection<T>, expected: Collection<T>) { assertSameElements(actual, expected) } protected fun assertUnorderedPathsAreEqual(actual: Collection<String>, expected: Collection<String>) { assertEquals((CollectionFactory.createFilePathSet(expected)), (CollectionFactory.createFilePathSet(actual))) } protected fun <T> assertUnorderedElementsAreEqual(actual: Array<T>, vararg expected: T) { assertUnorderedElementsAreEqual(actual.toList(), *expected) } protected fun <T> assertUnorderedElementsAreEqual(actual: Collection<T>, vararg expected: T) { assertUnorderedElementsAreEqual(actual, expected.toList()) } protected fun <T> assertContain(actual: Collection<T>, vararg expected: T) { val expectedList = expected.toList() if (actual.containsAll(expectedList)) return val absent: MutableSet<T> = HashSet(expectedList) absent.removeAll(actual.toSet()) fail(""" expected: $expectedList actual: $actual this elements not present: $absent """.trimIndent()) } protected fun <T> assertDoNotContain(actual: List<T>, vararg expected: T) { val actualCopy: MutableList<T> = ArrayList(actual) actualCopy.removeAll(expected.toSet()) assertEquals(actual.toString(), actualCopy.size, actual.size) } protected fun assertUnorderedLinesWithFile(filePath: String?, expectedText: String?) { try { assertSameLinesWithFile(filePath!!, expectedText!!) } catch (e: FileComparisonFailedError) { val expected: String = e.expectedStringPresentation val actual: String = e.actualStringPresentation assertUnorderedElementsAreEqual(expected.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray(), *actual.split("\n".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray()) } } protected fun ensureConnected(connector: MavenServerConnector): MavenServerConnector { assertTrue("Connector is Dummy!", connector is MavenServerConnectorImpl) val timeout = TimeUnit.SECONDS.toMillis(10) val start = System.currentTimeMillis() while (connector.state == MavenServerConnector.State.STARTING) { if (System.currentTimeMillis() > start + timeout) { throw RuntimeException("Server connector not connected in 10 seconds") } EdtTestUtil.runInEdtAndWait<RuntimeException> { PlatformTestUtil.dispatchAllEventsInIdeEventQueue() } } assertTrue(connector.checkConnected()) return connector } private val testMavenHome: String? get() = System.getProperty("idea.maven.test.home") companion object { val preimportTestMode: Boolean = java.lang.Boolean.getBoolean("MAVEN_TEST_PREIMPORT") @Language("XML") fun createPomXml(@Language(value = "XML", prefix = "<project>", suffix = "</project>") xml: @NonNls String?): @NonNls String { return """ <?xml version="1.0"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> """.trimIndent() + xml + "</project>" } fun assumeTestCanBeReusedForPreimport(aClass: Class<*>, testName: String) { if (!preimportTestMode) return try { var annotation = aClass.getDeclaredAnnotation(InstantImportCompatible::class.java) if (annotation == null) { val testMethod = aClass.getMethod(testName) annotation = testMethod.getDeclaredAnnotation(InstantImportCompatible::class.java) if (annotation == null) { throw AssumptionViolatedException( "No InstantImportCompatible annotation present on class and method in pre-import testing mode, skipping test") } } } catch (ignore: NoSuchMethodException) { } } } }
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
27,922
intellij-community
Apache License 2.0
composeApp/src/androidMain/kotlin/com/unwur/mabiaho/MainActivity.kt
anwar-pasaribu
772,492,453
false
{"Kotlin": 215360, "Ruby": 4931, "Swift": 568, "HTML": 304}
package com.unwur.mabiaho import App import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.SystemBarStyle import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.compose.animation.core.Animatable import androidx.compose.animation.core.ExperimentalTransitionApi import androidx.compose.animation.core.PathEasing import androidx.compose.animation.core.Spring import androidx.compose.animation.core.VectorConverter import androidx.compose.animation.core.animateIntOffsetAsState import androidx.compose.animation.core.spring import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.awaitFirstDown import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.geometry.Offset import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Path import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.tooling.preview.PreviewLightDark import androidx.compose.ui.unit.IntOffset import androidx.compose.ui.unit.dp import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.launch import ui.theme.MyAppTheme import kotlin.math.roundToInt class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { val splashScreen = installSplashScreen() super.onCreate(savedInstanceState) enableEdgeToEdge() setContent { val darkTheme = isSystemInDarkTheme() // Update the edge to edge configuration to match the theme DisposableEffect(darkTheme) { enableEdgeToEdge( statusBarStyle = SystemBarStyle.auto( android.graphics.Color.TRANSPARENT, android.graphics.Color.TRANSPARENT, ) { darkTheme }, navigationBarStyle = SystemBarStyle.auto( lightScrim, darkScrim, ) { darkTheme }, ) onDispose {} } App(shouldDarkTheme = darkTheme) } } } /** * The default light scrim, as defined by androidx and the platform: * https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:activity/activity/src/main/java/androidx/activity/EdgeToEdge.kt;l=35-38;drc=27e7d52e8604a080133e8b842db10c89b4482598 */ private val lightScrim = android.graphics.Color.argb(0xe6, 0xFF, 0xFF, 0xFF) /** * The default dark scrim, as defined by androidx and the platform: * https://cs.android.com/androidx/platform/frameworks/support/+/androidx-main:activity/activity/src/main/java/androidx/activity/EdgeToEdge.kt;l=40-44;drc=27e7d52e8604a080133e8b842db10c89b4482598 */ private val darkScrim = android.graphics.Color.argb(0x80, 0x1b, 0x1b, 0x1b) @PreviewLightDark @Composable fun PreviewPlaceholder() { MyAppTheme { // MoodStateScreen( // modifier = Modifier, // formattedSelectedDate = "Senin, 21 April 2024", // moodRate = 2 // ) // Column(modifier = Modifier.fillMaxWidth(), ) { // GlassyButton(buttonText = { // Text(text = "Preview here ya") // }, onClick = {}) // // PathEasing() // } } } @OptIn(ExperimentalTransitionApi::class) @Composable fun TouchPointer() { // Creates an `Animatable` to animate Offset and `remember` it. val animatedOffset = remember { Animatable(Offset(0f, 0f), Offset.VectorConverter) } Box( Modifier .fillMaxSize() .background(Color(0xffb99aff)) .pointerInput(Unit) { coroutineScope { while (true) { val offset = this@pointerInput.awaitPointerEventScope { awaitFirstDown().position } // Launch a new coroutine for animation so the touch detection thread is not // blocked. launch { // Animates to the pressed position, with the given animation spec. animatedOffset.animateTo( offset, animationSpec = spring(stiffness = Spring.StiffnessLow) ) } } } } ) { Text("Tap anywhere", Modifier.align(Alignment.Center)) Box( Modifier .offset { // Use the animated offset as the offset of the Box. IntOffset( animatedOffset.value.x.roundToInt(), animatedOffset.value.y.roundToInt() ) } .size(40.dp) .background(Color(0xff3c1361), CircleShape) ) } } @Composable fun PathEasing() { // Creates a custom PathEasing curve and applies it to an animation var toggled by remember { mutableStateOf(true) } val pathForAnimation = remember { Path().apply { moveTo(0f, 0f) cubicTo(0.05f, 0f, 0.133333f, 0.06f, 0.166666f, 0.4f) cubicTo(0.208333f, 0.82f, 0.25f, 1f, 1f, 1f) } } val offset by animateIntOffsetAsState( targetValue = if (toggled) IntOffset.Zero else IntOffset(300, 300), label = "offset", animationSpec = tween(durationMillis = 1000, easing = PathEasing(pathForAnimation)) ) Box(modifier = Modifier .fillMaxSize() .clickable { toggled = !toggled }) { Box(modifier = Modifier .offset { offset } .size(100.dp) .background(Color.Blue)) } }
0
Kotlin
0
0
f817777fd67976f3ad11bca051606f908cbc9aff
6,702
Mabia
MIT License
idea/idea-core/src/org/jetbrains/kotlin/idea/core/script/ScriptConfigurationManagerImpl.kt
walltz556
219,828,597
false
null
/* * Copyright 2010-2019 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.core.script import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.components.ServiceManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.vfs.VirtualFile import com.intellij.psi.PsiFile import com.intellij.psi.PsiManager import com.intellij.psi.search.GlobalSearchScope import com.intellij.ui.EditorNotifications import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import org.jetbrains.annotations.TestOnly import org.jetbrains.kotlin.idea.core.script.ScriptConfigurationManager.Companion.toVfsRoots import org.jetbrains.kotlin.idea.core.script.dependencies.* import org.jetbrains.kotlin.idea.core.script.settings.KotlinScriptingSettings import org.jetbrains.kotlin.idea.core.util.EDT import org.jetbrains.kotlin.psi.KtFile import org.jetbrains.kotlin.scripting.definitions.ScriptDefinition import org.jetbrains.kotlin.scripting.definitions.findScriptDefinition import org.jetbrains.kotlin.scripting.definitions.isNonScript import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationResult import org.jetbrains.kotlin.scripting.resolve.ScriptCompilationConfigurationWrapper import org.jetbrains.kotlin.scripting.resolve.ScriptReportSink import kotlin.script.experimental.api.ScriptDiagnostic import kotlin.script.experimental.api.valueOrNull class ScriptConfigurationManagerImpl internal constructor(private val project: Project) : ScriptConfigurationManager { private val rootsManager = ScriptClassRootsManager(project) private val memoryCache = ScriptConfigurationMemoryCache(project) private val fileAttributesCache = ScriptConfigurationFileAttributeCache() private val fromRefinedLoader = FromRefinedConfigurationLoader() private val loaders = arrayListOf( OutsiderFileDependenciesLoader(this), fromRefinedLoader, fileAttributesCache ) private val backgroundLoader = BackgroundLoader(project, rootsManager, ::reloadConfigurationAsync) private val listener = ScriptsListener(project, this) /** * Save configurations into cache. * Start indexing for new class/source roots. * Re-highlight opened scripts with changed configuration. */ override fun saveCompilationConfigurationAfterImport(files: List<Pair<VirtualFile, ScriptCompilationConfigurationResult>>) { rootsManager.transaction { for ((file, result) in files) { saveConfiguration(file, result, skipNotification = true) } } } /** * Start configuration update for files if configuration isn't up to date. * Start indexing for new class/source roots. * * @return true if update was started for any file, false if all configurations are cached */ override fun updateConfigurationsIfNotCached(files: List<KtFile>): Boolean { if (!ScriptDefinitionsManager.getInstance(project).isReady()) return false val notCached = files.filterNot { isConfigurationUpToDate(it.originalFile.virtualFile) } if (notCached.isNotEmpty()) { rootsManager.transaction { for (file in notCached) { reloadConfiguration(file) } } return true } return false } /** * Check if configuration is already cached for [file] (in cache or FileAttributes). * Don't check if file was changed after the last update. * Supposed to be used to switch highlighting off for scripts without configuration. * to avoid all file being highlighted in red. */ override fun isConfigurationCached(file: KtFile): Boolean { return isConfigurationCached(file.originalFile.virtualFile) } /** * Clear configuration caches * Start re-highlighting for opened scripts */ override fun clearConfigurationCachesAndRehighlight() { ScriptDependenciesModificationTracker.getInstance(project).incModificationCount() if (project.isOpen) { rehighlightOpenedScripts() } } @Deprecated("Use getScriptClasspath(KtFile) instead") override fun getScriptClasspath(file: VirtualFile): List<VirtualFile> { val ktFile = PsiManager.getInstance(project).findFile(file) as? KtFile ?: return emptyList() return getScriptClasspath(ktFile) } override fun getScriptClasspath(file: KtFile): List<VirtualFile> = toVfsRoots(getConfiguration(file)?.dependenciesClassPath.orEmpty()) override fun getConfiguration(file: KtFile): ScriptCompilationConfigurationWrapper? { val virtualFile = file.originalFile.virtualFile val cached = getCachedConfiguration(virtualFile) if (cached != null) { return cached } if (ScriptDefinitionsManager.getInstance(project).isReady() && !isConfigurationUpToDate(virtualFile)) { rootsManager.transaction { reloadConfiguration(file) } } return getCachedConfiguration(virtualFile) } override fun getScriptDependenciesClassFilesScope(file: VirtualFile) = scriptDependenciesClassFilesScope(file) override fun getScriptSdk(file: VirtualFile) = scriptSdk(file) override fun getFirstScriptsSdk() = memoryCache.firstScriptSdk override fun getAllScriptsDependenciesClassFilesScope() = memoryCache.allDependenciesClassFilesScope override fun getAllScriptDependenciesSourcesScope() = memoryCache.allDependenciesSourcesScope override fun getAllScriptsDependenciesClassFiles() = memoryCache.allDependenciesClassFiles override fun getAllScriptDependenciesSources() = memoryCache.allDependenciesSources @TestOnly fun updateScriptDependenciesSynchronously(file: PsiFile) { val scriptDefinition = file.findScriptDefinition() ?: return assert(file is KtFile) { "PsiFile should be a KtFile, otherwise script dependencies cannot be loaded" } if (isConfigurationUpToDate(file.virtualFile)) return rootsManager.transaction { val result = fromRefinedLoader.loadDependencies(true, file as KtFile, scriptDefinition) if (result != null) { saveConfiguration(file.originalFile.virtualFile, result, skipNotification = true, skipSaveToAttributes = false) } } } private fun reloadConfiguration(file: KtFile) { val virtualFile = file.originalFile.virtualFile memoryCache.setUpToDate(virtualFile) val scriptDefinition = file.findScriptDefinition() ?: return val syncLoaders = loaders.filterNot { it.isAsync(file, scriptDefinition) } reloadConfigurationBy(file, scriptDefinition, syncLoaders) val asyncLoaders = loaders - syncLoaders if (asyncLoaders.isNotEmpty()) { backgroundLoader.scheduleAsync(file) } } private fun reloadConfigurationAsync(file: KtFile) { val scriptDefinition = file.findScriptDefinition() ?: return val asyncLoaders = loaders.filter { it.isAsync(file, scriptDefinition) } if (asyncLoaders.size > 1) { LOG.warn("There are more than one async compilation configuration loader. " + "This mean that the last one will overwrite the results of the previous ones: " + asyncLoaders.joinToString { it.javaClass.name }) } reloadConfigurationBy(file, scriptDefinition, asyncLoaders) } private fun reloadConfigurationBy(file: KtFile, scriptDefinition: ScriptDefinition, loaders: List<ScriptDependenciesLoader>) { val firstLoad = memoryCache.getCachedConfiguration(file.originalFile.virtualFile) == null loaders.forEach { loader -> val result = loader.loadDependencies(firstLoad, file, scriptDefinition) if (result != null) { return saveConfiguration(file.originalFile.virtualFile, result, loader.skipNotification, loader.skipSaveToAttributes) } } } /** * Save [newResult] for [file] into caches and update highlih. * Should be called inside `rootsManager.transaction { ... }`. * * @param skipNotification forces loading new configuration even if auto reload is disabled. * @param skipSaveToAttributes skips saving to FileAttributes (used in [ScriptConfigurationFileAttributeCache] only). * * @sample ScriptConfigurationManager.getConfiguration */ private fun saveConfiguration( file: VirtualFile, newResult: ScriptCompilationConfigurationResult, skipNotification: Boolean = false, skipSaveToAttributes: Boolean = false ) { debug(file) { "configuration received = $newResult" } saveReports(file, newResult.reports) val newConfiguration = newResult.valueOrNull() if (newConfiguration != null) { val oldConfiguration = getCachedConfiguration(file) if (oldConfiguration == newConfiguration) { file.removeScriptDependenciesNotificationPanel(project) } else { val autoReload = skipNotification || oldConfiguration == null || KotlinScriptingSettings.getInstance(project).isAutoReloadEnabled || ApplicationManager.getApplication().isUnitTestMode if (autoReload) { if (oldConfiguration != null) { file.removeScriptDependenciesNotificationPanel(project) } saveChangedConfiguration(file, newConfiguration, skipSaveToAttributes) } else { debug(file) { "configuration changed, notification is shown: old = $oldConfiguration, new = $newConfiguration" } file.addScriptDependenciesNotificationPanel( newConfiguration, project, onClick = { file.removeScriptDependenciesNotificationPanel(project) rootsManager.transaction { saveChangedConfiguration(file, it, skipSaveToAttributes) } } ) } } } } private fun saveChangedConfiguration( file: VirtualFile, newConfiguration: ScriptCompilationConfigurationWrapper?, skipSaveToAttributes: Boolean ) { debug(file) { "configuration changed = $newConfiguration" } if (newConfiguration != null) { rootsManager.checkNonCachedRoots(memoryCache, file, newConfiguration) if (!skipSaveToAttributes) { debug(file) { "configuration saved to file attributes: $newConfiguration" } fileAttributesCache.save(file, newConfiguration) } memoryCache.replaceConfiguration(file, newConfiguration) memoryCache.clearClassRootsCaches() } updateHighlighting(listOf(file)) } private fun saveReports( file: VirtualFile, newReports: List<ScriptDiagnostic> ) { val oldReports = IdeScriptReportSink.getReports(file) if (oldReports != newReports) { debug(file) { "new script reports = $newReports" } ServiceManager.getService(project, ScriptReportSink::class.java).attachReports(file, newReports) GlobalScope.launch(EDT(project)) { if (project.isDisposed) return@launch EditorNotifications.getInstance(project).updateAllNotifications() } } } private fun updateHighlighting(files: List<VirtualFile>) { if (files.isEmpty()) return GlobalScope.launch(EDT(project)) { if (project.isDisposed) return@launch val openFiles = FileEditorManager.getInstance(project).openFiles val openScripts = files.filter { it.isValid && openFiles.contains(it) } openScripts.forEach { PsiManager.getInstance(project).findFile(it)?.let { psiFile -> DaemonCodeAnalyzer.getInstance(project).restart(psiFile) } } } } private fun getCachedConfiguration(file: VirtualFile): ScriptCompilationConfigurationWrapper? = memoryCache.getCachedConfiguration(file) private fun isConfigurationCached(file: VirtualFile): Boolean { return getCachedConfiguration(file) != null || file in fileAttributesCache } private fun isConfigurationUpToDate(file: VirtualFile): Boolean { return isConfigurationCached(file) && memoryCache.isConfigurationUpToDate(file) } private fun rehighlightOpenedScripts() { val openedScripts = FileEditorManager.getInstance(project).openFiles.filterNot { it.isNonScript() } updateHighlighting(openedScripts) } private fun scriptDependenciesClassFilesScope(file: VirtualFile): GlobalSearchScope { return memoryCache.scriptsDependenciesClasspathScopeCache[file] ?: GlobalSearchScope.EMPTY_SCOPE } private fun scriptSdk(file: VirtualFile): Sdk? { return memoryCache.scriptsSdksCache[file] } }
7
null
0
1
f17e9ba9febdabcf7a5e0f17e4be02e0f9e87f13
13,744
kotlin
Apache License 2.0
infra/src/main/kotlin/uk/co/developmentanddinosaurs/apps/poker/infra/application/PokerVpc.kt
development-and-dinosaurs
717,724,846
false
{"Kotlin": 87536}
package uk.co.developmentanddinosaurs.apps.poker.infra.application import software.amazon.awscdk.services.ec2.IVpc import software.amazon.awscdk.services.ec2.VpcLookupOptions import software.constructs.Construct import software.amazon.awscdk.services.ec2.Vpc as AwsVpc class PokerVpc { companion object { private var vpc: IVpc? = null fun default(construct: Construct): IVpc { if (vpc != null) return vpc!! vpc = AwsVpc.fromLookup(construct, "DefaultVpc", VpcLookupOptions.builder().isDefault(true).build()) return vpc!! } } }
9
Kotlin
0
2
73ed46c666bbdfb1cac462a37e968c7fdd2416a2
598
planning-poker
MIT License
app/src/main/java/com/etasdemir/ethinspector/ui/shared/AddressViewModel.kt
etasdemir
584,191,764
false
null
package com.etasdemir.ethinspector.ui.shared import androidx.compose.material3.* import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.etasdemir.ethinspector.data.Repository import com.etasdemir.ethinspector.data.domain_model.* import com.etasdemir.ethinspector.ui.components.AddressSaveModalState import com.etasdemir.ethinspector.ui.components.DetailTopBarState import com.etasdemir.ethinspector.utils.clip import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch @OptIn(ExperimentalMaterial3Api::class) abstract class AddressViewModel<T> constructor( private val repository: Repository ) : ViewModel() { private lateinit var type: AddressType private lateinit var topBarTitle: String private var data: T? = null lateinit var modalState: AddressSaveModalState private set private val _isSheetShown = MutableStateFlow(false) val isSheetShown = _isSheetShown.asStateFlow() private val _topBarState = MutableStateFlow<DetailTopBarState?>(null) val topBarState = _topBarState.asStateFlow() fun initialize(address: String, title: String, type: AddressType) { this.type = type this.topBarTitle = title val sheetState = SheetState( skipPartiallyExpanded = true, initialValue = SheetValue.Hidden, skipHiddenState = false ) this.modalState = AddressSaveModalState( address, this::onModalCancel, this::onModalSave, sheetState ) } fun initData(data: T) { this.data = data _topBarState.value = DetailTopBarState( topBarTitle, isFavourite(), this::onFavouriteClick, getAddress()!! ) changeTopBarFavouriteState(isFavourite()) } private fun onModalCancel() { _isSheetShown.value = false viewModelScope.launch { val address = getAddress() address?.let { val name = address.clip(6) updateDbData(name = name, isFavourite = true) } } } private fun onModalSave(name: String) { _isSheetShown.value = false viewModelScope.launch { updateDbData(name = name, isFavourite = true) } } private fun onFavouriteClick(previous: Boolean, now: Boolean) { if (now) { _isSheetShown.value = true } else { viewModelScope.launch { updateDbData(isFavourite = false) changeTopBarFavouriteState(false) } } } private suspend fun updateDbData(name: String? = null, isFavourite: Boolean? = null) { data?.let { if (type == AddressType.ACCOUNT && it is Account) { val newName = name ?: it.userGivenName val newIsFav = isFavourite ?: it.isFavourite val copy = it.copy(userGivenName = newName, isFavourite = newIsFav) repository.saveAccount(copy) } else if (type == AddressType.CONTRACT && it is Contract) { val newName = name ?: it.userGivenName val newIsFav = isFavourite ?: it.isFavourite val copy = it.copy(userGivenName = newName, isFavourite = newIsFav) repository.saveContract(copy) } } } private fun changeTopBarFavouriteState(isFavourite: Boolean) { val prevState = topBarState.value if (prevState?.isFavouriteEnabled == isFavourite) { return } prevState?.let { _topBarState.value = DetailTopBarState( prevState.barTitle, isFavourite, prevState.onFavouriteClick, prevState.textToCopy ) } } private fun isFavourite(): Boolean { if (data is Account) { return (data as Account).isFavourite } else if (data is Contract) { return (data as Contract).isFavourite } return false } private fun getAddress(): String? { if (data is Account) { return (data as Account).accountInfo.accountAddress } else if (data is Contract) { return (data as Contract).contractInfo.contractAddress } return null } }
0
null
0
4
753c16ebcb2973bdef76078bb391792892187826
4,451
eth-inspector
MIT License
app/src/main/java/com/apdallahyousry/customgalleryapplication/ui/views/AlbumDetailsFragment.kt
apdallah
751,674,668
false
{"Kotlin": 35155}
package com.apdallahyousry.customgalleryapplication.ui.views import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.recyclerview.widget.GridLayoutManager import com.apdallahyousry.customgalleryapplication.data.models.AlbumModel import com.apdallahyousry.customgalleryapplication.databinding.LayoutFragmentAlbumDetailsBinding import com.apdallahyousry.customgalleryapplication.ui.adapters.MediaItemsAdapter import com.apdallahyousry.customgalleryapplication.ui.viewmodels.AlbumsViewModel import com.apdallahyousry.customgalleryapplication.utils.getDisplaySpanCount import dagger.hilt.android.AndroidEntryPoint @AndroidEntryPoint class AlbumDetailsFragment : Fragment() { private var _binding: LayoutFragmentAlbumDetailsBinding? = null private val binding get() = _binding!! private val viewModel: AlbumsViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = LayoutFragmentAlbumDetailsBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.selectedAlbum.observe(viewLifecycleOwner) { bindData(it) } } private fun bindData(data: AlbumModel) { binding.topToolBar.title=data.title val adapter = MediaItemsAdapter(data.mediaItems) binding.mediaRv.adapter = adapter binding.mediaRv.layoutManager = GridLayoutManager(requireContext(), getDisplaySpanCount()) } override fun onDestroy() { super.onDestroy() _binding = null } }
0
Kotlin
0
0
4cfdf99aec4d0f439db430436d8014f5b10bfb4b
1,907
CustomGalleryApplicationTask
MIT License
kdenticon/src/main/kotlin/com/github/thibseisel/kdenticon/draw/raster/Edge.kt
thibseisel
109,754,408
false
null
/* * Copyright 2017 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.thibseisel.kdenticon.draw.raster import com.github.thibseisel.kdenticon.rendering.PointF /** * Specifies an edge of a polygon that is being rendered. */ internal class Edge( val polygonId: Int, val from: PointF, val to: PointF, val color: Int) { override fun toString() = "$polygonId: $from; $to" fun intersection(y: Float): Float { val dx = (to.x - from.x) * (from.y - y) / (from.y - to.y) return from.x + dx } }
1
Kotlin
0
2
52696593537f83ba3c853894d5d83af0e27a7fdb
1,117
Kdenticon
Apache License 2.0
feature/home/src/main/kotlin/com/finwise/feature/home/HomeNavigation.kt
nimaiwalsh
757,345,803
false
{"Kotlin": 69208, "Shell": 2385}
package com.finwise.feature.home import androidx.compose.runtime.getValue import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavGraphBuilder import androidx.navigation.compose.composable import kotlinx.serialization.Serializable @Serializable object HomeDestination fun NavGraphBuilder.homeScreen( onNavigateBack: () -> Unit, onNavigateToLogin: () -> Unit, ) { composable<HomeDestination> { // view models live as long as destinations in the NavHost, // which we create using composable(route) function. val viewModel: HomeViewModel = hiltViewModel() val state by viewModel.state.collectAsStateWithLifecycle() HomeScreen( onLogoutClicked = onNavigateToLogin, welcomeText = state.welcomeText, ) } }
0
Kotlin
0
0
883c3d7fba139be2e208a2f84688f5dd60e5a4dd
881
finwise
Apache License 2.0
compiler/testData/codegen/box/reflection/callBy/simpleMemberFunciton.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
class A(val result: String = "OK") { fun foo(x: Int = 42): String { assert(x == 42) { x } return result } } fun box(): String = A::foo.callBy(mapOf(A::foo.parameters.first() to A()))
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
208
kotlin
Apache License 2.0
app/src/main/java/me/codeenzyme/welearn/di/modules/NetworkModule.kt
Victor-El
305,075,837
false
null
package me.codeenzyme.welearn.di.modules import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.android.components.ApplicationComponent import me.codeenzyme.welearn.data.remote.* import javax.inject.Singleton @InstallIn(ApplicationComponent::class) @Module abstract class NetworkModule { @Singleton @Binds abstract fun bindAuthService(firebaseAuthService: FirebaseAuthService): AuthService @Singleton @Binds abstract fun bindUserProfileService(firebaseUserProfileService: FirebaseUserProfileService): UserProfileService @Singleton @Binds abstract fun bindCoursesService(firebaseCoursesService: FirebaseCoursesService): CoursesService }
0
Kotlin
1
1
47e6e41b881c2654281ae128043293a435f8c2ae
711
WeLearn
MIT License
src/main/kotlin/table/x1f6.kt
oklookat
808,293,457
false
{"Kotlin": 806745, "Python": 4615}
package table internal val x0fc = listOf( "", // 0x00 "", // 0x01 "", // 0x02 "", // 0x03 "", // 0x04 "", // 0x05 "", // 0x06 "", // 0x07 "", // 0x08 "", // 0x09 "", // 0x0a "", // 0x0b "", // 0x0c "", // 0x0d "", // 0x0e "", // 0x0f "", // 0x10 "", // 0x11 "", // 0x12 "", // 0x13 "", // 0x14 "", // 0x15 "", // 0x16 "", // 0x17 "", // 0x18 "", // 0x19 "", // 0x1a "", // 0x1b "", // 0x1c "", // 0x1d "", // 0x1e "", // 0x1f "", // 0x20 "", // 0x21 "", // 0x22 "", // 0x23 "", // 0x24 "", // 0x25 "", // 0x26 "", // 0x27 "", // 0x28 "", // 0x29 "", // 0x2a "", // 0x2b "", // 0x2c "", // 0x2d "", // 0x2e "", // 0x2f "", // 0x30 "", // 0x31 "", // 0x32 "", // 0x33 "", // 0x34 "", // 0x35 "", // 0x36 "", // 0x37 "", // 0x38 "", // 0x39 "", // 0x3a "", // 0x3b "", // 0x3c "", // 0x3d "", // 0x3e "", // 0x3f "", // 0x40 "", // 0x41 "", // 0x42 "", // 0x43 "", // 0x44 "", // 0x45 "", // 0x46 "", // 0x47 "", // 0x48 "", // 0x49 "", // 0x4a "", // 0x4b "", // 0x4c "", // 0x4d "", // 0x4e "", // 0x4f "", // 0x50 "", // 0x51 "", // 0x52 "", // 0x53 "", // 0x54 "", // 0x55 "", // 0x56 "", // 0x57 "", // 0x58 "", // 0x59 "", // 0x5a "", // 0x5b "", // 0x5c "", // 0x5d "", // 0x5e "", // 0x5f "", // 0x60 "", // 0x61 "", // 0x62 "", // 0x63 "", // 0x64 "", // 0x65 "", // 0x66 "", // 0x67 "", // 0x68 "", // 0x69 "", // 0x6a "", // 0x6b "", // 0x6c "", // 0x6d "", // 0x6e "", // 0x6f "", // 0x70 "", // 0x71 "", // 0x72 "", // 0x73 "", // 0x74 "", // 0x75 "", // 0x76 "", // 0x77 "", // 0x78 "", // 0x79 "", // 0x7a "", // 0x7b "", // 0x7c "", // 0x7d "", // 0x7e "", // 0x7f "", // 0x80 "", // 0x81 "", // 0x82 "", // 0x83 "", // 0x84 "", // 0x85 "", // 0x86 "", // 0x87 "", // 0x88 "", // 0x89 "", // 0x8a "", // 0x8b "", // 0x8c "", // 0x8d "", // 0x8e "", // 0x8f "", // 0x90 "", // 0x91 "", // 0x92 "", // 0x93 "", // 0x94 "", // 0x95 "", // 0x96 "", // 0x97 "", // 0x98 "", // 0x99 "", // 0x9a "", // 0x9b "", // 0x9c "", // 0x9d "", // 0x9e "", // 0x9f "", // 0xa0 "", // 0xa1 "", // 0xa2 "", // 0xa3 "", // 0xa4 "", // 0xa5 "", // 0xa6 "", // 0xa7 "", // 0xa8 "", // 0xa9 "", // 0xaa "", // 0xab "", // 0xac "", // 0xad "", // 0xae "", // 0xaf "", // 0xb0 "", // 0xb1 "", // 0xb2 "", // 0xb3 "", // 0xb4 "", // 0xb5 "", // 0xb6 "", // 0xb7 "", // 0xb8 "", // 0xb9 "", // 0xba "", // 0xbb "", // 0xbc "", // 0xbd "", // 0xbe "", // 0xbf "", // 0xc0 "", // 0xc1 "", // 0xc2 "", // 0xc3 "", // 0xc4 "", // 0xc5 "", // 0xc6 "", // 0xc7 "", // 0xc8 "", // 0xc9 "", // 0xca "", // 0xcb "", // 0xcc "", // 0xcd "", // 0xce "", // 0xcf "", // 0xd0 "", // 0xd1 "", // 0xd2 "", // 0xd3 "", // 0xd4 "", // 0xd5 "", // 0xd6 "", // 0xd7 "", // 0xd8 "", // 0xd9 "", // 0xda "", // 0xdb "", // 0xdc "", // 0xdd "", // 0xde "", // 0xdf "", // 0xe0 "", // 0xe1 "", // 0xe2 "", // 0xe3 "", // 0xe4 "", // 0xe5 "", // 0xe6 "", // 0xe7 "", // 0xe8 "", // 0xe9 "", // 0xea "", // 0xeb "", // 0xec "", // 0xed "", // 0xee "", // 0xef "", // 0xf0 "", // 0xf1 "", // 0xf2 "", // 0xf3 "", // 0xf4 "", // 0xf5 "", // 0xf6 "", // 0xf7 "", // 0xf8 "", // 0xf9 "", // 0xfa "", // 0xfb "", // 0xfc "", // 0xfd "", // 0xfe "", // 0xff )
0
Kotlin
0
0
b85c17dfaeef152a7d8313f612570149d0b6acba
3,116
unidecode4k
MIT License
Chapter16/Chapter16/KotlinRuntimePermission/app/src/main/java/com/packtpub/kotlinruntimepermission/MainActivity.kt
PacktPublishing
153,045,590
false
{"Java": 307910, "Kotlin": 6839}
package com.packtpub.kotlinruntimepermission import android.Manifest import android.content.pm.PackageManager import android.support.v4.app.ActivityCompat import android.support.v4.content.ContextCompat import android.support.v7.app.AlertDialog import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.view.View import android.widget.Toast private const val REQUEST_PERMISSION = 1 class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) } private fun checkPermission(permission: String): Boolean { val permissionCheck = ContextCompat.checkSelfPermission(this, permission) return permissionCheck == PackageManager.PERMISSION_GRANTED } private fun requestPermission(permissionName: String, permissionRequestCode: Int) { ActivityCompat.requestPermissions(this, arrayOf(permissionName), permissionRequestCode) } private fun showExplanation(title: String, message: String, permission: String, permissionRequestCode: Int) { val builder = AlertDialog.Builder(this) builder.setTitle(title) .setMessage(message) .setPositiveButton(android.R.string.ok ) { dialog, id -> requestPermission(permission, permissionRequestCode) } builder.create().show() } fun doSomething(view: View) { if (!checkPermission(Manifest.permission.SEND_SMS)) { if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.SEND_SMS)) { showExplanation("Permission Needed", "Rationale", Manifest.permission.SEND_SMS, REQUEST_PERMISSION) } else { requestPermission(Manifest.permission.SEND_SMS, REQUEST_PERMISSION) } } else { Toast.makeText(this@MainActivity, "Permission (already) Granted!", Toast.LENGTH_SHORT) .show() } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { when (requestCode) { REQUEST_PERMISSION -> { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Toast.makeText(this@MainActivity, "Granted!", Toast.LENGTH_SHORT) .show() } else { Toast.makeText(this@MainActivity, "Denied!", Toast.LENGTH_SHORT) .show() } return } } } }
0
Java
22
31
e7959b7586b83542ae4251dd4e3d0002f5a54d0a
2,933
Android-9-Development-Cookbook
MIT License
protocol/osrs-223/src/main/kotlin/net/rsprox/protocol/game/incoming/decoder/codec/objs/OpObj4Decoder.kt
blurite
822,339,098
false
null
package net.rsprox.protocol.game.incoming.decoder.codec.objs import net.rsprot.buffer.JagByteBuf import net.rsprot.protocol.ClientProt import net.rsprox.protocol.ProxyMessageDecoder import net.rsprox.protocol.game.incoming.decoder.prot.GameClientProt import net.rsprox.protocol.game.incoming.model.objs.OpObj import net.rsprox.protocol.session.Session public class OpObj4Decoder : ProxyMessageDecoder<OpObj> { override val prot: ClientProt = GameClientProt.OPOBJ4 override fun decode( buffer: JagByteBuf, session: Session, ): OpObj { val controlKey = buffer.g1Alt2() == 1 val id = buffer.g2Alt1() val z = buffer.g2Alt2() val x = buffer.g2() return OpObj( id, x, z, controlKey, 4, ) } }
9
null
4
9
41535908e6ccb633c8f2564e8961efa771abd6de
829
rsprox
MIT License
protocol/osrs-223/src/main/kotlin/net/rsprox/protocol/game/incoming/decoder/codec/objs/OpObj4Decoder.kt
blurite
822,339,098
false
null
package net.rsprox.protocol.game.incoming.decoder.codec.objs import net.rsprot.buffer.JagByteBuf import net.rsprot.protocol.ClientProt import net.rsprox.protocol.ProxyMessageDecoder import net.rsprox.protocol.game.incoming.decoder.prot.GameClientProt import net.rsprox.protocol.game.incoming.model.objs.OpObj import net.rsprox.protocol.session.Session public class OpObj4Decoder : ProxyMessageDecoder<OpObj> { override val prot: ClientProt = GameClientProt.OPOBJ4 override fun decode( buffer: JagByteBuf, session: Session, ): OpObj { val controlKey = buffer.g1Alt2() == 1 val id = buffer.g2Alt1() val z = buffer.g2Alt2() val x = buffer.g2() return OpObj( id, x, z, controlKey, 4, ) } }
9
null
4
9
41535908e6ccb633c8f2564e8961efa771abd6de
829
rsprox
MIT License
src/main/kotlin/external/composition_api/provide_inject.kt
SorenV
208,917,750
false
null
@file:JsModule("@vue/composition-api") package external.composition_api external interface InjectionKey : Symbol external fun <T> provide(key: Symbol, value: T) external fun <T> provide(key: String, value: T) external fun <T> inject(key: Symbol): Any? /* T | Unit */ external fun <T> inject(key: String): Any? /* T | Unit */ external fun <T> inject(key: Symbol, defaultValue: T): T external fun <T> inject(key: String, defaultValue: T): T
2
Kotlin
2
34
1e83d2d27390890747cbd79315a825caf7ec98d6
442
kotlin-vue
Apache License 2.0
Chapter04/src/main/kotlin/com/rivuchk/packtpub/reactivekotlin/chapter04/chapter4_19.kt
PacktPublishing
111,785,750
false
null
package com.rivuchk.packtpub.reactivekotlin.chapter04 import io.reactivex.Flowable fun main(args: Array<String>) { val flowable = Flowable.range(1,111)//(1) flowable.buffer(10) .subscribe { println(it) } }
0
Kotlin
36
71
a2333e22fc1190dbacefba46cdf8c0339d509d75
227
Reactive-Programming-in-Kotlin
MIT License
src/main/kotlin/ltd/lths/wireless/ikuai/router/network/interfaces/wan/AdslWan.kt
LTHS20
487,755,461
false
null
package ltd.lths.wireless.ikuai.router.network.interfaces.wan import com.google.gson.JsonObject /** * ikuai-entourage * ltd.lths.wireless.ikuai.router.network.interfaces.wan.AdslWan * * @author Score2 * @since 2022/06/10 23:58 */ interface AdslWan : WanInterface { val json: JsonObject var username: String get() = json.get("username").asString set(value) = json.addProperty("username", value) var password: String get() = json.get("passwd").asString set(value) = json.addProperty("passwd", value) val ip: String get() = json.get("pppoe_ip_addr").asString }
0
null
0
3
22f7a15a63e9808de132e743a5186412e2012d2c
625
ikuai-entourage
MIT License
library/src/main/java/io/nyris/sdk/network/model/io/nyris/sdk/OfferResponse.kt
nyris
128,911,315
false
null
/* * Copyright (C) 2018 nyris GmbH * * 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 io.nyris.sdk import androidx.annotation.Keep import okhttp3.Headers /** * OfferResponse.kt - class model implement IResponse * @see IResponse * * @author <NAME> * Created by nyris GmbH * Copyright © 2018 nyris GmbH. All rights reserved. */ @Keep class OfferResponse : IResponse { /** * Get Headers * * @return the headers */ var headers: Headers? = null internal set /** * Get Offer Response Body * * @see OfferResponseBody * @return the offer response body */ var body: OfferResponseBody? = null internal set /** * Get Request Id * * @return the request id */ fun getRequestId(): String? { return headers!!["X-Matching-Request"] } }
0
null
2
5
f699e11470339a01e36f6d92926921359f5d2b21
1,368
SDK.Android
Apache License 2.0
car-rental-analytics/src/main/kotlin/com/lvb/studies/kotlin/api/dto/CarPostDTO.kt
Velosofurioso
636,948,488
false
null
package com.lvb.studies.kotlin.api.dto import com.fasterxml.jackson.annotation.JsonInclude @JsonInclude data class CarPostDTO( val model: String = "", val brand: String = "", val price: Double = 0.0, val description: String = "", val engineVersion: String = "", val city: String = "", val createdDate: String = "", val ownerId: Long = 0, val ownerName: String = "", val ownerType: String = "", val contact: String = "" )
0
Kotlin
0
0
21bc34004b70bd5b08fe85fa21b99a1c003012cf
468
api-car-rental
MIT License
app/src/main/java/org/sesac/management/view/adapter/recyclerview/NoticeRecyclerViewAdapter.kt
SeSAC-3th
703,429,812
false
{"Kotlin": 178829}
package org.sesac.management.view.adapter.recyclerview import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import org.sesac.management.data.local.Notice import org.sesac.management.databinding.ItemNoticeBinding import org.sesac.management.util.extension.setOnAvoidDuplicateClickFlow import java.text.SimpleDateFormat import java.util.Locale class NoticeRecyclerAdapter( private var items: List<Notice>, private val onClick: (Int) -> Unit, private val onDeleteClick: (Int) -> Unit, ) : RecyclerView.Adapter<NoticeRecyclerAdapter.NoticeInfo>() { inner class NoticeInfo(val itemBinding: ItemNoticeBinding) : RecyclerView.ViewHolder(itemBinding.root) { fun bind(item: Notice) { with(itemBinding) { tvTitle.text = item.title tvDate.text = SimpleDateFormat( "yyyy년 MMM dd일", Locale.KOREA).format(item.createdAt) root.setOnAvoidDuplicateClickFlow { onClick(item.noticeId) } ivDeleteNotice.setOnAvoidDuplicateClickFlow { onDeleteClick(item.noticeId) } } } } override fun onCreateViewHolder( parent: ViewGroup, viewType: Int ): NoticeInfo { val binding = ItemNoticeBinding.inflate(LayoutInflater.from(parent.context), parent, false) return NoticeInfo(binding) } override fun onBindViewHolder(holder: NoticeInfo, position: Int) { holder.bind(items[position]) } override fun getItemCount(): Int = items.size }
4
Kotlin
4
0
eed031a47183b52c48a333187264a1e42f8879f1
1,672
SeSalChai
MIT License
core/src/main/kotlin/gropius/repository/issue/timeline/RemovedAffectedEntityEventRepository.kt
ccims
487,996,394
false
{"Kotlin": 1075633, "TypeScript": 458570, "MDX": 61340, "JavaScript": 27194, "HTML": 19890, "CSS": 4796, "Shell": 2363}
package gropius.repository.issue.timeline import gropius.model.issue.timeline.RemovedAffectedEntityEvent import gropius.repository.GropiusRepository import org.springframework.stereotype.Repository /** * Repository for [RemovedAffectedEntityEvent] */ @Repository interface RemovedAffectedEntityEventRepository : GropiusRepository<RemovedAffectedEntityEvent, String>
7
Kotlin
1
0
a91ea183ad7c671143947fa793e95b43444136ab
369
gropius-backend
MIT License
app/src/main/java/com/github/psm/moviedb/ui/person/PersonViewModel.kt
Pidsamhai
371,868,606
false
{"Kotlin": 243787, "CMake": 1715}
package com.github.psm.moviedb.ui.person import androidx.lifecycle.LiveData import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.github.psm.moviedb.db.BoxStore import com.github.psm.moviedb.db.model.person.Person import com.github.psm.moviedb.db.model.person.Person_ import com.github.psm.moviedb.db.model.person.movie.PersonMovieCredit import com.github.psm.moviedb.db.model.person.movie.PersonMovieCredit_ import com.github.psm.moviedb.db.model.person.tv.PersonTvCredit import com.github.psm.moviedb.db.model.person.tv.PersonTvCredit_ import com.github.psm.moviedb.repository.TMDBRepository import com.github.psm.moviedb.utils.asFirstLiveData import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class PersonViewModel @Inject constructor( savedStateHandle: SavedStateHandle, private val repository: TMDBRepository, boxStore: BoxStore ) : ViewModel() { private val personId = requireNotNull(savedStateHandle.get<Long?>("personId")) val person: LiveData<Person?> = boxStore .person .query() .equal(Person_.id, personId) .asFirstLiveData() val personTvCredit: LiveData<PersonTvCredit?> = boxStore .personTvCredit .query() .equal(PersonTvCredit_.id, personId) .asFirstLiveData() val personMovieCredit: LiveData<PersonMovieCredit?> = boxStore .personMovieCredit .query() .equal(PersonMovieCredit_.id, personId) .asFirstLiveData() init { viewModelScope.launch { repository.getPersonDetail(personId) repository.getPersonTvCredit(personId) repository.getPersonMovieCredit(personId) } } }
1
Kotlin
1
3
6f4e67ee83349604b3396902469f4c3a83a68c3c
1,822
movie_db
Apache License 2.0
okio/src/mingwX64Main/kotlin/okio/Windows.kt
square
17,812,502
false
{"Kotlin": 1559919, "Java": 43685, "Shell": 1180}
/* * Copyright (C) 2020 Square, 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 okio import kotlinx.cinterop.ByteVarOf import kotlinx.cinterop.allocArray import kotlinx.cinterop.memScoped import platform.windows.DWORD import platform.windows.ERROR_FILE_NOT_FOUND import platform.windows.ERROR_PATH_NOT_FOUND import platform.windows.FORMAT_MESSAGE_FROM_SYSTEM import platform.windows.FORMAT_MESSAGE_IGNORE_INSERTS import platform.windows.FormatMessageA import platform.windows.GetLastError import platform.windows.LANG_NEUTRAL import platform.windows.SUBLANG_DEFAULT internal fun lastErrorToIOException(): IOException { val lastError = GetLastError() return when (lastError.toInt()) { ERROR_FILE_NOT_FOUND, ERROR_PATH_NOT_FOUND -> FileNotFoundException(lastErrorString(lastError)) else -> IOException(lastErrorString(lastError)) } } internal fun lastErrorString(lastError: DWORD): String { memScoped { val messageMaxSize = 2048 val message = allocArray<ByteVarOf<Byte>>(messageMaxSize) FormatMessageA( dwFlags = (FORMAT_MESSAGE_FROM_SYSTEM or FORMAT_MESSAGE_IGNORE_INSERTS).toUInt(), lpSource = null, dwMessageId = lastError, dwLanguageId = (SUBLANG_DEFAULT * 1024 + LANG_NEUTRAL).toUInt(), // MAKELANGID macro. lpBuffer = message, nSize = messageMaxSize.toUInt(), Arguments = null ) return Buffer().writeNullTerminated(message).readUtf8().trim() } }
89
Kotlin
1178
8,795
0f6c9cf31101483e6ee9602e80a10f7697c8f75a
1,962
okio
Apache License 2.0
services/csm.cloud.project.activity/src/main/kotlin/com/bosch/pt/csm/cloud/projectmanagement/project/taskschedule/facade/listener/strategies/activity/TaskScheduleAggregateComparator.kt
boschglobal
805,348,245
false
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
/* * ************************************************************************ * * Copyright:       <NAME> Power Tools GmbH, 2021 * * ************************************************************************* */ package com.bosch.pt.csm.cloud.projectmanagement.project.taskschedule.facade.listener.strategies.activity import com.bosch.pt.csm.cloud.common.extensions.toLocalDate import com.bosch.pt.csm.cloud.projectmanagement.project.common.facade.listener.strategies.activity.AggregateComparator import com.bosch.pt.csm.cloud.projectmanagement.project.common.facade.listener.strategies.activity.AttributeChangeEnum import com.bosch.pt.csm.cloud.projectmanagement.project.common.facade.listener.strategies.activity.AttributeChangeEnum.CREATED import com.bosch.pt.csm.cloud.projectmanagement.project.common.facade.listener.strategies.activity.AttributeChangeEnum.REMOVED import com.bosch.pt.csm.cloud.projectmanagement.project.common.facade.listener.strategies.activity.AttributeChangeEnum.UPDATED import com.bosch.pt.csm.cloud.projectmanagement.project.taskschedule.model.TaskSchedule import com.bosch.pt.csm.cloud.projectmanagement.project.taskschedule.model.TaskScheduleSlot import java.util.Date import java.util.UUID import org.springframework.data.mongodb.core.MongoOperations import org.springframework.stereotype.Component @Component class TaskScheduleAggregateComparator(mongoOperations: MongoOperations) : AggregateComparator(mongoOperations) { fun compare( currentVersion: TaskSchedule, previousVersion: TaskSchedule ): Collection<TaskScheduleAttributeChange> { val changedAttributes = super.compare(currentVersion, previousVersion) .apply { remove("slots") } .map { TaskScheduleAttributeChange( attribute = it.value.attribute, attributeIdentifier = null, oldValue = with(it.value.oldValue) { when (this) { is Date -> this.toLocalDate() else -> this } }, newValue = with(it.value.newValue) { when (this) { is Date -> this.toLocalDate() else -> this } }, changeType = it.value.changeType) } .toSet() val slotsChangedAttributes = compareSlots(currentVersion.slots, previousVersion.slots) return changedAttributes + slotsChangedAttributes } private fun compareSlots( currentSlots: Collection<TaskScheduleSlot>, previousSlots: Collection<TaskScheduleSlot> ): Collection<TaskScheduleAttributeChange> { val currentSlotsMap = currentSlots.map { it.dayCardIdentifier to it.date }.toMap() val previousSlotsMap = previousSlots.map { it.dayCardIdentifier to it.date }.toMap() // Insert val insertAttributes = currentSlotsMap.filterNot { previousSlotsMap.contains(it.key) }.map { TaskScheduleAttributeChange( attribute = "daycard", attributeIdentifier = it.key, oldValue = null, newValue = it.value, changeType = CREATED) } // Update val updateAttributes = currentSlotsMap .filter { previousSlotsMap.contains(it.key) && previousSlotsMap.getValue(it.key) != it.value } .map { TaskScheduleAttributeChange( attribute = "daycard", attributeIdentifier = it.key, oldValue = previousSlotsMap.getValue(it.key), newValue = it.value, changeType = UPDATED) } // Delete val deleteAttributes = previousSlotsMap.filterNot { currentSlotsMap.contains(it.key) }.map { TaskScheduleAttributeChange( attribute = "daycard", attributeIdentifier = it.key, oldValue = it.value, newValue = null, changeType = REMOVED) } return insertAttributes + updateAttributes + deleteAttributes } } data class TaskScheduleAttributeChange( val attribute: String, val attributeIdentifier: UUID?, val oldValue: Any?, val newValue: Any?, val changeType: AttributeChangeEnum )
0
Kotlin
3
9
9f3e7c4b53821bdfc876531727e21961d2a4513d
4,474
bosch-pt-refinemysite-backend
Apache License 2.0
common/src/main/java/com/strategair/strategy/common/image/ImageLoader.kt
phantomVK
219,900,125
false
null
package com.strategair.strategy.common.image import com.strategair.strategy.common.image.implement.ContentLoader import com.strategair.strategy.common.image.implement.UserAvatar object ImageLoader { @JvmStatic val user = UserAvatar @JvmStatic val content = ContentLoader }
0
Kotlin
0
0
e93a8f1bbb0bec955ee7bde977b778d27575d5f5
293
Strategy
Apache License 2.0
kubernetes/dsl/src/main/kotlin-gen/com/fkorotkov/openshift/runtimeArtifacts.kt
ichaki5748
124,968,379
true
{"Kotlin": 309714}
// GENERATED package com.fkorotkov.openshift import io.fabric8.openshift.api.model.SourceBuildStrategy import kotlin.collections.List fun SourceBuildStrategy.`runtimeArtifact`(block: io.fabric8.openshift.api.model.ImageSourcePath.() -> Unit = {}) { val newObject = io.fabric8.openshift.api.model.ImageSourcePath() newObject.block() this.`runtimeArtifacts`.add(newObject) }
0
Kotlin
0
0
b00b6ddb4b851a864a2737a3374603f7db659af7
383
k8s-kotlin-dsl
MIT License
src/main/kotlin/dev/willebrands/intellij/sloppyfocus/veto/VetoableFocusSwitcher.kt
jwillebrands
526,333,491
false
{"Kotlin": 14096}
package dev.willebrands.intellij.sloppyfocus.veto import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.project.Project import com.intellij.openapi.wm.IdeFocusManager import dev.willebrands.intellij.sloppyfocus.FocusSwitcher import java.awt.Component class VetoableFocusSwitcher(private val project: Project) : FocusSwitcher { private val vetoersExtensionPoint: ExtensionPointName<VetoableFocusSwitchListener> = ExtensionPointName.create("dev.willebrands.intellij.sloppyfocus.vetoableFocusSwitchListener") override fun switchFocus(target: Component) { if (vetoersExtensionPoint.extensions.all { it.allowFocusSwitch(target, project) }) { IdeFocusManager.getInstance(project).requestFocus(target, true) } } }
3
Kotlin
0
4
3616e458ed7cef93fd28ca0bf7ff769deac6007f
789
ij-sloppy-focus
MIT License
app/src/test/java/net/yupol/transmissionremote/app/analytics/AnalyticsTest.kt
y-polek
58,270,602
false
null
package net.yupol.transmissionremote.app.analytics import com.google.firebase.analytics.FirebaseAnalytics.Event import com.google.firebase.analytics.FirebaseAnalytics.Param import org.junit.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify class AnalyticsTest { private val analyticsProvider = mock<AnalyticsProvider>() private val analytics = Analytics(analyticsProvider) @Test fun `test logScreenView`() { // given class MainScreen // when analytics.logScreenView("Main", MainScreen::class.java) // then verify(analyticsProvider).logEvent( Event.SCREEN_VIEW, Param.SCREEN_NAME to "Main", Param.SCREEN_CLASS to "MainScreen" ) } @Test fun `test setTorrentsCount`() { // when analytics.setTorrentsCount(42) // then verify(analyticsProvider).setUserProperty("torrents_count", "41-50") } @Test fun `test logStartupTimeSLI`() { // when analytics.logStartupTimeSLI(345L) // then verify(analyticsProvider).logEvent( name = "sli_startup_time", "startup_time_millis" to 345L ) } }
43
null
38
159
498ac08ce7011a6c57cd8e97026485bf066f589a
1,234
TransmissionRemote
Apache License 2.0
app/src/main/java/com/bendaniel10/weatherlite/app/WeatherLiteApplication.kt
bendaniel10
95,213,073
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 1, "XML": 17, "Kotlin": 12}
package com.bendaniel10.weatherlite.app import android.app.Application /** * Created by bendaniel on 22/06/2017. */ class WeatherLiteApplication : Application() { override fun onCreate() { super.onCreate() instance = this } companion object { lateinit var instance: WeatherLiteApplication private set const val OPEN_WEATHER_API_URL = "http://api.openweathermap.org/data/2.5/" const val OPEN_WEATHER_API_IMAGE_URL = "http://openweathermap.org/img/w/" const val OPEN_WEATHER_API_KEY = "<KEY>" } }
0
Kotlin
0
4
f41cb73a232d19aef5c25c657a7a27a8a62eeeec
579
weather-lite-kotlin
Apache License 2.0
Engine/src/main/kotlin/dev/rakrae/gameengine/core/Game.kt
kraemer-raimund
387,230,355
false
{"Kotlin": 174907}
package dev.rakrae.gameengine.core import dev.rakrae.gameengine.scene.Scene abstract class Game : GameLifeCycleReceiver { abstract val title: String abstract val scene: Scene private val engine: Engine by lazy { Engine(this) } val window get() = engine.window fun start() = engine.start() fun stop() = engine.stop() }
0
Kotlin
0
0
989040fceaf8b980fce45227a01611c85a940ef9
348
game-engine
MIT License
analysis/low-level-api-fir/testData/fileStructure/functionWithImplicitTypeAndFunctionInsideScript.kts
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
package myPack @Target( AnnotationTarget.PROPERTY, AnnotationTarget.TYPE_PARAMETER, AnnotationTarget.FUNCTION, AnnotationTarget.VALUE_PARAMETER, AnnotationTarget.TYPE, AnnotationTarget.EXPRESSION, ) @Retention(AnnotationRetention.SOURCE) annotation class Anno(val number: Int)/* DeclarationStructureElement *//* ClassDeclarationStructureElement */ @Anno(functionProperty) const val functionProperty = 42/* DeclarationStructureElement */ @Anno(parameterProperty) const val parameterProperty = 42/* DeclarationStructureElement */ @Anno(defaultValueProperty) const val defaultValueProperty = 42/* DeclarationStructureElement */ @Anno(receiverProperty) const val receiverProperty = 42/* DeclarationStructureElement */ @Anno(receiverTypeProperty) const val receiverTypeProperty = 42/* DeclarationStructureElement */ @Anno(typeParameterProperty) const val typeParameterProperty = 42/* DeclarationStructureElement */ @Anno(valueParameterTypeProperty) const val valueParameterTypeProperty = 42/* DeclarationStructureElement */ @Anno(expressionProperty) const val expressionProperty = 42/* DeclarationStructureElement */ fun topLevelFun() = run { @Anno(functionProperty) fun <@Anno(typeParameterProperty) T> @receiver:Anno(receiverProperty) @Anno(receiverTypeProperty) Int.function( @Anno(parameterProperty) param: @Anno( valueParameterTypeProperty ) Int = defaultValueProperty, ) = @Anno(expressionProperty) "str" }/* DeclarationStructureElement */
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,515
kotlin
Apache License 2.0
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/TransformationUtil.kt
playbar
82,760,271
false
null
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.transformations import com.intellij.openapi.progress.ProgressManager import com.intellij.openapi.util.RecursionManager import com.intellij.psi.PsiClass import com.intellij.psi.PsiClassType import com.intellij.psi.PsiMethod import com.intellij.util.containers.ContainerUtil import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.GrTypeDefinition class TransformationResult( val methods: Array<PsiMethod>, val fields: Array<GrField>, val innerClasses: Array<PsiClass>, val implementsTypes: Array<PsiClassType>, val extendsTypes: Array<PsiClassType> ) private val ourTransformationContext = object : ThreadLocal<MutableMap<GrTypeDefinition, Boolean>>() { override fun initialValue(): MutableMap<GrTypeDefinition, Boolean> { return ContainerUtil.newHashMap() } } fun transformDefinition(definition: GrTypeDefinition): TransformationResult { ourTransformationContext.get().put(definition, true) try { return RecursionManager.doPreventingRecursion(definition, false) { val transformationContext = TransformationContextImpl(definition) if (definition.name != null) { for (transformation in org.jetbrains.plugins.groovy.transformations.AstTransformationSupport.EP_NAME.extensions) { ProgressManager.checkCanceled() transformation.applyTransformation(transformationContext) } } transformationContext.transformationResult }!! } finally { ourTransformationContext.get().remove(definition) } } fun isUnderTransformation(clazz: PsiClass?): Boolean { return if (clazz is GrTypeDefinition) { val result = ourTransformationContext.get()[clazz] result != null && result } else { false } }
1
null
1
1
b8af29ff552e564d23ee97cec93d5f4f51636be9
2,426
intellij-community
Apache License 2.0
feature-editTodo/src/main/java/com/riyusoft/todo/feature/edittodo/EditTodoViewModel.kt
jeonhoeun
520,344,732
false
{"Kotlin": 70352, "Shell": 578, "HTML": 509}
package com.riyusoft.todo.feature.edittodo import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.riyusoft.todo.core.data.repository.todo.TodoRepository import com.riyusoft.todo.core.model.Todo import com.riyusoft.todo.feature.edittodo.navigation.EditTodoDestination import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class EditTodoViewModel @Inject constructor( savedStateHandle: SavedStateHandle, val todoRepository: TodoRepository ) : ViewModel() { private val todoId: Long = checkNotNull(savedStateHandle[EditTodoDestination.editTodoIdArg]) private lateinit var editingTodo: Todo var editTodoScreenUiState = MutableStateFlow<EditTodoScreenUiState>(EditTodoScreenUiState.Loading) private set init { println("testtest: todoID:$todoId") if (todoId >= 0) { viewModelScope.launch(Dispatchers.IO) { editingTodo = todoRepository.getTodoById(todoId).also { println("testtest: title:${it.title}") launch(Dispatchers.Main) { editTodoScreenUiState.value = EditTodoScreenUiState.Success( EditTodoUiState( title = it.title, description = it.description ) ) } } } } else { editingTodo = Todo( title = "", description = "", groupId = 2 ) editTodoScreenUiState.value = EditTodoScreenUiState.Success( EditTodoUiState( title = "", description = "" ) ) } } fun onClickSave(title: String, description: String, callback: (Boolean) -> Unit) { println("testtest:onClickSave start before runblocking") viewModelScope.launch(Dispatchers.IO) { println("testtest: todo id : $todoId") if (todoId == -1L) { todoRepository.insertTodo( Todo( title = title, description = description, groupId = 2 ) ).also { launch(Dispatchers.Main) { callback(it >= 0) } } } else { todoRepository.updateTodo( Todo( id = todoId, title = title, description = description, priority = editingTodo.priority, groupId = editingTodo.groupId ) ).also { launch(Dispatchers.Main) { callback(it >= 0) } } } } } } data class EditTodoUiState( val title: String, val description: String ) sealed interface EditTodoScreenUiState { object Loading : EditTodoScreenUiState data class Success( val editTodoUiState: EditTodoUiState ) : EditTodoScreenUiState }
1
Kotlin
0
0
175e250d1e53da29ce8b9bb5e4f24ae513d9404b
3,466
aos-todo-cleanarch-compose-tdd
MIT License
src/main/kotlin/com/expansemc/bending/api/collision/CollisionResult.kt
ExpanseMC
272,346,844
false
null
package com.expansemc.bending.api.collision enum class CollisionResult { WINS, LOSES, UNDEFINED }
0
Kotlin
0
0
c663dbc917c02c2896769fa30ff927cf5aa212ad
110
bending-api
MIT License
api/src/main/kotlin/no/nav/poao_tilgang/api/dto/request/policy_input/NavAnsattNavIdentTilgangTilNavEnhetPolicyInputV1Dto.kt
navikt
491,417,288
false
{"Kotlin": 324038, "Dockerfile": 95}
package no.nav.poao_tilgang.api.dto.request.policy_input data class NavAnsattNavIdentTilgangTilNavEnhetPolicyInputV1Dto( val navIdent: String, val navEnhetId: String )
7
Kotlin
4
0
e53575bb6b637763bf23e175af127345a2ebf55b
171
poao-tilgang
MIT License
project/src/main/kotlin/cga/exercise/components/geometry/Transformable.kt
JannikAlx
389,366,062
true
{"Kotlin": 171322, "GLSL": 16707}
package cga.exercise.components.geometry import org.joml.Matrix4f import org.joml.Vector3f import org.joml.Vector4f open class Transformable(var modelMatrix: Matrix4f = Matrix4f(), var parent: Transformable? = null) { /** * Rotates object around its own origin. * @param pitch radiant angle around x-axis ccw * @param yaw radiant angle around y-axis ccw * @param roll radiant angle around z-axis ccw */ fun rotateLocal(pitch: Float, yaw: Float, roll: Float) { modelMatrix.rotateXYZ(pitch, yaw, roll) } fun rotateLocalAxis(angle: Float, axis: Vector3f) { modelMatrix.rotate(angle, axis) } fun rotateGlobalAxis(angle: Float, axis: Vector3f) { Matrix4f().rotate(angle, axis).mul(modelMatrix,modelMatrix) } /** * Rotates object around given rotation center. * @param pitch radiant angle around x-axis ccw * @param yaw radiant angle around y-axis ccw * @param roll radiant angle around z-axis ccw * @param altMidpoint rotation center */ fun rotateAroundPoint(pitch: Float, yaw: Float, roll: Float, altMidpoint: Vector3f) { val rotMat = Matrix4f().rotateXYZ(pitch, yaw, roll) val transMatBack = Matrix4f() .translate(altMidpoint) val transMat = Matrix4f().translate(Vector3f(altMidpoint).negate()) val test = Matrix4f() test.mul(transMat) test.mul(rotMat) test.mul(transMatBack) test.mul(modelMatrix, modelMatrix) } /** * Translates object based on its own coordinate system. * @param deltaPos delta positions */ fun translateLocal(deltaPos: Vector3f) { val result = Matrix4f().translate(deltaPos) modelMatrix.mul(result) } /** * Translates object based on its parent coordinate system. * Hint: global operations will be left-multiplied * @param deltaPos delta positions (x, y, z) */ fun translateGlobal(deltaPos: Vector3f) = Matrix4f().translate(deltaPos).mul(modelMatrix, modelMatrix) /** * Scales object related to its own origin * @param scale scale factor (x, y, z) */ fun scaleLocal(scale: Vector3f) { val scaleMat = Matrix4f().scale(scale) modelMatrix.mul(scaleMat) } /** * Returns position based on aggregated translations. * Hint: last column of model matrix * @return position */ fun getPosition(): Vector3f { return Vector3f(modelMatrix.m30(), modelMatrix.m31(), modelMatrix.m32()) } fun setPosition(position: Vector3f) { modelMatrix.m30(position.x) modelMatrix.m31(position.y) modelMatrix.m32(position.z) } /** * Returns position based on aggregated translations incl. parents. * Hint: last column of world model matrix * @return position */ fun getWorldPosition(): Vector3f { val mm = getWorldModelMatrix() return Vector3f(mm.m30(), mm.m31(), mm.m32()) } fun getWorldPosition4f(): Vector4f { val mm = getWorldModelMatrix() return Vector4f(mm.m30(), mm.m31(), mm.m32(),mm.m33()) } /** * Returns x-axis of object coordinate system * Hint: first normalized column of model matrix * @return x-axis */ fun getXAxis(): Vector3f = Vector3f(modelMatrix.m00(), modelMatrix.m01(), modelMatrix.m02()).normalize() /** * Returns y-axis of object coordinate system * Hint: second normalized column of model matrix * @return y-axis */ fun getYAxis(): Vector3f = Vector3f(modelMatrix.m10(), modelMatrix.m11(), modelMatrix.m12()).normalize() /** * Returns z-axis of object coordinate system * Hint: third normalized column of model matrix * @return z-axis */ fun getZAxis(): Vector3f = Vector3f(modelMatrix.m20(), modelMatrix.m21(), modelMatrix.m22()).normalize() /** * Returns x-axis of world coordinate system * Hint: first normalized column of world model matrix * @return x-axis */ fun getWorldXAxis(): Vector3f { val m = getWorldModelMatrix() val v = Vector3f(m.m00(), m.m01(), m.m02()) return v.normalize() } /** * Returns y-axis of world coordinate system * Hint: second normalized column of world model matrix * @return y-axis */ fun getWorldYAxis(): Vector3f { val m = getWorldModelMatrix() val v = Vector3f(m.m10(), m.m11(), m.m12()) return v.normalize() } /** * Returns z-axis of world coordinate system * Hint: third normalized column of world model matrix * @return z-axis */ fun getWorldZAxis(): Vector3f { val m = getWorldModelMatrix() val v = Vector3f(m.m20(), m.m21(), m.m22()) return v.normalize() } /** * Returns multiplication of world and object model matrices. * Multiplication has to be recursive for all parents. * Hint: scene graph * @return world modelMatrix */ fun getWorldModelMatrix(): Matrix4f { if (parent == null) { return getLocalModelMatrix() } else { val parentMM = parent?.getWorldModelMatrix() ?: throw IllegalStateException("Excuse me wtf?") return Matrix4f(parentMM).mul(modelMatrix) } } /** * Returns object model matrix * @return modelMatrix */ fun getLocalModelMatrix(): Matrix4f { return Matrix4f(modelMatrix) } }
0
Kotlin
0
0
36b6fe8d014673cfab60b54722b150594235b3a1
5,519
Cayuga
MIT License
sample/src/main/java/com/xtensolutions/sample/ui/fragment/RestaurantFragment.kt
riontech-xten
337,764,638
false
null
package com.xtensolutions.sample.ui.fragment import android.os.Bundle import android.view.View import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.xtensolutions.sample.R import com.xtensolutions.sample.core.adapter.BaseViewHolder import com.xtensolutions.sample.databinding.FragmentRestaurantBinding import com.xtensolutions.sample.ui.adapter.RestaurantAdapter import com.xtensolutions.sample.ui.viewmodel.RestaurantViewModel import dagger.hilt.android.AndroidEntryPoint /** * Created by <NAME> on 10-02-2023 - 20:43. * Email : <EMAIL> * Mob : +919727206702 **/ @AndroidEntryPoint class RestaurantFragment : Fragment(R.layout.fragment_restaurant), BaseViewHolder.ViewHolderClickListener { private lateinit var binding: FragmentRestaurantBinding private val viewModel: RestaurantViewModel by viewModels() private lateinit var adapter: RestaurantAdapter override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) binding = FragmentRestaurantBinding.bind(view) initList() loadRestaurant() } private fun initList() { adapter = RestaurantAdapter(requireContext(), emptyList()) adapter.viewHolderClickListener = this binding.rvRestaurants.layoutManager = LinearLayoutManager(requireContext()) binding.rvRestaurants.adapter = adapter // binding.rvRestaurants.addItemDecoration(DividerItemDecoration(requireContext(), VERTICAL)) } private fun loadRestaurant() { viewModel.getRestaurants().observe(viewLifecycleOwner) { it ?: showNoDataView(true) if (it.isEmpty()) { showNoDataView(true) return@observe } adapter.updateList(it.toMutableList()) showNoDataView(false) // binding.progressRestaurant.isVisible = false } } private fun showNoDataView(visibility: Boolean) { requireActivity().runOnUiThread { binding.progressRestaurant.isVisible = false binding.viewNoData.root.isVisible = visibility } } override fun onViewHolderViewClicked(view: View?, position: Int) { view ?: return if (view.id == R.id.clRowRestaurantRoot) { val restaurant = adapter.getItem(position) val direction = RestaurantFragmentDirections.restaurantToDeal(restaurant) findNavController().navigate(direction) } } }
0
Kotlin
0
1
22f4df855cbd945635128ab1e8a116e5c8ca435c
2,678
StoryLayout
Apache License 2.0
app/src/main/java/changhwan/experiment/sopthomework/data/remote/model/response/wrapper/ResponseWrapper.kt
29th-WE-SOPT-Android-Part
413,076,866
false
null
package changhwan.experiment.sopthomework.data.remote.model.response.wrapper data class ResponseWrapper<T>( val status: Int, val success: Boolean, val message: String, val data: T? )
0
Kotlin
0
1
e9929a84a4bd840a013b2e11139d55b6b77475b7
200
Android-Changhwan
Apache License 2.0