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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/main/kotlin/com/cjbooms/fabrikt/model/KotlinTypeInfo.kt | cjbooms | 229,844,927 | false | null | package com.cjbooms.fabrikt.model
import com.cjbooms.fabrikt.cli.CodeGenTypeOverride
import com.cjbooms.fabrikt.generators.MutableSettings
import com.cjbooms.fabrikt.model.OasType.Companion.toOasType
import com.cjbooms.fabrikt.util.KaizenParserExtensions.getEnumValues
import com.cjbooms.fabrikt.util.KaizenParserExtensions.isInlinedTypedAdditionalProperties
import com.cjbooms.fabrikt.util.KaizenParserExtensions.isNotDefined
import com.cjbooms.fabrikt.util.KaizenParserExtensions.isOneOfSuperInterfaceWithDiscriminator
import com.cjbooms.fabrikt.util.ModelNameRegistry
import com.reprezen.kaizen.oasparser.model3.Schema
import java.math.BigDecimal
import java.net.URI
import java.time.LocalDate
import java.time.OffsetDateTime
import java.util.UUID
import kotlin.reflect.KClass
sealed class KotlinTypeInfo(val modelKClass: KClass<*>, val generatedModelClassName: String? = null) {
object Text : KotlinTypeInfo(String::class)
object Date : KotlinTypeInfo(LocalDate::class)
object DateTime : KotlinTypeInfo(OffsetDateTime::class)
object Instant : KotlinTypeInfo(java.time.Instant::class)
object LocalDateTime : KotlinTypeInfo(java.time.LocalDateTime::class)
object Double : KotlinTypeInfo(kotlin.Double::class)
object Float : KotlinTypeInfo(kotlin.Float::class)
object Numeric : KotlinTypeInfo(BigDecimal::class)
object Integer : KotlinTypeInfo(Int::class)
object BigInt : KotlinTypeInfo(Long::class)
object Uuid : KotlinTypeInfo(UUID::class)
object Uri : KotlinTypeInfo(URI::class)
object ByteArray : KotlinTypeInfo(kotlin.ByteArray::class)
object Boolean : KotlinTypeInfo(kotlin.Boolean::class)
object UntypedObject : KotlinTypeInfo(Any::class)
object AnyType : KotlinTypeInfo(Any::class)
data class Object(val simpleClassName: String) : KotlinTypeInfo(GeneratedType::class, simpleClassName)
data class Array(val parameterizedType: KotlinTypeInfo) : KotlinTypeInfo(List::class)
data class Map(val parameterizedType: KotlinTypeInfo) : KotlinTypeInfo(Map::class)
object UnknownAdditionalProperties : KotlinTypeInfo(Any::class)
object UntypedObjectAdditionalProperties : KotlinTypeInfo(Any::class)
data class GeneratedTypedAdditionalProperties(val simpleClassName: String) :
KotlinTypeInfo(GeneratedType::class, simpleClassName)
data class MapTypeAdditionalProperties(val parameterizedType: KotlinTypeInfo) :
KotlinTypeInfo(Map::class)
data class Enum(val entries: List<String>, val enumClassName: String) :
KotlinTypeInfo(GeneratedType::class, enumClassName)
val isComplexType: kotlin.Boolean
get() = when (this) {
is Array, is Object, is Map, is GeneratedTypedAdditionalProperties -> true
else -> false
}
companion object {
fun from(schema: Schema, oasKey: String = "", enclosingSchema: EnclosingSchemaInfo? = null): KotlinTypeInfo =
when (schema.toOasType(oasKey)) {
OasType.Date -> Date
OasType.DateTime -> getOverridableDateTimeType()
OasType.Text -> Text
OasType.Enum ->
Enum(schema.getEnumValues(), ModelNameRegistry.getOrRegister(schema, enclosingSchema))
OasType.Uuid -> Uuid
OasType.Uri -> Uri
OasType.Base64String -> ByteArray
OasType.Binary -> ByteArray
OasType.Double -> Double
OasType.Float -> Float
OasType.Number -> Numeric
OasType.Int32 -> Integer
OasType.Int64 -> BigInt
OasType.Integer -> Integer
OasType.Boolean -> Boolean
OasType.Array ->
if (schema.itemsSchema.isNotDefined())
throw IllegalArgumentException("Property ${schema.name} cannot be parsed to a Schema. Check your input")
else Array(from(schema.itemsSchema, oasKey, enclosingSchema))
OasType.Object -> Object(ModelNameRegistry.getOrRegister(schema, enclosingSchema))
OasType.Map ->
Map(from(schema.additionalPropertiesSchema, "", enclosingSchema))
OasType.TypedObjectAdditionalProperties -> GeneratedTypedAdditionalProperties(
ModelNameRegistry.getOrRegister(schema, valueSuffix = schema.isInlinedTypedAdditionalProperties())
)
OasType.UntypedObjectAdditionalProperties -> UntypedObjectAdditionalProperties
OasType.UntypedObject -> UntypedObject
OasType.UnknownAdditionalProperties -> UnknownAdditionalProperties
OasType.TypedMapAdditionalProperties ->
MapTypeAdditionalProperties(
from(schema.additionalPropertiesSchema, "", enclosingSchema)
)
OasType.Any -> AnyType
OasType.OneOfAny ->
if (schema.isOneOfSuperInterfaceWithDiscriminator()) {
Object(ModelNameRegistry.getOrRegister(schema, enclosingSchema))
} else {
AnyType
}
}
private fun getOverridableDateTimeType(): KotlinTypeInfo {
val typeOverrides = MutableSettings.typeOverrides()
return when {
CodeGenTypeOverride.DATETIME_AS_INSTANT in typeOverrides -> Instant
CodeGenTypeOverride.DATETIME_AS_LOCALDATETIME in typeOverrides -> LocalDateTime
else -> DateTime
}
}
}
}
| 5 | null | 41 | 99 | 81a003c45e518573a871621aef1a48599735c86f | 5,637 | fabrikt | Apache License 2.0 |
src/test/kotlin/ApplicationLocal.kt | navikt | 206,805,010 | false | null | package no.nav.familie.ef.sak
import no.nav.familie.ef.sak.database.DbContainerInitializer
import no.nav.familie.ef.sak.infrastruktur.config.ApplicationConfig
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration
import org.springframework.boot.builder.SpringApplicationBuilder
@SpringBootApplication(exclude = [ErrorMvcAutoConfiguration::class])
class ApplicationLocal
fun main(args: Array<String>) {
SpringApplicationBuilder(ApplicationConfig::class.java)
.initializers(DbContainerInitializer())
.profiles(
"local",
"mock-arbeidssøker",
"mock-integrasjoner",
"mock-pdl",
"mock-infotrygd-replika",
"mock-kodeverk",
"mock-iverksett",
"mock-inntekt",
"mock-ereg",
"mock-aareg",
"mock-brev",
"mock-dokument",
"mock-tilbakekreving",
"mock-klage",
"mock-sigrun",
"mock-historiskpensjon",
"mock-featuretoggle",
"mock-egen-ansatt",
)
.run(*args)
}
| 8 | Kotlin | 2 | 0 | d1d8385ead500c4d24739b970940af854fa5fe2c | 1,201 | familie-ef-sak | MIT License |
app/src/main/java/com/codelab/basiclayouts/ui/screens/author/AuthorMainScreen.kt | zjh101550-boop | 796,965,228 | false | {"Kotlin": 87078} | package com.codelab.basiclayouts.ui.screens.author
import com.codelab.basiclayouts.R
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.NavigationBar
import androidx.compose.material3.NavigationBarItem
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountCircle
import androidx.compose.material.icons.filled.Spa
import androidx.compose.material3.Button
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.codelab.basiclayouts.ui.theme.AppTheme
@Composable
fun NewStoryElement(
@DrawableRes drawable: Int,
@StringRes text: Int,
onClick:()->Unit,
modifier: Modifier = Modifier
) {
Button(
onClick=onClick,
modifier=modifier,
shape= CircleShape
){
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally,
) {
Image(
painter = painterResource(drawable),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier
.size(88.dp)
.clip(CircleShape)
)
Text(
text = stringResource(text),
modifier = Modifier.paddingFromBaseline(top = 24.dp, bottom = 8.dp),
style = MaterialTheme.typography.bodyMedium
)
}
}
}
//
// Step: Favorite collection card - Material Surface
@Composable
fun DraftStoryElement(
@DrawableRes drawable: Int,
@StringRes text: Int,
modifier: Modifier = Modifier
) {
Surface(
shape = MaterialTheme.shapes.medium,
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = modifier
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.width(255.dp)
) {
Image(
painter = painterResource(drawable),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.size(80.dp)
)
Text(
text = stringResource(text),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(horizontal = 16.dp),
)
}
}
}
// Step: Align your body row - Arrangements
@Composable
fun DraftRow(
modifier: Modifier = Modifier
) {
LazyColumn(
verticalArrangement = Arrangement.spacedBy(8.dp),
contentPadding = PaddingValues(horizontal = 50.dp),
modifier = modifier
) {
items(draftCollectionsData) { item ->
DraftStoryElement(item.drawable, item.text)
}
}
}
@Composable
fun DoneStoryElement(
@DrawableRes drawable: Int,
@StringRes text: Int,
modifier: Modifier = Modifier
) {
Surface(
shape = MaterialTheme.shapes.medium,
color = MaterialTheme.colorScheme.surfaceVariant,
modifier = modifier
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.width(255.dp)
) {
Image(
painter = painterResource(drawable),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.size(80.dp)
)
Text(
text = stringResource(text),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier.padding(horizontal = 16.dp),
)
}
}
}
@Composable
fun DoneRow(
modifier: Modifier = Modifier
) {
LazyColumn(
verticalArrangement = Arrangement.spacedBy(8.dp),
contentPadding = PaddingValues(horizontal = 50.dp),
modifier = modifier
) {
items(doneCollectionsData) { item ->
DoneStoryElement(item.drawable, item.text)
}
}
}
@Composable
fun HomeSection(
@StringRes title: Int,
modifier: Modifier = Modifier,
content: @Composable () -> Unit
) {
Column(modifier) {
Text(
text = stringResource(title),
style = MaterialTheme.typography.titleMedium,
modifier = Modifier
.padding(horizontal = 16.dp)
.paddingFromBaseline(top = 40.dp, bottom = 16.dp)
)
Box(modifier = Modifier
.fillMaxWidth() // 确保使用全部可用宽度
.padding(horizontal = 16.dp), // 与标题相同的水平padding以对齐
contentAlignment = Alignment.Center) { // 在Box内居中内容
content()
}
}
}
@Composable
fun HomeScreen(modifier: Modifier = Modifier,navController:NavController) {
Column(
modifier
.verticalScroll(rememberScrollState())
) {
Spacer(Modifier.height(16.dp))
HomeSection(title = R.string.new_story) {
NewStoryElement(drawable = R.drawable.write_story, text = R.string.write_story,
onClick = {navController.navigate("authorNewStoryScreen")})
}
HomeSection(title = R.string.draft_story) {
DraftRow(modifier = Modifier.height(150.dp))
}
HomeSection(title = R.string.done_story) {
DoneRow(modifier = Modifier.height(150.dp))
}
Spacer(Modifier.height(16.dp))
}
}
// Step: Bottom navigation - Material
@Composable
public fun BottomNavigation(modifier: Modifier = Modifier) {
NavigationBar(
containerColor = MaterialTheme.colorScheme.surfaceVariant,
modifier = modifier
) {
NavigationBarItem(
icon = {
Icon(
imageVector = Icons.Default.Spa,
contentDescription = null
)
},
label = {
Text(stringResource(R.string.bottom_navigation_home))
},
selected = true,
onClick = {
// 使用NavController导航到HomeScreen
// navController.navigate("home")
// {
// // 清理导航栈,确保返回时不会回到前一个页面
// popUpTo("home") {
// saveState = true
// }
// launchSingleTop = true
// restoreState = true
// }
}
)
NavigationBarItem(
icon = {
Icon(
imageVector = Icons.Default.AccountCircle,
contentDescription = null
)
},
label = {
Text(stringResource(R.string.bottom_navigation_profile))
},
selected = false,
onClick = {}
)
}
}
@Composable
fun AuthorMainScreen(navController: NavController) {
AppTheme {
Scaffold(
bottomBar = { BottomNavigation() }
) { padding ->
HomeScreen(Modifier.padding(padding),navController)
}
}
}
private val draftCollectionsData = listOf(
R.drawable.fc1_short_mantras to R.string.fc1_short_mantras,
R.drawable.fc2_nature_meditations to R.string.draft1_forest_tour,
R.drawable.fc3_stress_and_anxiety to R.string.fc3_stress_and_anxiety,
R.drawable.fc4_self_massage to R.string.fc4_self_massage,
R.drawable.fc5_overwhelmed to R.string.fc5_overwhelmed,
R.drawable.fc6_nightly_wind_down to R.string.fc6_nightly_wind_down
).map { DrawableStringPair(it.first, it.second) }
private val doneCollectionsData = listOf(
R.drawable.ab1_inversions to R.string.ab1_inversions,
R.drawable.ab2_quick_yoga to R.string.ab2_quick_yoga,
R.drawable.ab3_stretching to R.string.ab3_stretching,
R.drawable.ab4_tabata to R.string.ab4_tabata,
R.drawable.ab5_hiit to R.string.ab5_hiit,
R.drawable.ab6_pre_natal_yoga to R.string.ab6_pre_natal_yoga
).map { DrawableStringPair(it.first, it.second) }
private data class DrawableStringPair(
@DrawableRes val drawable: Int,
@StringRes val text: Int
)
//@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)
//@Composable
//fun SearchBarPreview() {
// MySootheTheme { SearchBar(Modifier.padding(8.dp)) }
//}
//@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)
//@Composable
//fun NewStoryElementPreview() {
// MySootheTheme {
// NewStoryElement(
// text = R.string.write_story,
// drawable = R.drawable.write_story,
// modifier = Modifier.padding(8.dp)
//
// )
// }
//}
//@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)
//@Composable
//fun DraftStoryElementPreview() {
// MySootheTheme {
// DraftStoryElement(
// text = R.string.draft1_forest_tour,
// drawable = R.drawable.fc2_nature_meditations,
// modifier = Modifier.padding(8.dp),
// )
// }
//}
//@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)
//@Composable
//fun DraftRowPreview() {
// MySootheTheme { DraftRow(modifier=Modifier.height(300.dp)) }
//}
//@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)
//@Composable
//fun DoneRowPreview() {
// MySootheTheme { DoneRow(modifier=Modifier.height(300.dp)) }
//}
//@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)
//@Composable
//fun HomeSectionPreview() {
// MySootheTheme {
// HomeSection(R.string.draft_story) {
// DraftRow(modifier=Modifier.height(300.dp))
// }
// }
//}
//@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE, heightDp = 800)
//@Composable
//fun ScreenContentPreview() {
// MySootheTheme { HomeScreen() }
//}
//@Preview(showBackground = true, backgroundColor = 0xFFF5F0EE)
//@Composable
//fun BottomNavigationPreview() {
// MySootheTheme { SootheBottomNavigation(Modifier.padding(top = 24.dp)) }
//}
//
//@Preview(widthDp = 360, heightDp = 640)
//@Composable
//fun AuthorMainScreenPreview() {
// AuthorMainScreen(navController : NavController)
//}
| 0 | Kotlin | 0 | 0 | 5fdc3f1bdcfacdb8ccd76be6865ec9d6c674b4be | 12,137 | storyApp_compose_kt | Apache License 2.0 |
app/src/main/java/pl/droidcon/app/agenda/AgendaItemPresenter.kt | droidconpl | 103,277,279 | false | {"Kotlin": 123751} | package pl.droidcon.app.agenda
import android.widget.ImageView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import io.reactivex.schedulers.Schedulers
import pl.droidcon.app.agenda.interactor.AgendaRepository
import pl.droidcon.app.data.local.FavoriteLocal
import pl.droidcon.app.domain.Agenda
import pl.droidcon.app.domain.Session
import pl.droidcon.app.favorite.interactor.FavoriteRepository
import javax.inject.Inject
class AgendaItemPresenter @Inject constructor(
private val agendaRepository: AgendaRepository,
private val favoriteRepository: FavoriteRepository
) {
private var view: AgendaItemView? = null
private val disposables = CompositeDisposable()
fun attachView(agendaItemView: AgendaItemView?, dayId: Int) {
this.view = agendaItemView
if (view == null) {
disposables.clear()
} else {
agendaRepository.get()
.subscribeOn(Schedulers.io())
.distinctUntilChanged()
.filter { agenda: Agenda -> agenda.days.isNotEmpty() }
.map { agenda -> agenda.days[dayId].talkPanels }
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ view?.display(it) }, { it.printStackTrace() })
.addTo(disposables)
}
}
fun openSession(speakerPicture: ImageView, session: Session) {
view?.openSession(speakerPicture, session)
}
fun observeFavorite(sessionId: Long): Observable<Boolean> {
return favoriteRepository.getFavorite(sessionId).map { favorite: FavoriteLocal -> favorite.isFavorite }
}
} | 1 | Kotlin | 0 | 0 | 116caf6e0c93d8dde2b19e7037ee6ad49b39e939 | 1,779 | droidcon-mobile-app | Apache License 2.0 |
feature-wallet-impl/src/main/java/jp/co/soramitsu/feature_wallet_impl/data/repository/WalletRepositoryImpl.kt | trustex | 385,920,487 | true | {"Kotlin": 1715024} | package jp.co.soramitsu.feature_wallet_impl.data.repository
import jp.co.soramitsu.common.data.mappers.mapSigningDataToKeypair
import jp.co.soramitsu.common.data.network.HttpExceptionHandler
import jp.co.soramitsu.common.utils.mapList
import jp.co.soramitsu.common.utils.networkType
import jp.co.soramitsu.core.model.Node
import jp.co.soramitsu.core.model.SigningData
import jp.co.soramitsu.core_db.dao.PhishingAddressDao
import jp.co.soramitsu.core_db.dao.TransactionDao
import jp.co.soramitsu.core_db.model.PhishingAddressLocal
import jp.co.soramitsu.core_db.model.TransactionLocal
import jp.co.soramitsu.fearless_utils.extensions.toHexString
import jp.co.soramitsu.fearless_utils.ss58.SS58Encoder.toAccountId
import jp.co.soramitsu.feature_wallet_api.data.cache.AssetCache
import jp.co.soramitsu.feature_wallet_api.data.mappers.mapTokenTypeToTokenTypeLocal
import jp.co.soramitsu.feature_wallet_api.domain.interfaces.WalletRepository
import jp.co.soramitsu.feature_wallet_api.domain.model.Asset
import jp.co.soramitsu.feature_wallet_api.domain.model.Fee
import jp.co.soramitsu.feature_wallet_api.domain.model.Token
import jp.co.soramitsu.feature_wallet_api.domain.model.Transaction
import jp.co.soramitsu.feature_wallet_api.domain.model.Transfer
import jp.co.soramitsu.feature_wallet_api.domain.model.TransferValidityStatus
import jp.co.soramitsu.feature_wallet_api.domain.model.WalletAccount
import jp.co.soramitsu.feature_wallet_api.domain.model.amountFromPlanks
import jp.co.soramitsu.feature_wallet_impl.data.mappers.mapAssetLocalToAsset
import jp.co.soramitsu.feature_wallet_impl.data.mappers.mapFeeRemoteToFee
import jp.co.soramitsu.feature_wallet_impl.data.mappers.mapTransactionLocalToTransaction
import jp.co.soramitsu.feature_wallet_impl.data.mappers.mapTransactionToTransactionLocal
import jp.co.soramitsu.feature_wallet_impl.data.mappers.mapTransferToTransaction
import jp.co.soramitsu.feature_wallet_impl.data.network.blockchain.SubstrateRemoteSource
import jp.co.soramitsu.feature_wallet_impl.data.network.model.request.AssetPriceRequest
import jp.co.soramitsu.feature_wallet_impl.data.network.model.request.TransactionHistoryRequest
import jp.co.soramitsu.feature_wallet_impl.data.network.model.response.AssetPriceStatistics
import jp.co.soramitsu.feature_wallet_impl.data.network.model.response.SubscanResponse
import jp.co.soramitsu.feature_wallet_impl.data.network.phishing.PhishingApi
import jp.co.soramitsu.feature_wallet_impl.data.network.subscan.SubscanNetworkApi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
import java.math.BigDecimal
import java.util.Locale
@Suppress("EXPERIMENTAL_API_USAGE")
class WalletRepositoryImpl(
private val substrateSource: SubstrateRemoteSource,
private val transactionsDao: TransactionDao,
private val subscanApi: SubscanNetworkApi,
private val httpExceptionHandler: HttpExceptionHandler,
private val phishingApi: PhishingApi,
private val assetCache: AssetCache,
private val phishingAddressDao: PhishingAddressDao
) : WalletRepository {
override fun assetsFlow(account: WalletAccount): Flow<List<Asset>> {
return assetCache.observeAssets(account.address)
.mapList(::mapAssetLocalToAsset)
}
override suspend fun syncAssetsRates(account: WalletAccount) = coroutineScope {
val networkType = account.network.type
val currentPriceStatsDeferred = async { getAssetPrice(networkType, AssetPriceRequest.createForNow()) }
val yesterdayPriceStatsDeferred = async { getAssetPrice(networkType, AssetPriceRequest.createForYesterday()) }
updateAssetRates(account, currentPriceStatsDeferred.await(), yesterdayPriceStatsDeferred.await())
}
override fun assetFlow(account: WalletAccount, type: Token.Type): Flow<Asset> {
return assetCache.observeAsset(account.address, mapTokenTypeToTokenTypeLocal(type))
.map { mapAssetLocalToAsset(it) }
}
override suspend fun getAsset(account: WalletAccount, type: Token.Type): Asset? {
val assetLocal = assetCache.getAsset(account.address, mapTokenTypeToTokenTypeLocal(type))
return assetLocal?.let(::mapAssetLocalToAsset)
}
override suspend fun syncAsset(account: WalletAccount, type: Token.Type) {
return syncAssetsRates(account)
}
override fun transactionsFirstPageFlow(currentAccount: WalletAccount, pageSize: Int, accounts: List<WalletAccount>): Flow<List<Transaction>> {
return observeTransactions(currentAccount, accounts)
}
override suspend fun syncTransactionsFirstPage(pageSize: Int, account: WalletAccount, accounts: List<WalletAccount>) {
val page = getTransactionPage(pageSize, 0, account, accounts)
val accountAddress = account.address
val toInsertLocally = page.map {
mapTransactionToTransactionLocal(it, accountAddress, TransactionLocal.Source.SUBSCAN)
}
transactionsDao.insertFromSubScan(accountAddress, toInsertLocally)
}
override suspend fun getTransactionPage(pageSize: Int, page: Int, currentAccount: WalletAccount, accounts: List<WalletAccount>): List<Transaction> {
return withContext(Dispatchers.Default) {
val subDomain = subDomainFor(currentAccount.network.type)
val request = TransactionHistoryRequest(currentAccount.address, pageSize, page)
val response = apiCall { subscanApi.getTransactionHistory(subDomain, request) }
val transfers = response.content?.transfers
val accountsByAddress = accounts.associateBy { it.address }
val transactions = transfers?.map {
val accountName = defineAccountNameForTransaction(accountsByAddress, currentAccount.address, it.from, it.to)
mapTransferToTransaction(it, currentAccount, accountName)
}
transactions ?: getCachedTransactions(page, currentAccount, accounts)
}
}
override suspend fun getContacts(account: WalletAccount, query: String): Set<String> {
return transactionsDao.getContacts(query, account.address).toSet()
}
override suspend fun getTransferFee(account: WalletAccount, transfer: Transfer): Fee {
val feeRemote = substrateSource.getTransferFee(account, transfer)
return mapFeeRemoteToFee(feeRemote, transfer)
}
override suspend fun performTransfer(account: WalletAccount, signingData: SigningData, transfer: Transfer, fee: BigDecimal) {
val keypair = mapSigningDataToKeypair(signingData)
val transactionHash = substrateSource.performTransfer(account, transfer, keypair)
val transaction = createTransaction(transactionHash, transfer, account.address, fee)
val transactionLocal = mapTransactionToTransactionLocal(transaction, account.address, TransactionLocal.Source.APP)
transactionsDao.insert(transactionLocal)
}
override suspend fun checkTransferValidity(account: WalletAccount, transfer: Transfer): TransferValidityStatus {
val feeResponse = getTransferFee(account, transfer)
val tokenType = transfer.tokenType
val recipientInfo = substrateSource.fetchAccountInfo(transfer.recipient, account.network.type)
val totalRecipientBalanceInPlanks = recipientInfo.totalBalanceInPlanks()
val totalRecipientBalance = tokenType.amountFromPlanks(totalRecipientBalanceInPlanks)
val assetLocal = assetCache.getAsset(account.address, mapTokenTypeToTokenTypeLocal(transfer.tokenType))!!
val asset = mapAssetLocalToAsset(assetLocal)
return transfer.validityStatus(asset.transferable, asset.total, feeResponse.feeAmount, totalRecipientBalance)
}
override suspend fun updatePhishingAddresses() = withContext(Dispatchers.Default) {
val publicKeys = phishingApi.getPhishingAddresses().values.flatten()
.map { it.toAccountId().toHexString(withPrefix = true) }
val phishingAddressesLocal = publicKeys.map(::PhishingAddressLocal)
phishingAddressDao.clearTable()
phishingAddressDao.insert(phishingAddressesLocal)
}
override suspend fun isAddressFromPhishingList(address: String) = withContext(Dispatchers.Default) {
val phishingAddresses = phishingAddressDao.getAllAddresses()
val addressPublicKey = address.toAccountId().toHexString(withPrefix = true)
phishingAddresses.contains(addressPublicKey)
}
private fun defineAccountNameForTransaction(
accountsByAddress: Map<String, WalletAccount>,
transactionAccountAddress: String,
recipientAddress: String,
senderAddress: String
): String? {
val accountAddress = if (transactionAccountAddress == recipientAddress) {
senderAddress
} else {
recipientAddress
}
return accountsByAddress[accountAddress]?.name
}
private fun createTransaction(hash: String, transfer: Transfer, senderAddress: String, fee: BigDecimal) =
Transaction(
hash = hash,
tokenType = transfer.tokenType,
senderAddress = senderAddress,
recipientAddress = transfer.recipient,
amount = transfer.amount,
date = System.currentTimeMillis(),
isIncome = false,
fee = fee,
status = Transaction.Status.PENDING,
accountName = null
)
private suspend fun getCachedTransactions(page: Int, currentAccount: WalletAccount, accounts: List<WalletAccount>): List<Transaction> {
return if (page == 0) {
val accountsByAddress = accounts.associateBy { it.address }
transactionsDao.getTransactions(currentAccount.address)
.map {
val accountName = defineAccountNameForTransaction(accountsByAddress, it.accountAddress, it.recipientAddress, it.senderAddress)
mapTransactionLocalToTransaction(it, accountName)
}
} else {
emptyList()
}
}
private suspend fun updateAssetRates(
account: WalletAccount,
todayResponse: SubscanResponse<AssetPriceStatistics>?,
yesterdayResponse: SubscanResponse<AssetPriceStatistics>?
) = assetCache.updateToken(account.address.networkType()) { cached ->
val todayStats = todayResponse?.content
val yesterdayStats = yesterdayResponse?.content
var mostRecentPrice = todayStats?.price
if (mostRecentPrice == null) {
mostRecentPrice = cached.dollarRate
}
val change = todayStats?.calculateRateChange(yesterdayStats)
cached.copy(
dollarRate = mostRecentPrice,
recentRateChange = change
)
}
private fun observeTransactions(currentAccount: WalletAccount, accounts: List<WalletAccount>): Flow<List<Transaction>> {
return transactionsDao.observeTransactions(currentAccount.address)
.map {
val accountsByAddress = accounts.associateBy { it.address }
it.map {
val accountName = defineAccountNameForTransaction(accountsByAddress, it.accountAddress, it.recipientAddress, it.senderAddress)
mapTransactionLocalToTransaction(it, accountName)
}
}
}
private suspend fun getAssetPrice(networkType: Node.NetworkType, request: AssetPriceRequest): SubscanResponse<AssetPriceStatistics> {
return try {
apiCall { subscanApi.getAssetPrice(subDomainFor(networkType), request) }
} catch (_: Exception) {
SubscanResponse.createEmptyResponse()
}
}
private fun subDomainFor(networkType: Node.NetworkType): String {
return networkType.readableName.toLowerCase(Locale.ROOT)
}
private suspend fun <T> apiCall(block: suspend () -> T): T = httpExceptionHandler.wrap(block)
} | 0 | null | 0 | 0 | fbbe4a87199a2ff6a1590fc22f8f67972aa18c2f | 12,063 | fearless-Android | Apache License 2.0 |
app/src/main/java/io/horizontalsystems/bankwallet/modules/addtoken/AddTokenService.kt | fahimaltinordu | 312,207,740 | false | null | package io.horizontalsystems.bankwallet.modules.addtoken
import io.horizontalsystems.bankwallet.core.IAccountManager
import io.horizontalsystems.bankwallet.core.IAddTokenBlockchainService
import io.horizontalsystems.bankwallet.core.ICoinManager
import io.horizontalsystems.bankwallet.core.IWalletManager
import io.horizontalsystems.bankwallet.entities.Wallet
import io.reactivex.Observable
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import io.reactivex.subjects.PublishSubject
class AddTokenService(
private val coinManager: ICoinManager,
private val blockchainService: IAddTokenBlockchainService,
private val walletManager: IWalletManager,
private val accountManager: IAccountManager) {
private val stateSubject = PublishSubject.create<AddTokenModule.State>()
private var disposable: Disposable? = null
val stateObservable: Observable<AddTokenModule.State> = stateSubject
var state: AddTokenModule.State = AddTokenModule.State.Idle
private set(value) {
field = value
stateSubject.onNext(value)
}
fun set(reference: String?) {
disposable?.dispose()
val reference = if (reference.isNullOrEmpty()) {
state = AddTokenModule.State.Idle
return
} else {
reference
}
try {
blockchainService.validate(reference)
} catch (e: Exception) {
state = AddTokenModule.State.Failed(e)
return
}
blockchainService.existingCoin(reference, coinManager.coins)?.let {
state = AddTokenModule.State.AlreadyExists(it)
return
}
state = AddTokenModule.State.Loading
disposable = blockchainService.coinSingle(reference)
.subscribeOn(Schedulers.io())
.subscribe({ coin ->
state = AddTokenModule.State.Fetched(coin)
}, { error ->
state = AddTokenModule.State.Failed(error)
})
}
fun save() {
val coin = (state as? AddTokenModule.State.Fetched)?.coin ?: return
coinManager.save(coin)
val account = accountManager.account(coin.type) ?: return
val wallet = Wallet(coin, account)
walletManager.save(listOf(wallet))
}
fun onCleared() {
disposable?.dispose()
}
}
| 1 | null | 2 | 4 | d3094c4afaa92a5d63ce53583bc07c8fb343f90b | 2,432 | WILC-wallet-android | MIT License |
checks/src/main/kotlin/com/zhenai/lib/checks/utils/FunctionUtils.kt | dengqu | 202,319,834 | false | {"Roff": 9456617, "Java": 249902, "Kotlin": 173095, "Assembly": 12227, "FreeMarker": 729} | package com.zhenai.lib.checks.utils
import com.zhenai.lib.core.slang.api.FunctionDeclarationTree
import com.zhenai.lib.core.slang.api.ModifierTree
import com.zhenai.lib.core.slang.api.ModifierTree.Kind.OVERRIDE
import com.zhenai.lib.core.slang.api.ModifierTree.Kind.PRIVATE
class FunctionUtils {
companion object {
fun isPrivateMethod(method: FunctionDeclarationTree): Boolean {
return hasModifierMethod(method, PRIVATE)
}
fun isOverrideMethod(method: FunctionDeclarationTree): Boolean {
return hasModifierMethod(method, OVERRIDE)
}
fun hasModifierMethod(method: FunctionDeclarationTree, kind: ModifierTree.Kind): Boolean {
return method.modifiers().stream()
.filter { ModifierTree::class.java.isInstance(it) }
.map {
ModifierTree::class.java.cast(it)
}
.anyMatch { modifier -> modifier.kind() == kind }
}
}
} | 0 | Roff | 1 | 5 | c564aad5211bd45da11ab81f0b32fd31c0ed9ea3 | 990 | KotlinLintPlugin | Apache License 2.0 |
intellij-plugin/Edu-Python/src/com/jetbrains/edu/python/learning/PyNewConfigurator.kt | JetBrains | 43,696,115 | false | null | package com.jetbrains.edu.python.learning
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.PlatformUtils
import com.jetbrains.edu.learning.checker.TaskCheckerProvider
import com.jetbrains.edu.learning.compatibility.isDataSpellSupported
import com.jetbrains.edu.learning.configuration.EduConfigurator
import com.jetbrains.edu.learning.courseFormat.Course
import com.jetbrains.edu.python.learning.PyConfigurator.Companion.TASK_PY
import com.jetbrains.edu.python.learning.checker.PyNewTaskCheckerProvider
import com.jetbrains.edu.python.learning.newproject.PyProjectSettings
import icons.PythonIcons
import javax.swing.Icon
class PyNewConfigurator : EduConfigurator<PyProjectSettings> {
override val courseBuilder: PyNewCourseBuilder
get() = PyNewCourseBuilder()
override val testFileName: String
get() = TEST_FILE_NAME
override fun getMockFileName(course: Course, text: String): String = TASK_PY
override val testDirs: List<String>
get() = listOf(TEST_FOLDER)
override fun excludeFromArchive(project: Project, course: Course, file: VirtualFile): Boolean =
super.excludeFromArchive(project, course, file) || excludeFromArchive(file)
override val taskCheckerProvider: TaskCheckerProvider
get() = PyNewTaskCheckerProvider()
override val logo: Icon
get() = PythonIcons.Python.Python
override val defaultPlaceholderText: String
get() = "# TODO"
// BACKCOMPAT: 2023.2
override val isEnabled: Boolean
get() = if (PlatformUtils.isDataSpell()) isDataSpellSupported else super.isEnabled
companion object {
const val TEST_FILE_NAME = "test_task.py"
const val TEST_FOLDER = "tests"
}
}
| 6 | null | 48 | 135 | b00e7100e8658a07e79700a20ffe576872d494db | 1,711 | educational-plugin | Apache License 2.0 |
scanner_cli/src/test/kotlin/org/archguard/scanner/ctl/loader/AnalyserDispatcherTest.kt | archguard | 460,910,110 | false | {"Kotlin": 1763628, "Java": 611399, "TypeScript": 11395, "C#": 5593, "Dockerfile": 2549, "C": 1223, "Shell": 926, "JavaScript": 400, "Go": 291, "Scala": 97, "Python": 42, "Rust": 32} | package org.archguard.scanner.ctl.loader
import chapi.domain.core.CodeDataStruct
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.mockk
import io.mockk.mockkObject
import org.archguard.scanner.core.Analyser
import org.archguard.scanner.core.context.AnalyserType
import org.archguard.scanner.core.context.Context
import org.archguard.scanner.core.sourcecode.SourceCodeAnalyser
import org.archguard.scanner.ctl.command.ScannerCommand
import org.archguard.scanner.ctl.impl.CliSourceCodeContext
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
internal class AnalyserDispatcherTest {
@BeforeEach
internal fun setUp() {
mockkObject(AnalyserLoader)
}
@AfterEach
internal fun tearDown() {
clearAllMocks()
}
@Nested
inner class ForSourceCodeContext {
private val languageAnalyser = mockk<SourceCodeAnalyser>()
private val feature1Analyser = mockk<SourceCodeAnalyser>()
private val feature2Analyser = mockk<SourceCodeAnalyser>()
private val context = mockk<CliSourceCodeContext>()
private val command = mockk<ScannerCommand>()
private fun stubCommand() {
every { command.type } returns AnalyserType.SOURCE_CODE
every { command.path } returns "."
every { command.language } returns "kotlin"
every { command.features } returns listOf("feature1", "feature2")
every { command.buildClient() } returns mockk()
every { command.getAnalyserSpec(any()) } returns mockk()
}
private fun stubContext() {
every { context.language } returns "kotlin"
every { context.features } returns listOf("feature1", "feature2")
}
private fun stubLoad() {
every {
AnalyserLoader.load(any(), any())
} returns (languageAnalyser as Analyser<Context>) andThen (feature1Analyser as Analyser<Context>) andThen (feature2Analyser as Analyser<Context>)
}
private fun mockAnalysers() {
val ast = mockk<List<CodeDataStruct>>()
every { languageAnalyser.analyse(null) } returns ast
every { feature1Analyser.analyse(ast) } returns null
every { feature2Analyser.analyse(ast) } returns null
}
@Test
fun `should dispatch to the source code analyser, pass the ast to following feature analyser`() {
stubCommand()
stubContext()
stubLoad()
mockAnalysers()
AnalyserDispatcher().dispatch(command)
}
}
}
| 6 | Kotlin | 89 | 575 | 049f3cc8f2c0e2c34e65bb0049f645caa5be9bf8 | 2,697 | archguard | MIT License |
libs/ledger/ledger-consensual-data/src/main/kotlin/net/corda/ledger/consensual/data/transaction/ConsensualComponentGroup.kt | corda | 346,070,752 | false | null | package net.corda.ledger.consensual.data.transaction
/**
* Specifies Consensual transaction component groups' enum.
* For which each property corresponds to a transaction component group.
* The position in the enum class declaration (ordinal) is used for component-leaf ordering when computing the
* Merkle tree.
*
* @property METADATA The metadata parameters component group. Ordinal = 0. (It needs to be in the first position.)
* @property TIMESTAMP The timestamp parameter component group. Ordinal = 1.
* @property SIGNATORIES The required signing keys component group. Ordinal = 2.
* @property OUTPUT_STATES The output states component group. Ordinal = 3.
* @property OUTPUT_STATE_TYPES The output state types component group. Ordinal = 4.
*/
enum class ConsensualComponentGroup {
METADATA, // needs to be in sync with
// [net.corda.ledger.common.impl.transaction.WireTransactionImplKt.ALL_LEDGER_METADATA_COMPONENT_GROUP_ID]
TIMESTAMP,
SIGNATORIES,
OUTPUT_STATES,
OUTPUT_STATE_TYPES
} | 71 | Kotlin | 9 | 28 | fa43ea7a49afb8ed2d1686a6e847c8a02d376f85 | 1,036 | corda-runtime-os | Apache License 2.0 |
libs/ledger/ledger-consensual-data/src/main/kotlin/net/corda/ledger/consensual/data/transaction/ConsensualComponentGroup.kt | corda | 346,070,752 | false | null | package net.corda.ledger.consensual.data.transaction
/**
* Specifies Consensual transaction component groups' enum.
* For which each property corresponds to a transaction component group.
* The position in the enum class declaration (ordinal) is used for component-leaf ordering when computing the
* Merkle tree.
*
* @property METADATA The metadata parameters component group. Ordinal = 0. (It needs to be in the first position.)
* @property TIMESTAMP The timestamp parameter component group. Ordinal = 1.
* @property SIGNATORIES The required signing keys component group. Ordinal = 2.
* @property OUTPUT_STATES The output states component group. Ordinal = 3.
* @property OUTPUT_STATE_TYPES The output state types component group. Ordinal = 4.
*/
enum class ConsensualComponentGroup {
METADATA, // needs to be in sync with
// [net.corda.ledger.common.impl.transaction.WireTransactionImplKt.ALL_LEDGER_METADATA_COMPONENT_GROUP_ID]
TIMESTAMP,
SIGNATORIES,
OUTPUT_STATES,
OUTPUT_STATE_TYPES
} | 71 | Kotlin | 9 | 28 | fa43ea7a49afb8ed2d1686a6e847c8a02d376f85 | 1,036 | corda-runtime-os | Apache License 2.0 |
src/main/kotlin/no/nav/personbruker/dittnav/metrics/periodic/reporter/metrics/db/count/DbCountingMetricsProbe.kt | navikt | 275,789,479 | false | null | package no.nav.personbruker.dittnav.metrics.periodic.reporter.metrics.db.count
import no.nav.personbruker.dittnav.metrics.periodic.reporter.config.EventType
import org.slf4j.LoggerFactory
class DbCountingMetricsProbe {
private val log = LoggerFactory.getLogger(DbCountingMetricsProbe::class.java)
suspend fun runWithMetrics(eventType: EventType, block: suspend DbCountingMetricsSession.() -> Unit): DbCountingMetricsSession {
val session = DbCountingMetricsSession(eventType)
block.invoke(session)
session.calculateProcessingTime()
return session
}
}
| 0 | Kotlin | 0 | 0 | 2efab6c0115dacb23a872666d374e7aecd524d38 | 600 | dittnav-periodic-metrics-reporter | MIT License |
app/src/main/java/com/token/tokenator/model/Type.kt | JoshLudahl | 324,939,046 | false | null | package com.token.tokenator.model
enum class Type {
LOWERCASE,
NUMERIC,
SPECIAL,
UPPERCASE
}
| 9 | null | 1 | 1 | cadd5ac767df666e96de2694cce76c778e316682 | 110 | Tokenator | FSF All Permissive License |
es-notebooks/src/main/kotlin/com/amazon/opendistroforelasticsearch/notebooks/model/UpdateNotebookResponse.kt | opendistro-for-elasticsearch | 164,948,871 | false | null | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
/*
* Copyright 2020 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://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*
*/
package com.amazon.opendistroforelasticsearch.notebooks.model
import com.amazon.opendistroforelasticsearch.notebooks.NotebooksPlugin.Companion.LOG_PREFIX
import com.amazon.opendistroforelasticsearch.notebooks.model.RestTag.NOTEBOOK_ID_FIELD
import com.amazon.opendistroforelasticsearch.notebooks.util.logger
import org.opensearch.action.ActionRequest
import org.opensearch.action.ActionRequestValidationException
import org.opensearch.common.io.stream.StreamInput
import org.opensearch.common.io.stream.StreamOutput
import org.opensearch.common.xcontent.ToXContent
import org.opensearch.common.xcontent.ToXContentObject
import org.opensearch.common.xcontent.XContentBuilder
import org.opensearch.common.xcontent.XContentFactory
import org.opensearch.common.xcontent.XContentParser
import org.opensearch.common.xcontent.XContentParser.Token
import org.opensearch.common.xcontent.XContentParserUtils
import java.io.IOException
/**
* Notebook-get request.
* notebookId is from request query params
* <pre> JSON format
* {@code
* {
* "notebookId":"notebookId"
* }
* }</pre>
*/
internal class GetNotebookRequest(
val notebookId: String
) : ActionRequest(), ToXContentObject {
@Throws(IOException::class)
constructor(input: StreamInput) : this(
notebookId = input.readString()
)
companion object {
private val log by logger(GetNotebookRequest::class.java)
/**
* Parse the data from parser and create [GetNotebookRequest] object
* @param parser data referenced at parser
* @param useNotebookId use this id if not available in the json
* @return created [GetNotebookRequest] object
*/
fun parse(parser: XContentParser, useNotebookId: String? = null): GetNotebookRequest {
var notebookId: String? = useNotebookId
XContentParserUtils.ensureExpectedToken(Token.START_OBJECT, parser.currentToken(), parser)
while (Token.END_OBJECT != parser.nextToken()) {
val fieldName = parser.currentName()
parser.nextToken()
when (fieldName) {
NOTEBOOK_ID_FIELD -> notebookId = parser.text()
else -> {
parser.skipChildren()
log.info("$LOG_PREFIX:Skipping Unknown field $fieldName")
}
}
}
notebookId ?: throw IllegalArgumentException("$NOTEBOOK_ID_FIELD field absent")
return GetNotebookRequest(notebookId)
}
}
/**
* {@inheritDoc}
*/
@Throws(IOException::class)
override fun writeTo(output: StreamOutput) {
output.writeString(notebookId)
}
/**
* create XContentBuilder from this object using [XContentFactory.jsonBuilder()]
* @param params XContent parameters
* @return created XContentBuilder object
*/
fun toXContent(params: ToXContent.Params = ToXContent.EMPTY_PARAMS): XContentBuilder? {
return toXContent(XContentFactory.jsonBuilder(), params)
}
/**
* {@inheritDoc}
*/
override fun toXContent(builder: XContentBuilder?, params: ToXContent.Params?): XContentBuilder {
return builder!!.startObject()
.field(NOTEBOOK_ID_FIELD, notebookId)
.endObject()
}
/**
* {@inheritDoc}
*/
override fun validate(): ActionRequestValidationException? {
return null
}
}
| 6 | TypeScript | 11 | 23 | 089261766971bbaa3bcf58bc7109928d124d67f3 | 4,350 | kibana-notebooks | Apache License 2.0 |
app/src/main/java/com/example/sensebox/data/database/BoxDao.kt | cayas-software | 705,603,273 | false | {"Kotlin": 80773} | package com.example.sensebox.data.database
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.example.sensebox.data.model.Box
import com.example.sensebox.data.model.FavBox
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
@Dao
interface BoxDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun addItem(box: FavBox)
@Query("DELETE FROM favBoxes")
suspend fun deleteAllItems()
@Query("DELETE FROM favBoxes WHERE id = :id ")
suspend fun deleteItem(id: String)
@Query("SELECT * FROM favBoxes")
fun getAllItems() : Flow<List<FavBox>>
@Query("SELECT * FROM favBoxes WHERE id = :id ")
fun getItem(id: String) : Flow<FavBox?>
} | 0 | Kotlin | 0 | 0 | de5a518c86cc86f9c96c243b4955fa0110d810c6 | 814 | SenseBoxCompose | Apache License 2.0 |
library/src/main/kotlin/io/github/tomplum/libs/input/types/LongInput.kt | TomPlum | 317,517,927 | false | {"Kotlin": 161096} | package io.github.tomplum.libs.input.types
import io.github.tomplum.libs.input.InputReader
/**
* A [Long] input wrapper returned by [InputReader].
*/
class LongInput(input: List<String>) : Input<Long>(input.map { it.toLong() }) | 1 | Kotlin | 0 | 0 | 32ec1c13ee874f5b2c3893547bc9adf3d8f81cd5 | 231 | advent-of-code-libs | Apache License 2.0 |
kotlin/kotlin-dbms/src/test/kotlin/com/hypo/driven/simpledb/file/FileTest.kt | kackey0-1 | 542,333,436 | false | null | package com.hypo.driven.simpledb.file
import java.io.File
import java.io.IOException
import java.io.RandomAccessFile
import kotlin.test.Test
class FileTest {
@Test
fun `test_file_manager`() {
val fileManager = FileManager(File("filetest"), 400)
val block = BlockId("testfile", 2)
val page1 = Page(fileManager.blockSize)
val position1 = 88
page1.setString(position1, "abcdefghijklm")
val size = Page.maxLength("abcdefghijklm".length)
val position2 = position1 + size
page1.setInt(position2, 345)
fileManager.write(block, page1)
val p2 = Page(fileManager.blockSize)
fileManager.read(block, p2);
println("offset " + position2 + " contains " + p2.getInt(position2))
println("offset " + position1 + " contains " + p2.getInt(position1))
}
@Test
fun testRandomAccessFile() {
val file = File("testfile")
try {
// initialize the file
val f1 = RandomAccessFile(file, "rws")
f1.seek(123)
f1.writeInt(999)
f1.close()
// increment the file
val f2 = RandomAccessFile(file, "rws")
f2.seek(123)
val n = f2.readInt()
f2.seek(123)
f2.writeInt(n + 1)
f2.close()
// re-read the file
val f3 = RandomAccessFile(file, "rws")
f3.seek(123)
println("The new value is " + f3.readInt())
f3.close()
} catch (e: IOException) {
e.printStackTrace()
}
}
} | 3 | Kotlin | 0 | 0 | d9dffb6a17f624ea0dec86434906fa58be98970b | 1,606 | from-scrach | Apache License 2.0 |
tmp/arrays/youTrackTests/4186.kt | DaniilStepanov | 228,623,440 | false | {"Git Config": 1, "Gradle": 6, "Text": 3, "INI": 5, "Shell": 2, "Ignore List": 3, "Batchfile": 2, "Markdown": 2, "Kotlin": 15942, "JavaScript": 4, "ANTLR": 2, "XML": 12, "Java": 4} | // Original bug: KT-36279
fun <T> allConditionalPredicates(subject: T, conditionalPredicates: Map<() -> Boolean, (T) -> Boolean>) =
conditionalPredicates
.filter { it.key() }
.all { it.value(subject) }
| 1 | null | 12 | 1 | 602285ec60b01eee473dcb0b08ce497b1c254983 | 224 | bbfgradle | Apache License 2.0 |
components/ledger/ledger-utxo-flow/src/test/kotlin/net/corda/ledger/utxo/impl/token/selection/factories/TokenBalanceQueryExternalEventFactoryTest.kt | corda | 346,070,752 | false | {"Kotlin": 20585419, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244} | package net.corda.ledger.utxo.token.selection.impl.factories
import net.corda.data.KeyValuePairList
import net.corda.data.flow.event.external.ExternalEventContext
import net.corda.data.ledger.utxo.token.selection.data.TokenAmount
import net.corda.data.ledger.utxo.token.selection.data.TokenBalanceQuery
import net.corda.data.ledger.utxo.token.selection.data.TokenBalanceQueryResult
import net.corda.data.ledger.utxo.token.selection.event.TokenPoolCacheEvent
import net.corda.data.ledger.utxo.token.selection.key.TokenPoolCacheKey
import net.corda.flow.external.events.factory.ExternalEventRecord
import net.corda.flow.state.FlowCheckpoint
import net.corda.ledger.utxo.impl.token.selection.factories.TokenBalanceQueryExternalEventFactory
import net.corda.ledger.utxo.impl.token.selection.impl.ALICE_X500_HOLDING_ID
import net.corda.ledger.utxo.impl.token.selection.impl.BOB_X500_NAME
import net.corda.ledger.utxo.impl.token.selection.impl.TokenBalanceImpl
import net.corda.ledger.utxo.impl.token.selection.impl.toSecureHash
import net.corda.schema.Schemas.Services.TOKEN_CACHE_EVENT
import net.corda.v5.ledger.utxo.token.selection.TokenBalanceCriteria
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import java.math.BigDecimal
import java.nio.ByteBuffer
class TokenBalanceQueryExternalEventFactoryTest {
private val tokenType = "tt"
private val symbol = "s"
private val issuerHash = "issuer".toSecureHash()
private val notaryX500Name = BOB_X500_NAME
private val key = TokenPoolCacheKey.newBuilder()
.setShortHolderId(ALICE_X500_HOLDING_ID.shortHash.value)
.setTokenType(tokenType)
.setIssuerHash(issuerHash.toString())
.setNotaryX500Name(notaryX500Name.toString())
.setSymbol(symbol)
.build()
private val checkpoint = mock<FlowCheckpoint>().apply {
whenever(holdingIdentity).thenReturn(ALICE_X500_HOLDING_ID)
}
@Test
fun `createExternalEvent should return balance query event record`() {
val flowExternalEventContext = ExternalEventContext("r1", "f1", KeyValuePairList())
val parameters = TokenBalanceCriteria(tokenType, issuerHash, notaryX500Name, symbol)
val expectedBalanceQuery = TokenBalanceQuery().apply {
this.poolKey = key
this.requestContext = flowExternalEventContext
}
val expectedExternalEventRecord = ExternalEventRecord(
TOKEN_CACHE_EVENT,
key,
TokenPoolCacheEvent(key, expectedBalanceQuery)
)
val result = TokenBalanceQueryExternalEventFactory().createExternalEvent(
checkpoint,
flowExternalEventContext,
parameters
)
assertThat(result).isEqualTo(expectedExternalEventRecord)
}
@Test
fun `resumeWith returns the balance of the token pool`() {
val expectedTokenBalance = TokenBalanceImpl(BigDecimal(1.0), BigDecimal(2.0))
val response = TokenBalanceQueryResult().apply {
this.poolKey = key
this.availableBalance = expectedTokenBalance.availableBalance.toTokenAmount()
this.totalBalance = expectedTokenBalance.totalBalance.toTokenAmount()
}
val result = TokenBalanceQueryExternalEventFactory().resumeWith(checkpoint, response)
assertThat(result.availableBalance).isEqualTo(expectedTokenBalance.availableBalance)
assertThat(result.totalBalance).isEqualTo(expectedTokenBalance.totalBalance)
}
private fun BigDecimal.toTokenAmount() = TokenAmount.newBuilder()
.setScale(scale())
.setUnscaledValue(ByteBuffer.wrap(unscaledValue().toByteArray()))
.build()
}
| 110 | Kotlin | 27 | 69 | d478e119ab288af663910f9a2df42a7a7b9f5bce | 3,770 | corda-runtime-os | Apache License 2.0 |
test/src/me/anno/tests/engine/ui/Crash.kt | AntonioNoack | 456,513,348 | false | {"Kotlin": 9748753, "C": 236481, "GLSL": 9454, "Java": 6888, "Lua": 4404} | package me.anno.tests.engine.ui
import me.anno.config.DefaultConfig.style
import me.anno.engine.ui.render.PlayMode
import me.anno.engine.ui.render.RenderView1
import me.anno.gpu.GFX
import me.anno.mesh.Shapes.flatCube
import me.anno.studio.StudioBase
import me.anno.ui.Window
fun main() {
// this printed lots of errors and wasn't tonemapping correctly
object : StudioBase("Crashing", 1, false) {
override fun createUI() {
val renderView = RenderView1(PlayMode.PLAYING, flatCube.front, style)
val windowStack = GFX.someWindow.windowStack
val window = Window(renderView, false, windowStack)
window.drawDirectly = true
windowStack.add(window)
}
}.run()
} | 0 | Kotlin | 3 | 17 | bca49870309dc54c57daba1888c8faa2a3165025 | 742 | RemsEngine | Apache License 2.0 |
core/kotlin/app/src/test/kotlin/com/vxlisp/vx/data/CsvTest.kt | Vyridian | 622,934,367 | false | {"HTML": 13334653, "C++": 7610480, "Kotlin": 5373772, "C#": 5371384, "Java": 5262028, "JavaScript": 2000275, "Go": 787342, "Batchfile": 6051, "Makefile": 2191, "Shell": 1934} |
package com.vxlisp.vx.data
import com.vxlisp.vx.*
object vx_data_csvTest {
fun f_textblock_csv_from_string(context : vx_core.Type_context) : vx_test.Type_testcase {
var output : vx_test.Type_testcase = vx_core.vx_new(
vx_test.t_testcase,
":passfail", false,
":testpkg", "vx/data/csv",
":casename", "textblock-csv<-string",
":describelist",
vx_core.vx_new(
vx_test.t_testdescribelist,
f_textblock_csv_from_string_testdescribe_1(context)
)
)
return output
}
fun f_textblock_csv_from_string_testdescribe_1(context : vx_core.Type_context) : vx_test.Type_testdescribe {
var output : vx_test.Type_testdescribe = vx_core.vx_new(
vx_test.t_testdescribe,
":describename", "(test\n (tb/textblock\n :text\n`\"a\",\"b\"\n1,\"2\"`\n :startpos 1\n :endpos 13\n :children\n (tb/textblocklist\n (tb/textblock\n :text `\"a\"`\n :startpos 1\n :endpos 3\n :delim\n (copy tb/delimquote\n :pos 0)\n :children\n (tb/textblocklist\n (tb/textblock\n :text \"a\"\n :startpos 2\n :endpos 2)))\n (tb/textblock\n :text \",\"\n :startpos 4\n :endpos 4\n :delim\n (copy tb/delimcomma\n :pos 0))\n (tb/textblock\n :text `\"b\"`\n :startpos 5\n :endpos 7\n :delim\n (copy tb/delimquote\n :pos 0)\n :children\n (tb/textblocklist\n (tb/textblock\n :text \"b\"\n :startpos 6\n :endpos 6)))\n (tb/textblock\n :text \"\n\"\n :startpos 8\n :endpos 8\n :delim\n (copy tb/delimline\n :pos 0))\n (tb/textblock\n :text \"1\"\n :startpos 9\n :endpos 9)\n (tb/textblock\n :text \",\"\n :startpos 10\n :endpos 10\n :delim\n (copy tb/delimcomma\n :pos 0))\n (tb/textblock\n :text `\"2\"`\n :startpos 11\n :endpos 13\n :delim\n (copy tb/delimquote\n :pos 0)\n :children\n (tb/textblocklist\n (tb/textblock\n :text \"2\"\n :startpos 12\n :endpos 12)))))\n (textblock-csv<-string\n `\"a\",\"b\"\n1,\"2\"`))",
":testresult", vx_test.f_test(
context,
vx_core.f_new(
vx_data_textblock.t_textblock,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":text"),
vx_core.vx_new_string("\"a\",\"b\"\n1,\"2\""),
vx_core.vx_new_string(":startpos"),
vx_core.vx_new_int(1),
vx_core.vx_new_string(":endpos"),
vx_core.vx_new_int(13),
vx_core.vx_new_string(":children"),
vx_core.f_new(
vx_data_textblock.t_textblocklist,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.f_new(
vx_data_textblock.t_textblock,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":text"),
vx_core.vx_new_string("\"a\""),
vx_core.vx_new_string(":startpos"),
vx_core.vx_new_int(1),
vx_core.vx_new_string(":endpos"),
vx_core.vx_new_int(3),
vx_core.vx_new_string(":delim"),
vx_core.f_copy(
vx_data_textblock.c_delimquote,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":pos"),
vx_core.vx_new_int(0)
)
),
vx_core.vx_new_string(":children"),
vx_core.f_new(
vx_data_textblock.t_textblocklist,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.f_new(
vx_data_textblock.t_textblock,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":text"),
vx_core.vx_new_string("a"),
vx_core.vx_new_string(":startpos"),
vx_core.vx_new_int(2),
vx_core.vx_new_string(":endpos"),
vx_core.vx_new_int(2)
)
)
)
)
)
),
vx_core.f_new(
vx_data_textblock.t_textblock,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":text"),
vx_core.vx_new_string(","),
vx_core.vx_new_string(":startpos"),
vx_core.vx_new_int(4),
vx_core.vx_new_string(":endpos"),
vx_core.vx_new_int(4),
vx_core.vx_new_string(":delim"),
vx_core.f_copy(
vx_data_textblock.c_delimcomma,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":pos"),
vx_core.vx_new_int(0)
)
)
)
),
vx_core.f_new(
vx_data_textblock.t_textblock,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":text"),
vx_core.vx_new_string("\"b\""),
vx_core.vx_new_string(":startpos"),
vx_core.vx_new_int(5),
vx_core.vx_new_string(":endpos"),
vx_core.vx_new_int(7),
vx_core.vx_new_string(":delim"),
vx_core.f_copy(
vx_data_textblock.c_delimquote,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":pos"),
vx_core.vx_new_int(0)
)
),
vx_core.vx_new_string(":children"),
vx_core.f_new(
vx_data_textblock.t_textblocklist,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.f_new(
vx_data_textblock.t_textblock,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":text"),
vx_core.vx_new_string("b"),
vx_core.vx_new_string(":startpos"),
vx_core.vx_new_int(6),
vx_core.vx_new_string(":endpos"),
vx_core.vx_new_int(6)
)
)
)
)
)
),
vx_core.f_new(
vx_data_textblock.t_textblock,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":text"),
vx_core.vx_new_string("\n"),
vx_core.vx_new_string(":startpos"),
vx_core.vx_new_int(8),
vx_core.vx_new_string(":endpos"),
vx_core.vx_new_int(8),
vx_core.vx_new_string(":delim"),
vx_core.f_copy(
vx_data_textblock.c_delimline,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":pos"),
vx_core.vx_new_int(0)
)
)
)
),
vx_core.f_new(
vx_data_textblock.t_textblock,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":text"),
vx_core.vx_new_string("1"),
vx_core.vx_new_string(":startpos"),
vx_core.vx_new_int(9),
vx_core.vx_new_string(":endpos"),
vx_core.vx_new_int(9)
)
),
vx_core.f_new(
vx_data_textblock.t_textblock,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":text"),
vx_core.vx_new_string(","),
vx_core.vx_new_string(":startpos"),
vx_core.vx_new_int(10),
vx_core.vx_new_string(":endpos"),
vx_core.vx_new_int(10),
vx_core.vx_new_string(":delim"),
vx_core.f_copy(
vx_data_textblock.c_delimcomma,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":pos"),
vx_core.vx_new_int(0)
)
)
)
),
vx_core.f_new(
vx_data_textblock.t_textblock,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":text"),
vx_core.vx_new_string("\"2\""),
vx_core.vx_new_string(":startpos"),
vx_core.vx_new_int(11),
vx_core.vx_new_string(":endpos"),
vx_core.vx_new_int(13),
vx_core.vx_new_string(":delim"),
vx_core.f_copy(
vx_data_textblock.c_delimquote,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":pos"),
vx_core.vx_new_int(0)
)
),
vx_core.vx_new_string(":children"),
vx_core.f_new(
vx_data_textblock.t_textblocklist,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.f_new(
vx_data_textblock.t_textblock,
vx_core.vx_new(
vx_core.t_anylist,
vx_core.vx_new_string(":text"),
vx_core.vx_new_string("2"),
vx_core.vx_new_string(":startpos"),
vx_core.vx_new_int(12),
vx_core.vx_new_string(":endpos"),
vx_core.vx_new_int(12)
)
)
)
)
)
)
)
)
)
),
vx_data_csv.f_textblock_csv_from_string(
vx_core.vx_new_string("\"a\",\"b\"\n1,\"2\"")
)
)
)
return output
}
fun test_cases(context : vx_core.Type_context) : vx_test.Type_testcaselist {
var testcases : List<vx_core.Type_any> = vx_core.arraylist_from_array(
vx_data_csvTest.f_textblock_csv_from_string(context)
)
var output : vx_test.Type_testcaselist = vx_core.vx_new(
vx_test.t_testcaselist,
testcases
)
return output
}
fun test_coveragesummary() : vx_test.Type_testcoveragesummary {
var output : vx_test.Type_testcoveragesummary = vx_core.vx_new(
vx_test.t_testcoveragesummary,
":testpkg", "vx/data/csv",
":constnums", vx_core.vx_new(vx_test.t_testcoveragenums, ":pct", 0, ":tests", 0, ":total", 1),
":docnums", vx_core.vx_new(vx_test.t_testcoveragenums, ":pct", 63, ":tests", 7, ":total", 11),
":funcnums", vx_core.vx_new(vx_test.t_testcoveragenums, ":pct", 14, ":tests", 1, ":total", 7),
":bigospacenums", vx_core.vx_new(vx_test.t_testcoveragenums, ":pct", 0, ":tests", 0, ":total", 7),
":bigotimenums", vx_core.vx_new(vx_test.t_testcoveragenums, ":pct", 0, ":tests", 0, ":total", 7),
":totalnums", vx_core.vx_new(vx_test.t_testcoveragenums, ":pct", 9, ":tests", 1, ":total", 11),
":typenums", vx_core.vx_new(vx_test.t_testcoveragenums, ":pct", 0, ":tests", 0, ":total", 3)
)
return output
}
fun test_coveragedetail() : vx_test.Type_testcoveragedetail {
var output : vx_test.Type_testcoveragedetail = vx_core.vx_new(
vx_test.t_testcoveragedetail,
":testpkg", "vx/data/csv",
":typemap", vx_core.vx_new(
vx_core.t_intmap,
":csv", 0,
":csvrowmap", 0,
":csvrows", 0
),
":constmap", vx_core.vx_new(
vx_core.t_intmap,
":delimcsv", 0
),
":funcmap", vx_core.vx_new(
vx_core.t_intmap,
":csv-read<-file", 0,
":csv<-file", 0,
":csv<-string", 0,
":csv<-textblock", 0,
":csvrows<-textblock", 0,
":stringmap<-csv", 0,
":textblock-csv<-string", 1
)
)
return output
}
fun test_package(context : vx_core.Type_context) : vx_test.Type_testpackage {
var testcaselist : vx_test.Type_testcaselist = test_cases(context)
var output : vx_test.Type_testpackage = vx_core.vx_new(
vx_test.t_testpackage,
":testpkg", "vx/data/csv",
":caselist", testcaselist,
":coveragesummary", test_coveragesummary(),
":coveragedetail", test_coveragedetail()
)
return output
}
}
| 0 | HTML | 0 | 23 | 8e1d4a9fc905610ef7005d5751d52d1331cbf2b5 | 13,718 | vxlisp | MIT License |
marketkit/src/main/java/io/horizontalsystems/marketkit/models/CoinCategory.kt | horizontalsystems | 408,718,031 | false | null | package io.definenulls.marketkit.models
import android.os.Parcelable
import com.google.gson.annotations.SerializedName
import kotlinx.parcelize.Parcelize
import java.math.BigDecimal
@Parcelize
data class CoinCategory(
val uid: String,
val name: String,
val description: Map<String, String>,
@SerializedName("market_cap")
val marketCap: BigDecimal?,
@SerializedName("change_24h")
val diff24H: BigDecimal?,
@SerializedName("change_1w")
val diff1W: BigDecimal?,
@SerializedName("change_1m")
val diff1M: BigDecimal?,
) : Parcelable {
override fun toString(): String {
return "CoinCategory [uid: $uid; name: $name; descriptionCount: ${description.size}]"
}
}
| 1 | null | 23 | 9 | 103bf39cf42b8538ce7fb35bc189b95542ef8680 | 718 | market-kit-android | MIT License |
src/commonMain/kotlin/com/inari/firefly/physics/contact/ContactMap.kt | AndreasHefti | 387,557,032 | false | null | package com.inari.firefly.physics.contact
import com.inari.firefly.core.*
import com.inari.firefly.core.api.ComponentIndex
import com.inari.firefly.core.api.EntityIndex
import com.inari.firefly.graphics.tile.ETile
import com.inari.firefly.graphics.view.*
import com.inari.firefly.physics.movement.MovementSystem
import com.inari.util.collection.BitSet
import com.inari.util.collection.IndexIterator
import com.inari.util.geom.Vector4i
import kotlin.jvm.JvmField
abstract class ContactMap protected constructor() : Component(ContactMap), ViewLayerAware {
override val viewIndex: ComponentIndex
get() = viewRef.targetKey.componentIndex
override val layerIndex: ComponentIndex
get() = layerRef.targetKey.componentIndex
@JvmField val viewRef = CReference(View)
@JvmField val layerRef = CReference(Layer)
protected val entities: BitSet = BitSet()
internal fun notifyEntityActivation (index: EntityIndex) {
val transform = ETransform[index]
if (viewIndex != transform.viewIndex || layerIndex != transform.layerIndex)
return
entities[index] = true
}
internal fun notifyEntityDeactivation(index: EntityIndex) {
entities[index] = false
}
private val tempBitset = BitSet()
fun updateAll(entities: BitSet) {
tempBitset.clear()
tempBitset.and(entities)
tempBitset.and(this.entities)
var index = tempBitset.nextSetBit(0)
while (index >= 0) {
update(index)
index = tempBitset.nextSetBit(index + 1)
}
}
/** This is usually called by CollisionSystem in an entity move event and must update the entity in the pool
* if the entity id has some orientation related store attributes within the specified ContactPool implementation.
*
* @param entityIndex the index of an entity that has just moved and changed its position in the world
*/
abstract fun update(entityIndex: EntityIndex)
/** Use this to get an IntIterator of all entity id's that most possibly has a collision within the given region.
* The efficiency of this depends on an specified implementation and can be different for different needs.
*
* @param region The contact or collision region to check collision entity collisions against.
* @param entityIndex Entity index of the Entity to exclude from the search
* @return IndexIterator of all entity id's that most possibly has a collision within the given region
*/
abstract operator fun get(region: Vector4i, entityIndex: EntityIndex): IndexIterator
companion object : ComponentSystem<ContactMap>("ContactMap") {
val VIEW_LAYER_MAPPING = ViewLayerMapping()
override fun registerComponent(c: ContactMap): ComponentKey {
val key = super.registerComponent(c)
VIEW_LAYER_MAPPING.add(c, c.index)
return key
}
override fun unregisterComponent(index: ComponentIndex) {
val c = this[index]
VIEW_LAYER_MAPPING.delete(c, c.index)
super.unregisterComponent(index)
}
private val entityListener: ComponentEventListener = { key, type ->
val index = key.componentIndex
if (index in EContact && index !in ETile) {
if (type == ComponentEventType.ACTIVATED) {
val iter = iterator()
while (iter.hasNext())
iter.next().notifyEntityActivation(index)
} else if (type == ComponentEventType.DEACTIVATED) {
val iter = iterator()
while (iter.hasNext())
iter.next().notifyEntityDeactivation(key.componentIndex)
}
}
}
private val viewListener: ComponentEventListener = { key, type ->
if (type == ComponentEventType.DELETED) {
val iter = iterator()
while (iter.hasNext())
if (iter.next().viewIndex == key.componentIndex)
delete(key.componentIndex)
}
}
private val moveListener: (MovementSystem.MoveEvent) -> Unit = {
var index = activeComponentSet.nextIndex(0)
while (index >= 0) {
ContactMap[index].updateAll(it.entities)
index = activeComponentSet.nextIndex(index + 1)
}
}
init {
Entity.registerComponentListener(entityListener)
View.registerComponentListener(viewListener)
Engine.registerListener(MovementSystem.moveEvent, moveListener)
}
fun update(entityIndex: EntityIndex) {
val maps = VIEW_LAYER_MAPPING[ETransform[entityIndex]]
if (maps.isEmpty) return
var index = maps.nextSetBit(0)
while (index >= 0) {
ContactMap[index].update(index)
index = maps.nextSetBit(index + 1)
}
}
override fun allocateArray(size: Int): Array<ContactMap?> = arrayOfNulls(size)
override fun create(): ContactMap =
throw UnsupportedOperationException("ContactMap is abstract use a concrete implementation instead")
}
}
class SimpleContactMap private constructor(): ContactMap() {
override fun update(entityIndex: EntityIndex) {
// not needed here since this is just an ordinary list
}
private val selfExcluded = BitSet()
override fun get(region: Vector4i, entityIndex: EntityIndex): IndexIterator {
selfExcluded.clear()
selfExcluded.or(entities)
selfExcluded[entityIndex] = false
return IndexIterator(selfExcluded)
}
companion object : SubComponentBuilder<ContactMap, SimpleContactMap>(ContactMap) {
override fun create() = SimpleContactMap()
}
} | 6 | Kotlin | 0 | 11 | e0376a8445dc8f1becc4fa74a177b34f7a817f46 | 5,882 | flyko-lib | Apache License 2.0 |
src/main/kotlin/year_2020/Day01.kt | krllus | 572,617,904 | false | {"Kotlin": 86547} | package year_2020
import Day
import solve
class Day01 : Day(day = 1, year = 2020, "Report Repair") {
private val targetSum = 2020
override fun part1(): Int {
val set = mutableSetOf<Int>()
for (number in inputAsInts) {
val difference = targetSum - number
if(set.contains(difference)){
return difference * number
}
set.add(number)
}
return 0
}
override fun part2(): Int {
val set = HashMap<Int, Element>()
for (i in inputAsInts.indices){
for(j in i+1..<inputAsInts.size){
val v1 = inputAsInts[i]
val v2 = inputAsInts[j]
val sum = v1 + v2
val element = Element(v1, v2)
set[sum] = element
}
}
for (number in inputAsInts) {
val difference = targetSum - number
val element = set[difference]
if(element != null){
return number * element.v1 * element.v2
}
}
return 0
}
}
data class Element(val v1 : Int, val v2 : Int)
fun main() {
solve<Day01>(offerSubmit = true) {
"""
1721
979
366
299
675
1456
""".trimIndent()(part1 = 514579, part2 = 241861950)
}
} | 0 | Kotlin | 0 | 0 | f77cf4694a4b392251d57be0638c256a8609de8b | 1,449 | advent-of-code | Apache License 2.0 |
app/src/main/java/com/jumpingphantom/flow/core/data/entity/Subcategory.kt | JumpingPhantom | 811,400,534 | false | {"Kotlin": 109236} | package com.jumpingphantom.flow.core.data.entity
import androidx.annotation.DrawableRes
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.jumpingphantom.flow.core.data.common.Category
@Entity(tableName = "subcategories")
data class Subcategory (
@PrimaryKey(autoGenerate = true) val id: Int,
val name: String,
val parent: Category,
@DrawableRes val icon: Int? = null
) | 0 | Kotlin | 0 | 0 | 7c82814773d647043401c8e67781af0cae0947a9 | 407 | Flow | MIT License |
src/main/kotlin/com/github/thinkami/railroads/ui/RailroadIcon.kt | thinkAmi | 773,281,486 | false | {"Kotlin": 59121, "Ruby": 544} | package com.github.thinkami.railroads.ui
import com.intellij.icons.AllIcons
import icons.RubyIcons
class RailroadIcon {
companion object {
val Unknown = AllIcons.General.TodoQuestion
val NodeController = AllIcons.Nodes.Class
val NodeMethod = AllIcons.Nodes.Method
val NodeMountedEngine = AllIcons.Nodes.Plugin
val NodeRedirect = AllIcons.General.ArrowRight
val NodeRouteAction = RubyIcons.Rails.ProjectView.Action_method
}
} | 8 | Kotlin | 0 | 5 | 2e72efa0a78d8f19150abeb85afc0d0fe7f375fd | 483 | railroads | MIT License |
src/jsMain/kotlin/presentation/features/chat/clientChatScreen/ChatScreen.kt | Tanexc | 667,134,735 | false | null | package presentation.features.chat.clientChatScreen
import androidx.compose.foundation.VerticalScrollbar
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollbarAdapter
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Warning
import androidx.compose.material3.Icon
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Alignment.Companion.Center
import androidx.compose.ui.Alignment.Companion.CenterHorizontally
import androidx.compose.ui.Alignment.Companion.CenterVertically
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import org.koin.core.context.GlobalContext
import org.w3c.dom.events.KeyboardEventInit
import presentation.features.chat.components.MessageBubble
import presentation.features.chat.controller.ClientChatController
import presentation.style.icons.filled.IconFilledSend
import presentation.style.icons.rounded.IconRoundedCake
import presentation.style.strings.Strings
import presentation.style.strings.Strings.appName
import presentation.style.strings.Strings.nameWarning
import presentation.style.strings.applicationResources
import presentation.style.ui.theme.applicationColorScheme
@Composable
fun ChatScreen() {
val controller: ClientChatController by GlobalContext.get().inject()
controller.updateName()
controller.initializeChat()
val messageText: MutableState<String> = remember { mutableStateOf("") }
val lazyColumnState = rememberLazyListState()
LaunchedEffect(controller.messageList.size) {
if (controller.messageList.isNotEmpty()) {
lazyColumnState.animateScrollToItem(0)
}
}
Box(modifier = Modifier.fillMaxSize()) {
if (controller.showInsertNameDialog) {
Column(modifier = Modifier.align(Center)) {
Icon(
Icons.Outlined.Warning,
null,
modifier = Modifier.size(56.dp).align(CenterHorizontally)
)
Text(applicationResources(nameWarning), textAlign = TextAlign.Center)
}
} else {
Column(modifier = Modifier.align(Center)) {
Row(
modifier = Modifier
.widthIn(max = 804.dp)
.height(720.dp)
.padding(6.dp)
.background(
applicationColorScheme.secondaryContainer.copy(0.3f),
RoundedCornerShape(4.dp)
)
) {
Box(modifier = Modifier.fillMaxSize()) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
state = lazyColumnState,
reverseLayout = true
) {
items(controller.messageList) { messageItem ->
MessageBubble(
message = messageItem,
modifier = Modifier
.background(
applicationColorScheme.secondaryContainer.copy(0.6f),
when (controller.messageList.indexOf(messageItem)) {
(controller.messageList.lastIndex) -> if (controller.clientId.toString() == messageItem.sender) {
RoundedCornerShape(22.dp, 22.dp, 6.dp, 22.dp)
} else {
RoundedCornerShape(22.dp, 22.dp, 22.dp, 6.dp)
}
0 -> if (controller.clientId.toString() == messageItem.sender) {
RoundedCornerShape(22.dp, 6.dp, 22.dp, 22.dp)
} else {
RoundedCornerShape(6.dp, 22.dp, 22.dp, 22.dp)
}
else -> if (controller.clientId.toString() == messageItem.sender) {
RoundedCornerShape(22.dp, 6.dp, 6.dp, 22.dp)
} else {
RoundedCornerShape(6.dp, 22.dp, 22.dp, 6.dp)
}
}
),
align = if (controller.clientId.toString() == messageItem.sender) {
Alignment.CenterEnd
} else {
Alignment.CenterStart
}
)
}
}
Box(
modifier = Modifier
.fillMaxWidth()
.background(
brush = Brush.Companion.verticalGradient(
listOf(
applicationColorScheme.secondaryContainer.copy(0.3f),
applicationColorScheme.secondaryContainer.copy(0f)
)
),
)
) {
Column(modifier = Modifier.align(Alignment.TopCenter).padding(4.dp)) {
Row(modifier = Modifier.align(CenterHorizontally)) {
Box(
modifier = Modifier.background(
applicationColorScheme.primary,
CircleShape
)
.size(56.dp)
) {
Icon(
IconRoundedCake,
null,
modifier = Modifier
.fillMaxSize()
.padding(12.dp)
)
}
Text(
applicationResources(appName),
modifier = Modifier.padding(8.dp).align(CenterVertically)
)
}
}
}
}
}
Row(
modifier = Modifier
.widthIn(max = 804.dp)
.wrapContentHeight()
.padding(6.dp)
) {
OutlinedTextField(
value = messageText.value,
onValueChange = { messageText.value = it },
modifier = Modifier
.heightIn(48.dp, 256.dp)
.fillMaxWidth(),
placeholder = {
Text(applicationResources(Strings.typeMessage))
},
label = null,
trailingIcon = {
Icon(IconFilledSend,
null,
modifier = Modifier
.clickable {
controller.sendMessage(messageText.value)
messageText.value = ""
}
)
}
)
}
}
VerticalScrollbar(
modifier = Modifier
.align(Alignment.CenterEnd)
.fillMaxHeight(),
adapter = rememberScrollbarAdapter(
scrollState = lazyColumnState
),
reverseLayout = true
)
}
}
} | 0 | Kotlin | 0 | 2 | 8a13415a06b1b359897805721e9886c367be7fd2 | 9,357 | ComposeWebCakes | Apache License 2.0 |
python/python-psi-impl/src/com/jetbrains/python/codeInsight/completion/PyDictLiteralCompletionContributor.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2022 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.codeInsight.completion
import com.intellij.codeInsight.completion.*
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.patterns.PlatformPatterns.psiElement
import com.intellij.psi.PsiElement
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.ui.IconManager
import com.intellij.util.ProcessingContext
import com.jetbrains.python.PyNames
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyCallExpressionHelper
import com.jetbrains.python.psi.resolve.PyResolveContext
import com.jetbrains.python.psi.types.PyClassType
import com.jetbrains.python.psi.types.PyType
import com.jetbrains.python.psi.types.PyTypedDictType
import com.jetbrains.python.psi.types.TypeEvalContext
/**
* Provides completion variants for keys of dict literals marked as TypedDict
* @see PyTypedDictType
*/
class PyDictLiteralCompletionContributor : CompletionContributor() {
init {
extend(CompletionType.BASIC, psiElement().inside(PySequenceExpression::class.java), DictLiteralCompletionProvider())
}
}
private class DictLiteralCompletionProvider : CompletionProvider<CompletionParameters?>() {
private val DEFAULT_QUOTE = "\""
override fun addCompletions(parameters: CompletionParameters, context: ProcessingContext, result: CompletionResultSet) {
val originalElement = parameters.originalPosition?.parent ?: return
var possibleSequenceExpr = if (originalElement is PyStringLiteralExpression) originalElement.parent else originalElement
if (possibleSequenceExpr is PyKeyValueExpression) {
possibleSequenceExpr = possibleSequenceExpr.parent
}
if (possibleSequenceExpr is PyDictLiteralExpression || possibleSequenceExpr is PySetLiteralExpression) { // it's set literal when user is typing the first key
addCompletionToCallExpression(originalElement, possibleSequenceExpr as PySequenceExpression, result)
addCompletionToAssignment(originalElement, possibleSequenceExpr, result)
addCompletionToReturnStatement(originalElement, possibleSequenceExpr, result)
}
}
private fun addCompletionToCallExpression(originalElement: PsiElement,
possibleSequenceExpr: PySequenceExpression,
result: CompletionResultSet) {
val typeEvalContext = TypeEvalContext.codeCompletion(originalElement.project, originalElement.containingFile)
val actualType = typeEvalContext.getType(possibleSequenceExpr)
val quote = getForcedQuote(possibleSequenceExpr, originalElement)
PyCallExpressionHelper.getMappedParameters(possibleSequenceExpr, PyResolveContext.defaultContext(typeEvalContext)).forEach {
addCompletionForTypedDictKeys(it.getType(typeEvalContext), actualType, result, quote)
}
}
private fun getForcedQuote(possibleSequenceExpr: PySequenceExpression, originalElement: PsiElement): String {
if (originalElement !is PyStringLiteralExpression) {
val usedQuotes = possibleSequenceExpr.elements.mapNotNull { if (it is PyKeyValueExpression) it.key else it }
.filterIsInstance<PyStringLiteralExpression>()
.flatMap { it.stringElements }
.map { it.quote }
.toSet()
return usedQuotes.singleOrNull() ?: DEFAULT_QUOTE
}
return ""
}
private fun addCompletionToAssignment(originalElement: PsiElement,
possibleSequenceExpr: PySequenceExpression,
result: CompletionResultSet) {
val assignment = PsiTreeUtil.getParentOfType(originalElement, PyAssignmentStatement::class.java)
if (assignment != null) {
val typeEvalContext = TypeEvalContext.codeCompletion(originalElement.project, originalElement.containingFile)
val targetToValue = if (assignment.targets.size == 1) assignment.targets[0] to assignment.assignedValue
else assignment.targetsToValuesMapping.firstOrNull { it.second == possibleSequenceExpr }?.let { it.first to it.second }
if (targetToValue?.first != null && targetToValue.second != null) {
val expectedType = typeEvalContext.getType(targetToValue.first as PyTypedElement)
val actualType = typeEvalContext.getType(targetToValue.second as PyTypedElement)
addCompletionForTypedDictKeys(expectedType, actualType, result, getForcedQuote(possibleSequenceExpr, originalElement))
}
else { //multiple target expressions and there is a PsiErrorElement
val targetExpr = assignment.assignedValue
val element = if (targetExpr is PyTupleExpression) targetExpr.elements.firstOrNull {
it == possibleSequenceExpr
}
else return
if (element != null) {
val index = targetExpr.elements.indexOf(element)
if (index < assignment.targets.size) {
val expectedType = typeEvalContext.getType(assignment.targets[index])
val actualType = typeEvalContext.getType(element)
addCompletionForTypedDictKeys(expectedType, actualType, result, getForcedQuote(possibleSequenceExpr, originalElement))
}
}
}
}
}
private fun addCompletionToReturnStatement(originalElement: PsiElement,
possibleSequenceExpr: PySequenceExpression,
result: CompletionResultSet) {
val returnStatement = PsiTreeUtil.getParentOfType(originalElement, PyReturnStatement::class.java)
if (returnStatement != null) {
val typeEvalContext = TypeEvalContext.codeCompletion(originalElement.project, originalElement.containingFile)
val owner = ScopeUtil.getScopeOwner(returnStatement)
if (owner is PyFunction) {
val annotation = owner.annotation
val typeCommentAnnotation = owner.typeCommentAnnotation
if (annotation != null || typeCommentAnnotation != null) { // to ensure that we have return type specified, not inferred
val expectedType = typeEvalContext.getReturnType(owner)
val actualType = typeEvalContext.getType(possibleSequenceExpr)
addCompletionForTypedDictKeys(expectedType, actualType, result, getForcedQuote(possibleSequenceExpr, originalElement))
}
}
}
}
private fun addCompletionForTypedDictKeys(expectedType: PyType?,
actualType: PyType?,
dictCompletion: CompletionResultSet,
quote: String) {
if (expectedType is PyTypedDictType) {
val keys =
when {
actualType is PyTypedDictType -> expectedType.fields.keys.filterNot { it in actualType.fields }
actualType is PyClassType && PyNames.SET == actualType.name -> expectedType.fields.keys
else -> return
}
for (key in keys) {
dictCompletion.addElement(
LookupElementBuilder
.create("$quote$key$quote")
.withTypeText("dict key")
.withIcon(IconManager.getInstance().getPlatformIcon(com.intellij.ui.PlatformIcons.Parameter))
)
}
}
}
}
| 284 | null | 5162 | 16,707 | def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0 | 7,362 | intellij-community | Apache License 2.0 |
window/window-core/src/commonMain/kotlin/androidx/window/core/layout/WindowSizeClassUtil.kt | androidx | 256,589,781 | false | {"Kotlin": 98393993, "Java": 63366352, "C++": 9124958, "AIDL": 590909, "Python": 308602, "Shell": 186243, "TypeScript": 40586, "HTML": 29764, "Groovy": 24103, "Svelte": 20307, "ANTLR": 19860, "C": 16935, "CMake": 15482, "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.
*/
@file:JvmName("WindowSizeClassUtil")
package androidx.window.core.layout
import androidx.window.core.ExperimentalWindowCoreApi
/**
* A scoring function to calculate how close the width of a [WindowSizeClass] is to [widthDp]
* without exceeding it.
*
* @param widthDp the width bound to try to match.
* @return an integer from -1 to [Integer.MAX_VALUE] where a larger value indicates a better match.
*/
@ExperimentalWindowCoreApi
fun WindowSizeClass.scoreWithinWidthDp(widthDp: Int): Int {
return if (this.widthDp <= widthDp) {
Integer.MAX_VALUE / (1 + widthDp - this.widthDp)
} else {
-1
}
}
/**
* A scoring function to calculate how close the height of a [WindowSizeClass] is to [heightDp]
* without exceeding it.
*
* @param heightDp the height bound to try to match.
* @return an integer from -1 to [Integer.MAX_VALUE] where a larger value indicates a better match.
*/
@ExperimentalWindowCoreApi
fun WindowSizeClass.scoreWithinHeightDp(heightDp: Int): Int {
return if (this.heightDp <= heightDp) {
Integer.MAX_VALUE / (1 + heightDp - this.heightDp)
} else {
-1
}
}
/**
* A scoring function to calculate how close the area of a [WindowSizeClass] is to the area of a
* window without exceeding it.
*
* @param windowWidthDp the width of a window constraint.
* @param windowHeightDp the height of a window constraint.
*
* @return an integer from -1 to [Integer.MAX_VALUE] where a larger value indicates a better match.
*/
@ExperimentalWindowCoreApi
fun WindowSizeClass.scoreWithinAreaBounds(
windowWidthDp: Int,
windowHeightDp: Int
): Int {
if (windowWidthDp < this.widthDp || windowHeightDp < this.heightDp) {
return -1
}
val areaDifference = windowWidthDp * windowHeightDp - this.widthDp * this.heightDp
return Integer.MAX_VALUE / (1 + areaDifference)
}
/**
* Calculates which [WindowSizeClass] has the closest matching [windowWidthDp] within the given
* value. If there are multiple matches then the tallest [WindowSizeClass] is selected within the
* given value.
*
* @param windowWidthDp the width of the current window in DP to choose a [WindowSizeClass].
* @param windowHeightDp the height of the current window in DP to chose a [WindowSizeClass].
* @return a [WindowSizeClass] that has [WindowSizeClass.widthDp] less than or equal to the
* [windowWidthDp] and is the closest to [windowWidthDp] if possible `null` otherwise.
*/
fun Set<WindowSizeClass>.widestOrEqualWidthDp(
windowWidthDp: Int,
windowHeightDp: Int
): WindowSizeClass? {
require(0 <= windowHeightDp) {
"Window height must be non-negative but got windowHeightDp: $windowHeightDp"
}
require(0 <= windowWidthDp) {
"Window width must be non-negative but got windowHeightDp: $windowWidthDp"
}
var maxValue: WindowSizeClass? = null
forEach { sizeClass ->
if (sizeClass.widthDp > windowWidthDp) {
return@forEach
}
if (sizeClass.heightDp > windowHeightDp) {
return@forEach
}
val localMax = maxValue
if (localMax == null) {
maxValue = sizeClass
return@forEach
}
if (localMax.widthDp > sizeClass.widthDp) {
return@forEach
}
if (localMax.widthDp == sizeClass.widthDp && sizeClass.heightDp < localMax.heightDp) {
return@forEach
}
maxValue = sizeClass
}
return maxValue
}
| 27 | Kotlin | 900 | 4,945 | 40fc0be87bd96490fd0285c8b82b0b8febfd1bf5 | 4,092 | androidx | Apache License 2.0 |
matrix-sdk-android/src/rustCrypto/java/org/matrix/android/sdk/internal/crypto/store/db/RealmCryptoStoreMigration.kt | tchapgouv | 340,329,238 | false | null | /*
* Copyright 2020 The Matrix.org Foundation C.I.C.
*
* 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.matrix.android.sdk.internal.crypto.store.db
import io.realm.DynamicRealm
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo001Legacy
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo002Legacy
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo003RiotX
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo004
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo005
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo006
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo007
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo008
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo009
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo010
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo011
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo012
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo013
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo014
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo015
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo016
import org.matrix.android.sdk.internal.crypto.store.db.migration.MigrateCryptoTo017
import org.matrix.android.sdk.internal.util.database.MatrixRealmMigration
import org.matrix.android.sdk.internal.util.time.Clock
import javax.inject.Inject
/**
* Schema version history:
* 0, 1, 2: legacy Riot-Android;
* 3: migrate to RiotX schema;
* 4, 5, 6, 7, 8, 9: migrations from RiotX (which was previously 1, 2, 3, 4, 5, 6).
*/
internal class RealmCryptoStoreMigration @Inject constructor(
private val clock: Clock,
) : MatrixRealmMigration(
dbName = "Crypto",
schemaVersion = 17L,
) {
/**
* Forces all RealmCryptoStoreMigration instances to be equal.
* Avoids Realm throwing when multiple instances of the migration are set.
*/
override fun equals(other: Any?) = other is RealmCryptoStoreMigration
override fun hashCode() = 5000
override fun doMigrate(realm: DynamicRealm, oldVersion: Long) {
if (oldVersion < 1) MigrateCryptoTo001Legacy(realm).perform()
if (oldVersion < 2) MigrateCryptoTo002Legacy(realm).perform()
if (oldVersion < 3) MigrateCryptoTo003RiotX(realm).perform()
if (oldVersion < 4) MigrateCryptoTo004(realm).perform()
if (oldVersion < 5) MigrateCryptoTo005(realm).perform()
if (oldVersion < 6) MigrateCryptoTo006(realm).perform()
if (oldVersion < 7) MigrateCryptoTo007(realm).perform()
if (oldVersion < 8) MigrateCryptoTo008(realm, clock).perform()
if (oldVersion < 9) MigrateCryptoTo009(realm).perform()
if (oldVersion < 10) MigrateCryptoTo010(realm).perform()
if (oldVersion < 11) MigrateCryptoTo011(realm).perform()
if (oldVersion < 12) MigrateCryptoTo012(realm).perform()
if (oldVersion < 13) MigrateCryptoTo013(realm).perform()
if (oldVersion < 14) MigrateCryptoTo014(realm).perform()
if (oldVersion < 15) MigrateCryptoTo015(realm).perform()
if (oldVersion < 16) MigrateCryptoTo016(realm).perform()
if (oldVersion < 17) MigrateCryptoTo017(realm).perform()
}
}
| 75 | null | 6 | 9 | b248ca2dbb0953761d2780e4fba756acc3899958 | 4,141 | tchap-android | Apache License 2.0 |
app/src/main/java/com/szlachta/medialibrary/network/tvshows/TvShowsRepository.kt | bartlomiej-szlachta | 252,731,965 | false | null | package com.szlachta.medialibrary.network.tvshows
import androidx.lifecycle.MutableLiveData
import com.szlachta.medialibrary.model.ItemsList
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.util.stream.Collectors
class TvShowsRepository private constructor() {
companion object {
private var repository: TvShowsRepository? = null
fun getInstance(): TvShowsRepository {
if (repository == null) {
repository = TvShowsRepository()
}
return repository!!
}
}
private var api: TvShowsApi = RetrofitService.createService()
private lateinit var tvShowsList: MutableLiveData<ItemsList>
fun getTvShowsByQuery(query: String): MutableLiveData<ItemsList> {
tvShowsList = MutableLiveData()
api.getTvShowsByQuery(query).enqueue(object : Callback<List<TvShowResponse>> {
override fun onResponse(
call: Call<List<TvShowResponse>>,
response: Response<List<TvShowResponse>>
) {
if (response.code() == 200) {
val items = response.body()
?.stream()
?.map {
return@map it.toModel()
}
?.collect(Collectors.toList())
tvShowsList.value = ItemsList(items)
}
}
override fun onFailure(call: Call<List<TvShowResponse>>, t: Throwable) {
tvShowsList.value = ItemsList(errorMessage = t.message)
}
})
return tvShowsList
}
} | 0 | Kotlin | 0 | 0 | eacb7f3d4ec8ede458813bed2389f471e8aecaba | 1,669 | media-library | MIT License |
slack-lint-checks/src/main/java/slack/lint/DaggerIssuesDetector.kt | slackhq | 419,446,800 | false | {"Kotlin": 736750, "Java": 1150, "Shell": 797} | // Copyright (C) 2021 Slack Technologies, LLC
// SPDX-License-Identifier: Apache-2.0
package slack.lint
import com.android.tools.lint.client.api.UElementHandler
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Detector
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.JavaContext
import com.android.tools.lint.detector.api.Severity
import com.android.tools.lint.detector.api.SourceCodeScanner
import com.android.tools.lint.detector.api.TextFormat
import com.android.tools.lint.detector.api.isDuplicatedOverload
import com.android.tools.lint.detector.api.isReceiver
import com.intellij.lang.jvm.JvmClassKind
import com.intellij.psi.PsiTypes
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.uast.UAnnotated
import org.jetbrains.uast.UMethod
import org.jetbrains.uast.getContainingUClass
import slack.lint.util.sourceImplementation
/** This is a simple lint check to catch common Dagger+Kotlin usage issues. */
class DaggerIssuesDetector : Detector(), SourceCodeScanner {
companion object {
private val ISSUE_BINDS_MUST_BE_IN_MODULE: Issue =
Issue.create(
"MustBeInModule",
"@Binds/@Provides functions must be in modules",
"@Binds/@Provides functions must be in `@Module`-annotated classes.",
Category.CORRECTNESS,
6,
Severity.ERROR,
sourceImplementation<DaggerIssuesDetector>(),
)
private val ISSUE_BINDS_TYPE_MISMATCH: Issue =
Issue.create(
"BindsTypeMismatch",
"@Binds parameter/return must be type-assignable",
"@Binds function parameters must be type-assignable to their return types.",
Category.CORRECTNESS,
6,
Severity.ERROR,
sourceImplementation<DaggerIssuesDetector>(),
)
private val ISSUE_RETURN_TYPE: Issue =
Issue.create(
"BindingReturnType",
"@Binds/@Provides must have a return type",
"@Binds/@Provides functions must have a return type. Cannot be void or Unit.",
Category.CORRECTNESS,
6,
Severity.ERROR,
sourceImplementation<DaggerIssuesDetector>(),
)
private val ISSUE_RECEIVER_PARAMETER: Issue =
Issue.create(
"BindingReceiverParameter",
"@Binds/@Provides functions cannot be extensions",
"@Binds/@Provides functions cannot be extension functions. Move the receiver type to a parameter via IDE inspection (option+enter and convert to parameter).",
Category.CORRECTNESS,
6,
Severity.ERROR,
sourceImplementation<DaggerIssuesDetector>(),
)
private val ISSUE_BINDS_WRONG_PARAMETER_COUNT: Issue =
Issue.create(
"BindsWrongParameterCount",
"@Binds must have one parameter",
"@Binds functions require a single parameter as an input to bind.",
Category.CORRECTNESS,
6,
Severity.ERROR,
sourceImplementation<DaggerIssuesDetector>(),
)
private val ISSUE_BINDS_MUST_BE_ABSTRACT: Issue =
Issue.create(
"BindsMustBeAbstract",
"@Binds functions must be abstract",
"@Binds functions must be abstract and cannot have function bodies.",
Category.CORRECTNESS,
6,
Severity.ERROR,
sourceImplementation<DaggerIssuesDetector>(),
)
private val ISSUE_PROVIDES_CANNOT_BE_ABSTRACT: Issue =
Issue.create(
"ProvidesMustNotBeAbstract",
"@Provides functions cannot be abstract",
"@Provides functions cannot be abstract.",
Category.CORRECTNESS,
6,
Severity.ERROR,
sourceImplementation<DaggerIssuesDetector>(),
)
private val ISSUE_BINDS_REDUNDANT: Issue =
Issue.create(
"RedundantBinds",
"@Binds functions should return a different type",
"@Binds functions should return a different type (including annotations) than the input type.",
Category.CORRECTNESS,
6,
Severity.ERROR,
sourceImplementation<DaggerIssuesDetector>(),
)
private const val BINDS_ANNOTATION = "dagger.Binds"
private const val PROVIDES_ANNOTATION = "dagger.Provides"
val ISSUES: List<Issue> =
listOf(
ISSUE_BINDS_TYPE_MISMATCH,
ISSUE_RETURN_TYPE,
ISSUE_RECEIVER_PARAMETER,
ISSUE_BINDS_WRONG_PARAMETER_COUNT,
ISSUE_BINDS_MUST_BE_ABSTRACT,
ISSUE_BINDS_REDUNDANT,
ISSUE_BINDS_MUST_BE_IN_MODULE,
ISSUE_PROVIDES_CANNOT_BE_ABSTRACT,
)
}
override fun getApplicableUastTypes() = listOf(UMethod::class.java)
override fun createUastHandler(context: JavaContext): UElementHandler {
return object : UElementHandler() {
override fun visitMethod(node: UMethod) {
if (node.isDuplicatedOverload()) {
return
}
if (!node.isConstructor) {
val isBinds = node.hasAnnotation(BINDS_ANNOTATION)
val isProvides = node.hasAnnotation(PROVIDES_ANNOTATION)
if (!isBinds && !isProvides) return
val containingClass = node.getContainingUClass()
if (containingClass != null) {
// Fine to not use MetadataJavaEvaluator since we only care about current module
val moduleClass =
if (context.evaluator.hasModifier(containingClass, KtTokens.COMPANION_KEYWORD)) {
checkNotNull(containingClass.getContainingUClass()) {
"Companion object must be nested in a class"
}
} else {
containingClass
}
when {
!moduleClass.hasAnnotation("dagger.Module") -> {
context.report(
ISSUE_BINDS_MUST_BE_IN_MODULE,
context.getLocation(node),
ISSUE_BINDS_MUST_BE_IN_MODULE.getBriefDescription(TextFormat.TEXT),
)
return
}
isBinds && containingClass.isInterface -> {
// Cannot have a default impl in interfaces
if (node.uastBody != null) {
context.report(
ISSUE_BINDS_MUST_BE_ABSTRACT,
context.getLocation(node.uastBody),
ISSUE_BINDS_MUST_BE_ABSTRACT.getBriefDescription(TextFormat.TEXT),
)
return
}
}
containingClass.classKind == JvmClassKind.CLASS -> {
val isAbstract = context.evaluator.isAbstract(node)
// Binds must be abstract
if (isBinds && !isAbstract) {
context.report(
ISSUE_BINDS_MUST_BE_ABSTRACT,
context.getLocation(node),
ISSUE_BINDS_MUST_BE_ABSTRACT.getBriefDescription(TextFormat.TEXT),
)
return
} else if (isProvides && isAbstract) {
context.report(
ISSUE_PROVIDES_CANNOT_BE_ABSTRACT,
context.getLocation(node),
ISSUE_PROVIDES_CANNOT_BE_ABSTRACT.getBriefDescription(TextFormat.TEXT),
)
return
}
}
containingClass.classKind == JvmClassKind.INTERFACE && isProvides -> {
context.report(
ISSUE_PROVIDES_CANNOT_BE_ABSTRACT,
context.getLocation(node),
ISSUE_PROVIDES_CANNOT_BE_ABSTRACT.getBriefDescription(TextFormat.TEXT),
)
return
}
}
}
if (isBinds) {
if (node.uastParameters.size != 1) {
val locationToHighlight =
if (node.uastParameters.isEmpty()) {
node
} else {
node.parameterList
}
context.report(
ISSUE_BINDS_WRONG_PARAMETER_COUNT,
context.getLocation(locationToHighlight),
ISSUE_BINDS_WRONG_PARAMETER_COUNT.getBriefDescription(TextFormat.TEXT),
)
return
}
}
val returnType =
node.returnType?.takeUnless {
it == PsiTypes.voidType() ||
context.evaluator.getTypeClass(it)?.qualifiedName == "kotlin.Unit"
}
if (returnType == null) {
// Report missing return type
val nodeLocation = node.returnTypeElement ?: node
context.report(
ISSUE_RETURN_TYPE,
context.getLocation(nodeLocation),
ISSUE_RETURN_TYPE.getBriefDescription(TextFormat.TEXT),
)
return
}
if (node.uastParameters.isNotEmpty()) {
val firstParam = node.uastParameters[0]
if (firstParam.isReceiver()) {
context.report(
ISSUE_RECEIVER_PARAMETER,
context.getNameLocation(firstParam),
ISSUE_RECEIVER_PARAMETER.getBriefDescription(TextFormat.TEXT),
)
return
}
if (isBinds) {
val instanceType = firstParam.type
if (instanceType == returnType) {
// Check that they have different annotations, otherwise it's redundant
if (firstParam.qualifiers() == node.qualifiers()) {
context.report(
ISSUE_BINDS_REDUNDANT,
context.getLocation(node),
ISSUE_BINDS_REDUNDANT.getBriefDescription(TextFormat.TEXT),
)
return
}
}
if (!returnType.isAssignableFrom(instanceType)) {
context.report(
ISSUE_BINDS_TYPE_MISMATCH,
context.getLocation(node),
ISSUE_BINDS_TYPE_MISMATCH.getBriefDescription(TextFormat.TEXT),
)
}
}
}
}
}
}
}
private fun UAnnotated.qualifiers() =
uAnnotations
.asSequence()
.filter { it.resolve()?.hasAnnotation("javax.inject.Qualifier") == true }
.toSet()
}
| 18 | Kotlin | 13 | 232 | 4568cc3f9fabc3b3465fb1b9ac315a1557846651 | 10,309 | slack-lints | Apache License 2.0 |
app/src/main/java/com/marknkamau/justjava/ui/main/MainViewModel.kt | MarkNjunge | 86,477,705 | false | null | package com.marknkamau.justjava.ui.main
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.marknjunge.core.data.model.Resource
import com.marknjunge.core.data.repository.ProductsRepository
import com.marknjunge.core.data.model.Product
import kotlinx.coroutines.launch
class MainViewModel(private val productsRepository: ProductsRepository) : ViewModel() {
private val _loading = MutableLiveData<Boolean>()
val loading: LiveData<Boolean> = _loading
private val _products = MutableLiveData<Resource<List<Product>>>()
val products: LiveData<Resource<List<Product>>> = _products
fun getProducts() {
viewModelScope.launch {
_loading.value = true
_products.value = productsRepository.getProducts()
_loading.value = false
}
}
} | 1 | null | 36 | 74 | e3811f064797d50fadef4033bf1532b3c2ceef8d | 914 | JustJava-Android | Apache License 2.0 |
src/main/kotlin/com/lykke/matching/engine/outgoing/messages/v2/builders/CashTransferEventBuilder.kt | MyJetWallet | 334,417,928 | true | {"Kotlin": 1903525, "Java": 39278} | package com.lykke.matching.engine.outgoing.messages.v2.builders
import com.lykke.matching.engine.outgoing.messages.v2.enums.MessageType
import com.lykke.matching.engine.outgoing.messages.v2.events.CashTransferEvent
import com.lykke.matching.engine.outgoing.messages.v2.events.common.BalanceUpdate
import com.lykke.matching.engine.outgoing.messages.v2.events.common.CashTransfer
import com.lykke.matching.engine.outgoing.messages.v2.events.common.Header
class CashTransferEventBuilder : EventBuilder<CashTransferData, CashTransferEvent>() {
private var balanceUpdates: List<BalanceUpdate>? = null
private var cashTransfer: CashTransfer? = null
override fun getMessageType() = MessageType.CASH_TRANSFER
override fun setEventData(eventData: CashTransferData): EventBuilder<CashTransferData, CashTransferEvent> {
balanceUpdates = convertBalanceUpdates(eventData.clientBalanceUpdates)
cashTransfer = CashTransfer(
eventData.transferOperation.brokerId,
eventData.transferOperation.accountId,
eventData.transferOperation.fromClientId,
eventData.transferOperation.toClientId,
bigDecimalToString(eventData.transferOperation.volume),
bigDecimalToString(eventData.transferOperation.overdraftLimit),
eventData.transferOperation.asset!!.symbol,
convertFees(eventData.internalFees)
)
return this
}
override fun buildEvent(header: Header) = CashTransferEvent(header, balanceUpdates!!, cashTransfer!!)
} | 0 | Kotlin | 1 | 0 | fad1a43743bd7b833bfa4f1490da5e5350b992ff | 1,546 | MatchingEngine | MIT License |
toolKit/src/main/java/com/kokocinski/toolkit/androidExtensions/listeners/PageChangedListener.kt | hkokocin | 112,010,707 | false | null | package com.kokocinski.toolkit.androidExtensions.listeners
import android.support.v4.view.ViewPager
class PageChangedListener(
private val onPageSelected: (Int) -> Unit = {},
private val onPageScrollStateChanged: (Int) -> Unit = {},
private val onPageScrolled: (Int, Float, Int) -> Unit = {_, _, _ ->}
): ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) = onPageScrollStateChanged.invoke(state)
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
onPageScrolled.invoke(position, positionOffset, positionOffsetPixels)
}
override fun onPageSelected(position: Int) = onPageSelected.invoke(position)
} | 0 | Kotlin | 0 | 3 | 01ba60102467691c578993f6095b59072c8a11fb | 726 | IdleTimer | MIT License |
toolKit/src/main/java/com/kokocinski/toolkit/androidExtensions/listeners/PageChangedListener.kt | hkokocin | 112,010,707 | false | null | package com.kokocinski.toolkit.androidExtensions.listeners
import android.support.v4.view.ViewPager
class PageChangedListener(
private val onPageSelected: (Int) -> Unit = {},
private val onPageScrollStateChanged: (Int) -> Unit = {},
private val onPageScrolled: (Int, Float, Int) -> Unit = {_, _, _ ->}
): ViewPager.OnPageChangeListener {
override fun onPageScrollStateChanged(state: Int) = onPageScrollStateChanged.invoke(state)
override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {
onPageScrolled.invoke(position, positionOffset, positionOffsetPixels)
}
override fun onPageSelected(position: Int) = onPageSelected.invoke(position)
} | 0 | Kotlin | 0 | 3 | 01ba60102467691c578993f6095b59072c8a11fb | 726 | IdleTimer | MIT License |
notifications/src/main/kotlin/io/zerobase/smarttracing/notifications/EmailSender.kt | zerobase-io | 249,016,150 | false | null | package io.zerobase.smarttracing.notifications
interface EmailSender {
fun sendEmail(subject: String,
toAddress: String,
body: String,
contentType: String = "text/html; charset=UTF-8",
attachment: List<Attachment>
)
}
| 19 | Kotlin | 8 | 6 | e0514f99c78bae6883e1bf50da5ee6a5c87f0a7f | 299 | smart-tracing-api | Apache License 2.0 |
app/src/main/kotlin/com/semrad/order/OrderSettings.kt | bjsemrad | 873,946,490 | false | {"Kotlin": 11735, "Nix": 459, "Shell": 10} | package com.semrad.order
class OrderSettings {
var liftGateRequired: Boolean = false
var packingListInEachBox: Boolean = false
} | 0 | Kotlin | 0 | 0 | 66772c77de60a4c18e2bf893f5faa51c2aba24e2 | 137 | temporal-order-demo-kotlin | MIT License |
src/test/kotlin/no/nav/familie/dokument/storage/StorageControllerTest.kt | navikt | 222,470,666 | false | {"Kotlin": 109855, "HTML": 31392, "Dockerfile": 153} | package no.nav.familie.dokument.storage
import io.mockk.Runs
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.slot
import no.nav.familie.dokument.pdf.PdfService
import no.nav.familie.dokument.storage.attachment.AttachmentStorage
import no.nav.familie.dokument.storage.encryption.Hasher
import no.nav.familie.dokument.testutils.ExtensionMockUtil.setUpMockHentFnr
import no.nav.familie.dokument.virusscan.VirusScanService
import no.nav.security.token.support.core.context.TokenValidationContextHolder
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.http.HttpStatus
import java.io.File
import java.nio.file.Files
import java.nio.file.Paths
import java.util.UUID
internal class StorageControllerTest {
lateinit var storageController: StorageController
val storageMock = mockk<AttachmentStorage>()
val dokument1 = UUID.randomUUID()
val dokument2 = UUID.randomUUID()
val dokument3 = UUID.randomUUID()
@BeforeEach
internal fun setUp() {
val virusScanMock = mockk<VirusScanService>()
val contextHolderMock = mockk<TokenValidationContextHolder>()
setUpMockHentFnr()
val pdfServiceMock = PdfService()
storageController =
StorageController(storageMock, virusScanMock, contextHolderMock, 10, Hasher("Hemmelig salt"), pdfServiceMock)
every { contextHolderMock.hentFnr() } returns "12345678910"
every { storageMock.get(any(), dokument1.toString()) } returns leseVedlegg("vedlegg", "gyldig-0.8m.pdf")
every { storageMock.get(any(), dokument2.toString()) } returns leseVedlegg("pdf", "eksempel1.pdf")
every { storageMock.get(any(), dokument3.toString()) } returns leseVedlegg("vedlegg", "gyldig-0.8m.pdf")
}
@Test
internal fun `skal slå sammen en liste av innsendte dokumenter og lagre som et dokument`() {
val dokumentListe = listOf(dokument1, dokument2, dokument3)
val dokumentIdSlot = slot<String>()
val mergetDokumentSlot = slot<ByteArray>()
every { storageMock.put(any(), capture(dokumentIdSlot), capture(mergetDokumentSlot)) } just Runs
val response = storageController.mergeAndStoreDocuments("familievedlegg", dokumentListe)
assertThat(response.statusCode).isEqualTo(HttpStatus.CREATED)
assertThat(response.body.get("dokumentId")).isEqualTo(dokumentIdSlot.captured)
Files.createDirectories(Paths.get("target/mergetpdf"))
File("target/mergetpdf", "mergetfil.pdf").writeBytes(mergetDokumentSlot.captured)
}
private fun leseVedlegg(mappeNavn: String, navn: String): ByteArray {
return StorageControllerTest::class.java.getResource("/${mappeNavn}/${navn}").readBytes()
}
} | 4 | Kotlin | 0 | 0 | d07c4826ebdff9b6f0b29628b499cbe80d20924b | 2,827 | familie-dokument | MIT License |
platform/statistics/devkit/testSrc/com/intellij/internal/statistic/actions/devkit/StatisticsEventLogToolWindowTest.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.actions
import com.intellij.execution.process.ProcessOutputType
import com.intellij.internal.statistic.eventLog.LogEvent
import com.intellij.internal.statistic.eventLog.LogEventAction
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType
import com.intellij.internal.statistic.eventLog.validator.ValidationResultType.*
import com.intellij.internal.statistic.toolwindow.StatisticsEventLogFilter.Companion.LOG_PATTERN
import com.intellij.internal.statistic.toolwindow.StatisticsEventLogMessageBuilder
import com.intellij.internal.statistic.toolwindow.StatisticsEventLogToolWindow
import com.intellij.internal.statistic.toolwindow.StatisticsLogFilterModel
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import com.intellij.util.text.DateFormatUtil
import org.junit.Test
class StatisticsEventLogToolWindowTest : BasePlatformTestCase() {
private val eventId = "third.party"
private val eventTime = 1564643114456
private val eventGroup = "toolwindow"
private val groupVersion = "21"
private val formattedEventTime = DateFormatUtil.formatTimeWithSeconds(eventTime)
@Test
fun testShortenProjectId() {
val action = LogEventAction(eventId)
val data = hashMapOf(
"project" to "5410c65eafb1f0abd78c6d9bdf33752f13c17b17ed57c3ae26801ae6ee7d17ea",
"plugin_type" to "PLATFORM"
)
for ((key, value) in data) {
action.addData(key, value)
}
doTestCountCollector("{\"plugin_type\":\"PLATFORM\", \"project\":\"5410c65e...ea\"}", action, data)
}
@Test
fun testNotShortenProjectId() {
val action = LogEventAction(eventId)
val projectId = "12345"
action.addData("project", projectId)
doTestCountCollector("{\"project\":\"$projectId\"}", action, hashMapOf("project" to projectId))
}
@Test
fun testFilterSystemFields() {
val action = LogEventAction(eventId)
val data = hashMapOf(
"last" to "1564643442610",
"created" to "1564643442610"
)
for ((key, value) in data) {
action.addData(key, value)
}
doTestCountCollector("{}", action, data)
}
@Test
fun testLogIncorrectEventIdAsError() {
val incorrectEventId = INCORRECT_RULE.description
val action = LogEventAction(incorrectEventId)
val filterModel = StatisticsLogFilterModel()
val logMessage = StatisticsEventLogMessageBuilder().buildLogMessage(buildLogEvent(action), eventId, emptyMap())
assertEquals("$formattedEventTime - [\"$eventGroup\", v$groupVersion]: \"$incorrectEventId[$eventId]\" {}", logMessage)
val processingResult = filterModel.processLine(logMessage)
assertEquals(processingResult.key, ProcessOutputType.STDERR)
}
@Test
fun testLogIncorrectEventDataAsError() {
val action = LogEventAction(eventId)
action.addData("test", INCORRECT_RULE.description)
action.addData("project", UNDEFINED_RULE.description)
val filterModel = StatisticsLogFilterModel()
val rawData = hashMapOf(
"test" to "foo",
"project" to "5410c65eafb1f0abd78c6d9bdf33752f13c17b17ed57c3ae26801ae6ee7d17ea"
)
val logMessage = StatisticsEventLogMessageBuilder().buildLogMessage(buildLogEvent(action), eventId, rawData)
val expectedLine = buildExpectedLine(
"{\"test\":\"validation.incorrect_rule[foo]\", \"project\":\"validation.undefined_rule[5410c65eafb1f0abd78c6d9bdf33752f13c17b17ed57c3ae26801ae6ee7d17ea]\"}")
assertEquals(expectedLine, logMessage)
val processingResult = filterModel.processLine(logMessage)
assertEquals(processingResult.key, ProcessOutputType.STDERR)
}
@Test
fun testLogIncorrectEventDataWithoutRawData() {
val action = LogEventAction(eventId)
action.addData("test", INCORRECT_RULE.description)
action.addData("project", UNDEFINED_RULE.description)
val filterModel = StatisticsLogFilterModel()
val logMessage = StatisticsEventLogMessageBuilder().buildLogMessage(buildLogEvent(action), null, null)
val expectedLine = buildExpectedLine("{\"test\":\"validation.incorrect_rule\", \"project\":\"validation.undefined_rule\"}")
assertEquals(expectedLine, logMessage)
val processingResult = filterModel.processLine(logMessage)
assertEquals(processingResult.key, ProcessOutputType.STDERR)
}
@Test
fun testAllValidationTypesUsed() {
val correctValidationTypes = setOf(ACCEPTED, THIRD_PARTY)
for (resultType in ValidationResultType.values()) {
assertTrue("Don't forget to change toolWindow logic in case of a new value in ValidationResult",
StatisticsEventLogToolWindow.rejectedValidationTypes.contains(resultType) || correctValidationTypes.contains(resultType))
}
}
@Test
fun testHandleCollectionsInEventData() {
val action = LogEventAction(eventId)
action.addData("dataKey", listOf("1", "2", "3"))
doTestCountCollector("{\"dataKey\":[\"1\",\"2\",\"3\"]}", action, hashMapOf("dataKey" to listOf("1", "2", "3")))
}
@Test
fun testLogCountCollectors() {
val count = 2
val action = LogEventAction(eventId, false, count)
val actual = StatisticsEventLogMessageBuilder().buildLogMessage(buildLogEvent(action), eventId, emptyMap())
assertEquals("$formattedEventTime - [\"$eventGroup\", v$groupVersion]: \"$eventId\" (count=${count}) {}", actual)
}
@Test
fun testLogLineWithCountMatchesRegexpPattern() {
val action = LogEventAction(eventId, false, 2)
val logLineWithCount = StatisticsEventLogMessageBuilder().buildLogMessage(buildLogEvent(action), eventId, emptyMap())
val matcher = LOG_PATTERN.matcher(logLineWithCount)
assertTrue(matcher.find())
assertEquals(eventGroup, matcher.group("groupId"))
assertEquals(eventId, matcher.group("event"))
assertEquals("{}", matcher.group("eventData"))
}
@Test
fun testLogLineMatchesRegexpPattern() {
val action = LogEventAction(eventId, true)
action.addData("plugin_type", "PLATFORM")
val logLineWithCount = StatisticsEventLogMessageBuilder().buildLogMessage(buildLogEvent(action), eventId, emptyMap())
val matcher = LOG_PATTERN.matcher(logLineWithCount)
assertTrue(matcher.find())
assertEquals(eventGroup, matcher.group("groupId"))
assertEquals(eventId, matcher.group("event"))
assertEquals("{\"plugin_type\":\"PLATFORM\"}", matcher.group("eventData"))
}
private fun doTestCountCollector(expectedEventDataPart: String, action: LogEventAction, rawData: Map<String, Any> = emptyMap()) {
val actual = StatisticsEventLogMessageBuilder().buildLogMessage(buildLogEvent(action), eventId, rawData)
assertEquals(buildExpectedLine(expectedEventDataPart), actual)
}
private fun buildExpectedLine(expectedEventDataPart: String) =
"$formattedEventTime - [\"$eventGroup\", v$groupVersion]: \"$eventId\" $expectedEventDataPart"
private fun buildLogEvent(action: LogEventAction, groupId: String = eventGroup) = LogEvent("2e5b2e32e061", "193.1801", "176", eventTime,
groupId, groupVersion, "32", action)
} | 191 | null | 4372 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 7,220 | intellij-community | Apache License 2.0 |
app/src/main/java/com/example/petstate/databasetools/EmpModel.kt | whizydan | 483,489,445 | false | {"Kotlin": 148329, "Java": 62813} | package com.example.petstate
//creating a Data Model Class
class EmpModelClass (var userId: Int,
val userName:String ,
val userEmail: String
) | 0 | Kotlin | 3 | 0 | 149a02e51f6870c05b8d09f7318534e94e319ead | 184 | Petstate | Apache License 2.0 |
cinescout/account/presentation/src/main/kotlin/cinescout/account/presentation/action/ManageAccountAction.kt | fardavide | 280,630,732 | false | null | package cinescout.account.presentation.action
import cinescout.auth.domain.model.TraktAuthorizationCode
sealed interface ManageAccountAction {
object LinkToTrakt : ManageAccountAction
data class NotifyTraktAppAuthorized(val code: TraktAuthorizationCode) : ManageAccountAction
object UnlinkFromTrakt : ManageAccountAction
}
| 8 | Kotlin | 2 | 6 | dcbd0a0b70d6203a2ba1959b797038564d0f04c4 | 338 | CineScout | Apache License 2.0 |
admoblibrary/src/main/java/com/vapp/admoblibrary/ads/remote/BaseAdView.kt | khaisao | 766,449,406 | false | {"Kotlin": 472014, "Java": 220234} | package com.vapp.admoblibrary.ads.remote
import android.app.Activity
import android.content.Context
import android.os.Handler
import android.os.Looper
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.annotation.CallSuper
import com.vapp.admoblibrary.ads.remote.BannerPlugin.Companion.log
import kotlin.math.max
internal abstract class BaseAdView(
context: Context,
private val refreshRateSec: Int?
) : FrameLayout(context) {
private var nextRefreshTime = 0L
private val refreshHandler by lazy { Handler(Looper.getMainLooper()) }
private var isPausedOrDestroy = false
fun loadAd() {
log("LoadAd ...")
nextRefreshTime = 0L // Not allow scheduling until ad request is done
stopBannerRefreshScheduleIfNeed()
loadAdInternal {
log("On load ad done ...")
calculateNextBannerRefresh()
if (!isPausedOrDestroy) scheduleNextBannerRefreshIfNeed()
}
}
protected abstract fun loadAdInternal(onDone: () -> Unit)
@CallSuper
override fun onVisibilityAggregated(isVisible: Boolean) {
super.onVisibilityAggregated(isVisible)
if (isVisible) onResume()
else onPause()
}
@CallSuper
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
onDestroy()
}
private fun onResume() {
isPausedOrDestroy = false
scheduleNextBannerRefreshIfNeed()
}
private fun onPause() {
isPausedOrDestroy = true
stopBannerRefreshScheduleIfNeed()
}
private fun onDestroy() {
isPausedOrDestroy = true
stopBannerRefreshScheduleIfNeed()
}
private fun calculateNextBannerRefresh() {
if (refreshRateSec == null) return
nextRefreshTime = System.currentTimeMillis() + refreshRateSec * 1000L
}
private fun scheduleNextBannerRefreshIfNeed() {
if (refreshRateSec == null) return
if (nextRefreshTime <= 0L) return
val delay = max(0L, nextRefreshTime - System.currentTimeMillis())
stopBannerRefreshScheduleIfNeed()
log("Ads are scheduled to show in $delay mils")
refreshHandler.postDelayed({ loadAd() }, delay)
}
private fun stopBannerRefreshScheduleIfNeed() {
refreshHandler.removeCallbacksAndMessages(null)
}
internal object Factory {
fun getAdView(
activity: Activity,
adUnitId: String,
bannerType: BannerPlugin.BannerType,
refreshRateSec: Int?,
cbFetchIntervalSec: Int,bannerRemoteConfig: BannerRemoteConfig
): BaseAdView {
return when (bannerType) {
BannerPlugin.BannerType.Adaptive,
BannerPlugin.BannerType.Standard,
BannerPlugin.BannerType.CollapsibleBottom,
BannerPlugin.BannerType.CollapsibleTop -> BannerAdView(activity, adUnitId, bannerType, refreshRateSec, cbFetchIntervalSec ,bannerRemoteConfig)
}
}
}
} | 0 | Kotlin | 0 | 0 | 6415fd8218bf2fcb5cc650a7e097000c274d7205 | 3,037 | AppLock | Apache License 2.0 |
app/src/main/java/dev/marcocattaneo/sleep/di/DiExtensions.kt | mcatta | 469,373,328 | false | {"Kotlin": 201059} | /*
* Copyright 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 dev.marcocattaneo.playground.di
import android.app.Activity
import android.content.Context
import android.content.ContextWrapper
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.platform.LocalContext
import dagger.hilt.EntryPoints
import dagger.hilt.android.EntryPointAccessors
import dev.marcocattaneo.playground.di.component.ComposableComponentBuilderEntryPoint
fun Context.getActivity(): Activity = when (this) {
is Activity -> this
is ContextWrapper -> baseContext.getActivity()
else -> throw IllegalStateException("Cannot retrieve a valid Activity from $this")
}
@Composable
inline fun <reified T : Any> rememberComposableEntryPoint(): T {
val context = LocalContext.current
return remember {
val entryPoint = EntryPointAccessors.fromActivity(
context.getActivity(), ComposableComponentBuilderEntryPoint::class.java
)
EntryPoints.get(entryPoint.composableBuilder.build(), T::class.java)
}
} | 8 | Kotlin | 5 | 8 | 132451c3de7dc9812084191f8c99d957c38b29f9 | 1,620 | sleep | Apache License 2.0 |
KotlinTest/src/DataUserTest.kt | gubaojian | 354,480,658 | false | {"PureBasic": 9241771, "Java": 96109, "Kotlin": 23751, "C": 3386} | package datatest
data class User(val name:String, val age:Int)
fun main(args:Array<String>){
val jack = User(name="Jack", age = 1)
val olderJack = jack.copy(age = 2)
println(jack)
println(olderJack)
var jane = User("Jane", 35)
val (name,age) = jane
println("$name, $age years of age")
} | 0 | PureBasic | 0 | 0 | 480cd02ccad81c3dccc7a785e51eed22590711ca | 313 | ServerTechTest | Apache License 2.0 |
platform/workspace/storage/src/com/intellij/platform/workspace/storage/impl/RefsTable.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl
import com.google.common.collect.BiMap
import com.google.common.collect.HashBiMap
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.util.containers.HashSetInterner
import com.intellij.workspaceModel.storage.WorkspaceEntity
import com.intellij.workspaceModel.storage.impl.ConnectionId.ConnectionType
import com.intellij.workspaceModel.storage.impl.containers.*
import it.unimi.dsi.fastutil.ints.IntArrayList
import org.jetbrains.annotations.ApiStatus
import java.util.function.IntFunction
class ConnectionId private constructor(
val parentClass: Int,
val childClass: Int,
val connectionType: ConnectionType,
val isParentNullable: Boolean
) {
enum class ConnectionType {
ONE_TO_ONE,
ONE_TO_MANY,
ONE_TO_ABSTRACT_MANY,
ABSTRACT_ONE_TO_ONE
}
/**
* This function returns true if this connection allows removing parent of child.
*
* E.g. parent is optional (nullable) for child entity, so the parent can be safely removed.
*/
fun canRemoveParent(): Boolean = isParentNullable
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as ConnectionId
if (parentClass != other.parentClass) return false
if (childClass != other.childClass) return false
if (connectionType != other.connectionType) return false
if (isParentNullable != other.isParentNullable) return false
return true
}
override fun hashCode(): Int {
var result = parentClass.hashCode()
result = 31 * result + childClass.hashCode()
result = 31 * result + connectionType.hashCode()
result = 31 * result + isParentNullable.hashCode()
return result
}
override fun toString(): String {
return "Connection(parent=${ClassToIntConverter.INSTANCE.getClassOrDie(parentClass).simpleName} " +
"child=${ClassToIntConverter.INSTANCE.getClassOrDie(childClass).simpleName} $connectionType)"
}
fun debugStr(): String = """
ConnectionId info:
- Parent class: ${this.parentClass.findEntityClass<WorkspaceEntity>()}
- Child class: ${this.childClass.findEntityClass<WorkspaceEntity>()}
- Connection type: $connectionType
- Parent of child is nullable: $isParentNullable
""".trimIndent()
companion object {
/** This function should be [@Synchronized] because interner is not thread-save */
@Synchronized
fun <Parent : WorkspaceEntity, Child : WorkspaceEntity> create(
parentClass: Class<Parent>,
childClass: Class<Child>,
connectionType: ConnectionType,
isParentNullable: Boolean
): ConnectionId {
val connectionId = ConnectionId(parentClass.toClassId(), childClass.toClassId(), connectionType, isParentNullable)
return interner.intern(connectionId)
}
/** This function should be [@Synchronized] because interner is not thread-save */
@Synchronized
@ApiStatus.Internal
fun create(
parentClass: Int,
childClass: Int,
connectionType: ConnectionType,
isParentNullable: Boolean
): ConnectionId {
val connectionId = ConnectionId(parentClass, childClass, connectionType, isParentNullable)
return interner.intern(connectionId)
}
private val interner = HashSetInterner<ConnectionId>()
}
}
val ConnectionId.isOneToOne: Boolean
get() = this.connectionType == ConnectionType.ONE_TO_ONE || this.connectionType == ConnectionType.ABSTRACT_ONE_TO_ONE
/**
* [oneToManyContainer]: [ImmutableNonNegativeIntIntBiMap] - key - child, value - parent
*/
internal class RefsTable internal constructor(
override val oneToManyContainer: Map<ConnectionId, ImmutableNonNegativeIntIntBiMap>,
override val oneToOneContainer: Map<ConnectionId, ImmutableIntIntUniqueBiMap>,
override val oneToAbstractManyContainer: Map<ConnectionId, LinkedBidirectionalMap<ChildEntityId, ParentEntityId>>,
override val abstractOneToOneContainer: Map<ConnectionId, BiMap<ChildEntityId, ParentEntityId>>
) : AbstractRefsTable() {
constructor() : this(HashMap(), HashMap(), HashMap(), HashMap())
}
internal class MutableRefsTable(
override val oneToManyContainer: MutableMap<ConnectionId, NonNegativeIntIntBiMap>,
override val oneToOneContainer: MutableMap<ConnectionId, IntIntUniqueBiMap>,
override val oneToAbstractManyContainer: MutableMap<ConnectionId, LinkedBidirectionalMap<ChildEntityId, ParentEntityId>>,
override val abstractOneToOneContainer: MutableMap<ConnectionId, BiMap<ChildEntityId, ParentEntityId>>
) : AbstractRefsTable() {
private val oneToAbstractManyCopiedToModify: MutableSet<ConnectionId> = HashSet()
private val abstractOneToOneCopiedToModify: MutableSet<ConnectionId> = HashSet()
private fun getOneToManyMutableMap(connectionId: ConnectionId): MutableNonNegativeIntIntBiMap {
val bimap = oneToManyContainer[connectionId] ?: run {
val empty = MutableNonNegativeIntIntBiMap()
oneToManyContainer[connectionId] = empty
return empty
}
return when (bimap) {
is MutableNonNegativeIntIntBiMap -> bimap
is ImmutableNonNegativeIntIntBiMap -> {
val copy = bimap.toMutable()
oneToManyContainer[connectionId] = copy
copy
}
}
}
private fun getOneToAbstractManyMutableMap(connectionId: ConnectionId): LinkedBidirectionalMap<ChildEntityId, ParentEntityId> {
if (connectionId !in oneToAbstractManyContainer) {
oneToAbstractManyContainer[connectionId] = LinkedBidirectionalMap()
}
return if (connectionId in oneToAbstractManyCopiedToModify) {
oneToAbstractManyContainer[connectionId]!!
}
else {
val copy = LinkedBidirectionalMap<ChildEntityId, ParentEntityId>()
val original = oneToAbstractManyContainer[connectionId]!!
original.forEach { (k, v) -> copy[k] = v }
oneToAbstractManyContainer[connectionId] = copy
oneToAbstractManyCopiedToModify.add(connectionId)
copy
}
}
private fun getAbstractOneToOneMutableMap(connectionId: ConnectionId): BiMap<ChildEntityId, ParentEntityId> {
if (connectionId !in abstractOneToOneContainer) {
abstractOneToOneContainer[connectionId] = HashBiMap.create()
}
return if (connectionId in abstractOneToOneCopiedToModify) {
abstractOneToOneContainer[connectionId]!!
}
else {
val copy = HashBiMap.create<ChildEntityId, ParentEntityId>()
val original = abstractOneToOneContainer[connectionId]!!
original.forEach { (k, v) -> copy[k] = v }
abstractOneToOneContainer[connectionId] = copy
abstractOneToOneCopiedToModify.add(connectionId)
copy
}
}
private fun getOneToOneMutableMap(connectionId: ConnectionId): MutableIntIntUniqueBiMap {
val bimap = oneToOneContainer[connectionId] ?: run {
val empty = MutableIntIntUniqueBiMap()
oneToOneContainer[connectionId] = empty
return empty
}
return when (bimap) {
is MutableIntIntUniqueBiMap -> bimap
is ImmutableIntIntUniqueBiMap -> {
val copy = bimap.toMutable()
oneToOneContainer[connectionId] = copy
copy
}
}
}
fun removeRefsByParent(connectionId: ConnectionId, parentId: ParentEntityId) {
@Suppress("IMPLICIT_CAST_TO_ANY")
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> getOneToManyMutableMap(connectionId).removeValue(parentId.id.arrayId)
ConnectionType.ONE_TO_ONE -> getOneToOneMutableMap(connectionId).removeValue(parentId.id.arrayId)
ConnectionType.ONE_TO_ABSTRACT_MANY -> getOneToAbstractManyMutableMap(connectionId).removeValue(parentId)
ConnectionType.ABSTRACT_ONE_TO_ONE -> getAbstractOneToOneMutableMap(connectionId).inverse().remove(parentId)
}.let { }
}
fun removeOneToOneRefByParent(connectionId: ConnectionId, parentId: Int) {
getOneToOneMutableMap(connectionId).removeValue(parentId)
}
fun removeOneToAbstractOneRefByParent(connectionId: ConnectionId, parentId: ParentEntityId) {
getAbstractOneToOneMutableMap(connectionId).inverse().remove(parentId)
}
fun removeOneToAbstractOneRefByChild(connectionId: ConnectionId, childId: ChildEntityId) {
getAbstractOneToOneMutableMap(connectionId).remove(childId)
}
fun removeOneToOneRefByChild(connectionId: ConnectionId, childId: Int) {
getOneToOneMutableMap(connectionId).removeKey(childId)
}
fun removeOneToManyRefsByChild(connectionId: ConnectionId, childId: Int) {
getOneToManyMutableMap(connectionId).removeKey(childId)
}
fun removeOneToAbstractManyRefsByChild(connectionId: ConnectionId, childId: ChildEntityId) {
getOneToAbstractManyMutableMap(connectionId).remove(childId)
}
fun removeParentToChildRef(connectionId: ConnectionId, parentId: ParentEntityId, childId: ChildEntityId) {
@Suppress("IMPLICIT_CAST_TO_ANY")
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> getOneToManyMutableMap(connectionId).remove(childId.id.arrayId, parentId.id.arrayId)
ConnectionType.ONE_TO_ONE -> getOneToOneMutableMap(connectionId).remove(childId.id.arrayId, parentId.id.arrayId)
ConnectionType.ONE_TO_ABSTRACT_MANY -> getOneToAbstractManyMutableMap(connectionId).remove(childId, parentId)
ConnectionType.ABSTRACT_ONE_TO_ONE -> getAbstractOneToOneMutableMap(connectionId).remove(childId, parentId)
}.let { }
}
internal fun updateChildrenOfParent(connectionId: ConnectionId, parentId: ParentEntityId, childrenIds: Collection<ChildEntityId>) {
if (childrenIds !is Set<ChildEntityId> && childrenIds.size != childrenIds.toSet().size) error("Children have duplicates: $childrenIds")
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeValue(parentId.id.arrayId)
val children = childrenIds.map { it.id.arrayId }.toIntArray()
copiedMap.putAll(children, parentId.id.arrayId)
}
ConnectionType.ONE_TO_ONE -> {
val copiedMap = getOneToOneMutableMap(connectionId)
when (childrenIds.size) {
0 -> {
copiedMap.removeValue(parentId.id.arrayId)
}
1 -> copiedMap.putForce(childrenIds.single().id.arrayId, parentId.id.arrayId)
else -> error("Trying to add multiple children to one-to-one connection")
}
}
ConnectionType.ONE_TO_ABSTRACT_MANY -> {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.removeValue(parentId)
// In theory this removing can be avoided because keys will be replaced anyway, but without this cleanup we may get an
// incorrect ordering of the children
childrenIds.forEach { copiedMap.remove(it) }
childrenIds.forEach { copiedMap[it] = parentId }
}
ConnectionType.ABSTRACT_ONE_TO_ONE -> {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.inverse().remove(parentId)
childrenIds.forEach { copiedMap[it] = parentId }
}
}.let { }
}
fun updateOneToManyChildrenOfParent(connectionId: ConnectionId, parentId: Int, childrenEntityIds: List<ChildEntityId>) {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeValue(parentId)
val children = childrenEntityIds.mapToIntArray { it.id.arrayId }
copiedMap.putAll(children, parentId)
}
fun updateOneToAbstractManyChildrenOfParent(connectionId: ConnectionId,
parentId: ParentEntityId,
childrenEntityIds: Sequence<ChildEntityId>) {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.removeValue(parentId)
childrenEntityIds.forEach { copiedMap[it] = parentId }
}
fun updateOneToAbstractOneParentOfChild(
connectionId: ConnectionId,
childId: ChildEntityId,
parentId: ParentEntityId
) {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap.inverse().remove(parentId)
copiedMap[childId] = parentId
}
fun updateOneToAbstractOneChildOfParent(connectionId: ConnectionId,
parentId: ParentEntityId,
childEntityId: ChildEntityId) {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.inverse().remove(parentId)
copiedMap[childEntityId.id.asChild()] = parentId
}
fun updateOneToOneChildOfParent(connectionId: ConnectionId, parentId: Int, childEntityId: ChildEntityId) {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.removeValue(parentId)
copiedMap.put(childEntityId.id.arrayId, parentId)
}
fun updateOneToOneParentOfChild(
connectionId: ConnectionId,
childId: Int,
parentId: EntityId
) {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.removeKey(childId)
copiedMap.putForce(childId, parentId.arrayId)
}
internal fun updateParentOfChild(connectionId: ConnectionId, childId: ChildEntityId, parentId: ParentEntityId) {
when (connectionId.connectionType) {
ConnectionType.ONE_TO_MANY -> {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeKey(childId.id.arrayId)
copiedMap.putAll(intArrayOf(childId.id.arrayId), parentId.id.arrayId)
}
ConnectionType.ONE_TO_ONE -> {
val copiedMap = getOneToOneMutableMap(connectionId)
copiedMap.removeKey(childId.id.arrayId)
copiedMap.putForce(childId.id.arrayId, parentId.id.arrayId)
}
ConnectionType.ONE_TO_ABSTRACT_MANY -> {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap[childId] = parentId
}
ConnectionType.ABSTRACT_ONE_TO_ONE -> {
val copiedMap = getAbstractOneToOneMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap.forcePut(childId, parentId)
Unit
}
}.let { }
}
fun updateOneToManyParentOfChild(
connectionId: ConnectionId,
childId: Int,
parentId: ParentEntityId
) {
val copiedMap = getOneToManyMutableMap(connectionId)
copiedMap.removeKey(childId)
copiedMap.putAll(intArrayOf(childId), parentId.id.arrayId)
}
fun updateOneToAbstractManyParentOfChild(
connectionId: ConnectionId,
childId: ChildEntityId,
parentId: ParentEntityId
) {
val copiedMap = getOneToAbstractManyMutableMap(connectionId)
copiedMap.remove(childId)
copiedMap.put(childId, parentId)
}
fun toImmutable(): RefsTable = RefsTable(
oneToManyContainer.mapValues { it.value.toImmutable() },
oneToOneContainer.mapValues { it.value.toImmutable() },
oneToAbstractManyContainer.mapValues {
it.value.let { value ->
val map = LinkedBidirectionalMap<ChildEntityId, ParentEntityId>()
value.forEach { (k, v) -> map[k] = v }
map
}
},
abstractOneToOneContainer.mapValues {
it.value.let { value ->
val map = HashBiMap.create<ChildEntityId, ParentEntityId>()
value.forEach { (k, v) -> map[k] = v }
map
}
}
)
companion object {
fun from(other: RefsTable): MutableRefsTable = MutableRefsTable(
HashMap(other.oneToManyContainer), HashMap(other.oneToOneContainer),
HashMap(other.oneToAbstractManyContainer),
HashMap(other.abstractOneToOneContainer))
}
private fun <T> Sequence<T>.mapToIntArray(action: (T) -> Int): IntArray {
val intArrayList = IntArrayList()
this.forEach { item ->
intArrayList.add(action(item))
}
return intArrayList.toIntArray()
}
private fun <T> List<T>.mapToIntArray(action: (T) -> Int): IntArray {
val intArrayList = IntArrayList()
this.forEach { item ->
intArrayList.add(action(item))
}
return intArrayList.toIntArray()
}
}
internal sealed class AbstractRefsTable {
internal abstract val oneToManyContainer: Map<ConnectionId, NonNegativeIntIntBiMap>
internal abstract val oneToOneContainer: Map<ConnectionId, IntIntUniqueBiMap>
internal abstract val oneToAbstractManyContainer: Map<ConnectionId, LinkedBidirectionalMap<ChildEntityId, ParentEntityId>>
internal abstract val abstractOneToOneContainer: Map<ConnectionId, BiMap<ChildEntityId, ParentEntityId>>
fun <Parent : WorkspaceEntity, Child : WorkspaceEntity> findConnectionId(parentClass: Class<Parent>, childClass: Class<Child>): ConnectionId? {
val parentClassId = parentClass.toClassId()
val childClassId = childClass.toClassId()
return (oneToManyContainer.keys.find { it.parentClass == parentClassId && it.childClass == childClassId }
?: oneToOneContainer.keys.find { it.parentClass == parentClassId && it.childClass == childClassId }
?: oneToAbstractManyContainer.keys.find {
it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) &&
it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass)
}
?: abstractOneToOneContainer.keys.find {
it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) &&
it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass)
})
}
fun getParentRefsOfChild(childId: ChildEntityId): Map<ConnectionId, ParentEntityId> {
val childArrayId = childId.id.arrayId
val childClassId = childId.id.clazz
val childClass = childId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, ParentEntityId>()
val filteredOneToMany = oneToManyContainer.filterKeys { it.childClass == childClassId }
for ((connectionId, bimap) in filteredOneToMany) {
if (!bimap.containsKey(childArrayId)) continue
val value = bimap.get(childArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(value, connectionId.parentClass).asParent())
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredOneToOne = oneToOneContainer.filterKeys { it.childClass == childClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsKey(childArrayId)) continue
val value = bimap.get(childArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(value, connectionId.parentClass).asParent())
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredOneToAbstractMany = oneToAbstractManyContainer
.filterKeys { it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass) }
for ((connectionId, bimap) in filteredOneToAbstractMany) {
if (!bimap.containsKey(childId)) continue
val value = bimap[childId] ?: continue
val existingValue = res.putIfAbsent(connectionId, value)
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
if (!bimap.containsKey(childId)) continue
val value = bimap[childId] ?: continue
val existingValue = res.putIfAbsent(connectionId, value)
if (existingValue != null) thisLogger().error("This parent already exists")
}
return res
}
fun getParentOneToOneRefsOfChild(childId: ChildEntityId): Map<ConnectionId, ParentEntityId> {
val childArrayId = childId.id.arrayId
val childClassId = childId.id.clazz
val childClass = childId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, ParentEntityId>()
val filteredOneToOne = oneToOneContainer.filterKeys { it.childClass == childClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsKey(childArrayId)) continue
val value = bimap.get(childArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(value, connectionId.parentClass).asParent())
if (existingValue != null) thisLogger().error("This parent already exists")
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.childClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(childClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
if (!bimap.containsKey(childId)) continue
val value = bimap[childId] ?: continue
val existingValue = res.putIfAbsent(connectionId, value)
if (existingValue != null) thisLogger().error("This parent already exists")
}
return res
}
fun getChildrenRefsOfParentBy(parentId: ParentEntityId): Map<ConnectionId, List<ChildEntityId>> {
val parentArrayId = parentId.id.arrayId
val parentClassId = parentId.id.clazz
val parentClass = parentId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, List<ChildEntityId>>()
val filteredOneToMany = oneToManyContainer.filterKeys { it.parentClass == parentClassId }
for ((connectionId, bimap) in filteredOneToMany) {
val keys = bimap.getKeys(parentArrayId)
if (!keys.isEmpty()) {
val children = keys.map { createEntityId(it, connectionId.childClass) }.mapTo(ArrayList()) { it.asChild() }
val existingValue = res.putIfAbsent(connectionId, children)
if (existingValue != null) thisLogger().error("These children already exist")
}
}
val filteredOneToOne = oneToOneContainer.filterKeys { it.parentClass == parentClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsValue(parentArrayId)) continue
val key = bimap.getKey(parentArrayId)
val existingValue = res.putIfAbsent(connectionId, listOf(createEntityId(key, connectionId.childClass).asChild()))
if (existingValue != null) thisLogger().error("These children already exist")
}
val filteredOneToAbstractMany = oneToAbstractManyContainer
.filterKeys { it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) }
for ((connectionId, bimap) in filteredOneToAbstractMany) {
val keys = bimap.getKeysByValue(parentId) ?: continue
if (keys.isNotEmpty()) {
val existingValue = res.putIfAbsent(connectionId, keys.map { it })
if (existingValue != null) thisLogger().error("These children already exist")
}
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
val key = bimap.inverse()[parentId]
if (key == null) continue
val existingValue = res.putIfAbsent(connectionId, listOf(key))
if (existingValue != null) thisLogger().error("These children already exist")
}
return res
}
fun getChildrenOneToOneRefsOfParentBy(parentId: ParentEntityId): Map<ConnectionId, ChildEntityId> {
val parentArrayId = parentId.id.arrayId
val parentClassId = parentId.id.clazz
val parentClass = parentId.id.clazz.findEntityClass<WorkspaceEntity>()
val res = HashMap<ConnectionId, ChildEntityId>()
val filteredOneToOne = oneToOneContainer.filterKeys { it.parentClass == parentClassId }
for ((connectionId, bimap) in filteredOneToOne) {
if (!bimap.containsValue(parentArrayId)) continue
val key = bimap.getKey(parentArrayId)
val existingValue = res.putIfAbsent(connectionId, createEntityId(key, connectionId.childClass).asChild())
if (existingValue != null) thisLogger().error("These children already exist")
}
val filteredAbstractOneToOne = abstractOneToOneContainer
.filterKeys { it.parentClass.findEntityClass<WorkspaceEntity>().isAssignableFrom(parentClass) }
for ((connectionId, bimap) in filteredAbstractOneToOne) {
val key = bimap.inverse()[parentId]
if (key == null) continue
val existingValue = res.putIfAbsent(connectionId, key)
if (existingValue != null) thisLogger().error("These children already exist")
}
return res
}
fun getOneToManyChildren(connectionId: ConnectionId, parentId: Int): NonNegativeIntIntMultiMap.IntSequence? {
return oneToManyContainer[connectionId]?.getKeys(parentId)
}
fun getOneToAbstractManyChildren(connectionId: ConnectionId, parentId: ParentEntityId): List<ChildEntityId>? {
val map = oneToAbstractManyContainer[connectionId]
return map?.getKeysByValue(parentId)
}
fun getAbstractOneToOneChildren(connectionId: ConnectionId, parentId: ParentEntityId): ChildEntityId? {
val map = abstractOneToOneContainer[connectionId]
return map?.inverse()?.get(parentId)
}
fun getOneToAbstractOneParent(connectionId: ConnectionId, childId: ChildEntityId): ParentEntityId? {
return abstractOneToOneContainer[connectionId]?.get(childId)
}
fun getOneToAbstractManyParent(connectionId: ConnectionId, childId: ChildEntityId): ParentEntityId? {
val map = oneToAbstractManyContainer[connectionId]
return map?.get(childId)
}
fun getOneToOneChild(connectionId: ConnectionId, parentId: Int): Int? {
return oneToOneContainer[connectionId]?.getKey(parentId)
}
fun <Child : WorkspaceEntity> getOneToOneChild(connectionId: ConnectionId, parentId: Int, transformer: IntFunction<Child?>): Child? {
val bimap = oneToOneContainer[connectionId] ?: return null
if (!bimap.containsValue(parentId)) return null
return transformer.apply(bimap.getKey(parentId))
}
fun <Parent : WorkspaceEntity> getOneToOneParent(connectionId: ConnectionId, childId: Int, transformer: IntFunction<Parent?>): Parent? {
val bimap = oneToOneContainer[connectionId] ?: return null
if (!bimap.containsKey(childId)) return null
return transformer.apply(bimap.get(childId))
}
fun <Parent : WorkspaceEntity> getOneToManyParent(connectionId: ConnectionId, childId: Int, transformer: IntFunction<Parent?>): Parent? {
val bimap = oneToManyContainer[connectionId] ?: return null
if (!bimap.containsKey(childId)) return null
return transformer.apply(bimap.get(childId))
}
}
// TODO: 25.05.2021 Make it value class
internal data class ChildEntityId(val id: EntityId) {
override fun toString(): String {
return "ChildEntityId(id=${id.asString()})"
}
}
internal data class ParentEntityId(val id: EntityId) {
override fun toString(): String {
return "ParentEntityId(id=${id.asString()})"
}
}
internal fun EntityId.asChild(): ChildEntityId = ChildEntityId(this)
internal fun EntityId.asParent(): ParentEntityId = ParentEntityId(this)
internal fun sameClass(fromConnectionId: Int, myClazz: Int, type: ConnectionType): Boolean {
return when (type) {
ConnectionType.ONE_TO_ONE, ConnectionType.ONE_TO_MANY -> fromConnectionId == myClazz
ConnectionType.ONE_TO_ABSTRACT_MANY, ConnectionType.ABSTRACT_ONE_TO_ONE -> {
fromConnectionId.findWorkspaceEntity().isAssignableFrom(myClazz.findWorkspaceEntity())
}
}
}
| 7 | null | 5023 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 27,279 | intellij-community | Apache License 2.0 |
platform/script-debugger/backend/src/debugger/VmBase.kt | androidports | 115,100,208 | 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.debugger
import com.intellij.openapi.util.UserDataHolderBase
abstract class VmBase(override val debugListener: DebugEventListener) : Vm, AttachStateManager, UserDataHolderBase() {
override val evaluateContext by lazy(LazyThreadSafetyMode.NONE) { computeEvaluateContext() }
override val attachStateManager: AttachStateManager = this
protected open fun computeEvaluateContext(): EvaluateContext? = null
override var captureAsyncStackTraces: Boolean
get() = false
set(value) { }
} | 6 | null | 11 | 4 | 6e4f7135c5843ed93c15a9782f29e4400df8b068 | 1,121 | intellij-community | Apache License 2.0 |
modules/presentation/src/main/java/kr/co/knowledgerally/ui/coach/CoachViewModel.kt | YAPP-Github | 475,728,173 | false | {"Kotlin": 454888} | package kr.co.knowledgerally.ui.coach
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.filterIsInstance
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kr.co.knowledgerally.base.BaseViewModel
import kr.co.knowledgerally.bus.Event
import kr.co.knowledgerally.bus.EventBus
import kr.co.knowledgerally.domain.usecase.GetCoachLectureInfoListUseCase
import kr.co.knowledgerally.domain.usecase.GetUserStreamUseCase
import javax.inject.Inject
@HiltViewModel
class CoachViewModel @Inject constructor(
private val getUserStreamUseCase: GetUserStreamUseCase,
private val getCoachLectureInfoListUseCase: GetCoachLectureInfoListUseCase,
) : BaseViewModel() {
private val _tabState = MutableStateFlow(CoachTabState.Default)
val tabState = _tabState.asStateFlow()
private val _uiState = MutableStateFlow(CoachUiState())
val uiState: StateFlow<CoachUiState> = _uiState.asStateFlow()
init {
launch {
val user = getUserStreamUseCase().first()
if (user.coach) {
fetch()
} else {
_uiState.update { it.init() }
}
}
launch {
EventBus.event
.filterIsInstance<Event.LectureRegistered>()
.collect { refresh() }
}
}
private fun fetch() = launch {
getCoachLectureInfoListUseCase(null)
.onSuccess { _uiState.update { uiState -> uiState.from(it) } }
.onFailure { handleException(it) }
}
fun switchTab(newIndex: Int) {
if (newIndex != tabState.value.currentIndex) {
_tabState.update {
it.copy(currentIndex = newIndex)
}
}
}
fun refresh() {
_uiState.update { it.loading(true) }
fetch()
}
}
| 2 | Kotlin | 1 | 4 | 01db68b42594360a9285af458eb812ad83acef70 | 1,982 | 20th-ALL-Rounder-Team-2-Android | Apache License 2.0 |
src/main/kotlin/chapter02/Chapter02_2Main.kt | Sene68 | 582,619,559 | false | {"Kotlin": 29951} | package chapter02
fun main() {
val string1: String? = "Apple"
val string2: String? = null
val string3: String? = "Banana"
val resultA11 = startsWithA(string1)
//val resultA12 = startsWithA(string2)
val resultA13 = startsWithA(string3)
println("resultA11 : $resultA11")
//println("resultA12 : $resultA12")
println("resultA13 : $resultA13")
}
/**
* The !! Operator
* the not-null assertion operator (!!)
*/
fun startsWithA(str: String?): Boolean {
return str!!.startsWith("A")
} | 0 | Kotlin | 0 | 0 | 55adb5e92e8cb07bee9b4f8bf09aea503adc83b4 | 524 | java-to-kotlin | Apache License 2.0 |
libs/http/src/main/java/me/mo3in/kroid/http/HttpClient.kt | Kican | 144,122,131 | false | {"Kotlin": 78914, "Java": 1843} | package me.mo3in.kroid.http
import me.mo3in.kroid.commons.services.KServiceConfig
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.Executor
import java.util.concurrent.Executors
/**
* create an instance of retrofit interface for direct call
*/
object HttpClient {
fun makeBuilder(url: String, client: OkHttpClient? = null): Retrofit.Builder {
val builder = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
if (!url.isEmpty())
builder.baseUrl(url)
else
builder.baseUrl(KServiceConfig.httpEndPoint)
if (client != null)
builder.client(client)
return builder
}
inline fun <reified T> build(url: String = ""): T {
return makeBuilder(url).build().create(T::class.java)
}
inline fun <reified T> buildRx(url: String = ""): T {
val builder = makeBuilder(url)
.addCallAdapterFactory(RxJava2CallAdapterFactory.createAsync())
return builder.build().create(T::class.java)
}
} | 1 | Kotlin | 0 | 4 | 8cf0c0d20c96c6e375533758903518f7aca4e2e2 | 1,196 | Kroid | MIT License |
presentation/src/test/java/com/anytypeio/anytype/presentation/objects/appearance/LinkAppearanceInEditorTest.kt | anyproto | 647,371,233 | false | {"Kotlin": 11623123, "Java": 69306, "Shell": 11350, "Makefile": 1334} | package com.anytypeio.anytype.presentation.objects.appearance
import com.anytypeio.anytype.core_models.Block.Content.Link
import com.anytypeio.anytype.core_models.ObjectType
import com.anytypeio.anytype.core_models.Relations
import com.anytypeio.anytype.presentation.MockBlockContentFactory.StubLinkContent
import com.anytypeio.anytype.presentation.editor.editor.model.BlockView
import com.anytypeio.anytype.presentation.editor.editor.model.BlockView.Appearance.InEditor.Description
import kotlin.test.assertEquals
import org.junit.Test
class LinkAppearanceInEditorTest {
private val defaultLinkAppearance = StubLinkContent(
iconSize = Link.IconSize.NONE,
cardStyle = Link.CardStyle.TEXT,
description = Link.Description.NONE,
relations = emptySet()
)
@Test
fun `should create appearance params with default values`() {
val factory = LinkAppearanceFactory(
content = defaultLinkAppearance,
layout = ObjectType.Layout.BASIC
)
val actual = factory.createInEditorLinkAppearance()
val expected = BlockView.Appearance.InEditor(
isCard = false,
showIcon = false,
description = Description.NONE,
showCover = false,
showType = false,
icon = BlockView.Appearance.InEditor.Icon.NONE
)
assertEquals(expected, actual)
}
@Test
fun `when layout is null - create appearance params with default values`() {
val factory = LinkAppearanceFactory(
content = defaultLinkAppearance,
layout = null
)
val actual = factory.createInEditorLinkAppearance()
val expected = BlockView.Appearance.InEditor(
isCard = false,
showIcon = false,
description = Description.NONE,
showCover = false,
showType = false,
icon = BlockView.Appearance.InEditor.Icon.NONE
)
assertEquals(expected, actual)
}
@Test
fun `should create appearance params without cover`() {
val factory = LinkAppearanceFactory(
content = defaultLinkAppearance.copy(
relations = defaultLinkAppearance.relations + Relations.COVER
),
layout = ObjectType.Layout.BASIC
)
val actual = factory.createInEditorLinkAppearance()
val expected = BlockView.Appearance.InEditor(
isCard = false,
showIcon = false,
description = Description.NONE,
showCover = false,
showType = false,
icon = BlockView.Appearance.InEditor.Icon.NONE
)
assertEquals(expected, actual)
}
@Test
fun `when layout is todo`() {
val factory = LinkAppearanceFactory(
content = defaultLinkAppearance,
layout = ObjectType.Layout.TODO
)
val actual = factory.createInEditorLinkAppearance()
val expected = BlockView.Appearance.InEditor(
isCard = false,
showIcon = true,
description = Description.NONE,
showCover = false,
showType = false,
icon = BlockView.Appearance.InEditor.Icon.NONE
)
assertEquals(expected, actual)
}
@Test
fun `when layout is note`() {
val factory = LinkAppearanceFactory(
content = defaultLinkAppearance.copy(
iconSize = Link.IconSize.SMALL
),
layout = ObjectType.Layout.NOTE
)
val actual = factory.createInEditorLinkAppearance()
val expected = BlockView.Appearance.InEditor(
isCard = false,
showIcon = false,
description = Description.NONE,
showCover = false,
showType = false,
icon = BlockView.Appearance.InEditor.Icon.SMALL
)
assertEquals(expected, actual)
}
@Test
fun `when iconSize is none - no icon`() {
val factory = LinkAppearanceFactory(
content = defaultLinkAppearance.copy(
iconSize = Link.IconSize.NONE
),
layout = ObjectType.Layout.BASIC
)
val actual = factory.createInEditorLinkAppearance()
val expected = BlockView.Appearance.InEditor(
isCard = false,
showIcon = false,
description = Description.NONE,
showCover = false,
showType = false,
icon = BlockView.Appearance.InEditor.Icon.NONE
)
assertEquals(expected, actual)
}
@Test
fun `when card style text - relatoin description`() {
val factory = LinkAppearanceFactory(
content = defaultLinkAppearance.copy(
cardStyle = Link.CardStyle.TEXT,
description = Link.Description.ADDED
),
layout = ObjectType.Layout.BASIC
)
val actual = factory.createInEditorLinkAppearance()
val expected = BlockView.Appearance.InEditor(
isCard = false,
showIcon = false,
description = Description.RELATION,
showCover = false,
showType = false,
icon = BlockView.Appearance.InEditor.Icon.NONE
)
assertEquals(expected, actual)
}
@Test
fun `when card style text - snippet description`() {
val factory = LinkAppearanceFactory(
content = defaultLinkAppearance.copy(
cardStyle = Link.CardStyle.TEXT,
description = Link.Description.CONTENT
),
layout = ObjectType.Layout.BASIC
)
val actual = factory.createInEditorLinkAppearance()
val expected = BlockView.Appearance.InEditor(
isCard = false,
showIcon = false,
description = Description.SNIPPET,
showCover = false,
showType = false,
icon = BlockView.Appearance.InEditor.Icon.NONE
)
assertEquals(expected, actual)
}
@Test
fun `when card style card - there is description`() {
val factory = LinkAppearanceFactory(
content = defaultLinkAppearance.copy(
cardStyle = Link.CardStyle.CARD,
description = Link.Description.ADDED
),
layout = ObjectType.Layout.BASIC
)
val actual = factory.createInEditorLinkAppearance()
val expected = BlockView.Appearance.InEditor(
isCard = true,
showIcon = false,
description = Description.RELATION,
showCover = false,
showType = false,
icon = BlockView.Appearance.InEditor.Icon.NONE
)
assertEquals(expected, actual)
}
} | 45 | Kotlin | 43 | 528 | c708958dcb96201ab7bb064c838ffa8272d5f326 | 6,825 | anytype-kotlin | RSA Message-Digest License |
app/src/androidTest/java/com/steleot/jetpackcompose/playground/compose/ui/TextIndentScreenTest.kt | Vivecstel | 338,792,534 | false | null | package com.steleot.jetpackcompose.playground.compose.ui
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import com.steleot.jetpackcompose.playground.MainActivity
import com.steleot.jetpackcompose.playground.compose.theme.TestTheme
import org.junit.Rule
import org.junit.Test
class TextIndentScreenTest {
@get:Rule
val composeTestRule = createAndroidComposeRule<MainActivity>()
@Test
fun testTextIndentScreen() {
composeTestRule.setContent {
TestTheme {
TextIndentScreen()
}
}
// todo
}
} | 0 | Kotlin | 16 | 161 | d853dddc7b00735dc9067f3325a2662977a01348 | 592 | Jetpack-Compose-Playground | Apache License 2.0 |
mockk/src/main/kotlin/io/mockk/impl/RecordingCallRecorderState.kt | raosuj | 113,252,883 | true | {"Kotlin": 219752, "Java": 47524, "HTML": 2876, "CSS": 348, "Shell": 303} | package io.mockk.impl
import io.mockk.InternalPlatform
import io.mockk.Invocation
import io.mockk.Matcher
import io.mockk.MockKException
import kotlin.reflect.KClass
internal abstract class RecordingCallRecorderState(recorder: CallRecorderImpl) : CallRecorderState(recorder) {
private var callRoundBuilder: CallRoundBuilder? = null
private val callRounds = mutableListOf<CallRound>()
val childMocks = ChildMocks()
override fun catchArgs(round: Int, n: Int) {
val builder = callRoundBuilder
if (builder != null) {
callRounds.add(builder.build())
}
callRoundBuilder = recorder.factories.callRoundBuilder()
recorder.childHinter = recorder.factories.childHinter()
if (round == n) {
signMatchers()
mockRealChilds()
}
}
private fun signMatchers() {
recorder.calls.clear()
val detector = recorder.factories.signatureMatcherDetector(callRounds, childMocks.mocks)
recorder.calls.addAll(detector.detect())
}
override fun <T : Any> matcher(matcher: Matcher<*>, cls: KClass<T>): T {
val signatureValue = recorder.signatureValueGenerator.signatureValue(cls) {
recorder.instantiator.instantiate(cls)
}
builder().addMatcher(matcher, InternalPlatform.packRef(signatureValue)!!)
return signatureValue
}
override fun call(invocation: Invocation): Any? {
childMocks.requireNoArgIsChildMock(invocation.args)
val retType = recorder.childHinter.nextChildType { invocation.method.returnType }
builder().addSignedCall(retType, invocation)
return recorder.anyValueGenerator.anyValue(retType) {
childMocks.childMock(retType) {
recorder.mockFactory.childMock(retType)
}
}
}
fun mockRealChilds() {
val mocker = RealChildMocker(recorder.stubRepo, recorder.calls)
mocker.mock()
recorder.calls.clear()
recorder.calls.addAll(mocker.resultCalls)
log.trace { "Mocked childs" }
}
override fun nCalls(): Int = callRoundBuilder?.signedCalls?.size ?: 0
/**
* Main idea is to have enough random information
* to create signature for the argument.
*
* Max 40 calls looks like reasonable compromise
*/
override fun estimateCallRounds(): Int {
return builder().signedCalls
.flatMap { it.invocation.args }
.filterNotNull()
.map(this::typeEstimation)
.max() ?: 1
}
private fun typeEstimation(it: Any): Int {
return when (it::class) {
Boolean::class -> 40
Byte::class -> 8
Char::class -> 4
Short::class -> 4
Int::class -> 2
Float::class -> 2
else -> 1
}
}
private fun builder(): CallRoundBuilder = callRoundBuilder
?: throw MockKException("Call builder is not initialized. Bad state")
companion object {
val log = Logger<RecordingCallRecorderState>()
}
} | 0 | Kotlin | 0 | 0 | 2d46ac176678f2fa24be2389396646b43e4e3dc0 | 3,115 | mockk | Apache License 2.0 |
src/main/kotlin/com/templ/templ/TemplFormatter.kt | templ-go | 713,014,034 | false | {"Kotlin": 49966, "Java": 46747, "Lex": 10177, "templ": 5228} | package com.templ.templ
import com.intellij.execution.configurations.GeneralCommandLine
import com.intellij.execution.process.CapturingProcessAdapter
import com.intellij.execution.process.OSProcessHandler
import com.intellij.execution.process.ProcessEvent
import com.intellij.formatting.FormattingContext
import com.intellij.formatting.service.AsyncDocumentFormattingService
import com.intellij.formatting.service.AsyncFormattingRequest
import com.intellij.formatting.service.FormattingService
import com.intellij.psi.PsiFile
import com.intellij.util.SmartList
import java.io.File
import java.nio.charset.StandardCharsets
class TemplFormatter : AsyncDocumentFormattingService() {
override fun getFeatures(): MutableSet<FormattingService.Feature> {
return mutableSetOf(FormattingService.Feature.AD_HOC_FORMATTING)
}
override fun canFormat(psi: PsiFile): Boolean {
return psi.fileType == TemplFileType
}
override fun createFormattingTask(request: AsyncFormattingRequest): FormattingTask? {
val formattingContext: FormattingContext = request.context
val project = formattingContext.project
val file = request.ioFile ?: return null
val templConfigService = TemplSettings.getService(project)
if (file.extension != "templ") return null
val executable = File(templConfigService.getTemplLspPath())
if (!executable.exists()) return null
val params = SmartList<String>()
params.add("fmt")
params.add("-stdout")
params.add(file.absolutePath)
val commandLine: GeneralCommandLine = GeneralCommandLine()
.withParentEnvironmentType(GeneralCommandLine.ParentEnvironmentType.CONSOLE)
.withExePath(executable.absolutePath)
.withParameters(params)
val handler = OSProcessHandler(commandLine.withCharset(StandardCharsets.UTF_8))
return object : FormattingTask {
override fun run() {
handler.addProcessListener(object : CapturingProcessAdapter() {
override fun processTerminated(event: ProcessEvent) {
val exitCode = event.exitCode
if (exitCode == 0) {
request.onTextReady(output.stdout)
} else {
request.onError("TemplFormatter", output.stderr)
}
}
})
handler.startNotify()
}
override fun cancel(): Boolean {
handler.destroyProcess()
return true
}
}
}
override fun getNotificationGroupId() = "TemplFormatter"
override fun getName() = "TemplFormatter"
}
| 10 | Kotlin | 11 | 68 | 723bc0371dc0dc88883b042ef248f7378fdb538b | 2,772 | templ-jetbrains | MIT License |
libp2p/src/main/kotlin/io/libp2p/security/noise/NoiseXXSecureChannel.kt | libp2p | 189,293,403 | false | null | package io.libp2p.security.noise
import com.google.protobuf.ByteString
import com.southernstorm.noise.protocol.DHState
import com.southernstorm.noise.protocol.HandshakeState
import com.southernstorm.noise.protocol.Noise
import io.libp2p.core.P2PChannel
import io.libp2p.core.PeerId
import io.libp2p.core.crypto.PrivKey
import io.libp2p.core.crypto.PubKey
import io.libp2p.core.crypto.marshalPublicKey
import io.libp2p.core.crypto.unmarshalPublicKey
import io.libp2p.core.multistream.ProtocolDescriptor
import io.libp2p.core.security.SecureChannel
import io.libp2p.etc.types.toByteArray
import io.libp2p.etc.types.toByteBuf
import io.libp2p.etc.types.toUShortBigEndian
import io.libp2p.etc.types.uShortToBytesBigEndian
import io.libp2p.etc.util.netty.SplitEncoder
import io.libp2p.security.InvalidRemotePubKey
import io.libp2p.security.SecureHandshakeError
import io.netty.buffer.ByteBuf
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.CombinedChannelDuplexHandler
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.handler.codec.LengthFieldBasedFrameDecoder
import io.netty.handler.codec.LengthFieldPrepender
import io.netty.handler.timeout.ReadTimeoutHandler
import org.apache.logging.log4j.LogManager
import spipe.pb.Spipe
import java.util.concurrent.CompletableFuture
private enum class Role(val intVal: Int) { INIT(HandshakeState.INITIATOR), RESP(HandshakeState.RESPONDER) }
private val log = LogManager.getLogger(NoiseXXSecureChannel::class.java)
private const val HandshakeNettyHandlerName = "HandshakeNettyHandler"
private const val HandshakeReadTimeoutNettyHandlerName = "HandshakeReadTimeoutNettyHandler"
private const val NoiseCodeNettyHandlerName = "NoiseXXCodec"
private const val MaxCipheredPacketLength = 65535
private const val HandshakeTimeoutSec = 5
class UShortLengthCodec : CombinedChannelDuplexHandler<LengthFieldBasedFrameDecoder, LengthFieldPrepender>(
LengthFieldBasedFrameDecoder(MaxCipheredPacketLength + 2, 0, 2, 0, 2),
LengthFieldPrepender(2)
)
class NoiseXXSecureChannel(private val localKey: PrivKey) :
SecureChannel {
companion object {
const val protocolName = "Noise_XX_25519_ChaChaPoly_SHA256"
const val announce = "/noise"
@JvmStatic
var localStaticPrivateKey25519: ByteArray = ByteArray(32).also { Noise.random(it) }
// temporary flag to handle different Noise handshake treatments
// if true the noise handshake payload is prepended with 2 bytes encoded length
@JvmStatic
var rustInteroperability = false
}
override val protocolDescriptor = ProtocolDescriptor(announce)
fun initChannel(ch: P2PChannel): CompletableFuture<SecureChannel.Session> {
return initChannel(ch, "")
} // initChannel
override fun initChannel(
ch: P2PChannel,
selectedProtocol: String
): CompletableFuture<SecureChannel.Session> {
val handshakeComplete = CompletableFuture<SecureChannel.Session>()
// Packet length codec should stay forever.
ch.pushHandler(UShortLengthCodec())
// Handshake and ReadTimeout handlers are to be removed when handshake is complete
ch.pushHandler(HandshakeReadTimeoutNettyHandlerName, ReadTimeoutHandler(HandshakeTimeoutSec))
ch.pushHandler(
HandshakeNettyHandlerName,
NoiseIoHandshake(localKey, handshakeComplete, if (ch.isInitiator) Role.INIT else Role.RESP)
)
return handshakeComplete
} // initChannel
} // class NoiseXXSecureChannel
private class NoiseIoHandshake(
private val localKey: PrivKey,
private val handshakeComplete: CompletableFuture<SecureChannel.Session>,
private val role: Role
) : SimpleChannelInboundHandler<ByteBuf>() {
private val handshakeState = HandshakeState(NoiseXXSecureChannel.protocolName, role.intVal)
private val localNoiseState = Noise.createDH("25519")
private var sentNoiseKeyPayload = false
private var instancePayload: ByteArray? = null
private var activated = false
private var remotePeerId: PeerId? = null
init {
log.debug("Starting handshake")
// configure the localDHState with the private
// which will automatically generate the corresponding public key
localNoiseState.setPrivateKey(NoiseXXSecureChannel.localStaticPrivateKey25519, 0)
handshakeState.localKeyPair.copyFrom(localNoiseState)
handshakeState.start()
} // init
override fun channelActive(ctx: ChannelHandlerContext) {
if (activated) return
activated = true
// even though both the alice and bob parties can have the payload ready
// the Noise protocol only permits alice to send a packet first
if (role == Role.INIT) {
sendNoiseMessage(ctx)
}
} // channelActive
override fun channelRead0(ctx: ChannelHandlerContext, msg: ByteBuf) {
channelActive(ctx)
// we always read from the wire when it's the next action to take
// capture any payloads
if (handshakeState.action == HandshakeState.READ_MESSAGE) {
readNoiseMessage(msg.toByteArray())
}
// verify the signature of the remote's noise static public key once
// the remote public key has been provided by the XX protocol
with(handshakeState.remotePublicKey) {
if (hasPublicKey()) {
remotePeerId = verifyPayload(ctx, instancePayload!!, this)
}
}
// after reading messages and setting up state, write next message onto the wire
if (handshakeState.action == HandshakeState.WRITE_MESSAGE) {
sendNoiseStaticKeyAsPayload(ctx)
}
if (handshakeState.action == HandshakeState.SPLIT) {
splitHandshake(ctx)
}
} // channelRead0
override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
handshakeFailed(ctx, cause)
ctx.channel().close()
} // exceptionCaught
override fun channelUnregistered(ctx: ChannelHandlerContext) {
handshakeFailed(ctx, "Connection was closed ${ctx.channel()}")
super.channelUnregistered(ctx)
} // channelUnregistered
private fun readNoiseMessage(msg: ByteArray) {
log.debug("Noise handshake READ_MESSAGE")
var payload = ByteArray(msg.size)
var payloadLength = handshakeState.readMessage(msg, 0, msg.size, payload, 0)
if (NoiseXXSecureChannel.rustInteroperability) {
if (payloadLength > 0) {
if (payloadLength < 2) throw SecureHandshakeError()
payloadLength = payload.sliceArray(0..1).toUShortBigEndian()
if (payload.size < payloadLength + 2) throw SecureHandshakeError()
payload = payload.sliceArray(2 until payloadLength + 2)
}
}
log.trace("msg.size:" + msg.size)
log.trace("Read message size:$payloadLength")
if (instancePayload == null && payloadLength > 0) {
// currently, only allow storing a single payload for verification (this should maybe be changed to a queue)
instancePayload = ByteArray(payloadLength)
payload.copyInto(instancePayload!!, 0, 0, payloadLength)
}
} // readNoiseMessage
/**
* Sends the next Noise message with a payload of the identities and signatures
* Currently does not include additional data in the payload.
*/
private fun sendNoiseStaticKeyAsPayload(ctx: ChannelHandlerContext) {
// only send the Noise static key once
if (sentNoiseKeyPayload) return
sentNoiseKeyPayload = true
// the payload consists of the identity public key, and the signature of the noise static public key
// the actual noise static public key is sent later as part of the XX handshake
// get identity public key
val identityPublicKey: ByteArray = marshalPublicKey(localKey.publicKey())
// get noise static public key signature
val localNoiseStaticKeySignature =
localKey.sign(noiseSignaturePhrase(localNoiseState))
// generate an appropriate protobuf element
val noiseHandshakePayload =
Spipe.NoiseHandshakePayload.newBuilder()
.setLibp2PKey(ByteString.copyFrom(identityPublicKey))
.setNoiseStaticKeySignature(ByteString.copyFrom(localNoiseStaticKeySignature))
.setLibp2PData(ByteString.EMPTY)
.setLibp2PDataSignature(ByteString.EMPTY)
.build()
.toByteArray()
// create the message with the signed payload -
// verification happens once the noise static key is shared
log.debug("Sending signed Noise static public key as payload")
sendNoiseMessage(ctx, noiseHandshakePayload)
} // sendNoiseStaticKeyAsPayload
private fun sendNoiseMessage(ctx: ChannelHandlerContext, msg: ByteArray? = null) {
val lenMsg = if (!NoiseXXSecureChannel.rustInteroperability) {
msg
} else if (msg != null) {
msg.size.uShortToBytesBigEndian() + msg
} else {
null
}
val msgLength = lenMsg?.size ?: 0
val outputBuffer = ByteArray(msgLength + (2 * (handshakeState.localKeyPair.publicKeyLength + 16))) // 16 is MAC length
val outputLength = handshakeState.writeMessage(outputBuffer, 0, lenMsg, 0, msgLength)
log.debug("Noise handshake WRITE_MESSAGE")
log.trace("Sent message length:$outputLength")
ctx.writeAndFlush(outputBuffer.copyOfRange(0, outputLength).toByteBuf())
} // sendNoiseMessage
private fun verifyPayload(
ctx: ChannelHandlerContext,
payload: ByteArray,
remotePublicKeyState: DHState
): PeerId {
log.debug("Verifying noise static key payload")
val (pubKeyFromMessage, signatureFromMessage) = unpackKeyAndSignature(payload)
val verified = pubKeyFromMessage.verify(
noiseSignaturePhrase(remotePublicKeyState),
signatureFromMessage
)
log.debug("Remote verification is $verified")
if (!verified) {
handshakeFailed(ctx, InvalidRemotePubKey())
}
return PeerId.fromPubKey(pubKeyFromMessage)
} // verifyPayload
private fun unpackKeyAndSignature(payload: ByteArray): Pair<PubKey, ByteArray> {
val noiseMsg = Spipe.NoiseHandshakePayload.parseFrom(payload)
val publicKey = unmarshalPublicKey(noiseMsg.libp2PKey.toByteArray())
val signature = noiseMsg.noiseStaticKeySignature.toByteArray()
return Pair(publicKey, signature)
} // unpackKeyAndSignature
private fun splitHandshake(ctx: ChannelHandlerContext) {
val cipherStatePair = handshakeState.split()
val aliceSplit = cipherStatePair.sender
val bobSplit = cipherStatePair.receiver
log.debug("Split complete")
// put alice and bob security sessions into the context and trigger the next action
val secureSession = NoiseSecureChannelSession(
PeerId.fromPubKey(localKey.publicKey()),
remotePeerId!!,
localKey.publicKey(),
aliceSplit,
bobSplit
)
handshakeSucceeded(ctx, secureSession)
} // splitHandshake
private fun handshakeSucceeded(ctx: ChannelHandlerContext, session: NoiseSecureChannelSession) {
handshakeComplete.complete(session)
ctx.pipeline()
.addBefore(
HandshakeNettyHandlerName,
NoiseCodeNettyHandlerName,
NoiseXXCodec(session.aliceCipher, session.bobCipher)
)
// according to Libp2p spec transport payload should also be length-prefixed
// though Rust Libp2p implementation doesn't do it
// https://github.com/libp2p/specs/tree/master/noise#wire-format
// ctx.pipeline()
// .addBefore(HandshakeNettyHandlerName, "NoiseXXPayloadLenCodec", UShortLengthCodec())
ctx.pipeline().addAfter(
NoiseCodeNettyHandlerName,
"NoisePacketSplitter",
SplitEncoder(MaxCipheredPacketLength - session.aliceCipher.macLength)
)
ctx.pipeline().remove(HandshakeReadTimeoutNettyHandlerName)
ctx.pipeline().remove(this)
ctx.fireChannelActive()
} // handshakeSucceeded
private fun handshakeFailed(ctx: ChannelHandlerContext, cause: String) {
handshakeFailed(ctx, Exception(cause))
}
private fun handshakeFailed(ctx: ChannelHandlerContext, cause: Throwable) {
log.debug("Noise handshake failed", cause)
handshakeComplete.completeExceptionally(cause)
ctx.pipeline().remove(HandshakeReadTimeoutNettyHandlerName)
ctx.pipeline().remove(this)
}
} // class NoiseIoHandshake
private fun noiseSignaturePhrase(dhState: DHState) =
"noise-libp2p-static-key:".toByteArray() + dhState.publicKey
private val DHState.publicKey: ByteArray
get() {
val pubKey = ByteArray(publicKeyLength)
getPublicKey(pubKey, 0)
return pubKey
}
| 33 | null | 76 | 272 | 1cde874089d45f90e2f6ca20f39a77b69cd7e66e | 13,178 | jvm-libp2p | Apache License 2.0 |
src/main/kotlin/io/realworld/conduit/article/domain/Article.kt | Davidonium | 217,222,926 | false | null | package io.realworld.conduit.article.domain
import io.realworld.conduit.profile.domain.Profile
import java.time.OffsetDateTime
data class ArticleId(val value: Int = 0)
class Article(
val id: ArticleId,
val slug: String,
val title: String,
val description: String,
val body: String,
val createdAt: OffsetDateTime,
val updatedAt: OffsetDateTime? = null,
val author: Profile,
val tags: List<Tag> = listOf()
) {
fun withId(id: ArticleId): Article {
return Article(
id = id,
slug = slug,
title = title,
description = description,
body = body,
createdAt = createdAt,
updatedAt = updatedAt,
author = author,
tags = tags
)
}
}
| 0 | Kotlin | 1 | 3 | 3204f521806dfde901f415cdd4fcdfd5446a6524 | 790 | realworld-kotlin-javalin-jooq | MIT License |
app/src/main/java/com/bayraktar/healthybackandneck/ui/Food/TablayoutAdapters/FruitFragment.kt | OzerBAYRAKTAR | 681,364,096 | false | {"Kotlin": 364437} | package com.bayraktar.healthybackandneck.ui.Food.TablayoutAdapters
import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentTransaction
import androidx.recyclerview.widget.GridLayoutManager
import com.bayraktar.healthybackandneck.data.Models.FoodModel.FoodItems
import com.bayraktar.healthybackandneck.R
import com.bayraktar.healthybackandneck.databinding.FragmentFruitBinding
import com.bayraktar.healthybackandneck.ui.FoodDetail.FoodDetailFragment
import com.bayraktar.healthybackandneck.utils.Interfaces.RecyclerViewClickListener
import com.google.gson.Gson
class FruitFragment : Fragment(), RecyclerViewClickListener {
private var _binding: FragmentFruitBinding?= null
val binding get() = _binding!!
private lateinit var foodAdapter: FoodTablayoutAdapter
private var foodList= emptyList<FoodItems>()
lateinit var context: AppCompatActivity
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
_binding = FragmentFruitBinding.inflate(inflater,container,false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setRecyclerview()
foodList = listOf(
FoodItems(
id = 1,
title = getString(R.string.muz),
calori = "88 calorie",
imageFood = R.drawable.muz,
protein = "1.1 gr",
carb = "23 gr",
yag = "0.3 gr",
vitaminC = "8.7 mg",
sodium = "1 mg",
calsium = "5 mg",
potasium = "358 mg",
magnesium = "27 mg",
iron = "0.3 mg"
),
FoodItems(
id = 2,
title = getString(R.string.elma),
calori = "52 calorie",
imageFood = R.drawable.elma,
protein = "0.3 gr",
carb = "14 gr",
yag = "0.2 gr",
vitaminC = "4.6 mg",
sodium = "1 mg",
calsium = "6 mg",
potasium = "107 mg",
magnesium = "5 mg",
iron = "0.1 mg"
),
FoodItems(
id = 3,
title = getString(R.string.armut),
calori = "57 calorie",
imageFood = R.drawable.armut,
protein = "0.4 gr",
carb = "15 gr",
yag = "0.1 gr",
vitaminC = "4.3 mg",
sodium = "1 mg",
calsium = "9 mg",
potasium = "116 mg",
magnesium = "7 mg",
iron = "0.2 mg"
),
FoodItems(
id = 4,
title = getString(R.string.cilek),
calori = "32 calorie",
imageFood = R.drawable.cilek,
protein = "0.7 gr",
carb = "8 gr",
yag = "0.3 gr",
vitaminC = "58.8 mg",
sodium = "1 mg",
calsium = "16 mg",
potasium = "153 mg",
magnesium = "13 mg",
iron = "0.4 mg"
),
FoodItems(
id = 5,
title = getString(R.string.karpuz),
calori = "30 calorie",
imageFood = R.drawable.karpuz,
protein = "0.6 gr",
carb = "8 gr",
yag = "0.2 gr",
vitaminC = "8.1 mg",
sodium = "1 mg",
calsium = "7 mg",
potasium = "112 mg",
magnesium = "10 mg",
iron = "0.2 mg"
),
FoodItems(
id = 6,
title = getString(R.string.kavun),
calori = "33 calorie",
imageFood = R.drawable.kavun,
protein = "0.8 gr",
carb = "8 gr",
yag = "0.2 gr",
vitaminC = "36.7 mg",
sodium = "16 mg",
calsium = "9 mg",
potasium = "267 mg",
magnesium = "120 mg",
iron = "0.2 mg"
),
FoodItems(
id = 7,
title = getString(R.string.seftali),
calori = "39 calorie",
imageFood = R.drawable.seftali,
protein = "0.9 gr",
carb = "10 gr",
yag = "0.3 gr",
vitaminC = "6.6 mg",
sodium = "0 mg",
calsium = "6 mg",
potasium = "190 mg",
magnesium = "9 mg",
iron = "0.3 mg"
),
FoodItems(
id = 8,
title = getString(R.string.kayisi),
calori = "48 calorie",
imageFood = R.drawable.kayisi,
protein = "1.4 gr",
carb = "11 gr",
yag = "0.4 gr",
vitaminC = "10 mg",
sodium = "1 mg",
calsium = "13 mg",
potasium = "259 mg",
magnesium = "10 mg",
iron = "0.4 mg"
),
FoodItems(
id = 9,
title = getString(R.string.erik),
calori = "45 calorie",
imageFood = R.drawable.erik,
protein = "0.7 gr",
carb = "11 gr",
yag = "0.3 gr",
vitaminC = "9.5 mg",
sodium = "0 mg",
calsium = "6 mg",
potasium = "157 mg",
magnesium = "7 mg",
iron = "0.2 mg"
),
FoodItems(
id = 10,
title = getString(R.string.incir),
calori = "74 calorie",
imageFood = R.drawable.incir,
protein = "0.8 gr",
carb = "19 gr",
yag = "0.3 gr",
vitaminC = "2 mg",
sodium = "1 mg",
calsium = "35 mg",
potasium = "232 mg",
magnesium = "17 mg",
iron = "0.4 mg"
),
FoodItems(
id = 11,
title = getString(R.string.uzum),
calori = "67 calorie",
imageFood = R.drawable.uzum,
protein = "0.6 gr",
carb = "17 gr",
yag = "0.4 gr",
vitaminC = "4 mg",
sodium = "2 mg",
calsium = "14 mg",
potasium = "191 mg",
magnesium = "5 mg",
iron = "0.3 mg"
),
FoodItems(
id = 12,
title = getString(R.string.kiraz),
calori = "50 calorie",
imageFood = R.drawable.kiraz,
protein = "1 gr",
carb = "12 gr",
yag = "0.3 gr",
vitaminC = "10 mg",
sodium = "3 mg",
calsium = "16 mg",
potasium = "173 mg",
magnesium = "9 mg",
iron = "0.3 mg"
),
)
foodAdapter = FoodTablayoutAdapter(foodList,this)
binding.rvMealList.adapter = foodAdapter
foodAdapter.setData(foodList)
}
private fun setRecyclerview() = with(binding) {
val layoutmanager = GridLayoutManager(requireContext(),2)
rvMealList.layoutManager = layoutmanager
foodAdapter = FoodTablayoutAdapter(foodList,this@FruitFragment)
rvMealList.adapter = foodAdapter
}
override fun onAttach(context: Context) {
super.onAttach(context)
this.context = context as AppCompatActivity
}
override fun recyclerviewListClicked(v: View, position: Int) {
val listProduct = foodList
val id = foodList[position].id
val fm = context.supportFragmentManager
val bundle = Bundle()
val gson = Gson()
val json = gson.toJson(listProduct)
bundle.putInt("intValue",id)
bundle.putString("jsonList", json)
val receiver = FoodDetailFragment()
receiver.arguments = bundle
val transaction : FragmentTransaction = fm.beginTransaction()
transaction.replace(R.id.containerfood,receiver).addToBackStack("transactionTag")
transaction.commit()
}
} | 0 | Kotlin | 0 | 0 | ffff5bab67a36818fa49b9993b33d1f8842e3ac6 | 8,889 | HealthyBackandNeck | MIT License |
examples/media/userflowpolicy/src/main/kotlin/com/example/ivi/example/media/userflowpolicy/ExampleMediaSourceBrowseUserFlow.kt | tomtom-international | 545,425,009 | false | {"Kotlin": 11258} | package com.example.ivi.example.media.userflowpolicy
import com.tomtom.ivi.appsuite.media.api.common.core.SourceId
import com.tomtom.ivi.appsuite.media.api.common.frontend.MediaFrontendContext
import com.tomtom.ivi.appsuite.media.api.common.frontend.policies.BrowseSourceUserFlow
import com.tomtom.ivi.appsuite.media.api.common.frontend.policies.UserFlowResult
/**
* An implementation of [BrowseSourceUserFlow] which opens a custom [ExampleMediaSourcePanel] to
* browse the source.
*/
internal class ExampleMediaSourceBrowseUserFlow : BrowseSourceUserFlow {
/**
* Performs a browse source user flow. The new panel is created and added to the stack. Always
* returns successful result.
*/
override suspend fun perform(
mediaFrontendContext: MediaFrontendContext,
sourceId: SourceId,
): UserFlowResult {
mediaFrontendContext.mediaFrontendNavigation.openMediaTaskPanel(
ExampleMediaSourcePanel(mediaFrontendContext),
)
return UserFlowResult.Success
}
}
| 0 | Kotlin | 5 | 6 | bc16c957e7b74cb9204e3ea11603994e358e4eda | 1,039 | tomtom-digital-cockpit-sdk-examples | FSF All Permissive License |
app/shared/state-machine/ui/public/src/commonTest/kotlin/build/wallet/statemachine/limit/SetSpendingLimitUiStateMachineImplTests.kt | proto-at-block | 761,306,853 | false | {"C": 10474259, "Kotlin": 8243078, "Rust": 2779264, "Swift": 893661, "HCL": 349246, "Python": 338898, "Shell": 136508, "TypeScript": 118945, "C++": 69203, "Meson": 64811, "JavaScript": 36398, "Just": 32977, "Ruby": 13559, "Dockerfile": 5934, "Makefile": 3915, "Open Policy Agent": 1552, "Procfile": 80} | package build.wallet.statemachine.limit
import app.cash.turbine.plusAssign
import build.wallet.coroutines.turbine.turbines
import build.wallet.f8e.auth.HwFactorProofOfPossession
import build.wallet.limit.MobilePayEnabledDataMock
import build.wallet.limit.MobilePayServiceMock
import build.wallet.limit.SpendingLimit
import build.wallet.limit.SpendingLimitMock
import build.wallet.money.BitcoinMoney
import build.wallet.money.FiatMoney
import build.wallet.money.currency.USD
import build.wallet.money.display.FiatCurrencyPreferenceRepositoryMock
import build.wallet.money.formatter.MoneyDisplayFormatterFake
import build.wallet.statemachine.ScreenStateMachineMock
import build.wallet.statemachine.core.LoadingSuccessBodyModel
import build.wallet.statemachine.core.awaitScreenWithBody
import build.wallet.statemachine.core.awaitScreenWithBodyModelMock
import build.wallet.statemachine.core.form.FormBodyModel
import build.wallet.statemachine.core.test
import build.wallet.statemachine.data.keybox.ActiveKeyboxLoadedDataMock
import build.wallet.statemachine.limit.picker.SpendingLimitPickerUiProps
import build.wallet.statemachine.limit.picker.SpendingLimitPickerUiStateMachine
import build.wallet.statemachine.ui.clickPrimaryButton
import build.wallet.time.TimeZoneProviderMock
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import kotlinx.datetime.TimeZone
class SetSpendingLimitUiStateMachineImplTests : FunSpec({
val onCloseCalls = turbines.create<Unit>("close calls")
val onSetLimitCalls = turbines.create<SpendingLimit>("set limit calls")
val mobilePayService = MobilePayServiceMock(turbines::create)
val timeZoneProvider = TimeZoneProviderMock()
val fiatCurrencyPreferenceRepository = FiatCurrencyPreferenceRepositoryMock(turbines::create)
val stateMachine: SetSpendingLimitUiStateMachine =
SetSpendingLimitUiStateMachineImpl(
spendingLimitPickerUiStateMachine =
object : SpendingLimitPickerUiStateMachine,
ScreenStateMachineMock<SpendingLimitPickerUiProps>(
id = "spending-limit-picker"
) {},
timeZoneProvider = timeZoneProvider,
moneyDisplayFormatter = MoneyDisplayFormatterFake,
fiatCurrencyPreferenceRepository = fiatCurrencyPreferenceRepository,
mobilePayService = mobilePayService
)
val props = SpendingLimitProps(
currentSpendingLimit = null,
onClose = { onCloseCalls += Unit },
onSetLimit = { onSetLimitCalls += it },
accountData = ActiveKeyboxLoadedDataMock
)
beforeTest {
mobilePayService.reset()
}
test("initial state with no spending limit") {
mobilePayService.mobilePayData.value = MobilePayEnabledDataMock
stateMachine.test(props) {
awaitScreenWithBodyModelMock<SpendingLimitPickerUiProps> {
initialLimit.shouldBe(FiatMoney.zero(USD))
}
}
}
test("initial state with spending limit") {
mobilePayService.mobilePayData.value = MobilePayEnabledDataMock
val testProps = props.copy(
currentSpendingLimit = SpendingLimitMock.amount
)
stateMachine.test(testProps) {
awaitScreenWithBodyModelMock<SpendingLimitPickerUiProps> {
initialLimit.shouldBe(SpendingLimitMock.amount)
}
}
}
test("onSaveLimit leads to saving limit loading screen") {
val limit = SpendingLimit(active = true, FiatMoney.usd(100.0), TimeZone.UTC)
stateMachine.test(props) {
awaitScreenWithBodyModelMock<SpendingLimitPickerUiProps> {
onSaveLimit(
FiatMoney.usd(100.0),
BitcoinMoney.btc(1.0),
HwFactorProofOfPossession("")
)
}
awaitScreenWithBody<LoadingSuccessBodyModel> {
message.shouldNotBeNull().shouldBe("Saving Limit...")
}
mobilePayService.setLimitCalls.awaitItem()
awaitScreenWithBody<FormBodyModel> {
header.shouldNotBeNull().run {
headline.shouldBe("You're all set.")
sublineModel.shouldNotBeNull().string.shouldBe(
"Now you can spend up to $100.00 (100,000,000 sats) per day with just your phone."
)
}
clickPrimaryButton()
}
onSetLimitCalls.awaitItem().shouldBe(limit)
}
}
})
| 3 | C | 16 | 113 | 694c152387c1fdb2b6be01ba35e0a9c092a81879 | 4,242 | bitkey | MIT License |
features/popular/src/main/java/com/lcabral/artseventh/features/popular/presentation/viewmodel/PopularViewModel.kt | LucianaCabral | 706,897,860 | false | {"Kotlin": 155389} | package com.lcabral.artseventh.features.popular.presentation.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lcabral.artseventh.core.domain.model.Movie
import com.lcabral.artseventh.core.domain.usecase.GetPopularUseCase
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
internal class PopularViewModel(
private val popularUseCase: GetPopularUseCase,
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
) : ViewModel() {
private val _viewState: MutableLiveData<PopularViewState> = MutableLiveData<PopularViewState>()
val viewState: LiveData<PopularViewState> = _viewState
private val _viewAction: MutableLiveData<PopularViewAction> =
MutableLiveData<PopularViewAction>()
val viewAction: LiveData<PopularViewAction> = _viewAction
init {
getPopular()
}
private fun getPopular() {
viewModelScope.launch {
popularUseCase.invoke()
.flowOn(dispatcher)
.onStart { handleLoading() }
.catch { handleError() }
.collect(::handlePopularSuccess)
}
}
private fun handlePopularSuccess(popularResults: List<Movie>) {
_viewState.value = PopularViewState(
flipperChild = SUCCESS_CHILD, getPopularResultItems = popularResults
)
}
private fun handleError() {
_viewState.value = PopularViewState(flipperChild = FAILURE_CHILD)
}
private fun handleLoading() {
_viewState.value = PopularViewState(flipperChild = LOADING_CHILD,getPopularResultItems = null)
}
fun onAdapterItemClicked(popular: Movie) {
_viewAction.value = PopularViewAction.GoToDetails(popular)
}
}
| 0 | Kotlin | 0 | 0 | db5146b7ff83227568a255c2d38c4df2380f408f | 1,996 | ArtSeventh | MIT License |
features/popular/src/main/java/com/lcabral/artseventh/features/popular/presentation/viewmodel/PopularViewModel.kt | LucianaCabral | 706,897,860 | false | {"Kotlin": 155389} | package com.lcabral.artseventh.features.popular.presentation.viewmodel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.lcabral.artseventh.core.domain.model.Movie
import com.lcabral.artseventh.core.domain.usecase.GetPopularUseCase
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
internal class PopularViewModel(
private val popularUseCase: GetPopularUseCase,
private val dispatcher: CoroutineDispatcher = Dispatchers.IO
) : ViewModel() {
private val _viewState: MutableLiveData<PopularViewState> = MutableLiveData<PopularViewState>()
val viewState: LiveData<PopularViewState> = _viewState
private val _viewAction: MutableLiveData<PopularViewAction> =
MutableLiveData<PopularViewAction>()
val viewAction: LiveData<PopularViewAction> = _viewAction
init {
getPopular()
}
private fun getPopular() {
viewModelScope.launch {
popularUseCase.invoke()
.flowOn(dispatcher)
.onStart { handleLoading() }
.catch { handleError() }
.collect(::handlePopularSuccess)
}
}
private fun handlePopularSuccess(popularResults: List<Movie>) {
_viewState.value = PopularViewState(
flipperChild = SUCCESS_CHILD, getPopularResultItems = popularResults
)
}
private fun handleError() {
_viewState.value = PopularViewState(flipperChild = FAILURE_CHILD)
}
private fun handleLoading() {
_viewState.value = PopularViewState(flipperChild = LOADING_CHILD,getPopularResultItems = null)
}
fun onAdapterItemClicked(popular: Movie) {
_viewAction.value = PopularViewAction.GoToDetails(popular)
}
}
| 0 | Kotlin | 0 | 0 | db5146b7ff83227568a255c2d38c4df2380f408f | 1,996 | ArtSeventh | MIT License |
core/src/main/java/com/nabla/sdk/core/data/device/DeviceRepositoryImpl.kt | nabla | 478,468,099 | false | null | package com.nabla.sdk.core.data.device
import com.apollographql.apollo3.ApolloClient
import com.apollographql.apollo3.api.Optional
import com.benasher44.uuid.Uuid
import com.nabla.sdk.core.data.apollo.ApolloResponseExt.dataOrThrowOnError
import com.nabla.sdk.core.data.exception.GraphQLException
import com.nabla.sdk.core.domain.boundary.DeviceRepository
import com.nabla.sdk.core.domain.boundary.ErrorReporter
import com.nabla.sdk.core.domain.boundary.Logger
import com.nabla.sdk.core.domain.entity.ModuleType
import com.nabla.sdk.core.domain.entity.StringId
import com.nabla.sdk.core.graphql.RegisterOrUpdateDeviceMutation
import com.nabla.sdk.core.graphql.type.DeviceInput
import com.nabla.sdk.core.graphql.type.DeviceOs
import com.nabla.sdk.core.graphql.type.SdkModule
import com.nabla.sdk.core.kotlin.KotlinExt.runCatchingCancellable
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
internal class DeviceRepositoryImpl(
private val deviceDataSource: DeviceDataSource,
private val installationDataSource: InstallationDataSource,
private val sdkApiVersionDataSource: SdkApiVersionDataSource,
private val apolloClient: ApolloClient,
private val logger: Logger,
private val errorReporter: ErrorReporter,
private val backgroundScope: CoroutineScope,
) : DeviceRepository {
override fun sendDeviceInfoAsync(activeModules: List<ModuleType>, userId: StringId) {
backgroundScope.launch {
logger.debug("Identifying current device", domain = LOG_DOMAIN)
val device = deviceDataSource.getDevice()
val gqlActiveModules = activeModules.map {
when (it) {
ModuleType.VIDEO_CALL -> SdkModule.VIDEO_CALL
ModuleType.MESSAGING -> SdkModule.MESSAGING
ModuleType.SCHEDULING -> SdkModule.VIDEO_CALL_SCHEDULING
}
}
val deviceInput = DeviceInput(
deviceModel = device.deviceModel,
os = DeviceOs.ANDROID,
osVersion = Optional.present(device.osVersion),
codeVersion = sdkApiVersionDataSource.getSdkApiVersion(),
sdkModules = gqlActiveModules,
)
runCatchingCancellable {
val installId = installationDataSource.getInstallIdOrNull(userId)
registerOrUpdateDeviceOp(installId, deviceInput)
}
.fold(
onSuccess = { Result.success(it) },
onFailure = { throwable ->
if (throwable is GraphQLException && throwable.numericCode in errorsToRegisterNewDevice) {
logger.info("Recoverable device update failure: will register a new one", throwable, domain = LOG_DOMAIN)
runCatchingCancellable {
registerOrUpdateDeviceOp(installId = null, deviceInput)
}
} else {
Result.failure(throwable)
}
},
)
.onSuccess {
with(it.registerOrUpdateDevice) {
logger.debug("Device $deviceId registered/updated successfully", domain = LOG_DOMAIN)
installationDataSource.storeInstallId(deviceId, userId)
if (sentry != null) {
errorReporter.enable(dsn = sentry.dsn, env = sentry.env)
} else {
errorReporter.disable()
}
}
}
.onFailure { exception ->
logger.warn(
"Unable to identify device. This is not important and will be retried next time the app restarts.",
exception,
domain = LOG_DOMAIN,
)
}
}
}
private suspend fun registerOrUpdateDeviceOp(installId: Uuid?, deviceInput: DeviceInput): RegisterOrUpdateDeviceMutation.Data {
logger.debug(
message = if (installId == null) "Registering new device" else "Updating device with id $installId",
domain = LOG_DOMAIN,
)
return apolloClient.mutation(
RegisterOrUpdateDeviceMutation(
deviceId = Optional.presentIfNotNull(installId),
device = deviceInput,
),
).execute().dataOrThrowOnError
}
companion object {
private const val LOG_DOMAIN = "Device"
private const val ERROR_ENTITY_NOT_FOUND = 20_000
private const val ERROR_DEVICE_BELONGS_TO_ANOTHER_USER = 48_000
private val errorsToRegisterNewDevice = listOf(ERROR_ENTITY_NOT_FOUND, ERROR_DEVICE_BELONGS_TO_ANOTHER_USER)
}
}
| 0 | null | 1 | 18 | ca83926d41a2028ca992d4aa66f4d387152c6cb4 | 4,908 | nabla-android | MIT License |
src/main/kotlin/no/nav/syfo/aareg/Arbeidsavtale.kt | navikt | 656,574,894 | false | {"Kotlin": 188879, "Dockerfile": 257} | package no.nav.syfo.aareg
import java.io.Serializable
data class Arbeidsavtale(
var antallTimerPrUke: Double? = null,
var arbeidstidsordning: String? = null,
var beregnetAntallTimerPrUke: Double? = null,
var bruksperiode: Bruksperiode? = null,
var gyldighetsperiode: Gyldighetsperiode? = null,
var sistLoennsendring: String? = null,
var sistStillingsendring: String? = null,
var sporingsinformasjon: Sporingsinformasjon? = null,
var stillingsprosent: Double,
var yrke: String
) : Serializable {
companion object {
private const val serialVersionUID: Long = 1L
}
}
| 6 | Kotlin | 0 | 0 | 155d819fa82a81eb94e9be29e9a8119d26cfc0b3 | 622 | oppfolgingsplan-backend | MIT License |
features/details/src/main/java/com/mnh/features/details/DetailsViewModel.kt | mnhmasum | 788,996,547 | false | {"Kotlin": 68870} | package com.mnh.features.details
import androidx.lifecycle.ViewModel
import com.mnh.ble.model.DeviceInfo
import com.mnh.features.details.usecase.PeripheralDetailsUseCase
import com.napco.utils.DataState
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
@HiltViewModel
class DetailsViewModel @Inject constructor(private val detailsUseCase: PeripheralDetailsUseCase) :
ViewModel() {
val bleGattState: Flow<DataState<DeviceInfo>> = detailsUseCase.bleGattConnectionResult()
fun connect(address: String):Flow<DataState<DeviceInfo>> {
detailsUseCase.connect(address)
return detailsUseCase.bleGattConnectionResult()
}
fun disconnect(address: String) {
detailsUseCase.disconnect()
}
} | 0 | Kotlin | 1 | 0 | 6bc769188450ab30a6425c69262e47f7796cf430 | 793 | ble-device-scanner | Apache License 2.0 |
protocol/osrs-223/src/main/kotlin/net/rsprox/protocol/ServerPacketDecoderService.kt | blurite | 822,339,098 | false | {"Kotlin": 1453055} | package net.rsprox.protocol
import net.rsprot.buffer.JagByteBuf
import net.rsprot.compression.HuffmanCodec
import net.rsprot.protocol.message.IncomingMessage
import net.rsprox.cache.api.CacheProvider
import net.rsprox.protocol.game.outgoing.decoder.prot.ServerMessageDecoderRepository
import net.rsprox.protocol.session.Session
public class ServerPacketDecoderService(
huffmanCodec: HuffmanCodec,
cache: CacheProvider,
) : ServerPacketDecoder {
@OptIn(ExperimentalStdlibApi::class)
private val repository =
ServerMessageDecoderRepository.build(
huffmanCodec,
cache,
)
override fun decode(
opcode: Int,
payload: JagByteBuf,
session: Session,
): IncomingMessage {
return repository
.getDecoder(opcode)
.decode(payload, session)
}
}
| 2 | Kotlin | 4 | 9 | 41535908e6ccb633c8f2564e8961efa771abd6de | 857 | rsprox | MIT License |
app/src/main/java/com/thedeveloperworldisyours/mytasks/database/Task.kt | thedeveloperworldisyours | 151,304,041 | false | null | package com.thedeveloperworldisyours.mytasks.database
import android.arch.persistence.room.ColumnInfo
import android.arch.persistence.room.Entity
import android.arch.persistence.room.PrimaryKey
/**
* Created by javiergonzalezcabezas on 3/10/18.
*/
@Entity(tableName = "task")
data class Task(@ColumnInfo(name = "completed_flag") var completed: Boolean = false,
@ColumnInfo(name = "task_desciption") var description: String) {
@ColumnInfo(name = "id")
@PrimaryKey(autoGenerate = true) var id: Long = 0
} | 0 | Kotlin | 0 | 0 | 722221d711041dbe03fa3499606bd443d4317d9d | 530 | RoomAnko | Apache License 2.0 |
src/main/kotlin/no/nav/klage/dokument/clients/clamav/ScanResult.kt | navikt | 297,650,936 | false | null | package no.nav.klage.clients.clamav
import com.fasterxml.jackson.annotation.JsonAlias
data class ScanResult(
@JsonAlias("Filename")
val filename: String,
@JsonAlias("Result")
val result: ClamAvResult
)
enum class ClamAvResult {
FOUND, OK, ERROR
}
| 3 | Kotlin | 1 | 2 | 168c8c4b9ed5192ac6870f88b6e82a665b29a4b9 | 270 | kabal-api | MIT License |
data/src/main/java/app/tivi/data/repositories/popularshows/PopularShowsRepository.kt | smtcrms | 196,380,817 | false | null | /*
* Copyright 2018 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 app.tivi.data.repositories.popularshows
import androidx.paging.DataSource
import app.tivi.data.entities.Success
import app.tivi.data.repositories.shows.ShowStore
import app.tivi.data.repositories.shows.ShowRepository
import app.tivi.data.resultentities.PopularEntryWithShow
import app.tivi.extensions.parallelForEach
import io.reactivex.Observable
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class PopularShowsRepository @Inject constructor(
private val popularShowsStore: PopularShowsStore,
private val showStore: ShowStore,
private val traktDataSource: TraktPopularShowsDataSource,
private val showRepository: ShowRepository
) {
fun observeForPaging(): DataSource.Factory<Int, PopularEntryWithShow> = popularShowsStore.observeForPaging()
fun observeForObservable(): Observable<List<PopularEntryWithShow>> = popularShowsStore.observeForObservable(15, 0)
suspend fun loadNextPage() {
val lastPage = popularShowsStore.getLastPage()
if (lastPage != null) updatePopularShows(lastPage + 1, false) else refresh()
}
suspend fun refresh() {
updatePopularShows(0, true)
}
private suspend fun updatePopularShows(page: Int, resetOnSave: Boolean) {
when (val response = traktDataSource.getPopularShows(page, 20)) {
is Success -> {
response.data.map { (show, entry) ->
// Grab the show id if it exists, or save the show and use it's generated ID
val showId = showStore.getIdOrSavePlaceholder(show)
// Make a copy of the entry with the id
entry.copy(showId = showId, page = page)
}.also { entries ->
if (resetOnSave) {
popularShowsStore.deleteAll()
}
// Save the popular entriesWithShows
popularShowsStore.savePopularShowsPage(page, entries)
// Now update all of the related shows if needed
entries.parallelForEach { entry ->
if (showRepository.needsUpdate(entry.showId)) {
showRepository.updateShow(entry.showId)
}
if (showRepository.needsImagesUpdate(entry.showId)) {
showRepository.updateShowImages(entry.showId)
}
}
}
}
}
}
} | 0 | Kotlin | 0 | 1 | 40dea42e7a819ccba3ab8e35bc0d0db2b8437305 | 3,105 | tivi | Apache License 2.0 |
form/src/main/java/com/thejuki/kformmaster/widget/datepicker/IKFWheelHourPicker.kt | TheJuki | 121,467,673 | false | {"Gradle Kotlin DSL": 4, "XML": 66, "Markdown": 42, "Java Properties": 3, "Shell": 2, "Text": 1, "Ignore List": 3, "Batchfile": 2, "YAML": 5, "Proguard": 2, "Kotlin": 122, "Java": 1, "JSON": 1} | package com.thejuki.kformmaster.widget.datepicker
import org.threeten.bp.LocalDate
/**
* Wheel Hour Picker Interface
*
* @author **soareseneves** ([GitHub](https://github.com/soareseneves))
* @version 1.0
*/
interface IKFWheelHourPicker {
var selectedHour: Int
var selectedDate: LocalDate
var allHours: Boolean
} | 16 | Kotlin | 45 | 195 | d58338e52b22db38daf282183b9d962b9b9587e2 | 331 | KFormMaster | Apache License 2.0 |
work/src/main/kotlin/net/kotlinx/kotest/modules/lambdaDispatcher/LambdaDispatcherDefaultListener.kt | mypojo | 565,799,715 | false | {"Kotlin": 1495826, "Jupyter Notebook": 13540, "Java": 9531} | package net.kotlinx.kotest.modules.lambdaDispatcher
import com.google.common.eventbus.Subscribe
import mu.KotlinLogging
import net.kotlinx.aws.lambda.dispatch.LambdaDispatcherDeadEvent
import net.kotlinx.aws.lambda.dispatch.LambdaDispatcherFailEvent
import net.kotlinx.aws.lambda.dispatch.synch.LambdaDispatcherCommandEvent
import net.kotlinx.reflect.name
import net.kotlinx.slack.SlackMessageSenders
import net.kotlinx.string.abbr
/** 기본 이벤트 */
class LambdaDispatcherDefaultListener {
private val log = KotlinLogging.logger {}
companion object {
/** body에 들어갈 최대 글 수 */
const val BODY_LIMIT = 300
}
@Subscribe
fun onEvent(event: LambdaDispatcherFailEvent) {
SlackMessageSenders.Alert.send {
workDiv = LambdaDispatcherDeadEvent::class.name()
descriptions = listOf("작업 실패!!")
body = listOf(event.gsonData.toPreety().abbr(BODY_LIMIT))
exception = event.e
}
}
@Subscribe
fun onEvent(event: LambdaDispatcherDeadEvent) {
SlackMessageSenders.Alert.send {
workDiv = LambdaDispatcherDeadEvent::class.name()
descriptions = listOf("데드 메세지 발생!!")
body = listOf(event.gsonData.toPreety().abbr(BODY_LIMIT))
}
}
@Subscribe
fun onEvent(event: LambdaDispatcherCommandEvent) {
log.info { "[${event.commandName}] 로직이 처리됩니다.." }
event.output = mapOf(
"a" to "b",
"c" to "d"
)
}
} | 0 | Kotlin | 0 | 1 | 1b361a5ae8aae718f0e81768452e6803c0990e71 | 1,498 | kx_kotlin_support | MIT License |
work/src/main/kotlin/net/kotlinx/kotest/modules/lambdaDispatcher/LambdaDispatcherDefaultListener.kt | mypojo | 565,799,715 | false | {"Kotlin": 1495826, "Jupyter Notebook": 13540, "Java": 9531} | package net.kotlinx.kotest.modules.lambdaDispatcher
import com.google.common.eventbus.Subscribe
import mu.KotlinLogging
import net.kotlinx.aws.lambda.dispatch.LambdaDispatcherDeadEvent
import net.kotlinx.aws.lambda.dispatch.LambdaDispatcherFailEvent
import net.kotlinx.aws.lambda.dispatch.synch.LambdaDispatcherCommandEvent
import net.kotlinx.reflect.name
import net.kotlinx.slack.SlackMessageSenders
import net.kotlinx.string.abbr
/** 기본 이벤트 */
class LambdaDispatcherDefaultListener {
private val log = KotlinLogging.logger {}
companion object {
/** body에 들어갈 최대 글 수 */
const val BODY_LIMIT = 300
}
@Subscribe
fun onEvent(event: LambdaDispatcherFailEvent) {
SlackMessageSenders.Alert.send {
workDiv = LambdaDispatcherDeadEvent::class.name()
descriptions = listOf("작업 실패!!")
body = listOf(event.gsonData.toPreety().abbr(BODY_LIMIT))
exception = event.e
}
}
@Subscribe
fun onEvent(event: LambdaDispatcherDeadEvent) {
SlackMessageSenders.Alert.send {
workDiv = LambdaDispatcherDeadEvent::class.name()
descriptions = listOf("데드 메세지 발생!!")
body = listOf(event.gsonData.toPreety().abbr(BODY_LIMIT))
}
}
@Subscribe
fun onEvent(event: LambdaDispatcherCommandEvent) {
log.info { "[${event.commandName}] 로직이 처리됩니다.." }
event.output = mapOf(
"a" to "b",
"c" to "d"
)
}
} | 0 | Kotlin | 0 | 1 | 1b361a5ae8aae718f0e81768452e6803c0990e71 | 1,498 | kx_kotlin_support | MIT License |
browser-kotlin/src/jsMain/kotlin/web/html/HTMLTitleElement.kt | karakum-team | 393,199,102 | false | null | // Automatically generated - do not modify!
package web.html
abstract external class HTMLTitleElement :
HTMLElement {
/** Retrieves or sets the text of the object as a string. */
var text: String
}
| 0 | Kotlin | 6 | 22 | 00321b7e81352bc3d7243dd6631e1fb178f528c8 | 212 | types-kotlin | Apache License 2.0 |
app/src/main/java/com/ifanr/tangzhi/model/SearchLog.kt | cyrushine | 224,551,311 | false | {"Kotlin": 673925, "Java": 59856, "Python": 795} | package com.ifanr.tangzhi.model
import com.ifanr.tangzhi.ext.getSafeBoolean
import com.ifanr.tangzhi.ext.getSafeString
import com.minapp.android.sdk.database.Record
/**
* 搜索历史
*/
data class SearchLog (
val key: String,
val followed: Boolean? = null,
val status: String = BaseModel.STATUS_APPROVED
) {
companion object {
/**
* 搜索关键字
*/
const val COL_KEY = "key"
/**
* 是否关注
* optional
*/
const val COL_FOLLOWED = "followed"
/**
* @see BaseModel.STATUS_APPROVED 已记录
* @see BaseModel.STATUS_DELETED 已被用户删除
*/
const val COL_STATUS = "status"
}
constructor(record: Record): this (
key = record.getSafeString(COL_KEY),
followed = record.getSafeBoolean(COL_FOLLOWED),
status = record.getSafeString(COL_STATUS)
)
} | 0 | Kotlin | 0 | 0 | ab9a7a2eba7f53eca918e084da9d9907f7997cee | 886 | tangzhi_android | Apache License 2.0 |
komapper-tx-jdbc/src/main/kotlin/org/komapper/tx/jdbc/JdbcIsolationLevel.kt | komapper | 349,909,214 | false | null | package org.komapper.tx.jdbc
import java.sql.Connection
enum class JdbcIsolationLevel constructor(val value: Int) {
READ_UNCOMMITTED(Connection.TRANSACTION_READ_UNCOMMITTED),
READ_COMMITTED(Connection.TRANSACTION_READ_COMMITTED),
REPEATABLE_READ(Connection.TRANSACTION_REPEATABLE_READ),
SERIALIZABLE(Connection.TRANSACTION_SERIALIZABLE),
}
| 3 | Kotlin | 0 | 33 | 52f1fff537ee9da900d11d3229f13b274982dd52 | 358 | komapper | Apache License 2.0 |
price_calculator/src/main/kotlin/pl/edu/pg/rsww/pricecalculator/Geolocation.kt | YetAnotherSpieskowcy | 769,413,515 | false | {"Kotlin": 114779, "HTML": 16945, "Python": 13559, "Dockerfile": 7202, "Makefile": 3009, "JavaScript": 2688, "Shell": 1336} | package pl.edu.pg.rsww.pricecalculator
public class Geolocation(lat: Float, long: Float) {
val latitude: Float = lat
val longitude: Float = long
}
| 0 | Kotlin | 1 | 0 | 75efcf04e0245ae87fca20a45bc04d4ba05de7f2 | 156 | travel-agency-app | Apache License 2.0 |
src/main/kotlin/ru/razornd/twitch/clips/twitch/TwitchClient.kt | RazorNd | 599,688,021 | false | null | /*
* Copyright 2023 <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 ru.razornd.twitch.clips.twitch
import com.fasterxml.jackson.databind.PropertyNamingStrategies.SnakeCaseStrategy
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.FlowCollector
import kotlinx.coroutines.flow.flow
import org.springframework.aot.hint.annotation.RegisterReflectionForBinding
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.awaitBody
import org.springframework.web.util.UriBuilder
import ru.razornd.twitch.clips.logger
import ru.razornd.twitch.clips.model.ClipInformation
import java.net.URI
import java.time.Instant
private val log = logger<TwitchClient>()
private const val PAGE_SIZE = 100
class TwitchClient(private val webClient: WebClient) {
@RegisterReflectionForBinding(
classes = [Response::class, Pagination::class, ClipInformation::class, SnakeCaseStrategy::class]
)
fun getClips(
broadcasterId: Long,
startedAt: Instant? = null,
endedAt: Instant? = null
): Flow<ClipInformation> = flow {
var cursor: String? = null
do {
val (data, pagination) = webClient.get()
.uri { builder ->
builder.path("/clips")
.queryParam("broadcaster_id", broadcasterId)
.queryParamIfNonNull("started_at", startedAt)
.queryParamIfNonNull("ended_at", endedAt)
.queryParamIfNonNull("after", cursor)
.queryParam("first", PAGE_SIZE)
.build().also { logRequestUri(it) }
}
.retrieve()
.awaitBody<Response<ClipInformation>>()
emitAll(data)
cursor = pagination?.cursor
logCursor(cursor)
} while (cursor != null)
}
private suspend fun <T> FlowCollector<T>.emitAll(data: Collection<T>) = data.forEach { emit(it) }
private fun logCursor(cursor: String?) = if (cursor != null) {
log.debug("Response contains cursor to next page: {}", cursor)
} else {
log.debug("Response contains last page")
}
private fun logRequestUri(uri: URI) = log.debug("Make request to: {}", uri)
private data class Response<T>(val data: Collection<T>, val pagination: Pagination?)
private data class Pagination(val cursor: String?)
private fun UriBuilder.queryParamIfNonNull(name: String, value: Any?) =
if (value != null) queryParam(name, value) else this
}
| 0 | Kotlin | 0 | 0 | 06d58f73b004a78b5ada939140dfc1b1ea3d0ead | 3,135 | clips-stats-getter | Apache License 2.0 |
arms/src/main/java/com/jess/arms/base/delegate/AppLifecycles.kt | petma | 192,675,016 | true | {"Kotlin": 331292} | /*
* Copyright 2017 JessYan
*
* 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.jess.arms.base.delegate
import android.app.Application
import android.content.Context
/**
* ================================================
* 用于代理 [Application] 的生命周期
*
* @see AppDelegate
* Created by JessYan on 18/07/2017 17:43
* [Contact me](mailto:<EMAIL>)
* [Follow me](https://github.com/JessYanCoding)
* ================================================
*/
interface AppLifecycles {
fun attachBaseContext(base: Context)
fun onCreate(application: Application)
fun onTerminate(application: Application)
}
| 0 | Kotlin | 0 | 0 | 64ac1d9e092ef637f67b57a7effac7e0a6d029f9 | 1,138 | MVPArms | Apache License 2.0 |
blog/src/main/kotlin/com/liux/blog/controller/OtherController.kt | lx0758 | 334,699,858 | false | null | package com.liux.blog.controller
import com.liux.blog.renderMarkdown
import com.liux.blog.service.ArticleService
import com.liux.blog.service.ThemeService
import com.liux.blog.toDateString
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController
import java.util.*
@RestController
class OtherController {
@Autowired
private lateinit var articleService: ArticleService
@Autowired
private lateinit var themeService: ThemeService
@GetMapping("/search.json")
fun search(): List<Map<String, String>> {
val articles = articleService.listBySearch()
return articles.map { article ->
HashMap<String, String>().apply {
put("title", article.title!!)
put("content", article.renderMarkdown())
put("url", "/article/" + (article.url ?: article.id.toString()))
}
}
}
@GetMapping("/robots.txt", produces = ["plain/txt;charset=UTF-8"])
fun robots(): String {
val domain = themeService.getCacheBase().siteDomain
return """
User-agent: *
Disallow: /admin/
Sitemap: https://$domain/sitemap.xml
""".trimIndent()
}
@GetMapping("/sitemap.xml", produces = ["application/xml;charset=UTF-8"])
fun sitemap(): String {
val domain = themeService.getCacheBase().siteDomain
val articles = articleService.listBySitemap()
val urlset = StringBuilder().apply {
append("\t<url>\n")
append("\t\t<loc>https://$domain/</loc>\n")
append("\t\t<lastmod>${Date().toDateString()}</lastmod>\n")
append("\t\t<changefreq>always</changefreq>\n")
append("\t\t<priority>1.0</priority>\n")
append("\t</url>\n")
articles.forEach {
append("\t<url>\n")
append("\t\t<loc>https://$domain/article/${it.url ?: it.id.toString()}</loc>\n")
append("\t\t<lastmod>${(it.updateTime ?: it.createTime!!).toDateString()}</lastmod>\n")
append("\t\t<changefreq>monthly</changefreq>\n")
append("\t\t<priority>0.8</priority>\n")
append("\t</url>\n")
}
}.toString()
return """
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
$urlset
</urlset>
""".trimIndent()
}
}
| 0 | Kotlin | 0 | 0 | 5f39095253b5f2d171f4cc07c8a0a3a5135520f4 | 2,482 | Blog | MIT License |
skylight-android/src/androidTest/java/dev/drewhamilton/skylight/android/test/FakeDarkModeApplicator.kt | drewhamilton | 193,222,970 | false | {"Gradle": 5, "Markdown": 4, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "XML": 29, "INI": 2, "Java": 1, "Kotlin": 23, "TOML": 1, "YAML": 2, "Proguard": 1} | package dev.drewhamilton.skylight.android.test
import dev.drewhamilton.skylight.android.DarkModeApplicator
class FakeDarkModeApplicator : DarkModeApplicator {
var appliedMode: DarkModeApplicator.DarkMode? = null
private set
override fun applyMode(mode: DarkModeApplicator.DarkMode) {
appliedMode = mode
}
}
| 0 | Kotlin | 0 | 1 | a9de3bacf53845bc619378cc52a03b33a1d45d8c | 338 | SkylightAndroid | Apache License 2.0 |
service/src/main/kotlin/io/provenance/explorer/domain/entities/ExplorerCache.kt | provenance-io | 332,035,574 | false | {"Kotlin": 1046875, "PLpgSQL": 316369, "Shell": 679, "Python": 642} | package io.provenance.explorer.domain.entities
import io.provenance.explorer.OBJECT_MAPPER
import io.provenance.explorer.domain.core.sql.jsonb
import io.provenance.explorer.model.ChainAum
import io.provenance.explorer.model.ChainMarketRate
import io.provenance.explorer.model.CmcHistoricalQuote
import io.provenance.explorer.model.Spotlight
import io.provenance.explorer.model.ValidatorMarketRate
import io.provenance.explorer.model.base.USD_UPPER
import org.jetbrains.exposed.dao.Entity
import org.jetbrains.exposed.dao.EntityClass
import org.jetbrains.exposed.dao.IntEntity
import org.jetbrains.exposed.dao.IntEntityClass
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.IdTable
import org.jetbrains.exposed.dao.id.IntIdTable
import org.jetbrains.exposed.sql.SortOrder
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.and
import org.jetbrains.exposed.sql.andWhere
import org.jetbrains.exposed.sql.deleteWhere
import org.jetbrains.exposed.sql.insertIgnore
import org.jetbrains.exposed.sql.jodatime.date
import org.jetbrains.exposed.sql.jodatime.datetime
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.selectAll
import org.jetbrains.exposed.sql.transactions.transaction
import org.jetbrains.exposed.sql.update
import org.joda.time.DateTime
import java.math.BigDecimal
object SpotlightCacheTable : IntIdTable(name = "spotlight_cache") {
val spotlight = jsonb<SpotlightCacheTable, Spotlight>("spotlight", OBJECT_MAPPER)
val lastHit = datetime("last_hit")
}
class SpotlightCacheRecord(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<SpotlightCacheRecord>(SpotlightCacheTable) {
fun getSpotlight() = transaction {
SpotlightCacheRecord.all()
.orderBy(Pair(SpotlightCacheTable.id, SortOrder.DESC))
.limit(1)
.firstOrNull()
?.spotlight
}
fun insertIgnore(json: Spotlight) = transaction {
SpotlightCacheTable.insertIgnore {
it[this.spotlight] = json
it[this.lastHit] = DateTime.now()
}
}
}
var spotlight by SpotlightCacheTable.spotlight
var lastHit by SpotlightCacheTable.lastHit
}
object ValidatorMarketRateStatsTable : IntIdTable(name = "validator_market_rate_stats") {
val date = date("date")
val operatorAddress = varchar("operator_address", 96)
val minMarketRate = decimal("min_market_rate", 30, 10).nullable()
val maxMarketRate = decimal("max_market_rate", 30, 10).nullable()
val avgMarketRate = decimal("avg_market_rate", 30, 10).nullable()
init {
index(true, date, operatorAddress)
}
}
class ValidatorMarketRateStatsRecord(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<ValidatorMarketRateStatsRecord>(ValidatorMarketRateStatsTable) {
fun save(
address: String,
minMarketRate: BigDecimal?,
maxMarketRate: BigDecimal?,
avgMarketRate: BigDecimal?,
date: DateTime
) =
transaction {
ValidatorMarketRateStatsTable.insertIgnore {
it[this.operatorAddress] = address
it[this.minMarketRate] = minMarketRate
it[this.maxMarketRate] = maxMarketRate
it[this.avgMarketRate] = avgMarketRate
it[this.date] = date
}
}
fun findByAddress(address: String, fromDate: DateTime?, toDate: DateTime?, count: Int) = transaction {
val query =
ValidatorMarketRateStatsTable.select { ValidatorMarketRateStatsTable.operatorAddress eq address }
if (fromDate != null) {
query.andWhere { ValidatorMarketRateStatsTable.date greaterEq fromDate }
}
if (toDate != null) {
query.andWhere { ValidatorMarketRateStatsTable.date lessEq toDate.plusDays(1) }
}
query.orderBy(ValidatorMarketRateStatsTable.date, SortOrder.ASC).limit(count)
ValidatorMarketRateStatsRecord.wrapRows(query).map {
ValidatorMarketRate(
it.operatorAddress,
it.date.toString("yyyy-MM-dd"),
it.minMarketRate,
it.maxMarketRate,
it.avgMarketRate
)
}
}
}
var operatorAddress by ValidatorMarketRateStatsTable.operatorAddress
var minMarketRate by ValidatorMarketRateStatsTable.minMarketRate
var maxMarketRate by ValidatorMarketRateStatsTable.maxMarketRate
var avgMarketRate by ValidatorMarketRateStatsTable.avgMarketRate
var date by ValidatorMarketRateStatsTable.date
}
object ChainMarketRateStatsTable : IdTable<DateTime>(name = "chain_market_rate_stats") {
val date = date("date")
override val id = date.entityId()
val minMarketRate = decimal("min_market_rate", 30, 10).nullable()
val maxMarketRate = decimal("max_market_rate", 30, 10).nullable()
val avgMarketRate = decimal("avg_market_rate", 30, 10).nullable()
}
class ChainMarketRateStatsRecord(id: EntityID<DateTime>) : Entity<DateTime>(id) {
companion object : EntityClass<DateTime, ChainMarketRateStatsRecord>(ChainMarketRateStatsTable) {
fun save(minMarketRate: BigDecimal?, maxMarketRate: BigDecimal?, avgMarketRate: BigDecimal?, date: DateTime) =
transaction {
ChainMarketRateStatsTable.insertIgnore {
it[this.date] = date
it[this.minMarketRate] = minMarketRate
it[this.maxMarketRate] = maxMarketRate
it[this.avgMarketRate] = avgMarketRate
}
}
fun findForDates(fromDate: DateTime?, toDate: DateTime?, count: Int) = transaction {
val query = ChainMarketRateStatsTable.selectAll()
if (fromDate != null) {
query.andWhere { ChainMarketRateStatsTable.date greaterEq fromDate }
}
if (toDate != null) {
query.andWhere { ChainMarketRateStatsTable.date lessEq toDate.plusDays(1) }
}
query.orderBy(ChainMarketRateStatsTable.date, SortOrder.ASC).limit(count)
ChainMarketRateStatsRecord.wrapRows(query).map {
ChainMarketRate(
it.date.toString("yyyy-MM-dd"),
it.minMarketRate,
it.maxMarketRate,
it.avgMarketRate
)
}
}
}
var date by ChainMarketRateStatsTable.date
var minMarketRate by ChainMarketRateStatsTable.minMarketRate
var maxMarketRate by ChainMarketRateStatsTable.maxMarketRate
var avgMarketRate by ChainMarketRateStatsTable.avgMarketRate
}
object CacheUpdateTable : IntIdTable(name = "cache_update") {
val cacheKey = varchar("cache_key", 256)
val description = text("description")
val cacheValue = text("cache_value").nullable()
val lastUpdated = datetime("last_updated")
}
enum class CacheKeys(val key: String) {
PRICING_UPDATE("pricing_update"),
CHAIN_RELEASES("chain_releases"),
SPOTLIGHT_PROCESSING("spotlight_processing"),
STANDARD_BLOCK_TIME("standard_block_time"),
UTILITY_TOKEN_LATEST("utility_token_latest"),
FEE_BUG_ONE_ELEVEN_START_BLOCK("fee_bug_one_eleven_start_block"),
AUTHZ_PROCESSING("authz_processing")
}
class CacheUpdateRecord(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<CacheUpdateRecord>(CacheUpdateTable) {
fun fetchCacheByKey(key: String) = transaction {
CacheUpdateRecord.find { CacheUpdateTable.cacheKey eq key }.firstOrNull()
}
fun updateCacheByKey(key: String, value: String) = transaction {
fetchCacheByKey(key)?.apply {
this.cacheValue = value
this.lastUpdated = DateTime.now()
} ?: throw IllegalArgumentException("CacheUpdateTable: Key $key was not found as a cached value")
}
}
var cacheKey by CacheUpdateTable.cacheKey
var description by CacheUpdateTable.description
var cacheValue by CacheUpdateTable.cacheValue
var lastUpdated by CacheUpdateTable.lastUpdated
}
object ChainAumHourlyTable : IntIdTable(name = "chain_aum_hourly") {
val datetime = datetime("datetime")
val amount = decimal("amount", 100, 0)
val denom = varchar("denom", 256)
}
class ChainAumHourlyRecord(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<ChainAumHourlyRecord>(ChainAumHourlyTable) {
fun getAumForPeriod(fromDate: DateTime, toDate: DateTime) = transaction {
ChainAumHourlyRecord.find {
(ChainAumHourlyTable.datetime greaterEq fromDate) and
(ChainAumHourlyTable.datetime lessEq toDate.plusDays(1))
}
.orderBy(Pair(ChainAumHourlyTable.datetime, SortOrder.ASC))
.toList()
}
fun insertIgnore(date: DateTime, amount: BigDecimal, denom: String) = transaction {
ChainAumHourlyTable.insertIgnore {
it[this.datetime] = date
it[this.amount] = amount
it[this.denom] = denom
}
}
}
fun toDto() = ChainAum(this.datetime.toString("yyyy-MM-dd HH:mm:SS"), this.denom, this.amount)
var datetime by ChainAumHourlyTable.datetime
var amount by ChainAumHourlyTable.amount
var denom by ChainAumHourlyTable.denom
}
object TokenHistoricalDailyTable : IdTable<DateTime>(name = "token_historical_daily") {
val timestamp = datetime("historical_timestamp")
override val id = timestamp.entityId()
val data = jsonb<TokenHistoricalDailyTable, CmcHistoricalQuote>("data", OBJECT_MAPPER)
}
class TokenHistoricalDailyRecord(id: EntityID<DateTime>) : Entity<DateTime>(id) {
companion object : EntityClass<DateTime, TokenHistoricalDailyRecord>(TokenHistoricalDailyTable) {
fun save(date: DateTime, data: CmcHistoricalQuote) =
transaction {
TokenHistoricalDailyTable.insertIgnore {
it[this.timestamp] = date
it[this.data] = data
}
}
fun findForDates(fromDate: DateTime?, toDate: DateTime?) = transaction {
val query = TokenHistoricalDailyTable.selectAll()
if (fromDate != null) {
query.andWhere { TokenHistoricalDailyTable.timestamp greaterEq fromDate }
}
if (toDate != null) {
query.andWhere { TokenHistoricalDailyTable.timestamp lessEq toDate.plusDays(1) }
}
query.orderBy(TokenHistoricalDailyTable.timestamp, SortOrder.ASC)
TokenHistoricalDailyRecord.wrapRows(query).map { it.data }.toList()
}
fun lastKnownPriceForDate(date: DateTime) = transaction {
TokenHistoricalDailyRecord
.find { TokenHistoricalDailyTable.timestamp lessEq date }
.orderBy(Pair(TokenHistoricalDailyTable.timestamp, SortOrder.DESC))
.firstOrNull()?.data?.quote?.get(USD_UPPER)?.close ?: BigDecimal.ZERO
}
fun getLatestDateEntry(): TokenHistoricalDailyRecord? = transaction {
return@transaction TokenHistoricalDailyRecord
.all()
.orderBy(Pair(TokenHistoricalDailyTable.timestamp, SortOrder.DESC))
.limit(1)
.firstOrNull()
}
}
var timestamp by TokenHistoricalDailyTable.timestamp
var data by TokenHistoricalDailyTable.data
}
object ProcessQueueTable : IntIdTable(name = "process_queue") {
val processType = varchar("process_type", 128)
val processValue = text("process_value")
val processing = bool("processing").default(false)
}
enum class ProcessQueueType { ACCOUNT }
class ProcessQueueRecord(id: EntityID<Int>) : IntEntity(id) {
companion object : IntEntityClass<ProcessQueueRecord>(ProcessQueueTable) {
fun findByType(processType: ProcessQueueType) = transaction {
ProcessQueueRecord.find {
(ProcessQueueTable.processType eq processType.name) and
(ProcessQueueTable.processing eq false)
}.toList()
}
fun reset(processType: ProcessQueueType) = transaction {
ProcessQueueTable.update({ ProcessQueueTable.processType eq processType.name }) {
it[this.processing] = false
}
}
fun delete(processType: ProcessQueueType, value: String) = transaction {
ProcessQueueTable.deleteWhere {
(ProcessQueueTable.processType eq processType.name) and
(processValue eq value)
}
}
fun insertIgnore(processType: ProcessQueueType, processValue: String) = transaction {
ProcessQueueTable.insertIgnore {
it[this.processType] = processType.name
it[this.processValue] = processValue
}
}
}
var processType by ProcessQueueTable.processType
var processValue by ProcessQueueTable.processValue
var processing by ProcessQueueTable.processing
}
| 31 | Kotlin | 3 | 6 | bba7b8e7ed8279e41718704df7ad90c45e9c50c0 | 13,347 | explorer-service | Apache License 2.0 |
app/src/main/java/com/celzero/bravedns/RethinkDnsApplication.kt | fux0r2009 | 405,350,739 | true | {"Kotlin": 863559, "Java": 63406} | package com.celzero.bravedns
import android.app.Application
import android.os.StrictMode
import org.koin.android.ext.koin.androidContext
import org.koin.android.ext.koin.androidLogger
import org.koin.core.context.startKoin
/*
* Copyright 2020 RethinkDNS and its authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
class RethinkDnsApplication : Application() {
override fun onCreate() {
super.onCreate()
//turnOnStrictMode()
startKoin {
if (BuildConfig.DEBUG) androidLogger()
androidContext(this@RethinkDnsApplication)
koin.loadModules(AppModules)
}
}
private fun turnOnStrictMode() {
if (!BuildConfig.DEBUG) return
// Uncomment the code below to enable the StrictModes.
// To test the apps disk read/writes, network usages.
/*StrictMode.setThreadPolicy(
StrictMode.ThreadPolicy.Builder()
.detectAll()
.penaltyLog()
.permitDiskReads()
.permitDiskWrites()
.permitNetwork()
.build())*/
StrictMode.setVmPolicy(
StrictMode.VmPolicy.Builder().detectAll().detectLeakedSqlLiteObjects().penaltyLog().build())
}
}
| 0 | null | 0 | 0 | edc51e0269a2b12c9550ac9eccc29125552c76d3 | 1,746 | rethink-app | Apache License 2.0 |
app/src/main/java/com/github/dhaval2404/itunesplayer/data/remote/NetworkResponse.kt | Dhaval2404 | 318,816,023 | false | null | package com.github.dhaval2404.itunesplayer.data.remote
/**
* Network Response
*
* @author Dhaval Patel
* @version 1.0
* @since 06 December 2020
*/
sealed class NetworkResponse<out T : Any> {
data class Success<out T : Any>(val data: T) : NetworkResponse<T>()
data class Error(val error: String, val status: Int = 0) : NetworkResponse<Nothing>()
}
| 0 | Kotlin | 0 | 3 | d210f5c54d3205c092fb3f670eb2c0f270b5a9e7 | 364 | iTunesPlayer | Apache License 2.0 |
src/main/kotlin/astminer/storage/ast/CsvAstStorage.kt | kisate | 368,867,777 | true | {"Kotlin": 213019, "Java": 199813, "ANTLR": 76421, "C++": 25952, "JavaScript": 7698, "Python": 2535, "Dockerfile": 951, "Shell": 852} | package astminer.storage.ast
import astminer.cli.LabeledResult
import astminer.common.model.Node
import astminer.common.preOrder
import astminer.common.storage.*
import astminer.storage.Storage
import java.io.File
import java.io.PrintWriter
/**
* Stores multiple ASTs by their roots and saves them in .csv format.
* Output consists of 3 .csv files: with node types, with tokens and with ASTs.
*/
class CsvAstStorage(override val outputDirectoryPath: String) : Storage {
private val tokensMap: RankedIncrementalIdStorage<String> = RankedIncrementalIdStorage()
private val nodeTypesMap: RankedIncrementalIdStorage<String> = RankedIncrementalIdStorage()
private val astsOutputStream: PrintWriter
init {
File(outputDirectoryPath).mkdirs()
val astsFile = File("$outputDirectoryPath/asts.csv")
astsFile.createNewFile()
astsOutputStream = PrintWriter(astsFile)
astsOutputStream.write("id,ast\n")
}
override fun store(labeledResult: LabeledResult<out Node>) {
for (node in labeledResult.root.preOrder()) {
tokensMap.record(node.getToken())
nodeTypesMap.record(node.getTypeLabel())
}
dumpAst(labeledResult.root, labeledResult.label)
}
override fun close() {
dumpTokenStorage(File("$outputDirectoryPath/tokens.csv"))
dumpNodeTypesStorage(File("$outputDirectoryPath/node_types.csv"))
astsOutputStream.close()
}
private fun dumpTokenStorage(file: File) {
dumpIdStorageToCsv(tokensMap, "token", tokenToCsvString, file)
}
private fun dumpNodeTypesStorage(file: File) {
dumpIdStorageToCsv(nodeTypesMap, "node_type", nodeTypeToCsvString, file)
}
private fun dumpAst(root: Node, id: String) {
astsOutputStream.write("$id,${astString(root)}\n")
}
internal fun astString(node: Node): String {
return "${tokensMap.getId(node.getToken())} ${nodeTypesMap.getId(node.getTypeLabel())}{${
node.getChildren().joinToString(separator = "", transform = ::astString)
}}"
}
}
| 1 | null | 0 | 1 | a5c27c21c8523e9f7c471e90a369e84c74b3729b | 2,092 | astminer | MIT License |
app/src/main/java/com/l3udy/basicmvpkotlin/model/User.kt | SetiaBudy-Me | 508,501,582 | false | null | package com.l3udy.basicmvpkotlin.model
data class User(
var email: String? = null,
var password: String? = null
)
| 0 | Kotlin | 0 | 1 | 07efed1855b3d03af28fefbe368c9a9d5c364b3d | 123 | basic-mvp-kotlin-architecture-example | Apache License 2.0 |
app/src/main/java/com/example/appstore/data/repository/ProfileOrdersRepository.kt | rezakardan | 779,591,568 | false | {"Kotlin": 353707, "Java": 16027} | package com.example.appstore.data.repository
import com.example.appstore.data.server.ApiService
import javax.inject.Inject
class ProfileOrdersRepository@Inject constructor(private val api:ApiService) {
suspend fun profileOrders(status:String)=api.profileOrders(status)
} | 0 | Kotlin | 0 | 0 | c64368f08faae5b50d158dadb79a8a1a3cd3e140 | 277 | AppStore__Git | MIT License |
android-sdk/src/test/java/webtrekk/android/sdk/domain/external/TrackCustomMediaTest.kt | Webtrekk | 166,987,236 | false | null | package webtrekk.android.sdk.domain.external
import io.mockk.Called
import io.mockk.coVerify
import io.mockk.mockkClass
import kotlinx.coroutines.runBlocking
import webtrekk.android.sdk.api.RequestType
import webtrekk.android.sdk.domain.internal.CacheTrackRequestWithCustomParams
import webtrekk.android.sdk.util.cacheTrackRequestWithCustomParamsParams
import webtrekk.android.sdk.util.coroutinesDispatchersProvider
import webtrekk.android.sdk.util.trackRequest
import webtrekk.android.sdk.util.trackingParams
import webtrekk.android.sdk.util.trackingParamsMediaParam
/**
* Created by <NAME> on 16/07/2020.
* Copyright (c) 2020 MAPP.
*/
internal class TrackCustomMediaTest : AbstractExternalInteractor() {
val cacheTrackRequestWithCustomParams = mockkClass(CacheTrackRequestWithCustomParams::class)
val trackCustomMedia = TrackCustomMedia(
coroutineContext,
cacheTrackRequestWithCustomParams
)
init {
feature("track custom media") {
scenario("if opt out is active then return and don't track") {
val params = TrackCustomMedia.Params(
trackRequest = trackRequest,
trackingParams = trackingParamsMediaParam,
isOptOut = true
)
runBlocking {
trackCustomMedia(params, coroutinesDispatchersProvider())
coVerify {
cacheTrackRequestWithCustomParams wasNot Called
}
}
}
scenario("verify media request when user is optOut") {
val params = TrackCustomMedia.Params(
trackRequest = trackRequest,
trackingParams = trackingParams,
isOptOut = false
)
runBlocking {
trackCustomMedia(params, coroutinesDispatchersProvider())
val trackingParamsWithCT =
cacheTrackRequestWithCustomParamsParams.trackingParams.toMutableMap()
val cacheTrackRequestWithCT = CacheTrackRequestWithCustomParams.Params(
trackRequest, trackingParamsWithCT
)
coVerify {
cacheTrackRequestWithCustomParams(cacheTrackRequestWithCT)
}
}
}
}
}
} | 1 | Kotlin | 1 | 12 | 8ba7b8b3e95082b378af31b6277d94bd883e6ac5 | 2,432 | webtrekk-android-sdk-v5 | MIT License |
buildSrc/src/main/kotlin/net/meilcli/librarian/gradle/extensions/ProjectExtensions.kt | MeilCli | 250,963,046 | false | null | package net.meilcli.pipe.gradle.extensions
import com.android.build.gradle.BaseExtension
import org.gradle.api.Project
import java.io.File
fun Project.applyLintSetting() {
val extension = project.extensions.findByName("android") as? BaseExtension ?: return
extension.lintOptions {
xmlReport = true
val name =
project.projectDir.toRelativeString((project.rootProject.rootDir)).replace("/", "_")
xmlOutput = File("${project.rootProject.rootDir}/reports/lint/${name}.xml")
}
} | 24 | Kotlin | 1 | 4 | 35598bea44864f96e62a6abdccb274b4b3ca1622 | 524 | Librarian | MIT License |
src/main/kotlin/icu/windea/pls/config/cwt/config/CwtOptionValueConfig.kt | DragonKnightOfBreeze | 328,104,626 | false | null | package icu.windea.pls.config.config
import com.intellij.psi.*
import icu.windea.pls.cwt.psi.*
data class CwtOptionValueConfig(
override val pointer: SmartPsiElementPointer<CwtValue>, //NOTE 未使用
override val info: CwtConfigGroupInfo,
val value: String,
val booleanValue: Boolean? = null,
val intValue: Int? = null,
val floatValue: Float? = null,
val stringValue: String? = null,
val options: List<CwtOptionConfig>? = null,
val optionValues: List<CwtOptionValueConfig>? = null
) : CwtConfig<CwtValue> | 2 | null | 2 | 7 | 037b9b4ba467ed49ea221b99efb0a26cd630bb67 | 510 | Paradox-Language-Support | MIT License |
kotlin-remix-run-router/src/jsMain/generated/remix/run/router/DetectErrorBoundaryFunction.kt | JetBrains | 93,250,841 | false | null | @file:Suppress(
"NON_EXTERNAL_DECLARATION_IN_INAPPROPRIATE_FILE",
)
package remix.run.router
/**
* Function provided by the framework-aware layers to set `hasErrorBoundary`
* from the framework-aware `errorElement` prop
*
* @deprecated Use `mapRouteProperties` instead
*/
typealias DetectErrorBoundaryFunction = (route: AgnosticRouteObject) -> Boolean
| 28 | Kotlin | 170 | 1,209 | 2c81d207ab67e7bd8d85571a8b2c88812ef4a3cf | 364 | kotlin-wrappers | Apache License 2.0 |
kotlin-remix-run-router/src/jsMain/generated/remix/run/router/DetectErrorBoundaryFunction.kt | JetBrains | 93,250,841 | false | null | @file:Suppress(
"NON_EXTERNAL_DECLARATION_IN_INAPPROPRIATE_FILE",
)
package remix.run.router
/**
* Function provided by the framework-aware layers to set `hasErrorBoundary`
* from the framework-aware `errorElement` prop
*
* @deprecated Use `mapRouteProperties` instead
*/
typealias DetectErrorBoundaryFunction = (route: AgnosticRouteObject) -> Boolean
| 28 | Kotlin | 170 | 1,209 | 2c81d207ab67e7bd8d85571a8b2c88812ef4a3cf | 364 | kotlin-wrappers | Apache License 2.0 |
src/test/kotlin/nl/bjornvanderlaan/springwebfluxkotlinfunctional/router/MockedRepositoryIntegrationTest.kt | BjornvdLaan | 425,080,434 | false | {"Kotlin": 20028} | package nl.bjornvanderlaan.springwebfluxkotlinfunctional.router
import com.ninjasquad.springmockk.MockkBean
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.slot
import kotlinx.coroutines.flow.flow
import nl.bjornvanderlaan.springwebfluxkotlinfunctional.handler.CatHandler
import nl.bjornvanderlaan.springwebfluxkotlinfunctional.model.Cat
import nl.bjornvanderlaan.springwebfluxkotlinfunctional.model.CatDto
import nl.bjornvanderlaan.springwebfluxkotlinfunctional.model.toDto
import nl.bjornvanderlaan.springwebfluxkotlinfunctional.repository.CatRepository
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest
import org.springframework.context.annotation.Import
import org.springframework.http.MediaType
import org.springframework.test.web.reactive.server.WebTestClient
import org.springframework.test.web.reactive.server.expectBody
import org.springframework.test.web.reactive.server.expectBodyList
import org.springframework.web.reactive.function.BodyInserters.fromValue
@WebFluxTest
@Import(CatRouterConfiguration::class, CatHandler::class)
class MockedRepositoryIntegrationTest(
@Autowired private val client: WebTestClient
) {
@MockkBean
private lateinit var repository: CatRepository
private fun aCat(
name: String = "Obi",
type: String = "Dutch Ringtail",
age: Int = 3
) =
Cat(
name = name,
type = type,
age = age
)
private fun anotherCat(
name: String = "Wan",
type: String = "Japanese Bobtail",
age: Int = 5
) =
aCat(
name = name,
type = type,
age = age
)
@Test
fun `Retrieve all cats`() {
every {
repository.findAll()
} returns flow {
emit(aCat())
emit(anotherCat())
}
client
.get()
.uri("/api/cats")
.exchange()
.expectStatus()
.isOk
.expectBodyList<CatDto>()
.hasSize(2)
.contains(aCat().toDto(), anotherCat().toDto())
}
@Test
fun `Retrieve cat by existing id`() {
coEvery {
repository.findById(any())
} coAnswers {
aCat()
}
client
.get()
.uri("/api/cats/2")
.exchange()
.expectStatus()
.isOk
.expectBody<CatDto>()
.isEqualTo(aCat().toDto())
}
@Test
fun `Retrieve cat by non-existing id`() {
coEvery {
repository.findById(any())
} returns null
client
.get()
.uri("/api/cats/2")
.exchange()
.expectStatus()
.isNotFound
}
@Test
fun `Add a new cat`() {
val savedCat = slot<Cat>()
coEvery {
repository.save(capture(savedCat))
} coAnswers {
savedCat.captured
}
client
.post()
.uri("/api/cats/")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(aCat().toDto())
.exchange()
.expectStatus()
.isOk
.expectBody<CatDto>()
.isEqualTo(savedCat.captured.toDto())
}
@Test
fun `Add a new cat with empty request body`() {
val savedCat = slot<Cat>()
coEvery {
repository.save(capture(savedCat))
} coAnswers {
savedCat.captured
}
client
.post()
.uri("/api/cats/")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.body(fromValue("{}"))
.exchange()
.expectStatus()
.isBadRequest
}
@Test
fun `Update a cat`() {
coEvery {
repository.findById(any())
} coAnswers {
aCat()
}
val savedCat = slot<Cat>()
coEvery {
repository.save(capture(savedCat))
} coAnswers {
savedCat.captured
}
val updatedCat = aCat(name = "New fancy name").toDto()
client
.put()
.uri("/api/cats/2")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(updatedCat)
.exchange()
.expectStatus()
.isOk
.expectBody<CatDto>()
.isEqualTo(updatedCat)
}
@Test
fun `Update cat with non-existing id`() {
val requestedId = slot<Long>()
coEvery {
repository.findById(capture(requestedId))
} coAnswers {
nothing
}
val updatedCat = aCat(name = "New fancy name").toDto()
client
.put()
.uri("/api/cats/2")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.bodyValue(updatedCat)
.exchange()
.expectStatus()
.isNotFound
}
@Test
fun `Update cat with empty request body id`() {
coEvery {
repository.findById(any())
} coAnswers {
aCat()
}
client
.put()
.uri("/api/cats/2")
.accept(MediaType.APPLICATION_JSON)
.contentType(MediaType.APPLICATION_JSON)
.body(fromValue("{}"))
.exchange()
.expectStatus()
.isBadRequest
}
@Test
fun `Delete cat with existing id`() {
coEvery {
repository.existsById(any())
} coAnswers {
true
}
coEvery {
repository.deleteById(any())
} coAnswers {
nothing
}
client
.delete()
.uri("/api/cats/2")
.exchange()
.expectStatus()
.isNoContent
coVerify { repository.deleteById(any()) }
}
@Test
fun `Delete cat by non-existing id`() {
coEvery {
repository.existsById(any())
} coAnswers {
false
}
client
.delete()
.uri("/api/cats/2")
.exchange()
.expectStatus()
.isNotFound
coVerify(exactly = 0) { repository.deleteById(any()) }
}
}
| 0 | Kotlin | 4 | 9 | e20379de0f4ae688c036941ce85fcce2ab140304 | 6,605 | spring-boot-webflux-kotlin-h2-example | MIT License |
v1_29/src/main/java/de/loosetie/k8s/dsl/manifests/ValidatingAdmissionPolicyBinding.kt | loosetie | 283,145,621 | false | {"Kotlin": 8925107} | package de.loosetie.k8s.dsl.manifests
import de.loosetie.k8s.dsl.K8sTopLevel
import de.loosetie.k8s.dsl.K8sDslMarker
import de.loosetie.k8s.dsl.K8sManifest
import de.loosetie.k8s.dsl.HasMetadata
@K8sDslMarker
interface ValidatingAdmissionPolicy_admissionregistration_k8s_io_v1alpha1: K8sTopLevel, HasMetadata {
/** APIVersion defines the versioned schema of this representation of an object. Servers should convert recognized schemas
to the latest internal value, and may reject unrecognized values. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#resources */
override val apiVersion: String
get() = "admissionregistration.k8s.io/v1alpha1"
/** Kind is a string value representing the REST resource this object represents. Servers may infer this from the endpoint
the client submits requests to. Cannot be updated. In CamelCase. More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds */
override val kind: String
get() = "ValidatingAdmissionPolicy"
/** Standard object metadata; More info:
https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadata. */
val metadata: ObjectMeta_meta_v1
/** Specification of the desired behavior of the ValidatingAdmissionPolicy. */
val spec: Validatingadmissionpolicyspec_admissionregistration_k8s_io_v1alpha1
/** The status of the ValidatingAdmissionPolicy, including warnings that are useful to determine if the policy behaves in
the expected way. Populated by the system. Read-only. */
val status: Validatingadmissionpolicystatus_admissionregistration_k8s_io_v1alpha1?
} | 0 | Kotlin | 0 | 2 | 57d56ab780bc3134c43377e647e7f0336a5f17de | 1,670 | k8s-dsl | Apache License 2.0 |
src/main/kotlin/no/njoh/pulseengine/modules/graphics/RenderState.kt | NiklasJohansen | 239,208,354 | false | null | package no.njoh.pulseengine.modules.graphics
class RenderState
{
var rgba = 0f
var depth = 0f
init
{
setRGBA(1f, 1f, 1f, 1f)
}
fun increaseDepth()
{
depth += DEPTH_INC
}
fun resetDepth(value: Float)
{
depth = value
}
fun setRGBA(r: Float, g: Float, b: Float, a: Float)
{
val red = (r * 255).toInt()
val green = (g * 255).toInt()
val blue = (b * 255).toInt()
val alpha = (a * 255).toInt()
this.rgba = java.lang.Float.intBitsToFloat((red shl 24) or (green shl 16) or (blue shl 8) or alpha)
}
companion object
{
private const val DEPTH_INC = 0.000001f
}
} | 0 | Kotlin | 0 | 0 | d2c0d09732fed1f2221ee17e5a28f0e50857b333 | 702 | PulseEngine | MIT License |
backend/src/main/kotlin/men/brakh/bsuirstudent/notification/sender/GlobalNotificationSender.kt | N1ghtF1re | 184,453,033 | false | null | package men.brakh.bsuirstudent.notification.sender
import men.brakh.bsuirstudent.application.exception.BadRequestException
import men.brakh.bsuirstudent.domain.iis.student.Student
import men.brakh.bsuirstudent.notification.repository.NotificationTokenRepository
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
@Component
class GlobalNotificationSender(
notificationSenders: List<NotificationSender>,
private val notificationTokenRepository: NotificationTokenRepository
) {
private val logger = LoggerFactory.getLogger(GlobalNotificationSender::class.java)
private val notificationSendersMap = notificationSenders.mapNotNull { notificationSender ->
notificationSender.supportedTokenType?.let { it to notificationSender }
}.toMap()
fun send(user: Student, title: String, body: String) {
logger.info("Notification to ${user.id}. Title: $title. Body: $body")
notificationTokenRepository.findAllByStudent(user)
.forEach { token ->
notificationSendersMap[token.type]?.send(token, title, body)
?: throw BadRequestException("Unsupported token type: ${token.type}")
}
}
} | 0 | Kotlin | 0 | 9 | a4cd806c4658eb2aa736aa40daf47b19d39df80f | 1,210 | Bsuir-Additional-Api | Apache License 2.0 |
src/main/kotlin/br/com/leodelmiro/lista/ListaChavesGrpcEndpoint.kt | leodelmiro | 354,864,787 | true | {"Kotlin": 108698} | package br.com.leodelmiro.lista
import br.com.leodelmiro.*
import br.com.leodelmiro.compartilhado.chavepix.ChavePixRepository
import br.com.leodelmiro.compartilhado.exceptions.interceptor.ErrorHandler
import com.google.protobuf.Timestamp
import io.grpc.stub.StreamObserver
import java.time.ZoneId
import java.util.*
import javax.inject.Inject
import javax.inject.Singleton
@ErrorHandler
@Singleton
class ListaChavesGrpcEndpoint(@Inject private val repository: ChavePixRepository) :
KeyManagerListaGrpcServiceGrpc.KeyManagerListaGrpcServiceImplBase() {
override fun listaChaves(request: ListaChavesRequest, responseObserver: StreamObserver<ListaChavesResponse>) {
if (request.idCliente.isNullOrBlank())
throw IllegalArgumentException("Id cliente não pode ser nulo ou vazio!")
val idCliente = UUID.fromString(request.idCliente)
val listaChavesPix = repository.findAllByIdCliente(idCliente).map {
ListaChavesResponse.ChaveResponse.newBuilder()
.setIdPix(it.id.toString())
.setTipoChave(TipoChave.valueOf(it.tipoChave.name))
.setChave(it.chave)
.setTipoConta(TipoConta.valueOf(it.tipoConta.name))
.setCriadoEm(it.criadoEm.let { criadoEm ->
val instantCriadoEm = criadoEm.atZone(ZoneId.of("UTC")).toInstant()
Timestamp.newBuilder()
.setSeconds(instantCriadoEm.epochSecond)
.setNanos(instantCriadoEm.nano)
.build()
})
.build()
}
responseObserver.onNext(ListaChavesResponse.newBuilder()
.setIdCliente(idCliente.toString())
.addAllChavesPix(listaChavesPix)
.build()
)
responseObserver.onCompleted()
}
} | 0 | Kotlin | 0 | 0 | 32c2dc367648ce0dbf8aeb5275f444e08d6f39e7 | 1,930 | orange-talents-02-template-pix-keymanager-grpc | Apache License 2.0 |
day11/kotlin/corneil/src/main/kotlin/solution.kt | timgrossmann | 225,318,089 | false | {"Gradle": 17, "Shell": 21, "Dockerfile": 5, "AsciiDoc": 245, "Text": 188, "Ignore List": 24, "Batchfile": 2, "Git Attributes": 1, "Go": 5, "Java": 22, "Haskell": 14, "JSON with Comments": 17, "JavaScript": 17, "JSON": 25, "PHP": 9, "JetBrains MPS": 21, "XML": 9, "Kotlin": 33, "C++": 18, "Ruby": 24, "Python": 101, "INI": 5, "HTML": 10, "Jupyter Notebook": 10, "Dart": 26, "Groovy": 25, "TOML": 4, "Rust": 2, "Maven POM": 7, "Scala": 2, "Cypher": 3, "Java Properties": 1, "Groovy Server Pages": 14, "SVG": 2, "CSS": 5, "Markdown": 2, "Clojure": 3, "Tcl": 1} | package com.github.corneil.aoc2019.day11
import com.github.corneil.aoc2019.day11.DIRECTION.EAST
import com.github.corneil.aoc2019.day11.DIRECTION.NORTH
import com.github.corneil.aoc2019.day11.DIRECTION.SOUTH
import com.github.corneil.aoc2019.day11.DIRECTION.WEST
import com.github.corneil.aoc2019.intcode.Program
import com.github.corneil.aoc2019.intcode.readProgram
import java.io.File
enum class DIRECTION(val direction: Char) {
NORTH('^'),
EAST('>'),
SOUTH('v'),
WEST('<')
}
data class Cell(val color: Int = 0, val painted: Boolean = false)
data class Coord(val x: Int, val y: Int)
data class Robot(var position: Coord, var direction: DIRECTION) {
fun turn(direction: Int) {
if (direction == 0) {
turnLeft()
} else {
turnRight()
}
advance()
}
fun advance() {
position = when (direction) {
NORTH -> position.copy(y = position.y - 1)
EAST -> position.copy(x = position.x + 1)
SOUTH -> position.copy(y = position.y + 1)
WEST -> position.copy(x = position.x - 1)
}
}
fun turnLeft() {
direction = when (direction) {
NORTH -> WEST
WEST -> SOUTH
SOUTH -> EAST
EAST -> NORTH
}
}
fun turnRight() {
direction = when (direction) {
NORTH -> EAST
EAST -> SOUTH
SOUTH -> WEST
WEST -> NORTH
}
}
}
data class Grid(val cells: MutableMap<Coord, Cell> = mutableMapOf()) {
fun cellColor(pos: Coord): Int {
val cell = cells[pos] ?: Cell()
return cell.color
}
fun paintCell(pos: Coord, color: Int) {
cells[pos] = Cell(color, true)
}
}
fun runRobot(input: List<Long>, startingColor: Int): Int {
val robot = Robot(Coord(0, 0), NORTH)
val grid = Grid()
var outputState = false
val code = Program(input)
val program = code.createProgram(listOf(startingColor.toLong()), fetchInput = {
grid.cellColor(robot.position).toLong()
}, outputHandler = { output ->
if (!outputState) {
grid.paintCell(robot.position, output.toInt())
outputState = true
} else {
robot.turn(output.toInt())
outputState = false
}
})
do {
program.execute()
} while (!program.isHalted())
printGrid(grid)
return grid.cells.values.count { it.painted }
}
fun printGrid(grid: Grid) {
val maxX = grid.cells.keys.maxBy { it.x }?.x ?: 0
val minX = grid.cells.keys.minBy { it.x }?.x ?: 0
val maxY = grid.cells.keys.maxBy { it.y }?.y ?: 0
val minY = grid.cells.keys.minBy { it.y }?.y ?: 0
for (y in minY..maxY) {
for (x in minX..maxX) {
val color = grid.cellColor(Coord(x, y))
print(if (color == 0) ' ' else '#')
}
println()
}
}
fun main(args: Array<String>) {
val fileName = if (args.size > 1) args[0] else "input.txt"
val code = readProgram(File(fileName))
val painted = runRobot(code, 0)
println("Painted = $painted")
runRobot(code, 1)
}
| 1 | null | 1 | 1 | bb19fda33ac6e91a27dfaea27f9c77c7f1745b9b | 3,153 | aoc-2019 | MIT License |
liveview-android/src/test/java/com/dockyard/liveviewtest/liveview/components/LazyRowShotTest.kt | liveview-native | 459,214,950 | false | {"Kotlin": 1098756, "Elixir": 68578} | package com.dockyard.liveviewtest.liveview.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Text
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.dockyard.liveviewtest.liveview.util.LiveViewComposableTest
import org.junit.Test
class LazyRowShotTest : LiveViewComposableTest() {
private fun cellForTemplate(count: Int, fill: Boolean = true): String {
return StringBuffer().apply {
(1..count).forEach {
append(
"""
<Column padding="8">
<Text ${if (fill) "weight=\"1\"" else ""}>Item ${it}</Text>
<Text>#${it}</Text>
</Column>
"""
)
}
}.toString()
}
@Test
fun simpleLazyRowTest() {
val rowCount = 20
compareNativeComposableWithTemplate(
nativeComposable = {
LazyRow(Modifier.height(150.dp)) {
items((1..rowCount).toList()) { num ->
Column(Modifier.padding(8.dp)) {
Text(text = "Item $num", Modifier.weight(1f))
Text(text = "#$num")
}
}
}
}, template = """
<LazyRow height="150">
${cellForTemplate(rowCount)}
</LazyRow>
"""
)
}
@Test
fun lazyRowReverseTest() {
val rowCount = 30
compareNativeComposableWithTemplate(
nativeComposable = {
LazyRow(Modifier.height(150.dp), reverseLayout = true) {
items((1..rowCount).toList()) { num ->
Column(Modifier.padding(8.dp)) {
Text(text = "Item $num", Modifier.weight(1f))
Text(text = "#$num")
}
}
}
}, template = """
<LazyRow height="150" reverse-layout="true">
${cellForTemplate(rowCount)}
</LazyRow>
"""
)
}
@Test
fun lazyRowHorizontalArrangement() {
val rowCount = 5
compareNativeComposableWithTemplate(
nativeComposable = {
LazyRow(
modifier = Modifier
.height(100.dp)
.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceAround,
) {
items((1..rowCount).toList()) { num ->
Column(Modifier.padding(8.dp)) {
Text(text = "Item $num", Modifier.weight(1f))
Text(text = "#$num")
}
}
}
}, template = """
<LazyRow height="100" width="fill" horizontal-arrangement="spaceAround">
${cellForTemplate(rowCount)}
</LazyRow>
"""
)
}
@Test
fun lazyRowVerticalAlignment() {
val rowCount = 5
compareNativeComposableWithTemplate(
nativeComposable = {
LazyRow(
Modifier
.fillMaxWidth()
.height(200.dp),
verticalAlignment = Alignment.Bottom,
) {
items((1..rowCount).toList()) { num ->
Column(Modifier.padding(8.dp)) {
Text(text = "Item $num")
Text(text = "#$num")
}
}
}
}, template = """
<LazyRow width="fill" height="200" vertical-alignment="bottom">
${cellForTemplate(rowCount, false)}
</LazyRow>
"""
)
}
} | 44 | Kotlin | 3 | 68 | 7836c95b109b06ea676e499ac75bb9be9d443cbb | 4,381 | liveview-client-jetpack | MIT License |
src/test/kotlin/concurrency/VirtualThreadTest.kt | objektwerks | 353,663,201 | false | null | package concurrency
import java.util.concurrent.ExecutionException
import java.util.concurrent.Executors
import org.junit.Test
/**
* Configure in gradle: --enable-preview --add-modules jdk.incubator.concurrent
* Virtual Threads: openjdk.org/jeps/425
* Article: www.marcobehler.com/guides/java-project-loom
*/
class VirtualThreadTest {
@Test
@Throws(ExecutionException::class, InterruptedException::class)
fun virtualThreadTest() {
val tasks = listOf(
FileLineCountTask("./data/data.a.csv"),
FileLineCountTask("./data/data.b.csv")
)
val lines = Executors.newVirtualThreadPerTaskExecutor().use { executor ->
executor.invokeAll(tasks).sumOf { future -> future.get() }
}
assert(lines == 540959)
}
} | 0 | Kotlin | 0 | 0 | 8fa77fe8a15e8d145a63e3769a00951605ee53db | 793 | kotlin | Apache License 2.0 |
kpages/src/jvmMain/kotlin/PreferenceJvm.kt | Monkopedia | 316,826,954 | false | null | /*
* Copyright 2020 Jason Monk
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.monkopedia.kpages.preferences
import com.monkopedia.kpages.JvmControllerFactory
import com.monkopedia.kpages.Mutable
import com.monkopedia.kpages.Navigator
import com.monkopedia.kpages.ViewControllerFactory
import com.monkopedia.lanterna.navigation.Screen
actual interface PreferenceBaseProps {
actual var onClick: (suspend (Any) -> Unit)?
}
actual interface PreferenceProps : PreferenceBaseProps {
actual var title: String?
actual var subtitle: String?
}
actual fun PreferenceScreen(adapter: (String) -> PreferenceAdapter): ViewControllerFactory =
JvmPreferenceScreenFactory(adapter)
class JvmPreferenceScreenFactory(
private val adapter: (String) -> PreferenceAdapter
) : JvmControllerFactory() {
override fun create(navigator: Navigator, path: String, title: Mutable<CharSequence>): Screen {
return JvmPreferenceScreen(navigator, title, adapter(path))
}
}
actual inline fun PreferenceBuilder.preference(noinline handler: PreferenceProps.() -> Unit) {
add(createPreferenceProps().also(handler))
}
actual interface PreferenceCategoryProps : PreferenceBaseProps {
actual var title: String?
actual var children: ((PreferenceBuilder) -> Unit)?
}
actual inline fun PreferenceBuilder.preferenceCategory(
crossinline handler: PreferenceCategoryProps.() -> Unit,
crossinline builder: PreferenceBuilder.() -> Unit
) {
val props = createCategory()
props.handler()
props.children = {
it.builder()
}
add(props)
}
actual inline fun PreferenceBuilder.preferenceCategory(
title: String,
crossinline builder: PreferenceBuilder.() -> Unit
) {
val props = createCategory()
props.title = title
props.children = {
it.builder()
}
add(props)
}
actual interface SelectionOption {
actual var label: String
}
actual interface SelectionPreferenceProps<T : SelectionOption> : PreferenceProps {
actual var initialState: T?
actual var onChange: (suspend (T?) -> Unit)?
actual var options: List<T>?
}
actual inline fun <reified T : SelectionOption> PreferenceBuilder.selectionPreference(
noinline handler: SelectionPreferenceProps<T>.() -> Unit
) {
add(createSelectionPreferenceProps<T>().also(handler))
}
actual interface SwitchPreferenceProps : PreferenceProps {
actual var initialState: Boolean?
actual var onChange: (suspend (Boolean) -> Unit)?
}
actual inline fun PreferenceBuilder.switchPreference(
noinline handler: SwitchPreferenceProps.() -> Unit
) {
add(createSwitchPreferenceProps().also(handler))
}
actual interface SwitchPreferenceCategoryProps : PreferenceCategoryProps {
actual var initialState: Boolean?
actual var onChange: (suspend (Boolean) -> Unit)?
}
actual inline fun PreferenceBuilder.switchPreferenceCategory(
noinline handler: SwitchPreferenceCategoryProps.() -> Unit,
crossinline builder: PreferenceBuilder.() -> Unit
) {
add(
createSwitchPreferenceCategoryProps().apply {
handler()
this.children = {
it.builder()
}
}
)
}
actual inline fun PreferenceBuilder.switchPreferenceCategory(
title: String,
initialState: Boolean,
noinline onChange: (suspend (Boolean) -> Unit)?,
crossinline builder: PreferenceBuilder.() -> Unit
) {
add(
createSwitchPreferenceCategoryProps().apply {
this.title = title
this.initialState = initialState
this.onChange = onChange
this.children = {
it.builder()
}
}
)
}
actual interface TextInputPreferenceProps : PreferenceProps {
actual var value: String?
actual var dialogTitle: String?
actual var dialogDescription: String?
actual var hintText: String?
actual var onChange: (suspend (String) -> Unit)?
}
actual inline fun PreferenceBuilder.textInputPreference(
noinline handler: TextInputPreferenceProps.() -> Unit
) {
add(createTextInputPreferenceProps().also(handler))
}
actual abstract class PreferenceAdapter actual constructor() : PreferenceAdapterBase() {
actual fun notifyChanged() {
onChange()
}
actual abstract fun PreferenceBuilder.build()
actual abstract val title: String
}
| 0 | Kotlin | 0 | 0 | c766f5a0834a4e621170bd62be2737ba6c8d77bf | 4,862 | kpages | Apache License 2.0 |
src/main/kotlin/io/andrewohara/utils/mappers/jacksonYaml.kt | oharaandrew314 | 367,413,369 | false | null | package io.andrewohara.utils.mappers
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.dataformat.yaml.YAMLMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import io.andrewohara.utils.config.ConfigLoader
import io.andrewohara.utils.config.mapper as configMapper
import java.io.InputStream
import java.io.Reader
fun defaultJacksonYaml() = YAMLMapper().apply {
registerModule(KotlinModule())
disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
}
class JacksonYamlValueMapper<T>(private val mapper: YAMLMapper = defaultJacksonYaml(), private val type: Class<T>): ValueMapper<T> {
override fun read(reader: Reader): T = mapper.readValue(reader, type)
override fun read(input: InputStream): T = mapper.readValue(input, type)
override fun read(source: ByteArray): T = mapper.readValue(source, type)
override fun read(source: String): T = mapper.readValue(source, type)
override fun write(value: T): String = mapper.writeValueAsString(value)
}
inline fun <reified T> ValueMapper.Companion.jacksonYaml(mapper: YAMLMapper = defaultJacksonYaml()) = JacksonYamlValueMapper(mapper, T::class.java)
inline fun <reified T> ConfigLoader<ByteArray>.jacksonYaml(mapper: YAMLMapper = defaultJacksonYaml()) = configMapper(ValueMapper.jacksonYaml<T>(mapper))
inline fun <reified T> ConfigLoader<ByteArray>.jacksonYaml(consumer: (YAMLMapper) -> YAMLMapper): ConfigLoader<T> {
val mapper = consumer(defaultJacksonYaml())
return configMapper(ValueMapper.jacksonYaml(mapper))
} | 0 | Kotlin | 0 | 3 | f4e9be4e13884dac2f3c8aeebf190ea893a5012d | 1,555 | service-utils | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.