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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
composeApp/src/androidMain/kotlin/com/kmp/webinar/Country.kt
|
kotlin-hands-on
| 721,544,108 | false |
{"Kotlin": 19443, "Swift": 6020}
|
package com.kmp.webinar
import androidx.compose.foundation.layout.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import country.Country
@Composable
fun Country(modifier: Modifier, country: Country, navigateToWeather: (String, Double, Double)-> Unit) {
Row(modifier = Modifier.padding(8.dp)) {
Column(modifier = Modifier.width(130.dp)) {
Flag(modifier = Modifier.fillMaxWidth().padding(8.dp), country.flags)
}
Column(modifier = Modifier.fillMaxWidth().padding(8.dp)) {
CountryNames(name = country.name)
val capitalInfo = country.capitalInfo
if (country.capital.isNotEmpty() && capitalInfo != null) {
WeatherButton(capitals = country.capital, capitalInfo = capitalInfo,
navigateToWeather = navigateToWeather
)
}
}
}
}
| 0 |
Kotlin
|
3
| 11 |
f056e3c2b61ac29ec6299b7d817c2339bd5ee56a
| 929 |
native-ui-webinar
|
Apache License 2.0
|
module/connector/activemq/integration-test/src/test/kotlin/pl/beone/promena/connector/activemq/delivery/jms/TimeUtils.kt
|
BeOne-PL
| 235,044,896 | false | null |
package pl.beone.promena.connector.activemq.delivery.jms
import io.kotlintest.matchers.numerics.shouldBeGreaterThan
import io.kotlintest.matchers.numerics.shouldBeLessThan
import io.kotlintest.matchers.shouldBeInRange
fun getTimestamp(): Long =
System.currentTimeMillis()
fun validateTimestamps(transformationStartTimestamp: Long, transformationEndTimestamp: Long, startTimestamp: Long, endTimestamp: Long) {
transformationStartTimestamp.let {
it.shouldBeInRange(startTimestamp..endTimestamp)
it shouldBeLessThan transformationEndTimestamp
}
transformationEndTimestamp.let {
it.shouldBeInRange(startTimestamp..endTimestamp)
it shouldBeGreaterThan transformationStartTimestamp
}
}
| 2 |
Kotlin
|
1
| 9 |
adbc25d2cd3acf1990f7188938fee25d834aa0db
| 735 |
promena
|
Apache License 2.0
|
app/src/main/java/com/nikolai/finstagram/data/firebase/FirebaseChatsRepository.kt
|
mykolalatii
| 271,390,777 | false | null |
package com.nikolai.finstagram.data.firebase
import android.arch.lifecycle.LiveData
import com.google.android.gms.tasks.Task
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.ServerValue
import com.nikolai.finstagram.common.Event
import com.nikolai.finstagram.common.EventBus
import com.nikolai.finstagram.common.toUnit
import com.nikolai.finstagram.data.ChatsRepository
import com.nikolai.finstagram.data.common.map
import com.nikolai.finstagram.data.firebase.common.FirebaseLiveData
import com.nikolai.finstagram.data.firebase.common.database
import com.nikolai.finstagram.models.Chat
class FirebaseChatsRepository : ChatsRepository {
override fun createChat(uid: String, chat : Chat): Task<Unit> {
val reference = database.child("chats").child(uid).child(chat.cid)
return reference.setValue(chat).toUnit().addOnSuccessListener {
EventBus.publish(Event.CreateChat(chat))
}
}
override fun getChats(uid: String): LiveData<List<Chat>> {
return FirebaseLiveData(database.child("chats").child(uid)).map { it.children.map { it.asChat()!! } }
}
override fun setLastMessageSeen(uid: String, cid : String): Task<Unit> {
val updatesMap = mutableMapOf<String, Any?>()
updatesMap["seen"] = true
return database.child("chats").child(uid).child(cid).updateChildren(updatesMap).toUnit()
}
override fun updateLastMessage(uid: String, cid: String, message: String): Task<Unit> {
val updatesMap = mutableMapOf<String, Any?>()
updatesMap["last_message"] = message
updatesMap["time"] = ServerValue.TIMESTAMP
updatesMap["seen"] = false
return database.child("chats").child(uid).child(cid).updateChildren(updatesMap).toUnit()
}
override fun updateChatProfilePicture(url: String, uid: String, cid: String): Task<Unit> {
return database.child("chats/${uid}/${cid}/profile_picture").setValue(url).toUnit()
}
private fun DataSnapshot.asChat() : Chat? = getValue(Chat::class.java)?.copy(cid = key)
}
| 0 |
Kotlin
|
0
| 0 |
f480a8c1774c7f4816af30592f8bc82f9fd50f68
| 2,076 |
Clone-instagram-kotlin-with-chat
|
MIT License
|
data/src/test/kotlin/team/duckie/app/android/data/CategoryRepositoryTest.kt
|
duckie-team
| 503,869,663 | false |
{"Kotlin": 1819917}
|
/*
* Designed and developed by Duckie Team, 2022
*
* Licensed under the MIT.
* Please see full license: https://github.com/duckie-team/duckie-android/blob/develop/LICENSE
*/
@file:OptIn(ExperimentalCoroutinesApi::class)
package team.duckie.app.android.data
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.After
import org.junit.Test
import strikt.api.expectThat
import strikt.assertions.containsExactly
import strikt.assertions.isNotEmpty
import team.duckie.app.android.data.category.repository.CategoryRepositoryImpl
import team.duckie.app.android.data.dummy.CategoryDummyResponse
import team.duckie.app.android.data.util.ApiTest
import team.duckie.app.android.data.util.buildMockHttpClient
import team.duckie.app.android.domain.category.repository.CategoryRepository
import timber.log.Timber
class CategoryRepositoryTest : ApiTest(
isMock = true,
client = buildMockHttpClient(content = CategoryDummyResponse.RawData),
) {
private val repository: CategoryRepository by lazy { CategoryRepositoryImpl() }
@Test
fun response_to_domain_model() = runTest {
val actual = repository.getCategories(true)
if (isMock) {
val expected = CategoryDummyResponse.DomainData
expectThat(actual).containsExactly(expected)
} else {
Timber.e(actual.first().toString())
expectThat(actual).isNotEmpty()
}
}
@After
fun closeClient() {
client.close()
}
}
| 32 |
Kotlin
|
1
| 8 |
5dbd5b7a42c621931d05a96e66431f67a3a50762
| 1,528 |
duckie-android
|
MIT License
|
app/src/main/kotlin/ru/cinema/api/episode/model/EpisodeResponse.kt
|
alexBlack01
| 541,182,433 | false | null |
package ru.cinema.api.episode.model
import kotlinx.serialization.Contextual
import kotlinx.serialization.Serializable
import ru.cinema.api.common.extensions.toResourceUrl
import ru.cinema.domain.episode.model.Episode
import java.util.*
@Serializable
data class EpisodeResponse(
@Contextual
val episodeId: UUID,
val name: String,
val description: String,
val director: String,
val stars: List<String>,
val year: Int,
val images: List<String>,
val runtime: Int,
val preview: String?,
val filePath: String?
) {
@Suppress("LongParameterList")
companion object {
fun fromDomain(
data: Episode,
baseUrl: String,
uploadFolder: String,
episodeImageFolder: String,
previewFolder: String,
fileFolder: String
) = EpisodeResponse(
episodeId = data.episodeId,
name = data.name,
description = data.description,
director = data.director,
stars = data.stars,
year = data.year,
images = data.imageUrls.map { it.toResourceUrl(baseUrl, uploadFolder, episodeImageFolder) },
runtime = data.runtime,
preview = data.preview?.toResourceUrl(baseUrl, uploadFolder, previewFolder),
filePath = data.filePath?.toResourceUrl(baseUrl, uploadFolder, fileFolder)
)
}
}
| 0 |
Kotlin
|
0
| 0 |
42aae0917fe632a3a9e0b3011eb8072c53941998
| 1,411 |
cinema-backend
|
Apache License 1.1
|
library/src/main/java/com/tweener/czan/android/designsystem/molecule/carousel/Carousel.kt
|
Tweener
| 696,878,975 | false | null |
package com.tweener.czan.android.designsystem.molecule.carousel
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.interaction.collectIsDraggedAsState
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.PreviewLightDark
import com.tweener.czan.android.designsystem.atom.text.Text
import com.tweener.czan.android.preview.CzanThemePreview
import com.tweener.czan.android.theme.CzanUiDefaults
import com.tweener.czan.android.theme.Size
import kotlin.time.Duration
import kotlinx.coroutines.delay
/**
* @author Vivien Mahe
* @since 13/05/2023
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Carousel(
modifier: Modifier = Modifier,
userScrollEnabled: Boolean = true,
showDots: Boolean = true,
animationType: CarouselAnimationType = CarouselAnimationType.NONE,
slideDuration: Duration = CzanUiDefaults.Carousel.slideDuration(),
pagerState: PagerState = rememberPagerState { 0 },
itemContent: @Composable (index: Int) -> Unit,
) {
val isDragged by pagerState.interactionSource.collectIsDraggedAsState()
var pageIndex by remember { mutableIntStateOf(0) }
if (animationType != CarouselAnimationType.NONE) {
LaunchedEffect(pageIndex) {
delay(slideDuration)
val newPageIndex = (pagerState.currentPage + 1) % pagerState.pageCount
if (newPageIndex != 0 || animationType != CarouselAnimationType.ONE_TIME) {
pagerState.animateScrollToPage(newPageIndex)
pageIndex = newPageIndex
}
}
}
Column(modifier = modifier.fillMaxWidth()) {
HorizontalPager(
modifier = Modifier.fillMaxWidth(),
state = pagerState,
pageSpacing = Size.Padding.Default,
userScrollEnabled = userScrollEnabled
) { index ->
itemContent(index)
}
if (showDots) {
Spacer(modifier = Modifier.padding(vertical = Size.Padding.ExtraSmall))
CarouselDots(
modifier = Modifier.fillMaxWidth(),
pageCount = pagerState.pageCount,
currentPage = if (isDragged) pagerState.currentPage else pagerState.targetPage,
)
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@PreviewLightDark
@Composable
private fun CarouselWithDotsPreview() {
CzanThemePreview {
Carousel(pagerState = rememberPagerState { 4 }) {
Text("Page $it")
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@PreviewLightDark
@Composable
private fun CarouselWithoutDotsPreview() {
CzanThemePreview {
Carousel(
pagerState = rememberPagerState { 4 },
showDots = false
) {
Text("Page $it")
}
}
}
| 3 | null |
0
| 6 |
c048087db2cfd46cd56e451eea75eb945f3b902c
| 3,454 |
c-zan
|
Apache License 2.0
|
library/src/main/java/com/tweener/czan/android/designsystem/molecule/carousel/Carousel.kt
|
Tweener
| 696,878,975 | false | null |
package com.tweener.czan.android.designsystem.molecule.carousel
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.interaction.collectIsDraggedAsState
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.PreviewLightDark
import com.tweener.czan.android.designsystem.atom.text.Text
import com.tweener.czan.android.preview.CzanThemePreview
import com.tweener.czan.android.theme.CzanUiDefaults
import com.tweener.czan.android.theme.Size
import kotlin.time.Duration
import kotlinx.coroutines.delay
/**
* @author <NAME>
* @since 13/05/2023
*/
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun Carousel(
modifier: Modifier = Modifier,
userScrollEnabled: Boolean = true,
showDots: Boolean = true,
animationType: CarouselAnimationType = CarouselAnimationType.NONE,
slideDuration: Duration = CzanUiDefaults.Carousel.slideDuration(),
pagerState: PagerState = rememberPagerState { 0 },
itemContent: @Composable (index: Int) -> Unit,
) {
val isDragged by pagerState.interactionSource.collectIsDraggedAsState()
var pageIndex by remember { mutableIntStateOf(0) }
if (animationType != CarouselAnimationType.NONE) {
LaunchedEffect(pageIndex) {
delay(slideDuration)
val newPageIndex = (pagerState.currentPage + 1) % pagerState.pageCount
if (newPageIndex != 0 || animationType != CarouselAnimationType.ONE_TIME) {
pagerState.animateScrollToPage(newPageIndex)
pageIndex = newPageIndex
}
}
}
Column(modifier = modifier.fillMaxWidth()) {
HorizontalPager(
modifier = Modifier.fillMaxWidth(),
state = pagerState,
pageSpacing = Size.Padding.Default,
userScrollEnabled = userScrollEnabled
) { index ->
itemContent(index)
}
if (showDots) {
Spacer(modifier = Modifier.padding(vertical = Size.Padding.ExtraSmall))
CarouselDots(
modifier = Modifier.fillMaxWidth(),
pageCount = pagerState.pageCount,
currentPage = if (isDragged) pagerState.currentPage else pagerState.targetPage,
)
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@PreviewLightDark
@Composable
private fun CarouselWithDotsPreview() {
CzanThemePreview {
Carousel(pagerState = rememberPagerState { 4 }) {
Text("Page $it")
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@PreviewLightDark
@Composable
private fun CarouselWithoutDotsPreview() {
CzanThemePreview {
Carousel(
pagerState = rememberPagerState { 4 },
showDots = false
) {
Text("Page $it")
}
}
}
| 3 | null |
0
| 6 |
c048087db2cfd46cd56e451eea75eb945f3b902c
| 3,449 |
c-zan
|
Apache License 2.0
|
app/src/main/java/gins/android/gri_tri/Cart.kt
|
Ginny-Binny
| 562,392,018 | false |
{"Kotlin": 26608}
|
package gins.android.gri_tri
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.FrameLayout
class Cart : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_cart)
val addNowBtn : FrameLayout = findViewById(R.id.button_cart)
addNowBtn.setOnClickListener{
// val intent = Intent(this, MainActivity::class.java)
// startActivity(intent)
onBackPressed()
}
}
}
| 0 |
Kotlin
|
0
| 1 |
1b3cbc51b9662150fb148204f07c60f443706352
| 605 |
GRITRI
|
MIT License
|
android/src/main/java/it/agaweb/reactnativestripe/ReactCardInputManager.kt
|
Agaweb
| 309,384,249 | false | null |
package it.agaweb.reactnativestripe
import com.facebook.react.uimanager.BaseViewManager
import com.facebook.react.uimanager.ThemedReactContext
class ReactCardInputManager : BaseViewManager<ReactCardInputView, ReactCardInputShadowNode>() {
val REACT_CLASS = "RNTStripeCardInput"
override fun createViewInstance(reactContext: ThemedReactContext): ReactCardInputView {
return ReactCardInputView(reactContext)
}
override fun getName(): String {
return REACT_CLASS
}
override fun createShadowNodeInstance(): ReactCardInputShadowNode {
return ReactCardInputShadowNode()
}
override fun getShadowNodeClass(): Class<out ReactCardInputShadowNode> {
return ReactCardInputShadowNode::class.java
}
override fun updateExtraData(root: ReactCardInputView, extraData: Any?) {
// do nothing
}
}
| 1 |
Kotlin
|
8
| 21 |
eb7f293db101f229616553b50c1eeaef63c26883
| 826 |
react-native-stripe
|
MIT License
|
router/src/main/java/com/therouter/history/HistoryRecorder.kt
|
HuolalaTech
| 530,172,359 | false | null |
@file:JvmName("HistoryRecorder")
package com.therouter.history
import com.therouter.inject.RecyclerLruCache
import java.util.*
import kotlin.collections.ArrayList
/**
* 日志记录类,top-level,用于记录TheRouter的所有操作日志,可方便线上或debug环境导出
*/
private var counter: Long = 0
var HISTORY_LOG_MAX_SIZE = 30
private val mCacher = RecyclerLruCache<String?, History?>(HISTORY_LOG_MAX_SIZE).apply {
setOnEntryRemovedListener { key, oldValue, _ -> m2ndCacher[key] = oldValue }
}
private val m2ndCacher = WeakHashMap<String?, History?>()
@Synchronized
fun pushHistory(event: History) = mCacher.put("${counter++}", event)
/**
* 导出路由的全部记录
*/
@Synchronized
fun export(level: Level): List<String> {
val list = ArrayList<String>()
for (index in 0..counter) {
val item = mCacher.get("$index") ?: m2ndCacher["$index"]
item?.let { history ->
when (history) {
is ActivityNavigatorHistory -> {
if (level.v.and(Level.ACTIVITY.v) == Level.ACTIVITY.v) {
list.add(history.event)
}
}
is FragmentNavigatorHistory -> {
if (level.v.and(Level.FRAGMENT.v) == Level.FRAGMENT.v) {
list.add(history.event)
}
}
is ActionNavigatorHistory -> {
if (level.v.and(Level.ACTION.v) == Level.ACTION.v) {
list.add(history.event)
}
}
is ServiceProviderHistory -> {
if (level.v.and(Level.SERVICE_PROVIDER.v) == Level.SERVICE_PROVIDER.v) {
list.add(history.event)
}
}
is FlowTaskHistory -> {
if (level.v.and(Level.FLOW_TASK.v) == Level.FLOW_TASK.v) {
list.add(history.event)
}
}
}
}
}
return list
}
interface History
class ActivityNavigatorHistory(val event: String) : History
class FragmentNavigatorHistory(val event: String) : History
class ActionNavigatorHistory(val event: String) : History
class ServiceProviderHistory(val event: String) : History
class FlowTaskHistory(val event: String) : History
open class Level {
var v: Int = 0
private set
/**
* 仅类内部使用,写起来代码简洁一点
*/
private fun sv(value: Int): Level {
v = value
return this
}
companion object {
val NONE = Level().sv(0x000000)
val ACTIVITY = Level().sv(0x000001)
val FRAGMENT = Level().sv(0x000010)
val PAGE = Level().sv(0x000011)
val ACTION = Level().sv(0x001000)
val SERVICE_PROVIDER = Level().sv(0x010000)
val FLOW_TASK = Level().sv(0x100000)
val ALL = Level().sv(0x111111)
}
operator fun plus(o: Level): Level {
return Level().sv(o.v or v)
}
operator fun minus(o: Level): Level {
return Level().sv(o.v xor v)
}
}
| 8 | null |
130
| 994 |
74c000d6b582fee4eb78b8987e488a2315693aeb
| 3,037 |
hll-wp-therouter-android
|
Apache License 2.0
|
wallet/src/main/java/com/fzm/chat/wallet/ui/LocalNoteDialog.kt
|
txchat
| 507,831,442 | false |
{"Kotlin": 2234450, "Java": 384844}
|
package com.fzm.chat.wallet.ui
import android.app.Dialog
import android.content.Context
import android.view.Gravity
import android.view.LayoutInflater
import android.view.WindowManager
import androidx.core.widget.addTextChangedListener
import com.fzm.chat.wallet.databinding.DialogLocalNoteBinding
import com.zjy.architecture.util.KeyboardUtils
/**
* @author zhengjy
* @since 2021/08/16
* Description:
*/
class LocalNoteDialog(
context: Context,
oldNote: CharSequence?,
onSaveNote: (String) -> Unit
) : Dialog(context) {
private val binding: DialogLocalNoteBinding
private var localNote: String = ""
init {
window?.setBackgroundDrawableResource(android.R.color.transparent)
window?.attributes = window?.attributes?.apply {
gravity = Gravity.CENTER
width = WindowManager.LayoutParams.MATCH_PARENT
height = WindowManager.LayoutParams.WRAP_CONTENT
}
binding = DialogLocalNoteBinding.inflate(LayoutInflater.from(context))
window?.setContentView(binding.root)
binding.etNote.addTextChangedListener {
val text = it?.toString() ?: ""
binding.tvCount.text = "${text.length}/60"
localNote = text
}
binding.etNote.setText(oldNote)
if (!oldNote.isNullOrEmpty()) {
binding.etNote.setSelection(0, oldNote.length)
}
binding.etNote.postDelayed({ KeyboardUtils.showKeyboard(binding.etNote) }, 100)
binding.tvCancel.setOnClickListener { cancel() }
binding.tvConfirm.setOnClickListener {
onSaveNote(localNote)
dismiss()
}
}
}
| 0 |
Kotlin
|
1
| 1 |
6a3c6edf6ae341199764d4d08dffd8146877678b
| 1,664 |
ChatPro-Android
|
MIT License
|
OneSignalSDK/onesignal/core/src/main/java/com/onesignal/core/internal/device/IDeviceService.kt
|
OneSignal
| 33,515,679 | false |
{"Kotlin": 1782026, "Java": 49349, "Shell": 748}
|
package com.onesignal.core.internal.device
interface IDeviceService {
val isAndroidDeviceType: Boolean
val isFireOSDeviceType: Boolean
val isHuaweiDeviceType: Boolean
val deviceType: DeviceType
val isGMSInstalledAndEnabled: Boolean
val hasAllHMSLibrariesForPushKit: Boolean
val hasFCMLibrary: Boolean
val androidSupportLibraryStatus: AndroidSupportLibraryStatus
enum class AndroidSupportLibraryStatus {
MISSING,
OUTDATED,
OK,
}
enum class DeviceType(val value: Int) {
Fire(2),
Android(1),
Huawei(13),
}
}
| 72 |
Kotlin
|
368
| 591 |
91fc3989480853b1931e9d2febe83ea50e756b06
| 606 |
OneSignal-Android-SDK
|
Apache License 2.0
|
app/src/main/java/dev/arkbuilders/rate/data/model/CurrencyRepo.kt
|
ARK-Builders
| 515,514,394 | false | null |
package dev.arkbuilders.rate.data
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import dev.arkbuilders.rate.data.db.CurrencyRateLocalDataSource
import dev.arkbuilders.rate.data.db.FetchTimestampDataSource
import dev.arkbuilders.rate.data.network.NetworkStatus
import dev.arkbuilders.rate.utils.withContextAndLock
import java.util.concurrent.TimeUnit
abstract class CurrencyRepo(
private val local: CurrencyRateLocalDataSource,
private val networkStatus: NetworkStatus,
private val fetchTimestampDataSource: FetchTimestampDataSource
) {
protected abstract val type: CurrencyType
private var currencyRates: List<CurrencyRate>? = null
private var updatedTS: Long? = null
private val mutex = Mutex()
suspend fun getCurrencyRate(): List<CurrencyRate> =
withContextAndLock(Dispatchers.IO, mutex) {
if (!networkStatus.isOnline()) {
currencyRates = local.getByType(type)
return@withContextAndLock currencyRates!!
}
updatedTS ?: let {
updatedTS = fetchTimestampDataSource.getTimestamp(type)
}
if (
updatedTS == null ||
updatedTS!! + dayInMillis < System.currentTimeMillis()
) {
val result = fetchRemoteSafe()
result.onSuccess {
currencyRates = it
launch { fetchTimestampDataSource.rememberTimestamp(type) }
launch { local.insert(currencyRates!!, type) }
updatedTS = System.currentTimeMillis()
}
}
currencyRates ?: let {
currencyRates = local.getByType(type)
}
Log.d("Test", "${currencyRates!!.sortedBy { it.code }}")
return@withContextAndLock currencyRates!!
}
private suspend fun fetchRemoteSafe(): Result<List<CurrencyRate>> {
return try {
Result.success(fetchRemote())
} catch (e: Exception) {
Log.e("Fetch currency error", "currency type [$type]", e)
Result.failure(e)
}
}
protected abstract suspend fun fetchRemote(): List<CurrencyRate>
abstract suspend fun getCurrencyName(): List<CurrencyName>
private val dayInMillis = TimeUnit.DAYS.toMillis(1)
}
| 5 | null |
3
| 2 |
850aba354bd508c6016d436ce2efa30419d4d55d
| 2,425 |
ARK-Rate
|
MIT License
|
src/main/kotlin/com/rbkmoney/porter/listener/handler/party/PartySuspensionHandler.kt
|
rbkmoney
| 377,151,676 | false | null |
package com.rbkmoney.porter.listener.handler.party
import com.rbkmoney.damsel.payment_processing.PartyChange
import com.rbkmoney.machinegun.eventsink.MachineEvent
import com.rbkmoney.porter.listener.constant.HandleEventType
import com.rbkmoney.porter.listener.handler.ChangeHandler
import com.rbkmoney.porter.listener.handler.merge.PartyMerger
import com.rbkmoney.porter.repository.PartyRepository
import com.rbkmoney.porter.repository.entity.PartyEntity
import com.rbkmoney.porter.repository.entity.PartyStatus
import mu.KotlinLogging
import org.springframework.stereotype.Component
private val log = KotlinLogging.logger {}
@Component
class PartySuspensionHandler(
private val partyRepository: PartyRepository,
private val partyMerger: PartyMerger,
) : ChangeHandler<PartyChange, MachineEvent> {
override fun handleChange(change: PartyChange, event: MachineEvent) {
val partySuspension = change.partySuspension
val partyId = event.sourceId
val partyEntity = partyRepository.findByPartyId(partyId) ?: PartyEntity()
val updateParty = partyEntity.apply {
this.partyId = partyId
if (partySuspension.isSetSuspended) {
status = PartyStatus.suspended
} else if (partySuspension.isSetActive) {
status = PartyStatus.active
}
}
partyMerger.mergeEvent(partyEntity, updateParty)
log.info { "Save party entity on suspension event: $partyEntity" }
partyRepository.save(updateParty)
}
override val changeType: HandleEventType = HandleEventType.PARTY_SUSPENSION
}
| 0 |
Kotlin
|
1
| 0 |
af408a1d6cbe46a22ec56a14fb0485dcb72830f1
| 1,619 |
porter
|
Apache License 2.0
|
app/src/main/java/com/nandra/movieverse/util/Helper.kt
|
nandrasaputra
| 220,730,565 | false | null |
package com.nandra.movieverse.util
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.appcompat.app.AppCompatDelegate
import com.endiar.movieverse.core.utils.Constant
import com.nandra.movieverse.R
import java.text.SimpleDateFormat
sealed class FilmType(val typeValue: String) {
object FilmTypeMovie : FilmType("movie")
object FilmTypeTV : FilmType("tv")
}
@SuppressLint("SimpleDateFormat")
fun formatDate(stringDate: String) : String {
val inFormat = SimpleDateFormat("yyyy-MM-dd")
val outFormat = SimpleDateFormat("dd-MM-yyyy")
return try {
val date = inFormat.parse(stringDate)
outFormat.format(date ?: "")
} catch (exp: Exception) {
""
}
}
fun tabTitleProvider(context: Context, position: Int): String {
return when(position) {
0 -> context.getString(R.string.discover_tab_title_position_0)
1 -> context.getString(R.string.discover_tab_title_position_1)
else -> throw Exception("Invalid Position")
}
}
fun getFilmTypeFromString(typeInString: String): FilmType {
return when(typeInString) {
Constant.MOVIE_FILM_TYPE -> {
FilmType.FilmTypeMovie
}
Constant.TV_FILM_TYPE -> {
FilmType.FilmTypeTV
}
else -> throw Exception("Invalid typeInString")
}
}
fun hideKeyboardFrom(context: Context, view: View) {
val imm: InputMethodManager =
context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view.windowToken, 0)
}
fun showKeyboardFrom(context: Context) {
val imm: InputMethodManager =
context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)
}
fun changeThemeByThemeValue(value: String) {
when(value) {
"dark" -> {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)}
"day" -> {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)}
else -> {
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)}
}
}
| 0 |
Kotlin
|
3
| 3 |
a40bb90311ec8d2a8e3fa26c96ceaaf6603b485b
| 2,295 |
Movieverse
|
Apache License 2.0
|
src/main/kotlin/org/jetbrains/bio/util/LoggerExtensions.kt
|
karl-crl
| 208,228,814 | true |
{"Kotlin": 1021604}
|
package org.jetbrains.bio.util
import com.google.common.base.Stopwatch
import org.apache.log4j.Level
import org.apache.log4j.Logger
import java.util.concurrent.CancellationException
/**
* Measures the running time of a given possibly impure [block].
*/
inline fun <R> Logger.time(level: Level = Level.DEBUG,
message: String = "",
block: () -> R): R {
log(level, "$message...")
val stopwatch = Stopwatch.createStarted()
val res = try {
block()
} catch (e: CancellationException) {
stopwatch.stop()
log(level, "$message: [CANCELED] after $stopwatch")
throw e
} catch (e: Exception) {
stopwatch.stop()
log(level, "$message: [FAILED] after $stopwatch", e)
throw e
}
stopwatch.stop()
log(level, "$message: done in $stopwatch")
return res
}
| 0 |
Kotlin
|
0
| 0 |
469bed933860cc34960a61ced4599862acbea9bd
| 886 |
bioinf-commons
|
MIT License
|
android/common-ui/src/main/java/any/ui/common/lazy/LazyListScrollableState.kt
|
dokar3
| 572,488,513 | false | null |
package any.ui.common.lazy
import androidx.compose.foundation.lazy.LazyListItemInfo
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.Stable
import androidx.compose.runtime.remember
import androidx.compose.ui.unit.IntSize
import any.base.compose.Provider
import any.base.compose.rememberSaveableProvider
import any.ui.common.quickScrollToTop
@Composable
fun rememberLazyListScrollableState(
listStateProvider: Provider<LazyListState> = rememberSaveableProvider(
inputs = emptyArray(),
saver = LazyListState.Saver,
) {
LazyListState()
},
): LazyListScrollableState {
return remember {
LazyListScrollableState(listStateProvider)
}
}
private fun LazyListItemInfo.toLazyItemInfo(): LazyItemInfo {
return LazyItemInfo(
index = index,
offset = offset,
size = size,
key = key,
)
}
@Stable
class LazyListScrollableState(
private val listStateProvider: Provider<LazyListState>
) : LazyScrollableState {
val listState: LazyListState
get() = listStateProvider.get()
override val visibleItemsInfo: List<LazyItemInfo>
get() = listState.layoutInfo.visibleItemsInfo.map { it.toLazyItemInfo() }
override val totalItemsCount: Int
get() = listState.layoutInfo.totalItemsCount
override val viewportSize: IntSize
get() = listState.layoutInfo.viewportSize
override val viewportStartOffset: Int
get() = listState.layoutInfo.viewportStartOffset
override val viewportEndOffset: Int
get() = listState.layoutInfo.viewportEndOffset
override val columnCount: Float = 1f
override val beforeContentPadding: Int
get() = listState.layoutInfo.beforeContentPadding
override val afterContentPadding: Int
get() = listState.layoutInfo.afterContentPadding
override val isScrollInProgress: Boolean
get() = listState.isScrollInProgress
override suspend fun quickScrollToTop() {
listState.quickScrollToTop()
}
}
| 8 |
Kotlin
|
0
| 9 |
86ccf75753698d54a6b5a24d8747d5bd23ecf71e
| 2,088 |
any
|
Apache License 2.0
|
event-log/src/main/kotlin/dev/yn/entity/serialization/EntityJacksonSerialization.kt
|
dgoetsch
| 100,337,343 | false | null |
/*
* Copyright 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.yn.entity.serialization
import com.fasterxml.jackson.databind.ObjectMapper
import dev.yn.entity.domain.EntityError
import dev.yn.event.serialization.JacksonSerialization
open class EntityJacksonSerialization<T>(objectMapper: ObjectMapper, override val clazz: Class<T>): JacksonSerialization<EntityError, T>(objectMapper) {
override val jsonError: (Throwable) -> EntityError = { EntityError.JsonError(it) }
}
| 0 |
Kotlin
|
0
| 5 |
afe6b2caba24b2a08347dc508d019a70bdeba10f
| 1,046 |
akka-vertx-demo
|
Apache License 2.0
|
src/main/kotlin/pl/wendigo/chrome/api/security/Domain.kt
|
wendigo
| 83,794,841 | false | null |
package pl.wendigo.chrome.api.security
import kotlinx.serialization.json.Json
/**
* Security
*
* @link Protocol [Security](https://chromedevtools.github.io/devtools-protocol/tot/Security) domain documentation.
*/
class SecurityDomain internal constructor(connection: pl.wendigo.chrome.protocol.ProtocolConnection) :
pl.wendigo.chrome.protocol.Domain("Security", """Security""", connection) {
/**
* Disables tracking security state changes.
*
* @link Protocol [Security#disable](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-disable) method documentation.
*/
fun disable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Security.disable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Enables tracking security state changes.
*
* @link Protocol [Security#enable](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-enable) method documentation.
*/
fun enable(): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Security.enable", null, pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Enable/disable whether all certificate errors should be ignored.
*
* @link Protocol [Security#setIgnoreCertificateErrors](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-setIgnoreCertificateErrors) method documentation.
*/
@pl.wendigo.chrome.protocol.Experimental
fun setIgnoreCertificateErrors(input: SetIgnoreCertificateErrorsRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Security.setIgnoreCertificateErrors", Json.encodeToJsonElement(SetIgnoreCertificateErrorsRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Handles a certificate error that fired a certificateError event.
*
* @link Protocol [Security#handleCertificateError](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-handleCertificateError) method documentation.
*/
@Deprecated(level = DeprecationLevel.WARNING, message = "handleCertificateError is deprecated.")
fun handleCertificateError(input: HandleCertificateErrorRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Security.handleCertificateError", Json.encodeToJsonElement(HandleCertificateErrorRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* Enable/disable overriding certificate errors. If enabled, all certificate error events need to
be handled by the DevTools client and should be answered with `handleCertificateError` commands.
*
* @link Protocol [Security#setOverrideCertificateErrors](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-setOverrideCertificateErrors) method documentation.
*/
@Deprecated(level = DeprecationLevel.WARNING, message = "setOverrideCertificateErrors is deprecated.")
fun setOverrideCertificateErrors(input: SetOverrideCertificateErrorsRequest): io.reactivex.rxjava3.core.Single<pl.wendigo.chrome.protocol.websocket.RequestResponseFrame> = connection.request("Security.setOverrideCertificateErrors", Json.encodeToJsonElement(SetOverrideCertificateErrorsRequest.serializer(), input), pl.wendigo.chrome.protocol.websocket.RequestResponseFrame.serializer())
/**
* There is a certificate error. If overriding certificate errors is enabled, then it should be
handled with the `handleCertificateError` command. Note: this event does not fire if the
certificate error has been allowed internally. Only one client per target should override
certificate errors at the same time.
*/
fun certificateError(): io.reactivex.rxjava3.core.Flowable<CertificateErrorEvent> = connection.events("Security.certificateError", CertificateErrorEvent.serializer())
/**
* The security state of the page changed.
*/
fun visibleSecurityStateChanged(): io.reactivex.rxjava3.core.Flowable<VisibleSecurityStateChangedEvent> = connection.events("Security.visibleSecurityStateChanged", VisibleSecurityStateChangedEvent.serializer())
/**
* The security state of the page changed.
*/
fun securityStateChanged(): io.reactivex.rxjava3.core.Flowable<SecurityStateChangedEvent> = connection.events("Security.securityStateChanged", SecurityStateChangedEvent.serializer())
}
/**
* Represents request frame that can be used with [Security#setIgnoreCertificateErrors](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-setIgnoreCertificateErrors) operation call.
*
* Enable/disable whether all certificate errors should be ignored.
* @link [Security#setIgnoreCertificateErrors](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-setIgnoreCertificateErrors) method documentation.
* @see [SecurityDomain.setIgnoreCertificateErrors]
*/
@kotlinx.serialization.Serializable
data class SetIgnoreCertificateErrorsRequest(
/**
* If true, all certificate errors will be ignored.
*/
val ignore: Boolean
)
/**
* Represents request frame that can be used with [Security#handleCertificateError](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-handleCertificateError) operation call.
*
* Handles a certificate error that fired a certificateError event.
* @link [Security#handleCertificateError](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-handleCertificateError) method documentation.
* @see [SecurityDomain.handleCertificateError]
*/
@kotlinx.serialization.Serializable
data class HandleCertificateErrorRequest(
/**
* The ID of the event.
*/
val eventId: Int,
/**
* The action to take on the certificate error.
*/
val action: CertificateErrorAction
)
/**
* Represents request frame that can be used with [Security#setOverrideCertificateErrors](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-setOverrideCertificateErrors) operation call.
*
* Enable/disable overriding certificate errors. If enabled, all certificate error events need to
be handled by the DevTools client and should be answered with `handleCertificateError` commands.
* @link [Security#setOverrideCertificateErrors](https://chromedevtools.github.io/devtools-protocol/tot/Security#method-setOverrideCertificateErrors) method documentation.
* @see [SecurityDomain.setOverrideCertificateErrors]
*/
@kotlinx.serialization.Serializable
data class SetOverrideCertificateErrorsRequest(
/**
* If true, certificate errors will be overridden.
*/
val override: Boolean
)
/**
* There is a certificate error. If overriding certificate errors is enabled, then it should be
handled with the `handleCertificateError` command. Note: this event does not fire if the
certificate error has been allowed internally. Only one client per target should override
certificate errors at the same time.
*
* @link [Security#certificateError](https://chromedevtools.github.io/devtools-protocol/tot/Security#event-certificateError) event documentation.
*/
@kotlinx.serialization.Serializable
data class CertificateErrorEvent(
/**
* The ID of the event.
*/
val eventId: Int,
/**
* The type of the error.
*/
val errorType: String,
/**
* The url that was requested.
*/
val requestURL: String
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Security"
override fun eventName() = "certificateError"
}
/**
* The security state of the page changed.
*
* @link [Security#visibleSecurityStateChanged](https://chromedevtools.github.io/devtools-protocol/tot/Security#event-visibleSecurityStateChanged) event documentation.
*/
@kotlinx.serialization.Serializable
data class VisibleSecurityStateChangedEvent(
/**
* Security state information about the page.
*/
val visibleSecurityState: VisibleSecurityState
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Security"
override fun eventName() = "visibleSecurityStateChanged"
}
/**
* The security state of the page changed.
*
* @link [Security#securityStateChanged](https://chromedevtools.github.io/devtools-protocol/tot/Security#event-securityStateChanged) event documentation.
*/
@kotlinx.serialization.Serializable
data class SecurityStateChangedEvent(
/**
* Security state.
*/
val securityState: SecurityState,
/**
* True if the page was loaded over cryptographic transport such as HTTPS.
*/
val schemeIsCryptographic: Boolean,
/**
* List of explanations for the security state. If the overall security state is `insecure` or
`warning`, at least one corresponding explanation should be included.
*/
val explanations: List<SecurityStateExplanation>,
/**
* Information about insecure content on the page.
*/
val insecureContentStatus: InsecureContentStatus,
/**
* Overrides user-visible description of the state.
*/
val summary: String? = null
) : pl.wendigo.chrome.protocol.Event {
override fun domain() = "Security"
override fun eventName() = "securityStateChanged"
}
| 3 |
Kotlin
|
11
| 76 |
29b51e37ed509938e986d1ada8cc2b0c8461cb73
| 9,554 |
chrome-reactive-kotlin
|
Apache License 2.0
|
java-time/src/test/kotlin/com/github/debop/javatimes/ranges/DateRangeTest.kt
|
debop
| 62,798,850 | false |
{"Kotlin": 256811}
|
/*
* Copyright (c) 2016. <NAME> <<EMAIL>>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.debop.javatimes.ranges
import com.github.debop.javatimes.AbstractJavaTimesTest
import com.github.debop.javatimes.toDate
import org.amshove.kluent.shouldBeTrue
import org.amshove.kluent.shouldEqual
import org.junit.jupiter.api.Test
import java.time.Duration
import java.util.Date
class DateRangeTest : AbstractJavaTimesTest() {
@Test
fun `simple creation`() {
val start = Date()
val endInclusive = (start.toInstant() + Duration.ofDays(5)).toDate()
val range = DateRange(start, endInclusive)
range.start shouldEqual start
range.endInclusive shouldEqual endInclusive
range.first shouldEqual start
range.last shouldEqual endInclusive
range.toString() shouldEqual "$start..$endInclusive"
}
@Test
fun `empty range`() {
val start = Date()
val endInclusive = (start.toInstant() - Duration.ofDays(1)).toDate()
val range = DateRange.fromClosedRange(start, endInclusive)
range.isEmpty().shouldBeTrue()
range shouldEqual DateRange.EMPTY
val range2 = start..endInclusive
range2.isEmpty().shouldBeTrue()
range2 shouldEqual DateRange.EMPTY
range2 shouldEqual range
}
}
| 3 |
Kotlin
|
7
| 83 |
cbb0efedaa53bdf9d77b230d8477cb0ae0d7abd7
| 1,851 |
koda-time
|
Apache License 2.0
|
src/main/java/io/renren/modules/app/service/UserService.kt
|
AranAndroid009
| 314,123,865 | false |
{"JavaScript": 5420874, "Kotlin": 220187, "TSQL": 18775, "HTML": 12988, "Java": 3713, "Dockerfile": 134, "Assembly": 12}
|
/**
* Copyright (c) 2016-2019 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package io.renren.modules.app.service
import com.baomidou.mybatisplus.extension.service.IService
import io.renren.modules.app.entity.UserEntity
import io.renren.modules.app.form.LoginForm
/**
* 用户
*
* @author Mark [email protected]
*/
interface UserService : IService<UserEntity?> {
fun queryByMobile(mobile: String?): UserEntity?
/**
* 用户登录
* @param form 登录表单
* @return 返回用户ID
*/
fun login(form: LoginForm?): Long
}
| 0 |
JavaScript
|
0
| 1 |
7424176076915ffc54c6ad7dff1a5d41f860dbd3
| 574 |
reren_fast_kotlin
|
Apache License 2.0
|
src/main/kotlin/pcimcioch/gitlabci/dsl/job/CacheDsl.kt
|
pcimcioch
| 247,550,225 | false | null |
package pcimcioch.gitlabci.dsl.job
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import pcimcioch.gitlabci.dsl.DslBase
import pcimcioch.gitlabci.dsl.StringRepresentation
import pcimcioch.gitlabci.dsl.serializer.StringRepresentationSerializer
import pcimcioch.gitlabci.dsl.serializer.TwoTypeSerializer
@Serializable
class CacheDsl : DslBase() {
var paths: MutableSet<String>? = null
var untracked: Boolean? = null
var policy: CachePolicy? = null
@SerialName("when")
var whenCache: WhenCacheType? = null
@Transient
private var keyString: String? = null
@Transient
private var keyDsl: CacheKeyDsl? = null
@Serializable(with = KeySerializer::class)
var key: Any? = null
get() = keyString ?: keyDsl
private set
fun paths(vararg elements: String) = paths(elements.toList())
fun paths(elements: Iterable<String>) = ensurePaths().addAll(elements)
fun key(key: String) {
keyDsl = null
keyString = key
}
fun key(block: CacheKeyDsl.() -> Unit) {
keyString = null
ensureKeyDsl().apply(block)
}
fun key(key: CacheKeyDsl) {
keyString = null
keyDsl = key
}
override fun validate(errors: MutableList<String>) {
addErrors(errors, "[cache]", keyDsl)
}
private fun ensureKeyDsl() = keyDsl ?: CacheKeyDsl().also { keyDsl = it }
private fun ensurePaths() = paths ?: mutableSetOf<String>().also { paths = it }
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as CacheDsl
if (paths != other.paths) return false
if (untracked != other.untracked) return false
if (policy != other.policy) return false
if (whenCache != other.whenCache) return false
if (key != other.key) return false
return true
}
override fun hashCode(): Int {
var result = paths?.hashCode() ?: 0
result = 31 * result + (untracked?.hashCode() ?: 0)
result = 31 * result + (policy?.hashCode() ?: 0)
result = 31 * result + (whenCache?.hashCode() ?: 0)
result = 31 * result + (key?.hashCode() ?: 0)
return result
}
object KeySerializer : TwoTypeSerializer<Any>(
PrimitiveSerialDescriptor("Key", PrimitiveKind.STRING),
String::class, String.serializer(),
CacheKeyDsl::class, CacheKeyDsl.serializer()
)
companion object {
init {
addSerializer(CacheDsl::class, serializer())
}
}
}
fun createCache(block: CacheDsl.() -> Unit = {}) = CacheDsl().apply(block)
fun createCache(vararg elements: String, block: CacheDsl.() -> Unit = {}) = createCache(elements.toList(), block)
fun createCache(elements: Iterable<String>, block: CacheDsl.() -> Unit = {}) =
CacheDsl().apply { paths(elements) }.apply(block)
@Serializable
class CacheKeyDsl : DslBase() {
var prefix: String? = null
var files: MutableSet<String>? = null
fun files(vararg elements: String) = files(elements.toList())
fun files(elements: Iterable<String>) = ensureFiles().addAll(elements)
override fun validate(errors: MutableList<String>) {
addError(errors, files?.isNotEmpty() != true, "[key] files list can't be empty")
addError(
errors,
"." == prefix || "%2E" == prefix || "%2e" == prefix,
"[key] prefix value '$prefix' can't be '.' nor '%2E'"
)
addError(
errors,
prefix?.contains("/") == true || prefix?.contains("%2F") == true || prefix?.contains("%2f") == true,
"[key] prefix value '$prefix' can't contain '/' nor '%2F'"
)
}
private fun ensureFiles() = files ?: mutableSetOf<String>().also { files = it }
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as CacheKeyDsl
if (prefix != other.prefix) return false
if (files != other.files) return false
return true
}
override fun hashCode(): Int {
var result = prefix?.hashCode() ?: 0
result = 31 * result + (files?.hashCode() ?: 0)
return result
}
companion object {
init {
addSerializer(CacheKeyDsl::class, serializer())
}
}
}
fun createCacheKey(block: CacheKeyDsl.() -> Unit = {}) = CacheKeyDsl().apply(block)
@Serializable(with = CachePolicy.CachePolicySerializer::class)
enum class CachePolicy(
override val stringRepresentation: String
) : StringRepresentation {
PULL("pull"),
PULL_PUSH("pull-push"),
PUSH("push");
object CachePolicySerializer : StringRepresentationSerializer<CachePolicy>("CachePolicy")
}
@Serializable(with = WhenCacheType.WhenCacheTypeSerializer::class)
enum class WhenCacheType(
override val stringRepresentation: String
) : StringRepresentation {
ON_SUCCESS("on_success"),
ON_FAILURE("on_failure"),
ALWAYS("always");
object WhenCacheTypeSerializer : StringRepresentationSerializer<WhenCacheType>("WhenCacheType")
}
| 0 |
Kotlin
|
5
| 20 |
bf30d3edb0566613a27a787b7f6490f9507412d8
| 5,404 |
gitlab-ci-kotlin-dsl
|
Apache License 2.0
|
browser-kotlin/src/jsMain/kotlin/web/workers/WorkerGlobalScope.events.kt
|
karakum-team
| 393,199,102 | false |
{"Kotlin": 6214094}
|
// Automatically generated - do not modify!
package web.workers
import web.csp.SecurityPolicyViolationEvent
import web.events.Event
import web.events.EventInstance
import web.promise.PromiseRejectionEvent
inline val <C : WorkerGlobalScope> C.errorEvent: EventInstance<Event, C, C>
get() = EventInstance(this, Event.error())
inline val <C : WorkerGlobalScope> C.languageChangeEvent: EventInstance<Event, C, C>
get() = EventInstance(this, Event.languageChange())
inline val <C : WorkerGlobalScope> C.offlineEvent: EventInstance<Event, C, C>
get() = EventInstance(this, Event.offline())
inline val <C : WorkerGlobalScope> C.onlineEvent: EventInstance<Event, C, C>
get() = EventInstance(this, Event.online())
inline val <C : WorkerGlobalScope> C.rejectionHandledEvent: EventInstance<PromiseRejectionEvent, C, C>
get() = EventInstance(this, PromiseRejectionEvent.rejectionHandled())
inline val <C : WorkerGlobalScope> C.securityPolicyViolationEvent: EventInstance<SecurityPolicyViolationEvent, C, C>
get() = EventInstance(this, SecurityPolicyViolationEvent.securityPolicyViolation())
inline val <C : WorkerGlobalScope> C.unhandledRejectionEvent: EventInstance<PromiseRejectionEvent, C, C>
get() = EventInstance(this, PromiseRejectionEvent.unhandledRejection())
| 0 |
Kotlin
|
7
| 35 |
ac6d96e24eb8d07539990dc2d88cbe85aa811312
| 1,293 |
types-kotlin
|
Apache License 2.0
|
src/main/kotlin/com/danaepp/apidiscovery/APIDiscoveryScanCheck.kt
|
DanaEpp
| 819,138,713 | false |
{"Kotlin": 21503}
|
package com.danaepp.apidiscovery
import burp.api.montoya.MontoyaApi
import burp.api.montoya.http.message.HttpRequestResponse
import burp.api.montoya.scanner.AuditResult
import burp.api.montoya.scanner.AuditResult.auditResult
import burp.api.montoya.scanner.ConsolidationAction
import burp.api.montoya.scanner.ScanCheck
import burp.api.montoya.scanner.audit.insertionpoint.AuditInsertionPoint
import burp.api.montoya.scanner.audit.issues.AuditIssue
import burp.api.montoya.scanner.audit.issues.AuditIssueConfidence
import burp.api.montoya.scanner.audit.issues.AuditIssueSeverity
import java.net.URI
import java.time.LocalDateTime
import kotlinx.coroutines.runBlocking
class APIDiscoveryScanCheck( private val api: MontoyaApi ): ScanCheck {
private val checkedHosts = mutableListOf<CheckedHost>()
private val checkedPaths = mutableListOf<CheckedPath>()
override fun activeAudit(p0: HttpRequestResponse?, p1: AuditInsertionPoint?): AuditResult {
return auditResult(emptyList())
}
override fun passiveAudit(baseRequestResponse: HttpRequestResponse?): AuditResult {
val auditIssues = mutableListOf<AuditIssue>()
conductMetadataDiscovery(baseRequestResponse)?.let { auditIssues.add(it) }
conductPathDiscovery(baseRequestResponse)?.let { auditIssues.add(it) }
return auditResult( auditIssues )
}
override fun consolidateIssues(newIssue: AuditIssue?, existingIssue: AuditIssue?): ConsolidationAction {
return if(existingIssue!!.baseUrl() == newIssue!!.baseUrl()) ConsolidationAction.KEEP_EXISTING
else ConsolidationAction.KEEP_BOTH
}
private fun getHostName(url: String): String {
val uri = URI(url)
return uri.host
}
private fun getTargetPath(url: String): String {
val uri = URI(url)
return (uri.scheme + "://" + uri.host + uri.path)
}
private fun isWithinLastHour(dateTime: LocalDateTime): Boolean {
val now = LocalDateTime.now()
val oneHourAgo = now.minusHours(1)
return dateTime.isAfter(oneHourAgo) && dateTime.isBefore(now)
}
private fun conductMetadataDiscovery(baseRequestResponse: HttpRequestResponse?): AuditIssue? {
val detail = StringBuilder("")
// This should never happen, but fall back to localhost if the hostname/IP is missing
val hostname = getHostName(baseRequestResponse?.request()?.url() ?: "localhost")
val index = checkedHosts.indexOfFirst { it.hostname == hostname }
var targetHost = if (index != -1) checkedHosts[index] else null
// Did we already scan this host in the last hour?
if( targetHost != null && isWithinLastHour(targetHost.lastChecked) ) {
return null
}
// Conduct actual API discovery. Currently only look for API.json.
// Future can do full OAS/Swagger detection as well in subdirs
targetHost = APIDiscovery(api).scanHost(hostname)
if (targetHost.apiMetadataDetected) {
detail.append(
"API metadata was detected at <a href=\"${targetHost.apiMetadataURL}\">${targetHost.apiMetadataURL}</a>"
).append("<br><br>")
targetHost.apiMetadata?.let { metadata ->
detail.append("Name: ${metadata.name}").append("<br>")
detail.append("Description: ${metadata.description}").append("<br>")
detail.append("Last Modified: ${metadata.modified}").append("<br><br>")
detail.append("<b>Described APIs</b><br><br>")
val urlMap = mapOf(
"openapi" to "OpenAPI URL",
"swagger" to "Swagger URL",
"postmancollection" to "Postman Collection URL",
"asyncapi" to "AsyncAPI URL",
"wsdl" to "WSDL URL",
"wadl" to "WADL URL",
"raml" to "RAML URL"
)
metadata.apis.forEach { api ->
detail.apply {
append("API Name: ${api.name}").append("<br>")
append("API Description: ${api.description}").append("<br>")
append("API Base URL: <a href=\"${api.baseURL}\">${api.baseURL}</a>").append("<br>")
append("API Human URL: <a href=\"${api.humanURL}\">${api.humanURL}</a>").append("<br>")
}
api.properties.forEach { prop ->
val propType = prop.type.lowercase()
urlMap[propType]?.let { description ->
val urlText = "$description: <a href=\"${prop.url}\">${prop.url}</a>"
detail.append(urlText).append("<br>")
}
}
detail.append("<br>")
}
}
api.logging().logToOutput("Detected API configuration metadata at ${targetHost.apiMetadataURL}")
}
if (targetHost.apiCatalogDetected) {
detail.append(
"API catalog was detected at <a href=\"${targetHost.apiCatalogURL}\">${targetHost.apiCatalogURL}</a>"
).append("<br><br>")
targetHost.apiCatalogData?.linkset?.forEach { link ->
detail.append("Anchor: ${link.anchor}").append("<br>")
link.`service-desc`?.forEach { service ->
detail.append("Service Description: ${service.href}, Type: ${service.type}").append("<br>")
}
link.`service-doc`?.forEach { service ->
detail.append("Service Documentation: ${service.href}, Type: ${service.type}").append("<br>")
}
link.`service-meta`?.forEach { service ->
detail.append("Service Metadata: ${service.href}, Type: ${service.type}").append("<br>")
}
detail.append("<br>")
}
api.logging().logToOutput("Detected API catalog metadata at ${targetHost.apiCatalogURL}")
}
checkedHosts.apply {
if (index != -1) set(index, targetHost) else add(targetHost)
}
if(detail.toString() == "" ){
return null
}
return AuditIssue.auditIssue(
"API metadata discovered",
detail.toString(),
null,
targetHost.apiMetadataURL,
AuditIssueSeverity.INFORMATION,
AuditIssueConfidence.CERTAIN,
null,
null,
AuditIssueSeverity.LOW,
baseRequestResponse
)
}
private fun conductPathDiscovery(baseRequestResponse: HttpRequestResponse?): AuditIssue? {
val detail = StringBuilder("")
val target = getTargetPath(baseRequestResponse?.request()?.url() ?: "http://localhost")
val index = checkedPaths.indexOfFirst { it.target == target }
var targetPath = if (index != -1) checkedPaths[index] else null
// Did we already scan this path in the last hour?
if( targetPath != null && isWithinLastHour(targetPath.lastChecked) ) {
return null
}
runBlocking {
targetPath = APIDocPathEnumeration(api).enumerateAPIDocPaths(target)
}
if(targetPath?.apiDocPathDetected == true) {
detail.append(
"Potential API doc path(s) have been discovered at <a href=\"$target\">$target</a>"
).append("<br><br>")
targetPath!!.detectedPaths?.takeIf { it.isNotEmpty() }?.let { paths ->
detail.append("Potential doc paths:").append("<br>")
paths.forEach { path ->
detail.append(path).append("<br>")
}
}
detail.append("<br>")
api.logging().logToOutput("Detected potential API doc paths at $target")
}
checkedPaths.apply {
if (index != -1) targetPath?.let { set(index, it) } else targetPath?.let { add(it) }
}
if(detail.toString() == "" ){
return null
}
return AuditIssue.auditIssue(
"API doc path discovered",
detail.toString(),
null,
target,
AuditIssueSeverity.INFORMATION,
AuditIssueConfidence.CERTAIN,
null,
null,
AuditIssueSeverity.LOW,
baseRequestResponse
)
}
}
| 1 |
Kotlin
|
1
| 9 |
cced0f9f3ee4af580b5cdb6060fe49c023317a8f
| 8,507 |
APIDiscovery
|
MIT License
|
app/src/main/kotlin/com/ahmedadelsaid/githubrepos/kotlin/GithubReposGlideModule.kt
|
ahmedadeltito
| 142,363,202 | false | null |
package com.ahmedadelsaid.githubrepos.kotlin
import com.bumptech.glide.annotation.GlideModule
import com.bumptech.glide.module.AppGlideModule
/**
* Created by <NAME> on 27/07/2018.
*
* GithubReposGlideModule is for Glide recompilation.
*/
@GlideModule
class GithubReposGlideModule : AppGlideModule()
| 4 |
Kotlin
|
10
| 35 |
fde44ba2af985d4706573818a933bfbe9a8e7c50
| 306 |
github-repos
|
MIT License
|
source/listener/src/main/kotlin/com/gabrielcora/listener/eventlisteners/PaymentChangedEventListener.kt
|
gabrielcora20
| 781,071,020 | false |
{"Kotlin": 118392, "Dockerfile": 757, "JavaScript": 147}
|
package com.gabrielcora.listener.eventlisteners
import com.gabrielcora.listener.dto.PaymentEventResponseDto
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import org.springframework.amqp.rabbit.annotation.RabbitListener
@Component
class PaymentChangedEventListener {
private val logger: Logger = LoggerFactory.getLogger(PaymentChangedEventListener::class.java)
@RabbitListener(queues = ["processpaymentrecurrencechangeddo"])
fun handlePaymentRecurrenceChanged(message: PaymentEventResponseDto) {
logger.info("executing handlePaymentRecurrenceChanged")
}
@RabbitListener(queues = ["processpaymentdeleteddo"])
fun handlePaymentDeleted(message: PaymentEventResponseDto) {
logger.info("executing handlePaymentDeleted")
}
@RabbitListener(queues = ["processpaymentupdateddo"])
fun handlePaymentUpdated(message: PaymentEventResponseDto) {
logger.info("executing handlePaymentUpdated")
}
@RabbitListener(queues = ["processpaymentregistereddo"])
fun handlePaymentRegistered(message: PaymentEventResponseDto) {
logger.info("executing handlePaymentRegistered")
}
}
| 0 |
Kotlin
|
0
| 0 |
d27b1b42bf88e66c2cfdf5cee01f704774b4953b
| 1,198 |
pix-demo-project
|
MIT License
|
app/src/main/java/com/yinlei/sunnyweather/logic/model/PlaceResponse.kt
|
yinleiCoder
| 257,759,475 | false | null |
package com.yinlei.sunnyweather.logic.model
import com.google.gson.annotations.SerializedName
// 搜索城市数据的Model
data class PlaceResponse(val status: String, val places: List<Place>)
// JSON中一些字段命名可能和Kotlin规范不一致,所以使用@SerializedName来让JSON字段和Kotlin字段之间建立映射关系
data class Place(val name: String, val location: Location, @SerializedName("formatted_address") val address: String)
data class Location(val lng: String, val lat: String)
| 0 |
Kotlin
|
0
| 3 |
e560b250f72d52fa5d0a7af604d1fd93ea5277f6
| 428 |
SunnyWeather
|
Apache License 2.0
|
integration-library/src/main/java/ru/modulkassa/pos/integration/entity/payment/RefundResult.kt
|
modulkassa
| 175,192,825 | false | null |
package ru.modulkassa.pos.integration.entity.payment
import android.os.Bundle
import ru.modulkassa.pos.integration.entity.Bundable
/**
* Данные результата успешного возврата
*/
data class RefundResult(
/**
* Информация от платежной системы, которую необходимо распечатать на чеке
* Если слипов два, для них используется строка-разделитель Slip.DELIMITER_VALUE
*/
val slip: List<String>,
/**
* Данные транзакции
*/
val transactionDetails: TransactionDetails? = null
) : Bundable {
companion object {
private const val KEY_SLIP = "slip"
fun fromBundle(bundle: Bundle): RefundResult {
return RefundResult(
slip = bundle.getStringArrayList(KEY_SLIP) ?: arrayListOf(),
transactionDetails = TransactionDetails.fromBundle(bundle)
)
}
}
override fun toBundle(): Bundle {
return Bundle().apply {
putStringArrayList(KEY_SLIP, ArrayList(slip))
putAll(transactionDetails?.toBundle() ?: Bundle.EMPTY)
putString(RequestTypeSerialization.KEY, RequestType.REFUND.name)
}
}
}
| 0 |
Kotlin
|
1
| 6 |
c7b1618093b8d5a9c840c629be3831f37830a6d4
| 1,155 |
android-integration-sdk
|
MIT License
|
src/trataEntrada.kt
|
AddsonVinicyus
| 711,909,120 | false |
{"Kotlin": 9986}
|
package src
//lambda [parâmetro] : tipo . [corpo]
fun verificaEntrada(expressao: String): Int{
//0 para expressão válida
//1 para expressão não válida por erro na entrada
//-1 para expressão não válida por não ser bem-tipado
if(expressao.contains("lambda")) {
return when {
expressao.matches(
Regex("^lambda ([a-zA-Z0-9]+) : ([a-zA-Z0-9]+) . ([a-zA-Z0-9]+) ([a-zA-Z0-9]+) : " +
"([a-zA-Z0-9]+) . ([a-zA-Z0-9]+) end end$"
)
) -> 0
expressao.matches(
Regex(
"^(. lambda ([a-zA-Z0-9]+) : ([a-zA-Z0-9]+) . ([a-zA-Z0-9]+) ([a-zA-Z0-9]+) : " +
"([a-zA-Z0-9]+) . ([a-zA-Z0-9]+) end end .)$"
)
) -> 0
expressao.matches(
Regex(
"^lambda ([a-zA-Z0-9]+) : ([a-zA-Z0-9]+) . ([a-zA-Z0-9]+) ([a-zA-Z0-9]+) " +
"([a-zA-Z0-9]+) ([a-zA-Z0-9]+) ([a-zA-Z0-9]+) ([a-zA-Z0-9]+) endif end$"
)
) -> 0
expressao.matches(
Regex(
"^(. lambda ([a-zA-Z0-9]+) : ([a-zA-Z0-9]+) . ([a-zA-Z0-9]+) ([a-zA-Z0-9]+) " +
"([a-zA-Z0-9]+) ([a-zA-Z0-9]+) ([a-zA-Z0-9]+) ([a-zA-Z0-9]+) endif end .)$"
)
) -> 0
expressao.matches(Regex("^lambda ([a-zA-Z0-9]+) : (Bool|Nat) . ([a-zA-Z0-9]+) end$")) -> 0
expressao.matches(Regex("^(. lambda ([a-zA-Z0-9]+) : (Bool|Nat) . ([a-zA-Z0-9]+) end .)$")) -> 0
expressao.matches(Regex("^lambda ([a-zA-Z0-9]+) : (Bool|Nat) . ([a-zA-Z0-9]+) ([0-9]+) end$")) -> 0
expressao.matches(Regex("^(. lambda ([a-zA-Z0-9]+) : (Bool|Nat) . ([a-zA-Z0-9]+) ([0-9]+) end .)$")) -> 0
else -> 1
}
}
else if(expressao.startsWith("if") || expressao.startsWith("( if")){
return when{
expressao.matches(Regex("^if ([a-zA-Z0-9]+) then ([a-zA-Z0-9]+) else ([a-zA-Z0-9]+) endif}"))
-> 0
expressao.matches(Regex("^(. if ([a-zA-Z0-9]+) then ([a-zA-Z0-9]+) else ([a-zA-Z0-9]+) endif .)}"))
-> 0
else -> 1
}
}
else {
return when{
expressao.matches(Regex("^(suc|pred|ehzero) [0-9]+")) -> 0
expressao.matches(Regex("^(. (suc|pred|ehzero) [0-9]+ .)")) -> 0
expressao.matches(Regex("^(suc|pred|ehzero) ([a-z]|[A-Z])+")) -> -1
expressao.matches(Regex("^(. (suc|pred|ehzero) ([a-z]|[A-Z])+ .)")) -> -1
else -> 1
}
}
}
fun analisaEntrada(expressao: String){
when(verificaEntrada(expressao)){
1 -> println("!")
-1 -> println("-")
else -> println(analisarExpressao(expressao))
}
}
fun retiraParenteses(expressao: String): String{
if(expressao.startsWith("(")){
return (expressao.removePrefix("( ")).removeSuffix(" )")
} else
return expressao
}
fun analisarExpressao(expressao: String): Tipo{
val expressaoValidada = retiraParenteses(expressao)
if(expressaoValidada.matches(Regex("^(suc|pred|ehzero) ([0-9]+)")) ||
expressaoValidada.matches(Regex("^(. (suc|pred|ehzero) ([0-9]+) .)"))){
val termoSimples = expressaoValidada.split(" ")
return analisarExpressaoSimples(termoSimples[0])
}
if(expressaoValidada.split(" ").size == 1){
return analisarExpressaoSimples(expressaoValidada)
}
val(tipoParam, expressaoCorpo) = analisarLambda(expressaoValidada)
return tipoSetaTipo(tipoParam, expressaoCorpo)
}
| 0 |
Kotlin
|
0
| 0 |
7e26dce4855c90675d94483aa075e33a9f07d21a
| 3,662 |
implementacaoTipagem
|
MIT License
|
app/src/main/java/cn/houkyo/miuidock/ui/CustomSeekBar.kt
|
ouhoukyo
| 358,284,910 | false | null |
package cn.houkyo.miuidock.ui
import android.content.Context
import android.graphics.Canvas
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.LinearLayout
import android.widget.SeekBar
import android.widget.TextView
import cn.houkyo.miuidock.R
import java.lang.Exception
class CustomSeekBar : LinearLayout {
private var mainSeekBar: SeekBar? = null
private var minTextView: TextView? = null
private var valueTextView: TextView? = null
private var maxTextView: TextView? = null
private lateinit var onValueChangeListener: (value: Int) -> Unit
constructor(context: Context) : this(context, null)
constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
) {
init(context)
}
fun init(context: Context) {
val view = LayoutInflater.from(context).inflate(R.layout.custom_seek_bar, this)
mainSeekBar = view.findViewById(R.id.mainSeekBar)
minTextView = view.findViewById(R.id.minTextView)
valueTextView = view.findViewById(R.id.valueTextView)
maxTextView = view.findViewById(R.id.maxTextView)
onValueChangeListener = { value: Int ->
value
}
}
fun setValue(i: Int) {
mainSeekBar?.progress = i
valueTextView?.text = i.toString()
mainSeekBar?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
override fun onProgressChanged(p0: SeekBar?, p1: Int, p2: Boolean) {
valueTextView?.text = p1.toString()
}
override fun onStartTrackingTouch(p0: SeekBar?) {
}
override fun onStopTrackingTouch(p0: SeekBar?) {
if (p0 != null) {
onValueChangeListener.invoke(p0.progress)
}
}
})
}
fun setMinValue(i: Int) {
mainSeekBar?.min = i
minTextView?.text = i.toString()
}
fun setMaxValue(i: Int) {
mainSeekBar?.max = i
maxTextView?.text = i.toString()
}
fun getValue(): Int {
if (mainSeekBar != null) {
return mainSeekBar!!.progress
}
return 0
}
fun setOnValueChangeListener(callback: (value: Int) -> Unit) {
this.onValueChangeListener = callback
}
}
| 2 |
Kotlin
|
6
| 65 |
0939031e87bc2a0e8e29a250bc7cb7da046101b4
| 2,468 |
MIUIDock
|
MIT License
|
app/src/main/java/com/johnv/johnvinstagramclone/fragments/ProfileFragment.kt
|
jvaradi-qc
| 472,143,635 | false | null |
package com.johnv.johnvinstagramclone.fragments
import android.util.Log
import com.johnv.johnvinstagramclone.MainActivity
import com.johnv.johnvinstagramclone.Post
import com.parse.FindCallback
import com.parse.ParseException
import com.parse.ParseQuery
import com.parse.ParseUser
class ProfileFragment : FeedFragment() {
override fun queryPosts() {
// Specify which class to query
val query: ParseQuery<Post> = ParseQuery.getQuery(Post::class.java)
// Find all Post Objects
query.include(Post.KEY_USER)
// Only return posts from currently signed in user
query.whereEqualTo(Post.KEY_USER, ParseUser.getCurrentUser())
query.addDescendingOrder("createdAt")
query.findInBackground(object : FindCallback<Post> {
override fun done(posts: MutableList<Post>?, e: ParseException?) {
if (e != null) {
//something went wrong
Log.e(MainActivity.TAG,"Error fetching posts")
} else {
if(posts != null){
for (post in posts){
Log.i(MainActivity.TAG, "Post: " + post.getDescription() + ", username: " + post.getUser()?.username)
}
adapter.clear()
allPosts.addAll(posts)
adapter.notifyDataSetChanged()
swipeContainer.setRefreshing(false)
}
}
}
})
}
}
| 3 |
Kotlin
|
0
| 0 |
27ac16d3d07492ddc91f75e99cecefb3748d4873
| 1,567 |
JohnVInstagramClone
|
Apache License 2.0
|
src/main/kotlin/com/fiap/stock/application/driver/web/ProductAPI.kt
|
FIAP-3SOAT-G15
| 794,351,225 | false |
{"Kotlin": 122174, "HCL": 4424, "Gherkin": 372, "Dockerfile": 282}
|
package com.fiap.stock.application.driver.web
import com.fiap.stock.application.driver.web.request.ProductComposeRequest
import com.fiap.stock.application.driver.web.request.ProductRequest
import com.fiap.stock.application.driver.web.request.ProductStockBatchChangeRequest
import com.fiap.stock.application.driver.web.response.ProductResponse
import io.swagger.v3.oas.annotations.Operation
import io.swagger.v3.oas.annotations.Parameter
import io.swagger.v3.oas.annotations.enums.ParameterIn
import io.swagger.v3.oas.annotations.media.Schema
import io.swagger.v3.oas.annotations.responses.ApiResponse
import io.swagger.v3.oas.annotations.responses.ApiResponses
import io.swagger.v3.oas.annotations.tags.Tag
import jakarta.websocket.server.PathParam
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
@Tag(name = "produto", description = "Produtos")
@RequestMapping("/admin/products")
@SuppressWarnings
interface ProductAPI {
@Operation(
summary = "Retorna todos os produtos",
parameters = [
Parameter(
name = "x-admin-token",
required = true,
`in` = ParameterIn.HEADER,
schema = Schema(type = "string", defaultValue = "token"),
),
],
)
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Operação bem-sucedida"),
],
)
@GetMapping
fun findAll(): ResponseEntity<List<ProductResponse>>
@Operation(
summary = "Retorna todos os produtos identificados por número",
parameters = [
Parameter(
name = "x-admin-token",
required = true,
`in` = ParameterIn.HEADER,
schema = Schema(type = "string", defaultValue = "token"),
),
],
)
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Operação bem-sucedida"),
],
)
@GetMapping("/batch")
fun findAllByProductNumber(
@Parameter(description = "IDs de produtos") @RequestParam("numbers") productNumbers: List<Long>,
): ResponseEntity<List<ProductResponse>>
@Operation(
summary = "Incrementa estoque disponível para os produtos identificados",
parameters = [
Parameter(
name = "x-admin-token",
required = true,
`in` = ParameterIn.HEADER,
schema = Schema(type = "string", defaultValue = "token"),
),
],
)
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Operação bem-sucedida"),
],
)
@PostMapping("/batch/increment")
fun incrementStockOfProducts(
@Parameter(description = "Relações de produto e quantidade a incrementar")
@RequestBody productStockBatchChangeRequest: ProductStockBatchChangeRequest,
): ResponseEntity<String>
@Operation(
summary = "Decrementa estoque disponível para os produtos identificados",
parameters = [
Parameter(
name = "x-admin-token",
required = true,
`in` = ParameterIn.HEADER,
schema = Schema(type = "string", defaultValue = "token"),
),
],
)
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Operação bem-sucedida"),
],
)
@PostMapping("/batch/decrement")
fun decrementStockOfProducts(
@Parameter(description = "Relações de produto e quantidade a decrementar")
@RequestBody productStockBatchChangeRequest: ProductStockBatchChangeRequest,
): ResponseEntity<String>
@Operation(
summary = "Retorna produtos por categoria",
parameters = [
Parameter(
name = "x-admin-token",
required = true,
`in` = ParameterIn.HEADER,
schema = Schema(type = "string", defaultValue = "token"),
),
],
)
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Operação bem-sucedida"),
ApiResponse(responseCode = "400", description = "Categoria inválida"),
],
)
@GetMapping("/category/{category}")
fun findByCategory(
@Parameter(description = "Categoria") @PathVariable category: String,
): ResponseEntity<List<ProductResponse>>
@Operation(
description = "Api de produtos, Retorna produto pelo número",
summary = "Retorna produto pelo número",
parameters = [
Parameter(
name = "x-admin-token",
required = true,
`in` = ParameterIn.HEADER,
schema = Schema(type = "string", defaultValue = "token"),
),
],
)
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Operação bem-sucedida"),
ApiResponse(responseCode = "404", description = "Produto não encontrado"),
],
)
@GetMapping("/{productNumber}")
fun getByProductNumber(
@Parameter(description = "Número do produto") @PathVariable("productNumber") productNumber: Long,
): ResponseEntity<ProductResponse>
@Operation(
summary = "Pesquisa produto por nome",
parameters = [
Parameter(
name = "x-admin-token",
required = true,
`in` = ParameterIn.HEADER,
schema = Schema(type = "string", defaultValue = "token"),
),
],
)
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Operação bem-sucedida"),
],
)
@GetMapping("/search")
fun searchByName(
@Parameter(description = "Nome do produto") @PathParam("name") name: String,
): ResponseEntity<List<ProductResponse>>
@Operation(
summary = "Cadastra um novo produto",
parameters = [
Parameter(
name = "x-admin-token",
required = true,
`in` = ParameterIn.HEADER,
schema = Schema(type = "string", defaultValue = "token"),
),
],
)
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Operação bem-sucedida"),
ApiResponse(responseCode = "422", description = "Produto inválido"),
ApiResponse(responseCode = "500", description = "Erro não esperado"),
],
)
@PostMapping
fun create(
@Parameter(description = "Cadastro do produto") @RequestBody productRequest: ProductRequest,
): ResponseEntity<ProductResponse>
@Operation(
summary = "Atualiza produto",
parameters = [
Parameter(
name = "x-admin-token",
required = true,
`in` = ParameterIn.HEADER,
schema = Schema(type = "string", defaultValue = "token"),
),
],
)
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Operação bem-sucedida"),
ApiResponse(responseCode = "404", description = "Produto não encontrado"),
ApiResponse(responseCode = "422", description = "Produto inválido"),
],
)
@PutMapping("/{productNumber}")
fun update(
@Parameter(description = "Número do produto") @PathVariable productNumber: Long,
@Parameter(description = "Cadastro do produto") @RequestBody productRequest: ProductRequest,
): ResponseEntity<ProductResponse>
@Operation(
summary = "Remove produto",
parameters = [
Parameter(
name = "x-admin-token",
required = true,
`in` = ParameterIn.HEADER,
schema = Schema(type = "string", defaultValue = "token"),
),
],
)
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Operação bem-sucedida"),
ApiResponse(responseCode = "404", description = "Produto não encontrado"),
],
)
@DeleteMapping("/{productNumber}")
fun delete(
@Parameter(description = "Número do produto") @PathVariable("productNumber") productNumber: Long,
): ResponseEntity<ProductResponse>
@Operation(
summary = "Atribui subitems ao produto",
parameters = [
Parameter(
name = "x-admin-token",
required = true,
`in` = ParameterIn.HEADER,
schema = Schema(type = "string", defaultValue = "token"),
),
],
)
@ApiResponses(
value = [
ApiResponse(responseCode = "200", description = "Operação bem-sucedida"),
ApiResponse(responseCode = "404", description = "Produto não encontrado"),
],
)
@PostMapping("/compose")
fun compose(
@Parameter(description = "Montagem do produto") @RequestBody productComposeRequest: ProductComposeRequest,
): ResponseEntity<ProductResponse>
}
| 0 |
Kotlin
|
0
| 1 |
b8e9d9257b443c1e0f4e2afe0f84700a773a7986
| 9,677 |
stock-api
|
MIT License
|
app/src/main/java/test/com/github/www/sls1005/countingrodkeyboard/CountingRodKeyboard.kt
|
sls1005
| 748,078,094 | false |
{"Kotlin": 12520}
|
package test.com.github.www.sls1005.countingrodkeyboard
import android.view.View
import android.widget.ImageButton
import android.inputmethodservice.InputMethodService
import android.content.res.Configuration.ORIENTATION_LANDSCAPE
import android.view.KeyEvent
import android.view.KeyEvent.ACTION_DOWN
import android.view.KeyEvent.ACTION_UP
import android.view.KeyEvent.FLAG_SOFT_KEYBOARD
import android.view.KeyEvent.KEYCODE_DEL
import android.view.KeyEvent.KEYCODE_ENTER
class CountingRodKeyboard : InputMethodService() {
override fun onCreateInputView(): View {
val v = layoutInflater.inflate(
when(resources.configuration.orientation) {
ORIENTATION_LANDSCAPE -> R.layout.keyboard_horizontal
else -> R.layout.keyboard_vertical
}, null)
listOf(
R.id.button0,
R.id.button1,
R.id.button2,
R.id.button3,
R.id.button4,
R.id.button5,
R.id.button6,
R.id.button7,
R.id.button8,
R.id.button9
).forEachIndexed { idx, id ->
v.findViewById<ImageButton>(id).setOnClickListener {
currentInputConnection.commitText("$idx", 1)
}
}
v.findViewById<ImageButton>(R.id.button0).setOnLongClickListener {
switchKeyboard(this@CountingRodKeyboard)
(true)
}
listOf(
Pair(R.id.enterKey, KEYCODE_ENTER),
Pair(R.id.deleteKey, KEYCODE_DEL)
).forEach { it ->
val (id, code) = it
v.findViewById<ImageButton>(id).apply {
setOnClickListener {
with(currentInputConnection) {
listOf(ACTION_DOWN, ACTION_UP).forEach { action ->
sendKeyEvent(
KeyEvent.changeFlags(KeyEvent(action, code), FLAG_SOFT_KEYBOARD)
)
}
}
}
}
}
return v
}
}
| 0 |
Kotlin
|
0
| 0 |
730163a38fd2a54415047c4f0f8a35cde0ae936d
| 2,094 |
CountingRodKeyboard
|
MIT License
|
app/src/main/java/com/melody/text/effect/graph/CustomTextSpansGraph.kt
|
TheMelody
| 533,360,294 | false | null |
package com.melody.text.effect.graph
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import com.melody.text.effect.content.CustomTextSpansContent
/**
* 扩展getBoundingBox实现:文本跨行背景绘制
* @author TheMelody
* email <EMAIL>
* created 2022/9/2 21:23
*/
fun NavGraphBuilder.addCustomTextSpansGraph() {
composable("/text/CustomTextSpansGraph"){
CustomTextSpansContent()
}
}
| 1 |
Kotlin
|
2
| 9 |
6703ebc4ec1cd1a24331ec9cdacde2744173376f
| 426 |
ComposeTextEffect
|
Apache License 2.0
|
jk/src/main/interview/Solution.kt
|
lchang199x
| 431,924,215 | false |
{"Kotlin": 96628, "Java": 23581}
|
fun main() {
Solution().solve()
}
class Solution {
fun solve() {
"oké".replace('é', 'e', true)
println('Ä' - 'A')
println('Å' - 'A')
println('Á' - 'A')
println('Æ' - 'A')
}
}
| 0 |
Kotlin
|
0
| 0 |
c39e906ca5707199e3c69455fbc59db85eef77bf
| 227 |
Codelabs
|
Apache License 2.0
|
app/src/main/java/com/nidhin/customerapp/domain/usecases/paymentscreen/GetPaymentRelatedInfo.kt
|
nidhinrejoice
| 475,316,607 | false |
{"Kotlin": 216422}
|
package com.nidhin.customerapp.domain.usecases.paymentscreen
import com.nidhin.customerapp.commons.Constants
import com.nidhin.customerapp.commons.Resource
import com.nidhin.customerapp.domain.model.PaymentMetaData
import com.nidhin.customerapp.domain.repository.HomeRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import retrofit2.HttpException
import java.io.IOException
import javax.inject.Inject
class GetPaymentRelatedInfo @Inject constructor(
private val homeRepository: HomeRepository
) {
suspend operator fun invoke(razorPayId: String,amount:Float): Flow<Resource<PaymentMetaData>> = flow {
try {
emit(Resource.Loading())
val razorpay = homeRepository.getRazorPay()
val user = homeRepository.getUser()
val paymentMetaData = PaymentMetaData(
appName = Constants.APP_NAME, razorpayKeyId = razorpay.key.toString(),
userEmail = user.email, userMobile = user.mobile, razorpayId = razorPayId, amount = amount,
orderNo = "", razorpayPaymentID = ""
)
emit(Resource.Success(paymentMetaData))
} catch (e: HttpException) {
emit(Resource.Error(e.localizedMessage ?: "Something went wrong"))
} catch (e: IOException) {
emit(Resource.Error("Internet not available"))
} catch (e: Exception) {
emit(Resource.Error(e.message.toString()))
}
}
}
| 0 |
Kotlin
|
0
| 0 |
1ad74cf26a8b7931f6397ba89188ee064d34a0cb
| 1,479 |
BuyBooksOnline
|
Apache License 2.0
|
app/src/main/java/com/dan/school/BackupItemClickListener.kt
|
brookmg
| 337,460,093 | true |
{"Kotlin": 295512, "Java": 519}
|
package com.dan.school
import com.google.firebase.storage.StorageReference
/** Invoked when a RecyclerView item is clicked */
interface BackupItemClickListener {
fun backupItemClicked(storageReference: StorageReference)
}
| 0 | null |
0
| 1 |
e5ed89e60f8534ae90d6ee7684efe77bcb765a62
| 227 |
School
|
MIT License
|
contexts/course/src/main/kotlin/com/codely/course/application/CourseCreator.kt
|
coal182
| 688,410,161 | false |
{"Kotlin": 43900, "Dockerfile": 277}
|
package com.codely.course.application
import com.codely.common.domain.Publisher
import com.codely.course.domain.Course
import com.codely.course.domain.CourseDescription
import com.codely.course.domain.CourseId
import com.codely.course.domain.CourseName
import com.codely.course.domain.CourseRepository
class CourseCreator(private val repository: CourseRepository, private val publisher: Publisher) {
fun create(id: String, name: String, description: String) {
Course.create(CourseId.fromString(id), CourseName(name), CourseDescription(description)).let {
repository.save(it)
publisher.publish(it.events)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
207bac565a377c090ceaf70d628b6a427031889e
| 660 |
kotlin-api
|
Intel Open Source License
|
src/main/kotlin/main.kt
|
NiewidzialnyCzlowiek
| 447,654,857 | false |
{"Kotlin": 8141, "Dockerfile": 194}
|
package io.bartlomiejszal
import com.sksamuel.hoplite.ConfigLoader
import org.zeromq.SocketType
import org.zeromq.ZContext
import org.zeromq.ZMQ
import java.io.*
import java.time.Instant
import kotlin.concurrent.thread
import kotlin.random.Random
import io.bartlomiejszal.ZmqSocketExtension.send
import io.bartlomiejszal.ZmqSocketExtension.receive
data class Config(
val initiator: Boolean = false,
val address: String = "127.0.0.1:8090",
val followerAddress: String,
val ackOmissionRate: Float = 0.5f
)
enum class Color {
NONE,
WHITE,
BLACK;
companion object {
fun flip(color: Color): Color = when (color) {
NONE -> NONE
WHITE -> BLACK
BLACK -> WHITE
}
}
}
data class PeerState(
val predecessorColor: Color = Color.NONE,
val color: Color = Color.NONE,
val holdingToken: Boolean = false
)
data class AppData(
val color: Color,
val message: Serializable? = null
) : Serializable
enum class MessageType {
TOKEN,
TOKEN_ACK
}
data class AppMessage(
val type: MessageType,
val data: AppData
) : Serializable
class RingMutexPeer(private val config: Config) {
private val zContext = ZContext()
private val predecessorSocket = zContext.createSocket(SocketType.REP)
private val followerSocket = zContext.createSocket(SocketType.REQ)
private var runListener: Boolean = true
private var retransmitToken: Boolean = false
private val listener: Thread
private var tokenRetransmitter: Thread? = null
private val random = Random(Instant.now().toEpochMilli())
private var state: PeerState
init {
predecessorSocket.bind("tcp://${config.address}")
followerSocket.connect("tcp://${config.followerAddress}")
state = PeerState()
listener = thread { listenerLoop() }
}
fun passToken() {
println("Passing token to the next peer")
synchronized(this) {
state = state.copy(holdingToken = false)
}
val token = AppMessage(MessageType.TOKEN, AppData(state.color))
followerSocket.send(token)
val ack = followerSocket.receive()
if (ack == null || ack.type != MessageType.TOKEN_ACK || ack.data.color != state.color) {
tokenRetransmitter = thread { tokenRetransmitterLoop(token) }
}
}
fun ownsToken() = synchronized(this) { state.holdingToken }
fun work() {
if (!state.holdingToken) {
throw IllegalStateException("Cannot perform critical section - not holding the token")
}
println("Executing critical section tasks")
Thread.sleep(5000)
}
fun setInitiator() {
state = state.copy(color = Color.WHITE, holdingToken = true)
}
private fun listenerLoop() {
while (runListener) {
val message = predecessorSocket.receive()
if (message?.type == MessageType.TOKEN) {
println("Received token: $message")
val tokenColor = message.data.color
sendAck(predecessorSocket, tokenColor)
if (tokenColor != state.predecessorColor) {
stopTokenRetransmission()
val newColor = if (state.color != tokenColor) {
tokenColor
} else {
Color.flip(state.color)
}
synchronized(this) {
state = state.copy(
color = newColor,
predecessorColor = tokenColor,
holdingToken = true)
}
println("Current state: $state")
}
}
}
}
private fun sendAck(ackReceiver: ZMQ.Socket, tokenColor: Color) {
if (random.nextFloat() >= config.ackOmissionRate) {
println("Sending ack")
val ack = AppMessage(MessageType.TOKEN_ACK, AppData(tokenColor))
ackReceiver.send(ack)
} else {
println("Omitting ack")
ackReceiver.send(ByteArray(0))
}
}
private fun tokenRetransmitterLoop(token: AppMessage) {
retransmitToken = true
while (retransmitToken) {
println("Retransmitting token")
followerSocket.send(token)
val ack = followerSocket.receive()
if (ack != null && ack.type == MessageType.TOKEN_ACK && ack.data.color == state.color) {
retransmitToken = false
}
try {
Thread.sleep(1000)
} catch (e: InterruptedException) {
retransmitToken = false
}
}
}
private fun stopTokenRetransmission() {
retransmitToken = false
tokenRetransmitter?.interrupt()
tokenRetransmitter?.join()
tokenRetransmitter = null
}
}
object App {
@JvmStatic fun main(args: Array<String>) {
println("[SWN] - mutual exclusion algorithm in bidirectional ring topology")
val config = ConfigLoader().loadConfigOrThrow<Config>("/config.yaml")
println("Config parsed successfully: $config")
println("Is this node the initiator: ${config.initiator}")
var epoch = 1
val peer = RingMutexPeer(config)
if (config.initiator) {
println("Initiating sequence")
peer.setInitiator()
peer.work()
peer.passToken()
epoch += 1
}
while(true) {
println("Waiting to get token")
while (!peer.ownsToken()) {
Thread.sleep(1000)
}
println("Epoch $epoch")
peer.work()
peer.passToken()
epoch += 1
}
}
}
| 0 |
Kotlin
|
0
| 0 |
26fe258b8da152647bb5e35523cae4db17b4f8f2
| 5,831 |
ring-mutex
|
MIT License
|
shared/src/commonMain/kotlin/presentation/viewmodel/monthDetail/CategoryMonthDetailScreenIntents.kt
|
carlosgub
| 679,364,046 | false |
{"Kotlin": 197593, "Swift": 742, "Shell": 228, "Ruby": 101}
|
package presentation.viewmodel.monthDetail
import kotlinx.coroutines.Job
import domain.model.ExpenseScreenModel
interface CategoryMonthDetailScreenIntents {
fun setInitialConfiguration(
monthKey: String,
category: String
): Job
fun getMonthDetail(): Job
fun navigateToEditExpense(expenseScreenModel: ExpenseScreenModel): Job
}
| 0 |
Kotlin
|
0
| 2 |
d2708c1c9b044c77692984e04653807c73b7b481
| 362 |
myFinances
|
Apache License 2.0
|
core/src/androidTest/java/com/yashovardhan99/core/database/DbUtils.kt
|
yashovardhan99
| 138,253,271 | false |
{"Kotlin": 354548}
|
package com.yashovardhan99.core.database
import java.time.LocalDateTime
import java.time.Month
private val dateEarly = LocalDateTime.of(2019, Month.MAY, 24, 14, 25)
private val dateMid = LocalDateTime.of(2020, Month.JULY, 31, 19, 50)
private val dateLate = LocalDateTime.of(2021, Month.FEBRUARY, 28, 23, 4)
internal object DbUtils {
val patients = listOf(
Patient(0, "Amit", 100_00, 5000_00, "", dateEarly, dateEarly),
Patient(0, "Ankur", 500_00, 20_000_00, "", dateEarly, dateMid),
Patient(0, "Deepak", 500_00, 200_00, "", dateEarly, dateLate),
Patient(0, "Rohit", 300_00, 0, "", dateMid, dateMid),
Patient(0, "Mohit", 400_00, 1200_00, "", dateMid, dateMid),
Patient(0, "Rohit", 600_00, 9530_00, "", dateMid, dateLate),
Patient(0, "Soumya", 700_00, 9000_00, "", dateMid, dateLate),
Patient(0, "Disha", 1000_00, 10_000_00, "", dateLate, dateLate),
Patient(0, "Rajput", 300_00, 7500_00, "", dateLate, dateLate),
Patient(0, "Yash", 300_00, 6000_00, "", dateLate, dateLate),
)
}
| 8 |
Kotlin
|
1
| 8 |
fea03437b15321a9c6edb07f0a2e76a8d7b0e1d4
| 1,066 |
HealersDiary
|
Apache License 2.0
|
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/CellularData4.kt
|
Konyaco
| 574,321,009 | false | null |
package com.konyaco.fluent.icons.filled
import androidx.compose.ui.graphics.vector.ImageVector
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.fluentIcon
import com.konyaco.fluent.icons.fluentPath
public val Icons.Filled.CellularData4: ImageVector
get() {
if (_cellularData4 != null) {
return _cellularData4!!
}
_cellularData4 = fluentIcon(name = "Filled.CellularData4") {
fluentPath {
moveTo(8.0f, 14.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f)
verticalLineToRelative(4.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, 1.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -1.0f)
verticalLineToRelative(-4.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f)
close()
moveTo(4.0f, 17.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 0.98f)
verticalLineToRelative(1.04f)
arcTo(1.0f, 1.0f, 0.0f, false, true, 4.0f, 20.0f)
arcToRelative(1.0f, 1.0f, 0.0f, false, true, -1.0f, -0.98f)
verticalLineToRelative(-1.04f)
arcTo(1.0f, 1.0f, 0.0f, false, true, 4.0f, 17.0f)
close()
}
}
return _cellularData4!!
}
private var _cellularData4: ImageVector? = null
| 1 |
Kotlin
|
3
| 83 |
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
| 1,457 |
compose-fluent-ui
|
Apache License 2.0
|
sources/feature/photoReport/src/main/kotlin/com/egoriku/ladyhappy/photoreport/presentation/controller/PhotoReportItemController.kt
|
DoTheMonkeyBusiness
| 317,000,577 | true |
{"Kotlin": 340209, "JavaScript": 2522, "Shell": 289}
|
package com.egoriku.ladyhappy.photoreport.presentation.controller
import android.graphics.drawable.ColorDrawable
import android.view.ViewGroup
import coil.load
import com.egoriku.ladyhappy.extensions.colorFromAttr
import com.egoriku.ladyhappy.extensions.inflater
import com.egoriku.ladyhappy.photoreport.R
import com.egoriku.ladyhappy.photoreport.databinding.AdapterItemPhotoReportBinding
import ru.surfstudio.android.easyadapter.controller.BindableItemController
import ru.surfstudio.android.easyadapter.holder.BindableViewHolder
class PhotoReportItemController : BindableItemController<String, PhotoReportItemController.Holder>() {
override fun createViewHolder(parent: ViewGroup) =
Holder(AdapterItemPhotoReportBinding.inflate(parent.inflater(), parent, false))
override fun getItemId(data: String) = data.hashCode().toString()
class Holder(
private val itemBinding: AdapterItemPhotoReportBinding
) : BindableViewHolder<String>(itemBinding.root) {
private val placeholderDrawable = ColorDrawable(itemView.colorFromAttr(R.attr.colorPlaceholder))
override fun bind(data: String) {
itemBinding.reportPhotoItem.load(uri = data) {
placeholder(placeholderDrawable)
crossfade(true)
}
}
}
}
| 1 | null |
0
| 0 |
38c6b7ff347763cee016dc04b415951305d5768e
| 1,316 |
Lady-happy-Android
|
Apache License 2.0
|
app/src/main/java/com/haliltprkk/movieapplication/presentation/moviedetail/CastAdapter.kt
|
haliltprkk
| 520,972,775 | false |
{"Kotlin": 87379, "Shell": 306}
|
package com.haliltprkk.movieapplication.presentation.moviedetail
import android.annotation.SuppressLint
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.haliltprkk.movieapplication.common.extension.toFullImageLink
import com.haliltprkk.movieapplication.databinding.ListItemCastBinding
import com.haliltprkk.movieapplication.domain.models.Cast
class CastAdapter : RecyclerView.Adapter<ViewModel>() {
private val data = ArrayList<Cast>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewModel {
val binding = ListItemCastBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return ViewModel(binding)
}
@SuppressLint("NotifyDataSetChanged")
fun setItems(castList: List<Cast>) {
this.data.clear()
this.data.addAll(castList)
notifyDataSetChanged()
}
override fun onBindViewHolder(holder: ViewModel, position: Int) = with(holder) {
bind(data[position])
}
override fun getItemCount(): Int = data.size
}
class ViewModel(
private val binding: ListItemCastBinding
) : RecyclerView.ViewHolder(binding.root) {
fun bind(item: Cast) {
binding.tvCharacterName.text = item.character
binding.tvActorName.text = item.originalName
Glide.with(itemView.context).load(item.profilePath.toFullImageLink()).into(binding.ivActor)
}
}
| 0 |
Kotlin
|
0
| 6 |
7fd2e2fdb9051284125eade04fd2b85b3f12f54e
| 1,528 |
android-clean-architechture-movie-application
|
Apache License 2.0
|
app/src/main/java/com/noto/app/domain/model/FolderIdWithNotesCount.kt
|
alialbaali
| 245,781,254 | false | null |
package com.noto.app.domain.model
import androidx.room.ColumnInfo
data class FolderIdWithNotesCount(
@ColumnInfo(name = "folder_id")
val folderId: Long,
val notesCount: Int,
)
| 24 |
Kotlin
|
3
| 90 |
ac844512dc95572e6845a154fe339919588d460a
| 189 |
Noto
|
Apache License 2.0
|
app/src/main/java/com/example/moontech/data/dataclasses/RefreshToken.kt
|
MoonTech
| 717,246,459 | false |
{"Kotlin": 200697}
|
package com.example.moontech.data.dataclasses
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class RefreshToken(@SerialName("Token") val token: String)
| 0 |
Kotlin
|
0
| 1 |
85b78b560de4f8ce1ea16aa38c896f6364467177
| 207 |
MobileMonitoringMobile
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsassessrisksandneedshandoverservice/handlers/exceptions/HmppsHandoverServiceExceptionHandler.kt
|
ministryofjustice
| 803,229,302 | false |
{"Kotlin": 111890, "Dockerfile": 1126, "JavaScript": 743, "Makefile": 661}
|
package uk.gov.justice.digital.hmpps.hmppsassessrisksandneedshandoverservice.handlers.exceptions
import jakarta.validation.ValidationException
import org.slf4j.LoggerFactory
import org.springframework.http.HttpStatus
import org.springframework.http.HttpStatus.BAD_REQUEST
import org.springframework.http.HttpStatus.FORBIDDEN
import org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR
import org.springframework.http.HttpStatus.NOT_FOUND
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.RestControllerAdvice
import org.springframework.web.servlet.resource.NoResourceFoundException
@RestControllerAdvice
class HmppsAssessRisksAndNeedsHandoverServiceExceptionHandler {
@ExceptionHandler(value = [ValidationException::class, MethodArgumentNotValidException::class])
fun handleValidationExceptions(ex: Exception): ResponseEntity<ErrorResponse> {
val userMessage: String
val developerMessage: String
when (ex) {
is MethodArgumentNotValidException -> {
val errors = ex.bindingResult.fieldErrors.joinToString(", ") { "${it.field}: ${it.defaultMessage}" }
userMessage = "Validation failure: $errors"
developerMessage = errors
}
is ValidationException -> {
userMessage = "Validation failure: ${ex.message}"
developerMessage = ex.message ?: "Validation error"
}
else -> {
userMessage = "Validation failure"
developerMessage = "Unknown validation error"
}
}
val errorResponse = ErrorResponse(
status = HttpStatus.BAD_REQUEST,
userMessage = userMessage,
developerMessage = developerMessage,
)
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorResponse).also {
log.info("Validation exception: {}", ex.message)
}
}
@ExceptionHandler(NoResourceFoundException::class)
fun handleNoResourceFoundException(e: NoResourceFoundException): ResponseEntity<ErrorResponse> = ResponseEntity
.status(NOT_FOUND)
.body(
ErrorResponse(
status = NOT_FOUND,
userMessage = "No resource found failure: ${e.message}",
developerMessage = e.message,
),
).also { log.info("No resource found exception: {}", e.message) }
@ExceptionHandler(Exception::class)
fun handleException(e: Exception): ResponseEntity<ErrorResponse> = ResponseEntity
.status(INTERNAL_SERVER_ERROR)
.body(
ErrorResponse(
status = INTERNAL_SERVER_ERROR,
userMessage = "Unexpected error: ${e.message}",
developerMessage = e.message,
),
).also { log.error("Unexpected exception", e) }
@ExceptionHandler(org.springframework.security.access.AccessDeniedException::class)
fun handleAccessDeniedException(ex: org.springframework.security.access.AccessDeniedException): ResponseEntity<ErrorResponse> {
return ResponseEntity
.status(FORBIDDEN)
.body(
ErrorResponse(
status = FORBIDDEN,
userMessage = "Access denied",
developerMessage = ex.message ?: "",
),
)
}
private companion object {
private val log = LoggerFactory.getLogger(this::class.java)
}
}
data class ErrorResponse(
val status: Int,
val errorCode: Int? = null,
val userMessage: String? = null,
val developerMessage: String? = null,
val moreInfo: String? = null,
) {
constructor(
status: HttpStatus,
errorCode: Int? = null,
userMessage: String? = null,
developerMessage: String? = null,
moreInfo: String? = null,
) :
this(status.value(), errorCode, userMessage, developerMessage, moreInfo)
}
| 6 |
Kotlin
|
0
| 1 |
9ef1002ed139f8e7c641bd6c98cb21adbdd29972
| 3,760 |
hmpps-assess-risks-and-needs-handover-service
|
MIT License
|
apt-utils/src/main/java/com/bennyhuo/aptutils/types/TypeUtils.kt
|
bennyhuo
| 524,556,896 | false | null |
package com.jyc.fast.launcher.result.compiler.aptutils.types
import com.jyc.fast.launcher.result.compiler.aptutils.AptContext
import com.squareup.javapoet.TypeName
import com.squareup.kotlinpoet.*
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import javax.lang.model.element.Element
import javax.lang.model.element.ElementKind
import javax.lang.model.element.TypeElement
import javax.lang.model.type.ArrayType
import javax.lang.model.type.TypeKind
import javax.lang.model.type.TypeMirror
import kotlin.reflect.KClass
import com.squareup.kotlinpoet.TypeName as KotlinTypeName
/**
* Created by benny on 2/3/18.
*/
object TypeUtils {
internal fun doubleErasure(elementType: TypeMirror): String {
var name = AptContext.types.erasure(elementType).toString()
val typeParamStart = name.indexOf('<')
if (typeParamStart != -1) {
name = name.substring(0, typeParamStart)
}
return name
}
internal fun getTypeFromClassName(className: String) = AptContext.elements.getTypeElement(className)?.asType()
}
/**
* 当前Element 外部的 Element 那就是包
* 不支持匿名内部类 因为匿名内部类外部就是外部类 所以拿不到包名
*/
fun TypeElement.packageName(): String {
var element = this.enclosingElement
while (element != null && element.kind != ElementKind.PACKAGE) {
element = element.enclosingElement
}
return element?.asType()?.toString() ?: throw IllegalArgumentException("$this does not have an enclosing element of package.")
}
fun Element.simpleName(): String = simpleName.toString()
fun TypeElement.canonicalName(): String = qualifiedName.toString()
fun TypeMirror.simpleName() = TypeUtils.doubleErasure(this).let { name -> name.substring(name.lastIndexOf(".") + 1) }
fun TypeMirror.erasure() = AptContext.types.erasure(this)
//region subType
fun TypeMirror.isSubTypeOf(className: String): Boolean {
val type = TypeUtils.getTypeFromClassName(className) ?: return false
return AptContext.types.isSubtype(this.erasure(), type.erasure())
}
fun TypeMirror.isSubTypeOf(cls: Class<*>): Boolean {
return cls.canonicalName?.let { className ->
isSubTypeOf(className)
} ?: false
}
fun TypeMirror.isSubTypeOf(cls: KClass<*>) = isSubTypeOf(cls.java)
fun TypeMirror.isSubTypeOf(typeMirror: TypeMirror): Boolean {
return AptContext.types.isSubtype(this.erasure(), typeMirror.erasure())
}
//endregion
//region sameType
fun TypeMirror.isSameTypeWith(typeMirror: TypeMirror): Boolean {
return AptContext.types.isSameType(this, typeMirror)
}
fun TypeMirror.isSameTypeWith(cls: Class<*>): Boolean {
return cls.canonicalName?.let { className ->
isSameTypeWith(className)
} ?: false
}
fun TypeMirror.isSameTypeWith(cls: KClass<*>) = isSameTypeWith(cls.java)
fun TypeMirror.isSameTypeWith(className: String): Boolean {
return TypeUtils.getTypeFromClassName(className)?.let { isSameTypeWith(it) } ?: false
}
//endregion
//region Class/KClass
fun Class<*>.asTypeMirror(): TypeMirror {
return AptContext.elements.getTypeElement(canonicalName).asType()
}
fun Class<*>.asJavaTypeName() = this.asTypeMirror().asJavaTypeName()
fun Class<*>.asKotlinTypeName() = this.asTypeMirror().asKotlinTypeName()
fun Class<*>.asElement() = this.asTypeMirror().asElement()
fun KClass<*>.asTypeMirror(): TypeMirror {
return AptContext.elements.getTypeElement(qualifiedName/* == java.canonicalName*/).asType()
}
fun KClass<*>.asJavaTypeName() = this.asTypeMirror().asJavaTypeName()
fun KClass<*>.asKotlinTypeName() = this.asTypeMirror().asKotlinTypeName()
fun KClass<*>.asElement() = this.asTypeMirror().asElement()
//endregion
//region TypeMirror
fun TypeMirror.asElement() = AptContext.types.asElement(this)
fun TypeMirror.asJavaTypeName() = TypeName.get(this)
fun TypeMirror.asKotlinTypeName(): KotlinTypeName {
return when (kind) {
TypeKind.BOOLEAN -> BOOLEAN
TypeKind.BYTE -> BYTE
TypeKind.SHORT -> SHORT
TypeKind.INT -> INT
TypeKind.LONG -> LONG
TypeKind.CHAR -> CHAR
TypeKind.FLOAT -> FLOAT
TypeKind.DOUBLE -> DOUBLE
TypeKind.ARRAY -> {
val arrayType = this as ArrayType
when (arrayType.componentType.kind) {
TypeKind.BOOLEAN -> BOOLEAN_ARRAY
TypeKind.BYTE -> BYTE_ARRAY
TypeKind.SHORT -> SHORT_ARRAY
TypeKind.INT -> INT_ARRAY
TypeKind.LONG -> LONG_ARRAY
TypeKind.CHAR -> CHAR_ARRAY
TypeKind.FLOAT -> FLOAT_ARRAY
TypeKind.DOUBLE -> DOUBLE_ARRAY
else -> if (toString() == "java.lang.String[]") STRING_ARRAY else asTypeName()
}
}
else -> if (toString() == "java.lang.String") STRING else asTypeName()
}
}
private val STRING: ClassName = ClassName("kotlin", "String")
private val STRING_ARRAY = ClassName("kotlin", "Array").parameterizedBy(STRING)
private val LONG_ARRAY: ClassName = ClassName("kotlin", "LongArray")
private val INT_ARRAY: ClassName = ClassName("kotlin", "IntArray")
private val SHORT_ARRAY: ClassName = ClassName("kotlin", "ShortArray")
private val BYTE_ARRAY: ClassName = ClassName("kotlin", "ByteArray")
private val CHAR_ARRAY: ClassName = ClassName("kotlin", "CharArray")
private val BOOLEAN_ARRAY: ClassName = ClassName("kotlin", "BooleanArray")
private val FLOAT_ARRAY: ClassName = ClassName("kotlin", "FloatArray")
private val DOUBLE_ARRAY: ClassName = ClassName("kotlin", "DoubleArray")
//endregion
| 0 |
Kotlin
|
0
| 4 |
83835db59da0640d3f74cbd4f8c19086483c7484
| 5,510 |
Symbol-Processing-Utils
|
MIT License
|
desktop/adapters/src/main/kotlin/com/soyle/stories/storyevent/removeCharacterFromStoryEvent/RemoveCharacterFromStoryEventNotifier.kt
|
Soyle-Productions
| 239,407,827 | false | null |
package com.soyle.stories.storyevent.removeCharacterFromStoryEvent
import com.soyle.stories.common.Notifier
import com.soyle.stories.common.ThreadTransformer
import com.soyle.stories.usecase.storyevent.removeCharacterFromStoryEvent.RemoveCharacterFromStoryEvent
class RemoveCharacterFromStoryEventNotifier(
private val threadTransformer: ThreadTransformer
) : Notifier<RemoveCharacterFromStoryEvent.OutputPort>(), RemoveCharacterFromStoryEvent.OutputPort {
override fun receiveRemoveCharacterFromStoryEventResponse(response: RemoveCharacterFromStoryEvent.ResponseModel) {
threadTransformer.async {
notifyAll { it.receiveRemoveCharacterFromStoryEventResponse(response) }
}
}
override fun receiveRemoveCharacterFromStoryEventFailure(failure: Exception) {
threadTransformer.async {
notifyAll { it.receiveRemoveCharacterFromStoryEventFailure(failure) }
}
}
}
| 45 |
Kotlin
|
0
| 9 |
1a110536865250dcd8d29270d003315062f2b032
| 876 |
soyle-stories
|
Apache License 2.0
|
build-logic/convention/src/main/kotlin/AppComposePlugin.kt
|
AlexeyMerov
| 636,705,016 | false |
{"Kotlin": 694442}
|
import com.alexeymerov.radiostations.configureCompose
import com.android.build.api.dsl.ApplicationExtension
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.kotlin.dsl.configure
class AppComposePlugin : Plugin<Project> {
override fun apply(target: Project) {
with(target) {
with(pluginManager) {
apply("com.android.application")
}
extensions.configure<ApplicationExtension> {
configureCompose(this)
}
}
}
}
| 0 |
Kotlin
|
0
| 4 |
850e4241b3023507d48a98ee84b6659698817e12
| 540 |
RadioStations
|
MIT License
|
data/src/main/java/com/apiguave/tinderclonedata/source/mock/PictureRemoteDataSourceMockImpl.kt
|
alejandro-piguave
| 567,907,964 | false |
{"Kotlin": 216630}
|
package com.apiguave.tinderclonedata.source.mock
import android.content.Context
import android.net.Uri
import com.apiguave.tinderclonedata.R
import com.apiguave.tinderclonedata.repository.picture.PictureRemoteDataSource
import com.apiguave.tinderclonedata.source.mock.extension.resourceUri
import kotlinx.coroutines.delay
import kotlin.random.Random
class PictureRemoteDataSourceMockImpl(private val context: Context): PictureRemoteDataSource {
override suspend fun addPictures(localPictures: List<Uri>): List<String> {
delay(1000)
return localPictures.mapIndexed { _, i ->
"picture$i.jpg"
}
}
override suspend fun addPicture(localPicture: Uri): String {
delay(1000)
return "picture1.jpg"
}
override suspend fun deletePictures(pictureNames: List<String>) {
delay(500)
}
override suspend fun getPicture(userId: String, pictureName: String): Uri {
//The random delayed is used to showcase the picture asynchronous loading
delay(Random.nextLong(1000, 4000))
return when(pictureName){
"man_1.jpg" -> context.resourceUri(R.drawable.man_1)
"man_2.jpg" -> context.resourceUri(R.drawable.man_2)
"man_3.jpg" -> context.resourceUri(R.drawable.man_3)
"man_4.jpg" -> context.resourceUri(R.drawable.man_4)
"man_5.jpg" -> context.resourceUri(R.drawable.man_5)
"man_6.jpg" -> context.resourceUri(R.drawable.man_6)
"man_7.jpg" -> context.resourceUri(R.drawable.man_7)
"man_8.jpg" -> context.resourceUri(R.drawable.man_8)
"man_9.jpg" -> context.resourceUri(R.drawable.man_9)
"man_10.jpg" -> context.resourceUri(R.drawable.man_10)
"man_11.jpg" -> context.resourceUri(R.drawable.man_11)
"man_12.jpg" -> context.resourceUri(R.drawable.man_11)
"woman_1.jpg" -> context.resourceUri(R.drawable.woman_1)
"woman_2.jpg" -> context.resourceUri(R.drawable.woman_2)
"woman_3.jpg" -> context.resourceUri(R.drawable.woman_3)
"woman_4.jpg" -> context.resourceUri(R.drawable.woman_4)
"woman_5.jpg" -> context.resourceUri(R.drawable.woman_5)
"woman_6.jpg" -> context.resourceUri(R.drawable.woman_6)
"woman_7.jpg" -> context.resourceUri(R.drawable.woman_7)
"woman_8.jpg" -> context.resourceUri(R.drawable.woman_8)
"woman_9.jpg" -> context.resourceUri(R.drawable.woman_9)
"woman_10.jpg" -> context.resourceUri(R.drawable.woman_10)
"woman_11.jpg" -> context.resourceUri(R.drawable.woman_11)
"woman_12.jpg" -> context.resourceUri(R.drawable.woman_12)
else -> context.resourceUri(R.drawable.man_1)
}
}
}
| 1 |
Kotlin
|
13
| 46 |
dfd4a2a675b843401023f6b55c5be4349a5b5559
| 2,793 |
TinderCloneCompose
|
MIT License
|
feature_feed/src/main/kotlin/ru/razrabs/feature_feed/domain/LoadPost.kt
|
razrabs-media
| 526,204,757 | false | null |
package ru.razrabs.feature_feed.domain
import org.koin.core.annotation.Single
@Single
class LoadPost(private val feedRepository: FeedRepository) {
suspend operator fun invoke(postUid: String) = feedRepository.getPost(postUid)
}
| 16 |
Kotlin
|
1
| 9 |
b01de1209d348214b7f3fd50e8e453247c38ff92
| 233 |
journal-android
|
MIT License
|
app/src/main/kotlin/com/akagiyui/drive/model/response/announcement/AnnouncementResponse.kt
|
AkagiYui
| 647,653,830 | false | null |
package com.akagiyui.drive.model.response.announcement
import com.akagiyui.drive.entity.Announcement
/**
* 公告信息 响应
*
* @author AkagiYui
*/
data class AnnouncementResponse(
/**
* 公告ID
*/
val id: String,
/**
* 标题
*/
val title: String,
/**
* 内容
*/
val content: String?,
/**
* 用户ID
*/
val userId: String,
/**
* 用户名
*/
val username: String?,
/**
* 已启用
*/
val enabled: Boolean,
/**
* 发布时间
*/
val createTime: Long,
/**
* 修改时间
*/
val updateTime: Long,
) {
constructor(announcement: Announcement) : this(
id = announcement.id,
title = announcement.title,
content = announcement.content,
userId = announcement.author.id,
username = announcement.author.username,
enabled = announcement.enabled,
createTime = announcement.createTime.time,
updateTime = announcement.updateTime.time
)
}
/**
* 从公告实体列表转换
*/
fun List<Announcement>.toResponse(): List<AnnouncementResponse> {
return this.map { AnnouncementResponse(it) }.toList()
}
| 5 | null |
3
| 17 |
de835fa7724da0a79082b81dcbb41cb10fa34807
| 1,150 |
KenkoDrive
|
MIT License
|
app/src/main/kotlin/com/akagiyui/drive/model/response/announcement/AnnouncementResponse.kt
|
AkagiYui
| 647,653,830 | false | null |
package com.akagiyui.drive.model.response.announcement
import com.akagiyui.drive.entity.Announcement
/**
* 公告信息 响应
*
* @author AkagiYui
*/
data class AnnouncementResponse(
/**
* 公告ID
*/
val id: String,
/**
* 标题
*/
val title: String,
/**
* 内容
*/
val content: String?,
/**
* 用户ID
*/
val userId: String,
/**
* 用户名
*/
val username: String?,
/**
* 已启用
*/
val enabled: Boolean,
/**
* 发布时间
*/
val createTime: Long,
/**
* 修改时间
*/
val updateTime: Long,
) {
constructor(announcement: Announcement) : this(
id = announcement.id,
title = announcement.title,
content = announcement.content,
userId = announcement.author.id,
username = announcement.author.username,
enabled = announcement.enabled,
createTime = announcement.createTime.time,
updateTime = announcement.updateTime.time
)
}
/**
* 从公告实体列表转换
*/
fun List<Announcement>.toResponse(): List<AnnouncementResponse> {
return this.map { AnnouncementResponse(it) }.toList()
}
| 5 | null |
3
| 17 |
de835fa7724da0a79082b81dcbb41cb10fa34807
| 1,150 |
KenkoDrive
|
MIT License
|
app/src/main/java/com/hl/baseproject/repository/network/bean/HomeArticleList.kt
|
Heart-Beats
| 473,996,742 | false |
{"Kotlin": 1390415, "Java": 40623, "HTML": 2897, "AIDL": 1581}
|
package com.hl.baseproject.repository.network.bean
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
/**
* @author 张磊 on 2023/02/23 at 17:44
* Email: [email protected]
*/
@Keep
data class HomeArticleList(
/**
* 当前页码
*/
var curPage: Int? = null,
var datas: List<Article>? = null,
var offset: Int? = null,
var over: Boolean? = null,
/**
* 当前页总数
*/
var pageCount: Int? = null,
var size: Int? = null,
/**
* 数据总数
*/
var total: Int? = null
)
@Keep
data class Article(
@SerializedName("adminAdd")
var admin: Boolean? = null,
var apkLink: String? = null,
var audit: Int? = null,
var author: String? = null,
var canEdit: Boolean? = null,
var chapterId: Int? = null,
/**
* 文章名称
*/
var chapterName: String? = null,
var collect: Boolean? = null,
var courseId: Int? = null,
var desc: String? = null,
var descMd: String? = null,
var envelopePic: String? = null,
var fresh: Boolean? = null,
var host: String? = null,
var id: Int? = null,
var isAdminAdd: Boolean? = null,
/**
* 跳转链接
*/
var link: String? = null,
var niceDate: String? = null,
var niceShareDate: String? = null,
var origin: String? = null,
var prefix: String? = null,
var projectLink: String? = null,
/**
* 文章发布时间
*/
var publishTime: Long? = null,
var realSuperChapterId: Int? = null,
var route: Boolean? = null,
var selfVisible: Int? = null,
var shareDate: Long? = null,
/**
* 分享者
*/
var shareUser: String? = null,
var superChapterId: Int? = null,
var superChapterName: String? = null,
var tags: List<Tag?>? = null,
/**
* 文章标题
*/
var title: String? = null,
var type: Int? = null,
var userId: Int? = null,
var visible: Int? = null,
var zan: Int? = null
)
@Keep
data class Tag(
var name: String? = null,
var url: String? = null
)
| 1 |
Kotlin
|
3
| 2 |
d492826bc84277b2998aa2cf8263516f3cbbc188
| 1,813 |
BaseProject
|
Apache License 2.0
|
app/src/main/java/com/microsoft/research/karya/data/remote/response/GetAssignmentsResponse.kt
|
microsoft
| 463,097,428 | false | null |
package com.microsoft.research.karya.data.remote.response
import com.google.gson.annotations.SerializedName
import com.microsoft.research.karya.data.model.karya.MicroTaskAssignmentRecord
import com.microsoft.research.karya.data.model.karya.MicroTaskRecord
import com.microsoft.research.karya.data.model.karya.TaskRecord
data class GetAssignmentsResponse(
@SerializedName("tasks") val tasks: List<TaskRecord>,
@SerializedName("microtasks") val microTasks: List<MicroTaskRecord>,
@SerializedName("assignments") val assignments: List<MicroTaskAssignmentRecord>
)
| 5 |
Kotlin
|
2
| 5 |
f967a2a8e78551446d8beaff26ba2bdc6f9c56cc
| 568 |
rural-crowdsourcing-toolkit-client
|
MIT License
|
src/test/kotlin/com/aeolus/core/usecase/interpreter/provider/azure/AzureObjectsBuilder.kt
|
team-aeolus
| 668,382,094 | false | null |
package com.aeolus.core.usecase.interpreter.provider.azure
import com.aeolus.core.domain.server.*
import com.aeolus.core.usecase.interpreter.provider.azure.domain.*
fun getAzureItems(nextPageLink: String? = "dummy-link") = AzureItems(
listOf(getAzureItem()),
nextPageLink
)
fun getAzureItem() = AzureItem(
"USD", null, null, null,
null, null, null, null, null, null, null,
"SKU_ID", null, null, "SKU_NAME", null, null, null,
null, null, null, "Azure_Item_1", getSavingsPlan()
)
fun getSavingsPlan() = listOf(
AzureItemSavingPlan(11.0, 10.00, "1 Year")
)
fun getAzureItemsDetail() = AzureItemsDetail(listOf(getAzureItemDetail()))
fun getAzureItemDetail() = AzureItemDetail(
"Azure_Item_1", null, null,
null, null, null, null, null, null, null,
null, null, null, null, null, null,
2, 1000, null, 1000, null, null,
null, "USD", "standard", null, null, null, null,
null, null, null, null, null,
null, "2023-01-12"
)
fun getAzureRetailPriceSearchParameter(skip: Int = 0) = AzureRetailPriceSearchParameter(
location = "US East",
serviceName = "Virtual Machines",
skip = skip
);
fun getAzureItemDetailSearchParameter(paymentType: String, tier: String) = AzureItemDetailSearchParameter(
currency = "USD",
region = "eastus",
paymenttype = paymentType,
tier = tier
);
fun getAzureItemSimplified(currency:String = "USD",
currencyCode:String = "USD",
skuId:String = "SKU_ID",
armSkuName:String = "Azure_Item_1",
skuName:String = "SKU_NAME",
productName: String = "",
name:String = "Azure_Item_1",
tier:String = "standard",
memoryInMB:Long = 1000,
location: String = "",
osDiskSizeInMB:Long = 1000,
numberOfCores:Int = 2,
modifiedDate:String = "2023-01-12") = AzureItemSimplified(
currency = currency,
currencyCode = currencyCode,
skuId = skuId,
armSkuName = armSkuName,
productName = productName,
skuName = skuName,
location = location,
name = name,
tier = tier,
memoryInMB = memoryInMB,
osDiskSizeInMB = osDiskSizeInMB,
numberOfCores = numberOfCores,
modifiedDate = modifiedDate,
savingsPlan = listOf(AzureItemSavingPlanSimplified(11.0, 10.00, "1 Year"))
)
fun getServer(provider:Provider = Provider.AZURE,
sku:String = "SKU_ID",
offers:List<ServerOffer> = listOf(getServerOffer()),
location:Location = Location.US,
cpuCount:Int = 2,
memory:Int = 1,
operatingSystem:OperatingSystem = OperatingSystem.WINDOWS,
disk:String = "1000",
instanceType:String = "Azure_Item_1") = Server(
provider = provider,
sku = sku,
offers = offers,
location = location,
cpuCount = cpuCount,
memory = memory,
operatingSystem = operatingSystem,
disk = disk,
instanceType = instanceType
)
fun getServerOffer() = ServerOffer(
id = "",
sku = "SKU_ID",
type = OfferType.ONDEMAND,
reserveTime = 1,
price = 10.0,
priceTimeUnit = OfferTimeUnit.HOURS,
commitmentTime = 0,
commitmentTimeUnit = OfferTimeUnit.HOURS,
upfrontPaymentAmount = 0.0
)
| 0 |
Kotlin
|
0
| 0 |
be9bca77f166baa339962c6f3264beb164f91dfb
| 3,460 |
aeolus-service
|
MIT License
|
mvvm/src/iosMain/kotlin/dev/icerock/moko/mvvm/dispatcher/EventsDispatcher.kt
|
eligat
| 210,386,631 | true |
{"Kotlin": 36446, "Swift": 15080, "Ruby": 1370}
|
/*
* Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.moko.mvvm.dispatcher
import platform.darwin.dispatch_async
import platform.darwin.dispatch_get_main_queue
import kotlin.native.ref.WeakReference
actual class EventsDispatcher<ListenerType : Any>(listener: ListenerType) {
private val weakListener: WeakReference<ListenerType> = WeakReference(listener)
actual fun dispatchEvent(block: ListenerType.() -> Unit) {
val listener = weakListener.get() ?: return
val mainQueue = dispatch_get_main_queue()
dispatch_async(mainQueue) {
block(listener)
}
}
}
| 0 | null |
0
| 0 |
3caa7995f7cd1e68851a535aff228a7511cbaaf6
| 681 |
moko-mvvm
|
Apache License 2.0
|
app/app/src/main/java/co/tcc/koga/android/ui/adapter/SelectedUserAdapter.kt
|
FelipeKoga
| 289,781,345 | false |
{"Kotlin": 204658, "TypeScript": 120200, "JavaScript": 67238, "HTML": 59488, "SCSS": 20159}
|
package co.tcc.koga.android.ui.adapter
import kotlinx.android.synthetic.main.row_selected_user.view.*
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import co.tcc.koga.android.R
import co.tcc.koga.android.data.database.entity.UserEntity
import co.tcc.koga.android.databinding.RowSelectedUserBinding
import co.tcc.koga.android.databinding.RowUserBinding
import co.tcc.koga.android.utils.Constants
class SelectedUserAdapter :
ListAdapter<UserEntity, SelectedUserAdapter.SelectedUserViewHolder>(DIFF_CALLBACK) {
var onLoadAvatar: ((avatar: String?, imageView: ImageView) -> Unit)? = null
var onUserClicked: ((user: UserEntity) -> Unit)? = null
class SelectedUserViewHolder(val binding: RowSelectedUserBinding) :
RecyclerView.ViewHolder(binding.root) {
fun bindView(
user: UserEntity,
onUserClicked: ((user: UserEntity) -> Unit)?,
onLoadAvatar: ((avatar: String?, imageView: ImageView) -> Unit)?
) {
binding.run {
textViewSelectedUser.text = user.name
imageViewRemoveSelected.setOnClickListener { onUserClicked?.invoke(user) }
onLoadAvatar?.invoke(
if (user.avatar.isNullOrEmpty()) Constants.getAvatarURL(
user.name,
user.color
) else user.avatar,
imageViewSelectedUserAvatar
)
}
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SelectedUserViewHolder {
return SelectedUserViewHolder(RowSelectedUserBinding.inflate(LayoutInflater.from(parent.context)))
}
override fun onBindViewHolder(holder: SelectedUserViewHolder, position: Int) {
holder.bindView(getItem(position), onUserClicked, onLoadAvatar)
}
companion object {
private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<UserEntity>() {
override fun areItemsTheSame(oldItem: UserEntity, newItem: UserEntity): Boolean {
return oldItem.username == newItem.username
}
override fun areContentsTheSame(
oldItem: UserEntity,
newItem: UserEntity
): Boolean {
return oldItem == newItem
}
}
}
}
| 0 |
Kotlin
|
0
| 1 |
0bb0fc56fe86e463d61198ab8b8c7d2405d7d67b
| 2,617 |
fleet-management
|
Apache License 2.0
|
app/src/main/java/com/htueko/resumeapp/data/datasource/local/LocalDataSourceImpl.kt
|
htueko
| 458,821,932 | false | null |
package com.htueko.resumeapp.data.datasource.local
import com.htueko.resumeapp.data.local.dao.ResumeDao
import com.htueko.resumeapp.data.mapper.LocalMapper
import com.htueko.resumeapp.domain.datasource.LocalDataSource
import com.htueko.resumeapp.domain.model.Education
import com.htueko.resumeapp.domain.model.Project
import com.htueko.resumeapp.domain.model.Resume
import com.htueko.resumeapp.domain.model.Skill
import com.htueko.resumeapp.domain.model.Work
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
import javax.inject.Inject
/**
* separation of concern for single source of data for local database.
* @see [LocalDataSource] contract to implement for this class.
* @see [resumeDao] data access object for room database.
* @see [localMapper] to map the data from and to between domain and data layer for local database.
*/
@Suppress("TooManyFunctions", "EmptyCatchBlock", "TooGenericExceptionCaught", "SwallowedException")
class LocalDataSourceImpl @Inject constructor(
private val resumeDao: ResumeDao,
private val localMapper: LocalMapper,
) : LocalDataSource {
override fun getResumes(): Flow<List<Resume>> {
val response = resumeDao.getResumes()
return response.map { localMapper.mapToResumeModels(it) }
}
override suspend fun getEducationByResumeId(resumeId: Int): List<Education> =
withContext(Dispatchers.IO) {
try {
val response = resumeDao.getResumeWithEducations(resumeId)
response.flatMap { localMapper.mapToEducationModels(it.educations) }
} catch (e: Exception) {
emptyList<Education>()
}
}
override suspend fun getProjectsByResumeId(resumeId: Int): List<Project> =
withContext(Dispatchers.IO) {
try {
val response = resumeDao.getResumeWithProjects(resumeId)
response.flatMap { localMapper.mapToProjectModels(it.projects) }
} catch (e: Exception) {
emptyList<Project>()
}
}
override suspend fun getSkillsByResumeId(resumeId: Int): List<Skill> =
withContext(Dispatchers.IO) {
try {
val response = resumeDao.getResumeWithSkills(resumeId)
response.flatMap { localMapper.mapToSkillModels(it.skills) }
} catch (e: Exception) {
emptyList<Skill>()
}
}
override suspend fun getWorksByResumeId(resumeId: Int): List<Work> =
withContext(Dispatchers.IO) {
try {
val response = resumeDao.getResumeWithWorks(resumeId)
response.flatMap { localMapper.mapToWorkModels(it.works) }
} catch (e: Exception) {
emptyList<Work>()
}
}
override suspend fun insertOrUpdateResume(resume: Resume): Int? =
withContext(Dispatchers.IO) {
try {
resumeDao.insertOrUpdateResume(
localMapper.mapToResumeEntity(
resume
)
).toInt()
} catch (e: Exception) {
null
}
}
override suspend fun insertOrUpdateEducations(
resumeId: Int,
educations: List<Education>
): Int? =
withContext(Dispatchers.IO) {
try {
val data = resumeDao.insertOrUpdateEducations(
localMapper.mapToEducationEntities(
resumeId,
educations
)
)
// return the rowId of the firs index
data[0].toInt()
} catch (e: Exception) {
null
}
}
override suspend fun insertOrUpdateProjects(resumeId: Int, projects: List<Project>): Int? =
withContext(Dispatchers.IO) {
try {
val data = resumeDao.insertOrUpdateProjects(
localMapper.mapToProjectEntities(
resumeId,
projects
)
)
// return the rowId of the firs index
data[0].toInt()
} catch (e: Exception) {
null
}
}
override suspend fun insertOrUpdateSkills(resumeId: Int, skills: List<Skill>): Int? =
withContext(Dispatchers.IO) {
try {
val data =
resumeDao.insertOrUpdateSkills(localMapper.mapToSkillEntities(resumeId, skills))
// return the rowId of the firs index
data[0].toInt()
} catch (e: Exception) {
null
}
}
override suspend fun insertOrUpdateWorks(resumeId: Int, works: List<Work>): Int? =
withContext(Dispatchers.IO) {
try {
val data =
resumeDao.insertOrUpdateWorks(localMapper.mapToWorkEntities(resumeId, works))
// return the rowId of the firs index
data[0].toInt()
} catch (e: Exception) {
null
}
}
override suspend fun deleteResumeCascadeByResumeId(resume: Resume) {
withContext(Dispatchers.IO) {
try {
val data = localMapper.mapToResumeEntity(resume)
resumeDao.deleteResumeWithCascadeById(resume.resumeId)
} catch (e: Exception) {
}
}
}
override suspend fun deleteEducationById(education: Education) {
withContext(Dispatchers.IO) {
try {
val data = localMapper.mapToEducationEntity(education)
resumeDao.deleteEducationById(data.educationId)
} catch (e: Exception) {
}
}
}
override suspend fun deleteProjectById(project: Project) {
withContext(Dispatchers.IO) {
try {
val data = localMapper.mapToProjectEntity(project)
resumeDao.deleteProjectById(data.projectId)
} catch (e: Exception) {
}
}
}
override suspend fun deleteSkillById(skill: Skill) {
withContext(Dispatchers.IO) {
try {
val data = localMapper.mapToSkillEntity(skill)
resumeDao.deleteSkillById(data.skillId)
} catch (e: Exception) {
}
}
}
override suspend fun deleteWorkById(work: Work) {
withContext(Dispatchers.IO) {
try {
val data = localMapper.mapToWorkEntity(work)
resumeDao.deleteWorkById(data.workId)
} catch (e: Exception) {
}
}
}
override fun getResumeById(resumeId: Int): Resume? {
val response = resumeDao.getResumeById(resumeId)
return response?.let { localMapper.mapToResumeModel(it) }
}
}
| 0 |
Kotlin
|
0
| 2 |
07b35847def753a8d79a1da7c4c820bb4ce85911
| 7,033 |
ResumeApp
|
Apache License 2.0
|
app/src/main/java/com/htueko/resumeapp/data/datasource/local/LocalDataSourceImpl.kt
|
htueko
| 458,821,932 | false | null |
package com.htueko.resumeapp.data.datasource.local
import com.htueko.resumeapp.data.local.dao.ResumeDao
import com.htueko.resumeapp.data.mapper.LocalMapper
import com.htueko.resumeapp.domain.datasource.LocalDataSource
import com.htueko.resumeapp.domain.model.Education
import com.htueko.resumeapp.domain.model.Project
import com.htueko.resumeapp.domain.model.Resume
import com.htueko.resumeapp.domain.model.Skill
import com.htueko.resumeapp.domain.model.Work
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
import javax.inject.Inject
/**
* separation of concern for single source of data for local database.
* @see [LocalDataSource] contract to implement for this class.
* @see [resumeDao] data access object for room database.
* @see [localMapper] to map the data from and to between domain and data layer for local database.
*/
@Suppress("TooManyFunctions", "EmptyCatchBlock", "TooGenericExceptionCaught", "SwallowedException")
class LocalDataSourceImpl @Inject constructor(
private val resumeDao: ResumeDao,
private val localMapper: LocalMapper,
) : LocalDataSource {
override fun getResumes(): Flow<List<Resume>> {
val response = resumeDao.getResumes()
return response.map { localMapper.mapToResumeModels(it) }
}
override suspend fun getEducationByResumeId(resumeId: Int): List<Education> =
withContext(Dispatchers.IO) {
try {
val response = resumeDao.getResumeWithEducations(resumeId)
response.flatMap { localMapper.mapToEducationModels(it.educations) }
} catch (e: Exception) {
emptyList<Education>()
}
}
override suspend fun getProjectsByResumeId(resumeId: Int): List<Project> =
withContext(Dispatchers.IO) {
try {
val response = resumeDao.getResumeWithProjects(resumeId)
response.flatMap { localMapper.mapToProjectModels(it.projects) }
} catch (e: Exception) {
emptyList<Project>()
}
}
override suspend fun getSkillsByResumeId(resumeId: Int): List<Skill> =
withContext(Dispatchers.IO) {
try {
val response = resumeDao.getResumeWithSkills(resumeId)
response.flatMap { localMapper.mapToSkillModels(it.skills) }
} catch (e: Exception) {
emptyList<Skill>()
}
}
override suspend fun getWorksByResumeId(resumeId: Int): List<Work> =
withContext(Dispatchers.IO) {
try {
val response = resumeDao.getResumeWithWorks(resumeId)
response.flatMap { localMapper.mapToWorkModels(it.works) }
} catch (e: Exception) {
emptyList<Work>()
}
}
override suspend fun insertOrUpdateResume(resume: Resume): Int? =
withContext(Dispatchers.IO) {
try {
resumeDao.insertOrUpdateResume(
localMapper.mapToResumeEntity(
resume
)
).toInt()
} catch (e: Exception) {
null
}
}
override suspend fun insertOrUpdateEducations(
resumeId: Int,
educations: List<Education>
): Int? =
withContext(Dispatchers.IO) {
try {
val data = resumeDao.insertOrUpdateEducations(
localMapper.mapToEducationEntities(
resumeId,
educations
)
)
// return the rowId of the firs index
data[0].toInt()
} catch (e: Exception) {
null
}
}
override suspend fun insertOrUpdateProjects(resumeId: Int, projects: List<Project>): Int? =
withContext(Dispatchers.IO) {
try {
val data = resumeDao.insertOrUpdateProjects(
localMapper.mapToProjectEntities(
resumeId,
projects
)
)
// return the rowId of the firs index
data[0].toInt()
} catch (e: Exception) {
null
}
}
override suspend fun insertOrUpdateSkills(resumeId: Int, skills: List<Skill>): Int? =
withContext(Dispatchers.IO) {
try {
val data =
resumeDao.insertOrUpdateSkills(localMapper.mapToSkillEntities(resumeId, skills))
// return the rowId of the firs index
data[0].toInt()
} catch (e: Exception) {
null
}
}
override suspend fun insertOrUpdateWorks(resumeId: Int, works: List<Work>): Int? =
withContext(Dispatchers.IO) {
try {
val data =
resumeDao.insertOrUpdateWorks(localMapper.mapToWorkEntities(resumeId, works))
// return the rowId of the firs index
data[0].toInt()
} catch (e: Exception) {
null
}
}
override suspend fun deleteResumeCascadeByResumeId(resume: Resume) {
withContext(Dispatchers.IO) {
try {
val data = localMapper.mapToResumeEntity(resume)
resumeDao.deleteResumeWithCascadeById(resume.resumeId)
} catch (e: Exception) {
}
}
}
override suspend fun deleteEducationById(education: Education) {
withContext(Dispatchers.IO) {
try {
val data = localMapper.mapToEducationEntity(education)
resumeDao.deleteEducationById(data.educationId)
} catch (e: Exception) {
}
}
}
override suspend fun deleteProjectById(project: Project) {
withContext(Dispatchers.IO) {
try {
val data = localMapper.mapToProjectEntity(project)
resumeDao.deleteProjectById(data.projectId)
} catch (e: Exception) {
}
}
}
override suspend fun deleteSkillById(skill: Skill) {
withContext(Dispatchers.IO) {
try {
val data = localMapper.mapToSkillEntity(skill)
resumeDao.deleteSkillById(data.skillId)
} catch (e: Exception) {
}
}
}
override suspend fun deleteWorkById(work: Work) {
withContext(Dispatchers.IO) {
try {
val data = localMapper.mapToWorkEntity(work)
resumeDao.deleteWorkById(data.workId)
} catch (e: Exception) {
}
}
}
override fun getResumeById(resumeId: Int): Resume? {
val response = resumeDao.getResumeById(resumeId)
return response?.let { localMapper.mapToResumeModel(it) }
}
}
| 0 |
Kotlin
|
0
| 2 |
07b35847def753a8d79a1da7c4c820bb4ce85911
| 7,033 |
ResumeApp
|
Apache License 2.0
|
source/experiment/src/main/kotlin/de/webis/webisstud/thesis/reimer/experiment/FingerprintGroupsUtils.kt
|
webis-de
| 261,803,727 | false |
{"Kotlin": 235840, "Jupyter Notebook": 43040, "Java": 7525}
|
package de.webis.webisstud.thesis.reimer.experiment
import de.webis.webisstud.thesis.reimer.corpus.url.urls
import de.webis.webisstud.thesis.reimer.groups.canonical.CanonicalFingerprintGroups
import de.webis.webisstud.thesis.reimer.groups.canonical.asCanonicalFingerprintGroups
import de.webis.webisstud.thesis.reimer.groups.canonical.canonicalFingerprintGroups
import de.webis.webisstud.thesis.reimer.model.Corpus
import dev.reimer.domain.ktx.domainOrNull
val Corpus.canonicalFingerprintGroupsContainsWikipedia: CanonicalFingerprintGroups
get() {
val groups = canonicalFingerprintGroups.groups
val ids: Set<String> = groups.flatMapTo(mutableSetOf()) { it.ids }
val urls = urls.filter { (id, _) -> id in ids }
return groups.filterTo(mutableSetOf()) { group ->
group.ids.any { urls[it]?.domainOrNull?.root == "wikipedia.org" }
}.asCanonicalFingerprintGroups()
}
| 0 |
Kotlin
|
2
| 2 |
34cbd80dad107b6a7cd57b6a740d35f76013984a
| 877 |
sigir20-sampling-bias-due-to-near-duplicates-in-learning-to-rank
|
MIT License
|
foundation/foundation-assets/src/main/kotlin/com/decathlon/vitamin/compose/vitaminassets/flags/Nf.kt
|
Decathlon
| 492,727,156 | false | null |
package com.decathlon.vitamin.compose.vitaminassets.flags
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Brush.Companion.linearGradient
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.group
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.decathlon.vitamin.compose.vitaminassets.FlagsGroup
public val FlagsGroup.Nf: ImageVector
get() {
if (_nf != null) {
return _nf!!
}
_nf = Builder(name = "Nf", defaultWidth = 28.0.dp, defaultHeight = 20.0.dp, viewportWidth =
28.0f, viewportHeight = 20.0f).apply {
group {
path(fill = linearGradient(0.0f to Color(0xFFFFFFFF), 1.0f to Color(0xFFF0F0F0),
start = Offset(14.0f,0.0f), end = Offset(14.0f,20.0f)), stroke = null,
strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(28.0f, 0.0f)
horizontalLineTo(0.0f)
verticalLineTo(20.0f)
horizontalLineTo(28.0f)
verticalLineTo(0.0f)
close()
}
path(fill = linearGradient(0.0f to Color(0xFF219646), 1.0f to Color(0xFF197837),
start = Offset(20.6668f,0.0f), end = Offset(20.6668f,20.0f)), stroke = null,
strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(28.0002f, 0.0f)
horizontalLineTo(13.3335f)
verticalLineTo(20.0f)
horizontalLineTo(28.0002f)
verticalLineTo(0.0f)
close()
}
path(fill = linearGradient(0.0f to Color(0xFF219646), 1.0f to Color(0xFF197837),
start = Offset(4.66667f,0.0f), end = Offset(4.66667f,20.0f)), stroke = null,
strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(9.3333f, 0.0f)
horizontalLineTo(0.0f)
verticalLineTo(20.0f)
horizontalLineTo(9.3333f)
verticalLineTo(0.0f)
close()
}
path(fill = linearGradient(0.0f to Color(0xFFFFFFFF), 1.0f to Color(0xFFF0F0F0),
start = Offset(14.0002f,0.0f), end = Offset(14.0002f,20.0f)), stroke = null,
strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(20.0002f, 0.0f)
horizontalLineTo(8.0002f)
verticalLineTo(20.0f)
horizontalLineTo(20.0002f)
verticalLineTo(0.0f)
close()
}
path(fill = linearGradient(0.0f to Color(0xFF259D4B), 1.0f to Color(0xFF197837),
start = Offset(14.0002f,2.66666f), end = Offset(14.0002f,17.3333f)), stroke
= null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin =
Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) {
moveTo(12.5916f, 5.3375f)
lineTo(13.1543f, 3.3118f)
curveTo(13.2533f, 2.9555f, 13.6427f, 2.6667f, 14.0002f, 2.6667f)
curveTo(14.3684f, 2.6667f, 14.7492f, 2.9633f, 14.846f, 3.3118f)
lineTo(15.4087f, 5.3375f)
curveTo(15.384f, 5.3348f, 15.3589f, 5.3333f, 15.3335f, 5.3333f)
curveTo(14.9653f, 5.3333f, 14.6668f, 5.6318f, 14.6668f, 6.0f)
curveTo(14.6668f, 6.3682f, 14.9653f, 6.6667f, 15.3335f, 6.6667f)
curveTo(15.4863f, 6.6667f, 15.6272f, 6.6152f, 15.7396f, 6.5287f)
lineTo(16.1532f, 8.0176f)
curveTo(16.1041f, 8.0061f, 16.0528f, 8.0f, 16.0002f, 8.0f)
curveTo(15.632f, 8.0f, 15.3335f, 8.2985f, 15.3335f, 8.6667f)
curveTo(15.3335f, 9.0349f, 15.632f, 9.3333f, 16.0002f, 9.3333f)
curveTo(16.1814f, 9.3333f, 16.3458f, 9.261f, 16.466f, 9.1436f)
lineTo(16.9008f, 10.7089f)
curveTo(16.828f, 10.6816f, 16.7492f, 10.6667f, 16.6668f, 10.6667f)
curveTo(16.2986f, 10.6667f, 16.0002f, 10.9651f, 16.0002f, 11.3333f)
curveTo(16.0002f, 11.7015f, 16.2986f, 12.0f, 16.6668f, 12.0f)
curveTo(16.8785f, 12.0f, 17.0672f, 11.9013f, 17.1893f, 11.7475f)
lineTo(18.0002f, 14.6667f)
horizontalLineTo(14.6668f)
verticalLineTo(17.3333f)
horizontalLineTo(13.3335f)
verticalLineTo(14.6667f)
horizontalLineTo(10.0002f)
lineTo(10.8111f, 11.7475f)
curveTo(10.9332f, 11.9013f, 11.1218f, 12.0f, 11.3335f, 12.0f)
curveTo(11.7017f, 12.0f, 12.0002f, 11.7015f, 12.0002f, 11.3333f)
curveTo(12.0002f, 10.9651f, 11.7017f, 10.6667f, 11.3335f, 10.6667f)
curveTo(11.2512f, 10.6667f, 11.1723f, 10.6816f, 11.0996f, 10.7089f)
lineTo(11.5344f, 9.1436f)
curveTo(11.6545f, 9.261f, 11.8189f, 9.3333f, 12.0002f, 9.3333f)
curveTo(12.3684f, 9.3333f, 12.6668f, 9.0349f, 12.6668f, 8.6667f)
curveTo(12.6668f, 8.2985f, 12.3684f, 8.0f, 12.0002f, 8.0f)
curveTo(11.9475f, 8.0f, 11.8963f, 8.0061f, 11.8471f, 8.0176f)
lineTo(12.2607f, 6.5287f)
curveTo(12.3732f, 6.6152f, 12.514f, 6.6667f, 12.6668f, 6.6667f)
curveTo(13.035f, 6.6667f, 13.3335f, 6.3682f, 13.3335f, 6.0f)
curveTo(13.3335f, 5.6318f, 13.035f, 5.3333f, 12.6668f, 5.3333f)
curveTo(12.6414f, 5.3333f, 12.6163f, 5.3348f, 12.5916f, 5.3375f)
close()
}
}
}
.build()
return _nf!!
}
private var _nf: ImageVector? = null
| 25 |
Kotlin
|
17
| 188 |
e697003d8bcbe6280db848026c426f7e3f4afa5b
| 7,112 |
vitamin-compose
|
Apache License 2.0
|
app/src/main/java/io/github/joaogouveia89/checkmarket/marketList/presentation/components/MarketListContent.kt
|
joaogouveia89
| 842,192,758 | false |
{"Kotlin": 76944}
|
package io.github.joaogouveia89.checkmarket.marketList.presentation.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import io.github.joaogouveia89.checkmarket.R
import io.github.joaogouveia89.checkmarket.core.model.MarketItem
import io.github.joaogouveia89.checkmarket.core.model.MarketItemCategory
import kotlinx.datetime.Clock
import kotlinx.datetime.TimeZone
import kotlinx.datetime.toLocalDateTime
@Composable
fun MarketListContent(
modifier: Modifier = Modifier,
paddingValues: PaddingValues,
marketItemsList: Map<MarketItemCategory, List<MarketItem>>,
onItemClick: (Int) -> Unit) {
Column(
modifier = modifier
.padding(paddingValues)
){
LazyColumn(
modifier = modifier
) {
marketItemsList.keys.forEach { category ->
item{
CategoryMark(
modifier = Modifier.padding(vertical = 12.dp),
title = category.nameRes,
iconRes = category.iconRes
)
}
val categoryItems = marketItemsList[category]
items(categoryItems!!.size) { index ->
MarketListItem(
marketItem = categoryItems[index]
)
}
}
}
}
}
@Preview(showBackground = true)
@Composable
private fun MarketListContentPreview() {
val marketItemsList = listOf(
// FRUITS
MarketItem(
id = 1,
name = "Maçã",
category = MarketItemCategory.FRUITS,
price = 10.0,
quantity = 4,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 2,
name = "Banana",
category = MarketItemCategory.FRUITS,
price = 5.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 3,
name = "Ameixa",
category = MarketItemCategory.FRUITS,
price = 7.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
// CEREALS
MarketItem(
id = 4,
name = "Arroz",
category = MarketItemCategory.CEREALS,
price = 3.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 5,
name = "Trigo",
category = MarketItemCategory.CEREALS,
price = 4.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 6,
name = "Cevada",
category = MarketItemCategory.CEREALS,
price = 2.5,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
// MEAT
MarketItem(
id = 7,
name = "Bife",
category = MarketItemCategory.MEAT,
price = 15.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 8,
name = "Frango",
category = MarketItemCategory.MEAT,
price = 8.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 9,
name = "Porco",
category = MarketItemCategory.MEAT,
price = 10.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
// VEGETABLES
MarketItem(
id = 10,
name = "Cenoura",
category = MarketItemCategory.VEGETABLES,
price = 2.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 11,
name = "Alface",
category = MarketItemCategory.VEGETABLES,
price = 1.5,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 12,
name = "Tomate",
category = MarketItemCategory.VEGETABLES,
price = 3.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
// DAIRY
MarketItem(
id = 13,
name = "Leite",
category = MarketItemCategory.DAIRY,
price = 2.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 14,
name = "Queijo",
category = MarketItemCategory.DAIRY,
price = 5.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 15,
name = "Iogurte",
category = MarketItemCategory.DAIRY,
price = 1.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
// SNACKS
MarketItem(
id = 16,
name = "Chips",
category = MarketItemCategory.SNACKS,
price = 1.5,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 17,
name = "Chocolate",
category = MarketItemCategory.SNACKS,
price = 2.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 18,
name = "Biscoito",
category = MarketItemCategory.SNACKS,
price = 1.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
// BREAD
MarketItem(
id = 19,
name = "Pão",
category = MarketItemCategory.BREAD,
price = 1.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 20,
name = "<NAME>",
category = MarketItemCategory.BREAD,
price = 1.5,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 21,
name = "<NAME>",
category = MarketItemCategory.BREAD,
price = 2.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
// GENERAL_FOOD
MarketItem(
id = 22,
name = "Macarrão",
category = MarketItemCategory.GENERAL_FOOD,
price = 3.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 23,
name = "<NAME>",
category = MarketItemCategory.GENERAL_FOOD,
price = 4.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 24,
name = "Feijão",
category = MarketItemCategory.GENERAL_FOOD,
price = 5.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
// RESTROOM
MarketItem(
id = 25,
name = "<NAME>",
category = MarketItemCategory.RESTROOM,
price = 1.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 26,
name = "Sabonete",
category = MarketItemCategory.RESTROOM,
price = 0.5,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 27,
name = "Shampoo",
category = MarketItemCategory.RESTROOM,
price = 3.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
// KITCHEN
MarketItem(
id = 28,
name = "Esponja",
category = MarketItemCategory.KITCHEN,
price = 1.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 29,
name = "Detergente",
category = MarketItemCategory.KITCHEN,
price = 2.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 30,
name = "<NAME>",
category = MarketItemCategory.KITCHEN,
price = 1.5,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
// CLEANING
MarketItem(
id = 31,
name = "Desinfetante",
category = MarketItemCategory.CLEANING,
price = 2.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 32,
name = "<NAME>",
category = MarketItemCategory.CLEANING,
price = 3.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 33,
name = "<NAME>",
category = MarketItemCategory.CLEANING,
price = 1.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
// HOUSEHOLD
MarketItem(
id = 34,
name = "Lâmpada",
category = MarketItemCategory.HOUSEHOLD,
price = 5.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 35,
name = "Pilhas",
category = MarketItemCategory.HOUSEHOLD,
price = 3.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
),
MarketItem(
id = 36,
name = "<NAME>",
category = MarketItemCategory.HOUSEHOLD,
price = 2.0,
createdAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault()),
updatedAt = Clock.System.now().toLocalDateTime(TimeZone.currentSystemDefault())
)
)
val listGroupped = marketItemsList.groupBy { it.category }
MarketListContent(
marketItemsList = listGroupped,
paddingValues = PaddingValues(16.dp),
onItemClick = {}
)
}
| 0 |
Kotlin
|
0
| 0 |
655c7be9c4f379386d06051ac96135b17008727f
| 14,611 |
CheckMarket
|
MIT License
|
SunnyWeather/app/src/main/java/com/sunnyweather/android/ui/user/AppShare.kt
|
plattanus
| 709,212,164 | false |
{"Kotlin": 44216}
|
package com.sunnyweather.android.ui.user
import android.content.ContentValues
import android.content.Intent
import android.os.Bundle
import android.widget.EditText
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import com.sunnyweather.android.MainActivity
import com.sunnyweather.android.R
import com.sunnyweather.android.init.AccountDatabase
import com.sunnyweather.android.init.LoginActivity
class AppShare : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.updatepassbg)
val builder = AlertDialog.Builder(this)
// builder.setTitle("修改密码")
val dialogLayout = layoutInflater.inflate(R.layout.myappshare, null)
builder.setView(dialogLayout)
builder.setPositiveButton("确认") { _, _ ->
val intent = Intent(this@AppShare, MainActivity::class.java)
startActivityForResult(intent, 1)
}
builder.setNegativeButton("取消") {_,_->
val intent = Intent(this@AppShare, MainActivity::class.java)
startActivityForResult(intent, 1)
}
builder.show()
ActivityCollector.addActivity(this)
}
override fun onDestroy() {
super.onDestroy()
//用于删除当前Activity到activities的List中:用于可以随时随地的退出程序
ActivityCollector.removeActivity(this)
}
}
| 0 |
Kotlin
|
0
| 0 |
b8abb4b4a47c6cbbafb51491879d264175d40d9c
| 1,479 |
WeatherApp
|
MIT License
|
app/src/main/java/com/fyspring/stepcounter/dao/StepDataDao.kt
|
edmund03
| 447,064,449 | false | null |
package com.fyspring.stepcounter.dao
import android.content.ContentValues
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import com.fyspring.stepcounter.bean.StepEntity
class StepDataDao(mContext: Context) {
private var stepHelper: DBOpenHelper = DBOpenHelper(mContext)
private var stepDb: SQLiteDatabase? = null
/**
* 添加一条新记录
*
* @param stepEntity
*/
fun addNewData(stepEntity: StepEntity) {
stepDb = stepHelper.readableDatabase
val values = ContentValues()
values.put("curDate", stepEntity.curDate)
values.put("totalSteps", stepEntity.steps)
stepDb!!.insert("step", null, values)
stepDb!!.close()
}
/**
* 根据日期查询记录
*
* @param curDate
* @return
*/
fun getCurDataByDate(curDate: String): StepEntity? {
stepDb = stepHelper.readableDatabase
var stepEntity: StepEntity? = null
val cursor = stepDb!!.query("step", null, null, null, null, null, null)
while (cursor.moveToNext()) {
val date = cursor.getString(cursor.getColumnIndexOrThrow("curDate"))
if (curDate == date) {
val steps = cursor.getString(cursor.getColumnIndexOrThrow("totalSteps"))
stepEntity = StepEntity(date, steps)
//跳出循环
break
}
}
//关闭
stepDb!!.close()
cursor.close()
return stepEntity
}
/**
* 查询所有的记录
*
* @return
*/
fun getAllDatas(): List<StepEntity> {
val dataList: MutableList<StepEntity> = ArrayList()
stepDb = stepHelper.readableDatabase
val cursor = stepDb!!.rawQuery("select * from step", null)
while (cursor.moveToNext()) {
val curDate = cursor.getString(cursor.getColumnIndex("curDate"))
val totalSteps = cursor.getString(cursor.getColumnIndex("totalSteps"))
val entity = StepEntity(curDate, totalSteps)
dataList.add(entity)
}
//关闭数据库
stepDb!!.close()
cursor.close()
return dataList
}
/**
* 更新数据
* @param stepEntity
*/
fun updateCurData(stepEntity: StepEntity) {
stepDb = stepHelper.readableDatabase
val values = ContentValues()
values.put("curDate", stepEntity.curDate)
values.put("totalSteps", stepEntity.steps)
stepDb!!.update("step", values, "curDate=?", arrayOf(stepEntity.curDate))
stepDb!!.close()
}
/**
* 删除指定日期的记录
*
* @param curDate
*/
fun deleteCurData(curDate: String) {
stepDb = stepHelper.readableDatabase
if (stepDb!!.isOpen)
stepDb!!.delete("step", "curDate", arrayOf(curDate))
stepDb!!.close()
}
}
| 0 |
Kotlin
|
0
| 0 |
52f3aaf0968cf201747a2370f906f27c15e870bf
| 2,823 |
SimpleStepCounter
|
Apache License 2.0
|
cqrslite-core/src/main/kotlin/cqrslite/core/MapperThrowingOnFirstUse.kt
|
knirkefritt
| 776,716,335 | false |
{"Kotlin": 93560}
|
package cqrslite.core
import java.util.*
class MapperThrowingOnFirstUse : ExternalIdToAggregateMapper {
override suspend fun <T : AggregateRoot> getOrCreateAggregate(
externalId: String,
session: Session,
clazz: Class<T>,
): T {
throw MapperNotConfigured("getOrCreateAggregate")
}
override suspend fun <T : AggregateRoot> mapToAggregate(
externalId: String,
aggregateId: UUID,
clazz: Class<T>,
): Boolean {
throw MapperNotConfigured("mapToAggregate")
}
override suspend fun <T : AggregateRoot> findAggregate(existingId: String, session: Session, clazz: Class<T>): T? {
throw MapperNotConfigured("findAggregate")
}
class MapperNotConfigured(operation: String) : Exception(
"""
|Trying to $operation, but the mapper has not been configured. You need to add
| cqrs.lookup schema, mappingTable and map configuration in order to enable the mapper
""".trimMargin(),
)
}
| 0 |
Kotlin
|
0
| 0 |
b0a10e6b076c09bfa82f7c2352ef567c219adba0
| 1,021 |
cqrs-lite
|
Apache License 2.0
|
workflow-lib/factor/src/main/kotlin/org/archguard/codedb/factor/governance/document/ArchitectureDocument.kt
|
archguard
| 565,163,416 | false |
{"Kotlin": 212032, "TypeScript": 19660, "MDX": 5365, "CSS": 2612, "HTML": 1703, "JavaScript": 1360}
|
package org.archguard.codedb.factor.governance.document
/**
* An architecture document is a document that describes the architecture of a software system.
*/
class ArchitectureDocumentType {
/**
* Architecture Decision Record (ADR) is a lightweight document format for capturing architecture decisions.
*/
class ArchitectureDecisionRecord : DocumentType()
}
| 1 |
Kotlin
|
2
| 31 |
4c1f6a57568affeaab7771e83eb0665e934110a5
| 379 |
codedb
|
MIT License
|
app/src/main/java/at/guger/moneybook/ui/home/overview/budgets/OverviewBudgetsListAdapter.kt
|
guger
| 198,668,519 | false | null |
/*
* Copyright 2019 <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 at.guger.moneybook.ui.home.overview.budgets
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import at.guger.moneybook.R
import at.guger.moneybook.data.model.BudgetWithBalance
/**
* [RecyclerView.Adapter] for the overview dues card.
*/
class OverviewBudgetsListAdapter : ListAdapter<BudgetWithBalance, OverviewBudgetsBudgetViewHolder>(OverviewBudgetsBudgetDiffCallback()) {
//region Adapter
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OverviewBudgetsBudgetViewHolder {
return OverviewBudgetsBudgetViewHolder(DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.item_overview_budget, parent, false))
}
override fun onBindViewHolder(holder: OverviewBudgetsBudgetViewHolder, position: Int) {
holder.bind(getItem(position))
}
//endregion
class OverviewBudgetsBudgetDiffCallback : DiffUtil.ItemCallback<BudgetWithBalance>() {
override fun areItemsTheSame(oldItem: BudgetWithBalance, newItem: BudgetWithBalance): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: BudgetWithBalance, newItem: BudgetWithBalance): Boolean {
return oldItem == newItem
}
}
}
| 18 | null |
1
| 13 |
cc374cf434aad9db5a3fc8f336aaf3e4eb91100d
| 2,061 |
MoneyBook
|
Apache License 2.0
|
app/src/main/java/com/linweiyuan/mhp/ui/AboutFragmentUI.kt
|
linweiyuan
| 225,379,310 | false | null |
package com.linweiyuan.mhp.ui
import android.annotation.SuppressLint
import android.view.Gravity
import com.linweiyuan.mhp.BuildConfig
import com.linweiyuan.mhp.R
import com.linweiyuan.mhp.fragment.AboutFragment
import org.jetbrains.anko.*
class AboutFragmentUI : AnkoComponent<AboutFragment> {
@SuppressLint("SetTextI18n")
override fun createView(ui: AnkoContext<AboutFragment>) = with(ui) {
verticalLayout {
imageView {
imageResource = R.mipmap.ic_launcher
}.lparams(width = dimen(R.dimen.image_size), height = dimen(R.dimen.image_size)) {
gravity = Gravity.CENTER_HORIZONTAL
topMargin = dimen(R.dimen.value_10)
}
themedTextView(R.style.QDCommonDescription) {
text = "${resources.getString(R.string.current_version)} ${BuildConfig.VERSION_NAME}"
}.lparams(matchParent) {
margin = dimen(R.dimen.value_5)
padding = dimen(R.dimen.value_5)
}
scrollView {
verticalLayout {
owner.txtAbout = themedTextView(R.style.QDCommonDescription) {
text = resources.getString(R.string.about)
}.lparams(matchParent) {
margin = dimen(R.dimen.value_5)
padding = dimen(R.dimen.value_5)
}
}
}
}
}
}
| 0 |
Kotlin
|
1
| 0 |
b0ae2efa7d8ccc92b5d4f310ee11bbcdf2185405
| 1,466 |
MHP
|
Do What The F*ck You Want To Public License
|
src/me/anno/ecs/components/mesh/MeshCache.kt
|
AntonioNoack
| 456,513,348 | false | null |
package me.anno.ecs.components.mesh
import me.anno.cache.CacheData
import me.anno.cache.CacheSection
import me.anno.ecs.Component
import me.anno.ecs.Entity
import me.anno.ecs.Transform
import me.anno.ecs.prefab.Prefab.Companion.maxPrefabDepth
import me.anno.ecs.prefab.PrefabByFileCache
import me.anno.ecs.prefab.PrefabCache
import me.anno.io.files.FileReference
import me.anno.io.files.InvalidRef
import me.anno.utils.structures.lists.Lists.any2
import me.anno.utils.types.Matrices.set2
import org.apache.logging.log4j.LogManager
import org.joml.Matrix4x3f
object MeshCache : PrefabByFileCache<Mesh>(Mesh::class) {
private val LOGGER = LogManager.getLogger(MeshCache::class)
val cache = CacheSection("MeshCache2")
override operator fun get(ref: FileReference?, async: Boolean): Mesh? {
if (ref == null || ref == InvalidRef) return null
ensureMeshClasses()
val value0 = lru[ref]
if (value0 !== Unit) return value0 as? Mesh
val data = cache.getFileEntry(ref, false, PrefabCache.prefabTimeout, async) { ref1, _ ->
val mesh: Mesh? = when (val instance = PrefabCache.getPrefabInstance(ref1, maxPrefabDepth, async)) {
is Mesh -> instance
is MeshComponent -> {
// warning: if there is a dependency ring, this will produce a stack overflow
val ref2 = instance.mesh
if (ref == ref2) null
else get(ref2, async)
}
is MeshComponentBase -> instance.getMesh()
is Entity -> {
instance.forAll { if (it is Entity) it.validateTransform() }
val seq = ArrayList<Component>(64)
instance.forAll {
if (it is MeshComponentBase || it is MeshSpawner) {
seq.add(it as Component)
}
}
joinMeshes(seq)
}
is MeshSpawner -> joinMeshes(listOf(instance))
null -> null
else -> {
LOGGER.warn("Requesting mesh from ${instance.className}, cannot extract it")
null
}
}
CacheData(mesh)
} as? CacheData<*>
val value = data?.value as? Mesh
lru[ref] = value
return value
}
/**
* this should only be executed for decently small meshes ^^,
* large meshes might cause OutOfMemoryExceptions
* */
private fun joinMeshes(list: Iterable<Component>): Mesh? {
val meshes = ArrayList<Triple<Mesh, Transform?, FileReference>>()
for (comp in list) {
when (comp) {
is MeshComponentBase -> {
val mesh = comp.getMesh() ?: continue
if (mesh.proceduralLength > 0) continue
val mat0 = comp.materials
val mat1 = mesh.materials
for (i in 0 until mesh.numMaterials) {
// todo only write submesh
val mat = mat0.getOrNull(i)?.nullIfUndefined() ?: mat1.getOrNull(i) ?: InvalidRef
meshes.add(Triple(mesh, comp.transform, mat))
}
}
is MeshSpawner -> {
comp.forEachMesh { mesh, material, transform ->
if (mesh.proceduralLength <= 0) {
meshes.add(Triple(mesh, transform, material?.ref ?: InvalidRef))
}
}
}
}
}
val hasColors = meshes.any2 { it.first.color0 != null }
val hasBones = meshes.any2 { it.first.hasBones }
val hasUVs = meshes.any2 { it.first.uvs != null }
return object : MeshJoiner<Triple<Mesh, Transform?, FileReference>>(hasColors, hasBones, hasUVs) {
override fun getMesh(element: Triple<Mesh, Transform?, FileReference>) = element.first
override fun getMaterial(element: Triple<Mesh, Transform?, FileReference>) = element.third
override fun getTransform(element: Triple<Mesh, Transform?, FileReference>, dst: Matrix4x3f) {
val transform = element.second
if (transform != null) dst.set2(transform.globalTransform)
else dst.identity()
}
}.join(Mesh(), meshes)
}
}
| 0 |
Kotlin
|
0
| 10 |
f4420b4167949f9d0583b97a5b21a9556dbba5ec
| 4,481 |
RemsEngine
|
Apache License 2.0
|
src/main/kotlin/mods/octarinecore/client/gui/Utils.kt
|
Ghostlyr
| 54,911,434 | true |
{"Kotlin": 221613}
|
@file:JvmName("Utils")
package mods.octarinecore.client.gui
import net.minecraft.util.EnumChatFormatting
fun stripTooltipDefaultText(tooltip: MutableList<String>) {
var defaultRows = false
val iter = tooltip.iterator()
while (iter.hasNext()) {
if (iter.next().startsWith(EnumChatFormatting.AQUA.toString())) defaultRows = true
if (defaultRows) iter.remove()
}
}
| 0 |
Kotlin
|
0
| 0 |
a5cd7c8c8052e6218fd25d3e2578a2f2c055ad8c
| 395 |
BetterFoliage
|
MIT License
|
appcues/src/main/java/com/appcues/data/mapper/AppcuesMappingException.kt
|
appcues
| 413,524,565 | false | null |
package com.appcues.data.mapper
internal class AppcuesMappingException(message: String) : Exception(message)
| 1 |
Kotlin
|
1
| 9 |
075c9362e12684ddbeadb8d2bb6e16f03cce7c9a
| 110 |
appcues-android-sdk
|
MIT License
|
app/src/main/java/com/example/noteapp_architecture_sample/feature_note/di/NoteModule.kt
|
hossainMuktaR
| 667,001,535 | false |
{"Kotlin": 60656}
|
package com.example.noteapp_architecture_sample.feature_note.di
import android.app.Application
import androidx.room.Room
import com.example.noteapp_architecture_sample.feature_note.data.data_source.NoteDatabase
import com.example.noteapp_architecture_sample.feature_note.data.repository.NoteRepositoryImpl
import com.example.noteapp_architecture_sample.feature_note.domain.repository.NoteRepository
import com.example.noteapp_architecture_sample.feature_note.domain.use_case.AddNote
import com.example.noteapp_architecture_sample.feature_note.domain.use_case.DeleteNote
import com.example.noteapp_architecture_sample.feature_note.domain.use_case.GetAllNotes
import com.example.noteapp_architecture_sample.feature_note.domain.use_case.GetNoteById
import com.example.noteapp_architecture_sample.feature_note.domain.use_case.NoteUseCases
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NoteModule {
@Provides
@Singleton
fun provideNoteDatabase(app: Application): NoteDatabase {
return Room.databaseBuilder(
app,
NoteDatabase::class.java,
NoteDatabase.DATABASE_NAME
).build()
}
@Provides
@Singleton
fun provideNoteRepository(noteDatabase: NoteDatabase): NoteRepository {
return NoteRepositoryImpl(noteDatabase.noteDao)
}
@Provides
@Singleton
fun provideNoteUseCases(repository: NoteRepository): NoteUseCases {
return NoteUseCases(
getAllNotes = GetAllNotes(repository),
deleteNote = DeleteNote(repository),
addNote = AddNote(repository),
getNoteById = GetNoteById(repository)
)
}
}
| 0 |
Kotlin
|
0
| 0 |
d0bc2eee3ba5ef86de4bad75cb063e74a728ce62
| 1,811 |
NoteApp-Architecture-Sample.Android
|
MIT License
|
src/commonMain/kotlin/de/robolab/client/app/model/group/AbstractGroupAttemptPlanetDocument.kt
|
pixix4
| 243,975,894 | false | null |
package de.robolab.client.app.model.group
import de.robolab.client.app.model.base.IPlanetDocument
import de.robolab.client.app.repository.Attempt
import de.robolab.client.communication.RobolabMessage
import de.robolab.client.communication.toMqttPlanet
import de.robolab.client.communication.toRobot
import de.robolab.client.communication.toServerPlanet
import de.robolab.client.renderer.drawable.planet.LivePlanetDrawable
import de.robolab.client.renderer.utils.TransformationInteraction
import de.robolab.common.planet.Planet
import de.westermann.kobserve.list.observableListOf
import de.westermann.kobserve.property.constObservable
import de.westermann.kobserve.property.property
import kotlin.math.max
import kotlin.math.min
abstract class AbstractGroupAttemptPlanetDocument : IPlanetDocument {
abstract val attempt: Attempt
val messages = observableListOf<RobolabMessage>()
var duration = ""
val selectedIndexProperty = property(messages.lastIndex)
override val canUndoProperty = property(selectedIndexProperty, messages) {
selectedIndexProperty.value > 0
}
override fun undo() {
selectedIndexProperty.value = max(0, selectedIndexProperty.value - 1)
}
override val canRedoProperty = property(selectedIndexProperty, messages) {
val selectedIndex = selectedIndexProperty.value
val lastIndex = messages.lastIndex
selectedIndex < lastIndex
}
override fun redo() {
selectedIndexProperty.value = min(messages.lastIndex, selectedIndexProperty.value + 1)
}
val drawable = LivePlanetDrawable()
override val documentProperty = constObservable(drawable.view)
override fun centerPlanet() {
drawable.autoCentering = true
drawable.centerPlanet(duration = TransformationInteraction.ANIMATION_TIME)
}
val planetNameProperty = property("")
protected val backgroundPlanet = property<Planet>()
protected var serverPlanet = Planet.EMPTY
protected var mqttPlanet = Planet.EMPTY
private var lastSelectedIndex = selectedIndexProperty.value
fun update() {
val selectedIndex = selectedIndexProperty.value
val m = if (selectedIndex >= messages.lastIndex) messages else messages.take(selectedIndex + 1)
val (sp, visitedPoints) = m.toServerPlanet()
serverPlanet = sp
if (planetNameProperty.value != serverPlanet.name) {
planetNameProperty.value = serverPlanet.name
}
mqttPlanet = m.toMqttPlanet()
if (!isAttached) return
val planet = backgroundPlanet.value ?: Planet.EMPTY
drawable.importServerPlanet(
serverPlanet.importSplines(planet).importSenderGroups(planet, visitedPoints),
true
)
drawable.importMqttPlanet(mqttPlanet.importSplines(planet))
val backward = selectedIndex < lastSelectedIndex
lastSelectedIndex = selectedIndex
drawable.importRobot(m.toRobot(attempt.groupName.toIntOrNull(), backward))
}
abstract val isAttached: Boolean
init {
messages.onChange {
duration = messages.getDuration()
}
}
}
| 4 |
Kotlin
|
0
| 2 |
1f20731971a9b02f971f01ab8ae8f4e506ff542b
| 3,157 |
robolab-renderer
|
MIT License
|
src/main/kotlin/com/coder/gateway/CoderGatewayConnectionProvider.kt
|
coder
| 490,848,198 | false | null |
@file:Suppress("DialogTitleCapitalization")
package com.coder.gateway
import com.coder.gateway.sdk.humanizeDuration
import com.coder.gateway.sdk.isCancellation
import com.coder.gateway.sdk.isWorkerTimeout
import com.coder.gateway.sdk.suspendingRetryWithExponentialBackOff
import com.coder.gateway.services.CoderRecentWorkspaceConnectionsService
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.rd.util.launchUnderBackgroundProgress
import com.intellij.openapi.ui.Messages
import com.jetbrains.gateway.api.ConnectionRequestor
import com.jetbrains.gateway.api.GatewayConnectionHandle
import com.jetbrains.gateway.api.GatewayConnectionProvider
import com.jetbrains.gateway.api.GatewayUI
import com.jetbrains.gateway.ssh.SshDeployFlowUtil
import com.jetbrains.gateway.ssh.SshMultistagePanelContext
import com.jetbrains.gateway.ssh.deploy.DeployException
import com.jetbrains.rd.util.lifetime.LifetimeDefinition
import kotlinx.coroutines.launch
import net.schmizz.sshj.common.SSHException
import net.schmizz.sshj.connection.ConnectionException
import java.time.Duration
import java.util.concurrent.TimeoutException
class CoderGatewayConnectionProvider : GatewayConnectionProvider {
private val recentConnectionsService = service<CoderRecentWorkspaceConnectionsService>()
override suspend fun connect(parameters: Map<String, String>, requestor: ConnectionRequestor): GatewayConnectionHandle? {
val clientLifetime = LifetimeDefinition()
// TODO: If this fails determine if it is an auth error and if so prompt
// for a new token, configure the CLI, then try again.
clientLifetime.launchUnderBackgroundProgress(CoderGatewayBundle.message("gateway.connector.coder.connection.provider.title"), canBeCancelled = true, isIndeterminate = true, project = null) {
try {
indicator.text = CoderGatewayBundle.message("gateway.connector.coder.connecting")
val context = suspendingRetryWithExponentialBackOff(
action = { attempt ->
logger.info("Connecting... (attempt $attempt")
if (attempt > 1) {
// indicator.text is the text above the progress bar.
indicator.text = CoderGatewayBundle.message("gateway.connector.coder.connecting.retry", attempt)
}
SshMultistagePanelContext(parameters.toHostDeployInputs())
},
retryIf = {
it is ConnectionException || it is TimeoutException
|| it is SSHException || it is DeployException
},
onException = { attempt, nextMs, e ->
logger.error("Failed to connect (attempt $attempt; will retry in $nextMs ms)")
// indicator.text2 is the text below the progress bar.
indicator.text2 =
if (isWorkerTimeout(e)) "Failed to upload worker binary...it may have timed out"
else e.message ?: CoderGatewayBundle.message("gateway.connector.no-details")
},
onCountdown = { remainingMs ->
indicator.text = CoderGatewayBundle.message("gateway.connector.coder.connecting.failed.retry", humanizeDuration(remainingMs))
},
)
launch {
logger.info("Deploying and starting IDE with $context")
// At this point JetBrains takes over with their own UI.
@Suppress("UnstableApiUsage") SshDeployFlowUtil.fullDeployCycle(
clientLifetime, context, Duration.ofMinutes(10)
)
}
} catch (e: Exception) {
if (isCancellation(e)) {
logger.info("Connection canceled due to ${e.javaClass}")
} else {
logger.info("Failed to connect (will not retry)", e)
// The dialog will close once we return so write the error
// out into a new dialog.
ApplicationManager.getApplication().invokeAndWait {
Messages.showMessageDialog(
e.message ?: CoderGatewayBundle.message("gateway.connector.no-details"),
CoderGatewayBundle.message("gateway.connector.coder.connection.failed"),
Messages.getErrorIcon())
}
}
}
}
recentConnectionsService.addRecentConnection(parameters.toRecentWorkspaceConnection())
GatewayUI.getInstance().reset()
return null
}
override fun isApplicable(parameters: Map<String, String>): Boolean {
return parameters.areCoderType()
}
companion object {
val logger = Logger.getInstance(CoderGatewayConnectionProvider::class.java.simpleName)
}
}
| 23 |
Kotlin
|
1
| 9 |
24967e7b7b1dc6522f3bc978bc076c6bc7268ebe
| 5,182 |
jetbrains-coder
|
MIT License
|
src/main/kotlin/ColoredText.kt
|
jantb
| 656,995,015 | false |
{"Kotlin": 112847}
|
import slides.SlideColors
import java.awt.Color
import java.awt.Graphics2D
class ColoredText() {
private var textList = mutableListOf<String>()
var text = ""
private val colorList = mutableListOf<Color>()
var highlight = false
var highlightRange: IntRange? = null
fun isNotBlank(): Boolean {
return textList.isNotEmpty()
}
fun clear() {
textList.clear()
colorList.clear()
text = ""
}
fun addText(text: String, color: Color) {
colorList += color
this.textList += text
this.text += text
}
fun print(x: Int, y: Int, graphics: Graphics2D) {
val color = graphics.color
val fontMetrics = graphics.fontMetrics
var xx = x
textList.forEachIndexed { i, it ->
graphics.color = colorList[i]
graphics.drawString(it, xx, y)
xx += fontMetrics.stringWidth(it)
}
if (highlight) {
val first = text.substring(0, highlightRange!!.first.coerceIn(0..text.length))
val high = text.substring(
highlightRange!!.first.coerceIn(0..text.length),
(highlightRange!!.last + 1).coerceIn(0..text.length)
)
graphics.color = SlideColors.highlightRect
graphics.drawString(
high,
graphics.fontMetrics.stringWidth(first),
y
)
graphics.color = SlideColors.defaultText
}
graphics.color = color
}
fun getHighlightedText(): String {
return if (highlight) {
text.substring(
highlightRange!!.first.coerceIn(0..text.length),
(highlightRange!!.last + 1).coerceIn(0..text.length)
)
} else {
""
}
}
}
| 0 |
Kotlin
|
0
| 0 |
4acb3c016d9e532cb9f576ae7e5718a61d3bf120
| 1,834 |
s
|
MIT License
|
launcher_app/src/main/java/id/psw/vshlauncher/views/widgets/XmbDebugTouch.kt
|
EmiyaSyahriel
| 275,583,382 | false |
{"Kotlin": 646688, "C++": 59858, "GLSL": 5968, "Python": 3786, "CMake": 1421, "HTML": 219}
|
package id.psw.vshlauncher.views.widgets
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.PointF
import android.view.MotionEvent
import id.psw.vshlauncher.activities.Xmb
import id.psw.vshlauncher.views.XmbView
import id.psw.vshlauncher.views.XmbWidget
class XmbDebugTouch(view: XmbView) : XmbWidget(view) {
var dummyPaint = Paint()
var touchCurrentPointF = PointF()
var touchStartPointF = PointF()
var lastTouchAction : Int = 0
private fun drawDebugLocation(ctx: Canvas, xmb: Xmb) {
if(lastTouchAction == MotionEvent.ACTION_DOWN || lastTouchAction == MotionEvent.ACTION_MOVE){
dummyPaint.style= Paint.Style.FILL
dummyPaint.color = Color.argb(128,255,255,255)
ctx.drawCircle(touchCurrentPointF.x, touchCurrentPointF.y, 10.0f, dummyPaint)
ctx.drawCircle(touchStartPointF.x, touchStartPointF.y, 10.0f, dummyPaint)
}
}
}
| 16 |
Kotlin
|
6
| 74 |
108988b35a8f939d67bb5d09a0139de933d96377
| 975 |
CrossLauncher
|
MIT License
|
src/main/kotlin/Services/Auth.kt
|
daviskeene
| 256,627,934 | false | null |
package Services
import java.security.MessageDigest
/*
Authentication methods and helpers
*/
// Returns SHA-256 Hash
fun hash_string_md5(input: String): String {
val bytes = input.toByteArray()
val md = MessageDigest.getInstance("MD5")
val digest = md.digest(bytes)
return digest.fold("", { str, it -> str + "%02x".format(it) })
}
fun login(email: String, pwd: String): MutableMap<String, Any>? {
val hash = hash_string_md5("$email$pwd")
// Check if this account is a student or a teacher
val student = getStudent(hash)
val teacher = getTeacher(hash)
if (student == null) {
if (teacher == null) {
return null
}
// Set boolean for login
teacher.put("isTeacher", true)
return teacher
}
student.put("isTeacher", false)
return student
}
| 10 |
Kotlin
|
0
| 1 |
c11c3874415988279f468f044a872ed7a2049bbf
| 838 |
KTeach
|
MIT License
|
vivy_encryptor/src/main/java/com/vivy/symmetric/AesGcmNoPadding.kt
|
VivyTeam
| 166,982,417 | false | null |
package com.vivy.symmetric
import java.security.InvalidAlgorithmParameterException
import java.security.InvalidKeyException
import java.security.NoSuchAlgorithmException
import javax.crypto.BadPaddingException
import javax.crypto.Cipher
import javax.crypto.IllegalBlockSizeException
import javax.crypto.NoSuchPaddingException
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
class AesGcmNoPadding : SymmetricEncryption {
private val aesCipher: Cipher
get() {
try {
return Cipher.getInstance("AES/GCM/NoPadding")
} catch (e: NoSuchAlgorithmException) {
throw IllegalStateException("Failed to get cipher algorithm: AES/GCM/NoPadding", e)
} catch (e: NoSuchPaddingException) {
throw IllegalStateException("Failed to get cipher algorithm: AES/GCM/NoPadding", e)
}
}
override fun encrypt(
data: ByteArray,
key: ByteArray,
iv: ByteArray
): ByteArray {
val gcmBitLength = iv.size * 8
val ivSpec = GCMParameterSpec(gcmBitLength, iv)
val skeySpec = SecretKeySpec(key, "AES")
val cipher = aesCipher
try {
cipher.init(Cipher.ENCRYPT_MODE, skeySpec, ivSpec)
} catch (e: InvalidKeyException) {
throw IllegalStateException("Failed to initiate aes encrypt cipher", e)
} catch (e: InvalidAlgorithmParameterException) {
throw IllegalStateException("Failed to initiate aes encrypt cipher", e)
}
try {
return cipher.doFinal(data)
} catch (e: IllegalBlockSizeException) {
throw IllegalStateException("Failed to encrypt aes data", e)
} catch (e: BadPaddingException) {
throw IllegalStateException("Failed to encrypt aes data", e)
}
}
override fun decrypt(
encryptedData: ByteArray,
key: ByteArray,
iv: ByteArray
): ByteArray {
val gcmBitLength = iv.size * 8
val ivSpec = GCMParameterSpec(gcmBitLength, iv)
val skeySpec = SecretKeySpec(key, "AES")
val cipher = aesCipher
try {
cipher.init(Cipher.DECRYPT_MODE, skeySpec, ivSpec)
} catch (e: InvalidKeyException) {
throw IllegalStateException("Failed to initiate aes decrypt cipher", e)
} catch (e: InvalidAlgorithmParameterException) {
throw IllegalStateException("Failed to initiate aes decrypt cipher", e)
}
try {
return cipher.doFinal(encryptedData)
} catch (e: IllegalBlockSizeException) {
throw IllegalStateException("Failed to decrypt aes data", e)
} catch (e: BadPaddingException) {
throw IllegalStateException("Failed to decrypt aes data", e)
}
}
}
| 1 |
Kotlin
|
0
| 3 |
923dde9bf16623e3481dc25b37fff7031337d0fc
| 2,876 |
krypt-android
|
MIT License
|
KotlinMultiplatform/XFullStack/shared/src/commonMain/kotlin/core/models/request/GrokRequest.kt
|
pradyotprksh
| 385,586,594 | false |
{"Kotlin": 2932498, "Dart": 1066884, "Python": 319755, "Rust": 180589, "Swift": 149003, "C++": 113494, "JavaScript": 103891, "CMake": 94132, "HTML": 57188, "Go": 45704, "CSS": 18615, "SCSS": 17864, "Less": 17245, "Ruby": 13609, "Dockerfile": 9772, "C": 8043, "Shell": 7657, "PowerShell": 3045, "Nix": 2616, "Makefile": 1480, "PHP": 1241, "Objective-C": 380, "Handlebars": 354}
|
package core.models.request
import kotlinx.serialization.Serializable
@Serializable
data class GrokRequest(
val chatId: String,
val prompt: String,
val grokConversation: List<GrokConversation>,
)
| 0 |
Kotlin
|
11
| 24 |
a31e612a63e1dc42ed4cf2f50db90b8613fb5177
| 211 |
development_learning
|
MIT License
|
data/src/main/java/com/masscode/gonews/data/source/local/LocalDataSource.kt
|
agustiyann
| 314,437,955 | false | null |
package com.masscode.gonews.data.source.local
import com.masscode.gonews.data.source.local.entity.UserEntity
import com.masscode.gonews.data.source.local.room.UserDao
import io.reactivex.rxjava3.core.Flowable
import javax.inject.Inject
class LocalDataSource @Inject constructor(private val userDao: UserDao) {
fun getAllArticles(): Flowable<List<UserEntity>> = userDao.getAllArticles()
fun insertArticles(userList: List<UserEntity>) = userDao.insertArticles(userList)
}
| 0 |
Kotlin
|
2
| 6 |
ff775148196dde7736a4dc159e27fb48ef6b6310
| 481 |
RxJava-Dagger-Hilt-MVVM
|
Apache License 2.0
|
src/main/kotlin/com/zshnb/projectgenerator/generator/util/TypeUtil.kt
|
zshnb
| 312,987,617 | false |
{"JavaScript": 435869, "FreeMarker": 259027, "Kotlin": 99756, "SCSS": 79489, "Less": 78481, "CSS": 45063}
|
package com.zshnb.projectgenerator.generator.util
import com.zshnb.projectgenerator.generator.entity.web.*
import com.zshnb.projectgenerator.generator.entity.web.FieldType.*
import com.zshnb.projectgenerator.generator.entity.web.FieldType.Boolean
import org.springframework.stereotype.Component
@Component
class TypeUtil {
private val typeMap = mapOf(
ColumnType.INT to INT,
ColumnType.VARCHAR to STRING,
ColumnType.TEXT to STRING,
ColumnType.DOUBLE to DOUBLE,
ColumnType.DATETIME to LOCAL_DATE_TIME,
ColumnType.TINYINT to Boolean,
ColumnType.LOCAL_DATE to LOCAL_DATE,
ColumnType.DECIMAL to BIG_DECIMAL
)
fun convertColumnTypeToFieldType(columnType: ColumnType): FieldType = typeMap.getValue(columnType)
}
| 0 |
JavaScript
|
0
| 0 |
37791ded44683b00b29fadb07dc117612c9ae974
| 785 |
project-generator
|
Apache License 2.0
|
powermanager/src/main/java/com/pyamsoft/powermanager/logger/LoggerDialog.kt
|
pyamsoft
| 24,553,477 | false | null |
/*
* Copyright 2017 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.pyamsoft.powermanager.logger
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.pyamsoft.powermanager.R
import com.pyamsoft.powermanager.uicore.WatchedDialog
import timber.log.Timber
class LoggerDialog : WatchedDialog() {
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
return inflater?.inflate(R.layout.dialog_logger, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
addOptionsPreferenceFragment()
}
private fun addOptionsPreferenceFragment() {
val fragmentManager = childFragmentManager
if (fragmentManager.findFragmentByTag(LoggerPreferenceFragment.TAG) == null) {
fragmentManager.beginTransaction().replace(R.id.dialog_logger_options_container,
LoggerPreferenceFragment(), LoggerPreferenceFragment.TAG).commit()
}
}
fun onPrepareLogContentRetrieval() {
Timber.d("onPrepareLogContentRetrieval")
}
fun onLogContentRetrieved(logLine: String) {
Timber.d("onLogContentRetrieved: %s", logLine)
}
fun onAllLogContentsRetrieved() {
Timber.d("onAllLogContentsRetrieved")
}
fun onLogDeleted(logId: String) {
Timber.d("onLogDeleted: %s", logId)
}
}
| 0 |
Kotlin
|
0
| 1 |
bfc57e557e56a0503daae89a964a0ab447695b16
| 1,972 |
power-manager
|
Apache License 2.0
|
app/src/main/java/com/mrwinston/deadcellscompanion/MyApplication.kt
|
vanhine
| 266,949,919 | false | null |
package com.mrwinston.deadcellscompanion
import android.app.Application
import com.mrwinston.deadcellscompanion.di.AppComponent
import com.mrwinston.deadcellscompanion.di.DaggerAppComponent
open class MyApplication : Application() {
val appComponent: AppComponent by lazy {
initializeComponent()
}
open fun initializeComponent(): AppComponent {
return DaggerAppComponent.factory().create()
}
}
| 0 |
Kotlin
|
0
| 1 |
46f323fdfb1e54f67cd82c8822b80d3949176280
| 428 |
DeadCellsCompanion
|
The Unlicense
|
src/main/kotlin/me/arasple/mc/trmenu/modules/data/Metas.kt
|
DusKAugustus
| 288,902,080 | true |
{"Kotlin": 291052}
|
package me.arasple.mc.trmenu.modules.data
import io.izzel.taboolib.internal.apache.lang3.ArrayUtils
import io.izzel.taboolib.util.Strings
import io.izzel.taboolib.util.Variables
import me.arasple.mc.trmenu.api.Extends.getMenuSession
import me.arasple.mc.trmenu.display.function.InternalFunction
import me.arasple.mc.trmenu.display.menu.MenuLayout
import me.arasple.mc.trmenu.modules.script.Scripts
import me.arasple.mc.trmenu.utils.Msger
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
import java.util.*
/**
* @author Arasple
* @date 2020/7/6 22:06
*/
object Metas {
private val playerInventorys = mutableMapOf<UUID, Array<ItemStack?>>()
private val arguments = mutableMapOf<UUID, Array<String>>()
private val meta = mutableMapOf<UUID, MutableMap<String, Any>>()
fun getInventoryContents(player: Player): Array<ItemStack?> {
return playerInventorys.computeIfAbsent(player.uniqueId) { player.inventory.contents.clone() }
}
fun updateInventoryContents(player: Player) {
return mutableListOf<ItemStack?>().let {
val contents = player.inventory.contents
for (i in 9..35) it.add(contents[i])
for (i in 0..8) it.add(contents[i])
playerInventorys[player.uniqueId] = it.toTypedArray()
}
}
fun replaceWithArguments(player: Player, string: String): String {
try {
val session = player.getMenuSession()
val functions = session.menu?.settings?.functions?.internalFunctions
val argumented = Strings.replaceWithOrder(string, *getArguments(player))
val buffer = StringBuffer(argumented.length)
// Js & Placeholders from Menu
var content = InternalFunction.match(
argumented
.replace("{page}", session.page.toString())
.replace("{displayPage}", (session.page + 1).toString())
).let { m ->
while (m.find()) {
val group = m.group(1)
val split = group.split("_").toTypedArray()
// Internal Functions
functions?.firstOrNull { it.id.equals(split[0], true) }?.let {
m.appendReplacement(buffer, it.eval(player, ArrayUtils.remove(split, 0)))
}
// Global Js
if (group.startsWith("js:")) {
m.appendReplacement(buffer, Scripts.expression(player, group.removePrefix("js:")).asString())
}
}
m.appendTail(buffer).toString()
}
// Meta
getMeta(player).forEach {
content = content.replace(it.key, it.value.toString())
}
return content
} catch (e: Throwable) {
Msger.printErrors("ARGUMENT-REPLACE", e, string)
return string
}
}
fun getArguments(player: Player): Array<String> {
return arguments.computeIfAbsent(player.uniqueId) { arrayOf() }
}
fun setArguments(player: Player, arguments: Array<String>?) {
if (arguments == null) {
removeArguments(player)
return
}
[email protected][player.uniqueId] = filterInput(formatArguments(arguments)).toTypedArray()
Msger.debug("ARGUMENTS", player.name, getArguments(player).joinToString(","))
Msger.debug(player, "ARGUMENTS", player.name, getArguments(player).joinToString(","))
}
fun removeArguments(player: Player) {
arguments.remove(player.uniqueId)
}
fun setMeta(player: Player, key: String, value: Any): Any? {
return getMeta(player).put(key, value)
}
fun getMeta(player: Player, key: String): Any? {
return getMeta(player)[key]
}
fun getMeta(player: Player): MutableMap<String, Any> {
return meta.computeIfAbsent(player.uniqueId) { mutableMapOf() }
}
fun removeMeta(player: Player, key: String) {
getMeta(player).remove(key)
}
fun removeMeta(player: Player, matcher: Matcher) {
getMeta(player).entries.removeIf { matcher.match(it.key) }
}
fun removeMetaEndWith(player: Player, key: String) {
getMeta(player).entries.removeIf { it.key.endsWith(key) }
}
fun resetCache(player: Player) {
playerInventorys.remove(player.uniqueId)
meta.remove(player.uniqueId)
}
fun completeArguments(player: Player, arguments: Array<String>) {
if (arguments.isNotEmpty()) {
val currentArgs = getArguments(player)
if (currentArgs.isEmpty()) {
setArguments(player, arguments)
} else if (currentArgs.size < currentArgs.size) {
val args = currentArgs.toMutableList()
for (i in args.size until currentArgs.size) args.add(currentArgs[i])
setArguments(player, args.toTypedArray())
}
}
}
fun filterInput(string: String): String = string.replace(Regex("(?i)\\(|\\)|;|\"|bukkitServer|player"), "")
fun filterInput(strings: MutableList<String>): List<String> {
strings.indices.forEach {
strings[it] = filterInput(strings[it])
}
return strings
}
fun formatArguments(arguments: Array<String>) =
mutableListOf<String>().let { list ->
Variables(arguments.joinToString(" "), MenuLayout.ICON_KEY_MATCHER).find().variableList.forEach { it ->
if (it.isVariable) {
list.add(it.text)
} else {
list.addAll(it.text.split(" ").filter { it.isNotBlank() })
}
}
list
}
fun interface Matcher {
fun match(key: String): Boolean
}
}
| 0 | null |
0
| 1 |
fda531aa22f985b787f67995d82450d9704ad38b
| 5,842 |
TrMenu
|
MIT License
|
app/src/main/java/ru/sorokin/kirill/chartloader/presentation/view/move/LongTapListener.kt
|
llerik
| 562,272,861 | false | null |
package ru.sorokin.kirill.chartloader.presentation.view.move
import android.graphics.PointF
/**
* Интерфейс долдгого нажатия
*
* @author <NAME>
*/
interface LongTapListener {
/**
* Событие долгого нажатия в точку [point]
*/
fun onLongTap(point: PointF)
}
| 0 |
Kotlin
|
0
| 0 |
4444df5df042065902a61fbc3580f07f82380772
| 280 |
chartloader
|
Apache License 2.0
|
app/src/main/java/avila/daniel/rickmorty/di/qualifiers/KeySpecie.kt
|
daniaviladomingo
| 222,438,821 | false |
{"Gradle": 9, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 8, "Batchfile": 1, "INI": 3, "Proguard": 4, "Kotlin": 150, "XML": 50, "Java": 10}
|
package avila.daniel.rickmorty.di.qualifiers
import org.koin.core.qualifier.Qualifier
object KeySpecie : Qualifier
| 0 |
Kotlin
|
0
| 4 |
6193e2f38f585381eda8fed2b97e6e04c6607c2a
| 116 |
rick_and_morty
|
Apache License 2.0
|
DroidMedia/medialibs/playerLib/src/main/kotlin/com/me/harris/playerLibrary/compose/basic/ComposeVideoPlayerActivity.kt
|
Haldir65
| 55,217,175 | false |
{"Markdown": 61, "Dockerfile": 3, "Text": 47, "Ignore List": 34, "YAML": 32, "JSON": 3, "Gradle Kotlin DSL": 17, "Java Properties": 6, "Shell": 89, "Batchfile": 20, "EditorConfig": 1, "Makefile": 41, "INI": 26, "Gradle": 19, "Proguard": 27, "Kotlin": 348, "XML": 264, "TOML": 1, "Java": 594, "GLSL": 110, "Motorola 68K Assembly": 7, "C++": 411, "Unix Assembly": 10, "CMake": 37, "C": 599, "Roff Manpage": 3, "M4Sugar": 8, "Microsoft Visual Studio Solution": 4, "Awk": 3, "Module Management System": 1, "DIGITAL Command Language": 3, "Microsoft Developer Studio Project": 3, "GN": 6, "Python": 34, "Soong": 1, "Git Attributes": 1, "CoffeeScript": 1, "AIDL": 2, "Objective-C": 1, "Assembly": 4, "JSON with Comments": 3}
|
package com.me.harris.playerLibrary.compose.basic
import android.content.pm.ActivityInfo
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.WindowInsets
import android.view.WindowInsetsController
import android.view.WindowManager
import android.widget.FrameLayout
import androidx.activity.compose.setContent
import androidx.annotation.OptIn
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.Text
import androidx.compose.material3.Divider
import androidx.compose.material3.Surface
import androidx.compose.runtime.*
import androidx.compose.ui.*
import androidx.compose.ui.graphics.*
import androidx.compose.ui.platform.*
import androidx.compose.ui.tooling.preview.*
import androidx.compose.ui.unit.*
import androidx.compose.ui.viewinterop.*
import androidx.core.view.WindowCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.media3.common.C
import androidx.media3.common.MediaItem.fromUri
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DefaultDataSource
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import androidx.media3.ui.AspectRatioFrameLayout
import androidx.media3.ui.PlayerView
import com.me.harris.awesomelib.utils.VideoUtil
class ComposeVideoPlayerActivity:AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// WindowCompat.setDecorFitsSystemWindows(window, false)
hideSystemUI()
// ViewCompat.setOnApplyWindowInsetsListener(view) { view, windowInsets ->
// val insets = windowInsets.getInsets(
// WindowInsetsCompat.Type.systemGestures()
// )
// view.updatePadding(
// insets.left,
// insets.top,
// insets.right,
// insets.bottom
// )
// WindowInsetsCompat.CONSUMED
// }
setContent {
ExoPlayerComp()
}
}
fun hideSystemUI() {
//Hides the ugly action bar at the top
actionBar?.hide()
//Hide the status bars
WindowCompat.setDecorFitsSystemWindows(window, false)
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) {
window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)
} else {
window.insetsController?.apply {
hide(WindowInsets.Type.statusBars())
systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
}
}
}
@OptIn(UnstableApi::class)
@Composable
@Preview
fun ExoPlayerComp() {
requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE
Surface(
modifier = Modifier.fillMaxSize(),
color = Color.Black
) {
// val videoURL = "https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"
val videoURL = VideoUtil.strVideo
val context = LocalContext.current
val lifecycleOwner = rememberUpdatedState(LocalLifecycleOwner.current)
val exoPlayer = ExoPlayer.Builder(context)
.build()
.apply {
val defaultDataSourcFactpry = DefaultDataSource.Factory(context)
val dataSourceFactory :DataSource.Factory = DefaultDataSource.Factory(context,defaultDataSourcFactpry)
val source = ProgressiveMediaSource.Factory(dataSourceFactory)
.createMediaSource(fromUri(videoURL))
setMediaSource(source)
// setMediaItem(fromUri(videoURL))
playWhenReady = true
repeatMode = Player.REPEAT_MODE_ONE
videoScalingMode = C.VIDEO_SCALING_MODE_SCALE_TO_FIT
setTurnScreenOn(true)
prepare()
}
DisposableEffect(
key1 = AndroidView(
modifier = Modifier.fillMaxSize(),
factory = {
PlayerView(context).apply {
// resizeMode = AspectRatioFrameLayout.RESIZE_MODE_FIT
player = exoPlayer
// useController = false
resizeMode = AspectRatioFrameLayout.RESIZE_MODE_ZOOM
layoutParams = FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT)
}
}),
effect = {
val observer = LifecycleEventObserver { _, event ->
when (event) {
Lifecycle.Event.ON_RESUME -> {
Log.e("LIFECYCLE", "resumed")
exoPlayer.play()
}
Lifecycle.Event.ON_PAUSE -> {
Log.e("LIFECYCLE", "paused")
exoPlayer.stop()
}
else ->{
}
}
}
val lifecycle = lifecycleOwner.value.lifecycle
lifecycle.addObserver(observer)
onDispose {
exoPlayer.release()
lifecycle.removeObserver(observer)
}
}
)
}
}
@Composable
fun clickableButton1() {
var state by remember { mutableIntStateOf(1) }
Button(colors = ButtonDefaults.buttonColors(
backgroundColor = Color.LightGray,
contentColor = Color.Blue
), modifier = Modifier.background(Color.Green), onClick = {
state++
}
) {
val display = """
count as click $state
and
""".trimIndent()
Text(text = display, Modifier.padding(16.dp), color = Color.Blue)
Divider(modifier = Modifier
.size(20.dp)
.align(Alignment.Vertical { size, _ ->
size
}), color = Color.Yellow)
}
}
}
| 1 | null |
1
| 1 |
f117ab6ef4a6c8874030cb5cd78aa72259158cf9
| 6,723 |
Camera2Training
|
MIT License
|
app/src/main/java/com/andor/navigate/notepad/expanded/ExpandedNoteFragment.kt
|
andor201995
| 188,668,352 | false |
{"Kotlin": 95557}
|
package com.andor.navigate.notepad.expanded
import android.os.Bundle
import android.view.*
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.NavHostFragment.findNavController
import androidx.viewpager2.widget.ViewPager2
import com.andor.navigate.notepad.R
import com.andor.navigate.notepad.core.AppState
import com.andor.navigate.notepad.core.NoteViewModel
import com.andor.navigate.notepad.core.navigateSafe
import com.andor.navigate.notepad.listing.NotesActivity
import kotlinx.android.synthetic.main.fragment_expanded_note.*
class ExpandedNoteFragment : Fragment() {
private lateinit var oldState: AppState
private lateinit var viewPagerAdapter: ViewPagerAdapter
private lateinit var viewModel: NoteViewModel
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(activity!!).get(NoteViewModel::class.java)
viewModel.getAppStateStream().observe(viewLifecycleOwner, Observer { appState ->
appState.selectedNote?.let {
(activity as NotesActivity).setActionBarTitle(it.head)
}
updateViewPager(appState)
oldState = appState
})
}
private fun updateViewPager(appState: AppState) {
if (expanded_view_pager.adapter == null) {
this.viewPagerAdapter = ViewPagerAdapter(context!!) {
if (it is ViewPageItemEvent.DoubleClickEvent) {
if (it.adapterPosition >= 0) {
openEditor()
}
}
}
viewPagerAdapter.pageList = appState.listOfAllNotes
expanded_view_pager.adapter = viewPagerAdapter
expanded_view_pager.setCurrentItem(
appState.listOfAllNotes.indexOf(appState.selectedNote),
false
)
expanded_view_pager.registerOnPageChangeCallback(object :
ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
viewModel.updateSelectedNotes(viewModel.getAppStateStream().value!!.listOfAllNotes[position])
}
})
} else {
if (::oldState.isInitialized && oldState.listOfAllNotes != appState.listOfAllNotes) {
viewPagerAdapter = expanded_view_pager.adapter as ViewPagerAdapter
viewPagerAdapter.updateRecyclerView(appState.listOfAllNotes)
expanded_view_pager.setCurrentItem(
appState.listOfAllNotes.indexOf(appState.selectedNote),
false
)
}
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
setHasOptionsMenu(true)
return inflater.inflate(R.layout.fragment_expanded_note, container, false)
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
inflater.inflate(R.menu.expanded_note_option_menu, menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.edit) {
setBottomMenu()
}
return super.onOptionsItemSelected(item)
}
private fun setBottomMenu() {
findNavController(this).navigateSafe(
R.id.expandedNoteFragment,
R.id.action_expandedNoteFragment_to_addNewNoteFragment
)
}
private fun openEditor() {
val action =
ExpandedNoteFragmentDirections.actionExpandedNoteFragmentToUpdateNoteFragment(true)
findNavController(this).navigateSafe(R.id.expandedNoteFragment, action)
}
}
| 6 |
Kotlin
|
0
| 2 |
d3ee59258616a1a1333f45e1b1e4ddeccc4a2262
| 4,005 |
NoteIt
|
Apache License 2.0
|
shared/src/commonMain/kotlin/com/sknikod/standapp/domain/client/RestApiClient.kt
|
skni-kod
| 451,622,120 | false | null |
package com.sknikod.standapp.domain.client
import io.ktor.client.statement.*
interface RestApiClient {
suspend fun getListOfProjects(): HttpResponse
suspend fun getProject(id: Int): HttpResponse
suspend fun getListOfArticles(): HttpResponse
suspend fun getArticles(id: Int): HttpResponse
suspend fun getImage(path: String): HttpResponse
}
| 0 |
Kotlin
|
0
| 0 |
66005c06f6b74c6bcd5ebf6cc0010d46b05f4051
| 361 |
StandApp
|
MIT License
|
analysis/analysis-api-impl-base/tests/org/jetbrains/kotlin/analysis/api/impl/base/test/cases/symbols/AbstractSymbolTest.kt
|
JetBrains
| 3,432,266 | false |
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
|
/*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.api.impl.base.test.cases.symbols
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.analysis.api.KaSession
import org.jetbrains.kotlin.analysis.api.impl.base.test.cases.symbols.SymbolTestDirectives.DO_NOT_CHECK_NON_PSI_SYMBOL_RESTORE
import org.jetbrains.kotlin.analysis.api.impl.base.test.cases.symbols.SymbolTestDirectives.DO_NOT_CHECK_NON_PSI_SYMBOL_RESTORE_K1
import org.jetbrains.kotlin.analysis.api.impl.base.test.cases.symbols.SymbolTestDirectives.DO_NOT_CHECK_NON_PSI_SYMBOL_RESTORE_K2
import org.jetbrains.kotlin.analysis.api.impl.base.test.cases.symbols.SymbolTestDirectives.DO_NOT_CHECK_SYMBOL_RESTORE
import org.jetbrains.kotlin.analysis.api.impl.base.test.cases.symbols.SymbolTestDirectives.DO_NOT_CHECK_SYMBOL_RESTORE_K1
import org.jetbrains.kotlin.analysis.api.impl.base.test.cases.symbols.SymbolTestDirectives.DO_NOT_CHECK_SYMBOL_RESTORE_K2
import org.jetbrains.kotlin.analysis.api.impl.base.test.cases.symbols.SymbolTestDirectives.PRETTY_RENDERER_OPTION
import org.jetbrains.kotlin.analysis.api.renderer.declarations.KaDeclarationRenderer
import org.jetbrains.kotlin.analysis.api.renderer.declarations.impl.KaDeclarationRendererForDebug
import org.jetbrains.kotlin.analysis.api.renderer.declarations.renderers.KaClassifierBodyRenderer
import org.jetbrains.kotlin.analysis.api.renderer.types.KaExpandedTypeRenderingMode
import org.jetbrains.kotlin.analysis.api.renderer.types.renderers.KaFunctionalTypeRenderer
import org.jetbrains.kotlin.analysis.api.symbols.*
import org.jetbrains.kotlin.analysis.api.symbols.pointers.KaPsiBasedSymbolPointer
import org.jetbrains.kotlin.analysis.api.symbols.pointers.KaSymbolPointer
import org.jetbrains.kotlin.analysis.test.framework.base.AbstractAnalysisApiBasedTest
import org.jetbrains.kotlin.analysis.test.framework.projectStructure.KtTestModule
import org.jetbrains.kotlin.analysis.test.framework.utils.executeOnPooledThreadInReadAction
import org.jetbrains.kotlin.analysis.utils.printer.prettyPrint
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.test.builders.TestConfigurationBuilder
import org.jetbrains.kotlin.test.directives.model.Directive
import org.jetbrains.kotlin.test.directives.model.RegisteredDirectives
import org.jetbrains.kotlin.test.directives.model.SimpleDirectivesContainer
import org.jetbrains.kotlin.test.services.TestServices
import org.jetbrains.kotlin.test.services.assertions
import org.jetbrains.kotlin.utils.addIfNotNull
import org.jetbrains.kotlin.utils.mapToSetOrEmpty
import org.opentest4j.AssertionFailedError
import kotlin.reflect.full.*
import kotlin.reflect.jvm.javaField
import kotlin.test.fail
abstract class AbstractSymbolTest : AbstractAnalysisApiBasedTest() {
/**
* Currently [KaFileSymbol] cannot be restored without a backed PSI element,
* so it is better to suppress it to not hide other problems.
*/
open val suppressPsiBasedFilePointerCheck: Boolean get() = true
open val defaultRenderer = KaDeclarationRendererForDebug.WITH_QUALIFIED_NAMES
open val defaultRendererOption: PrettyRendererOption? = null
override fun configureTest(builder: TestConfigurationBuilder) {
super.configureTest(builder)
with(builder) {
useDirectives(SymbolTestDirectives)
}
}
abstract fun KaSession.collectSymbols(ktFile: KtFile, testServices: TestServices): SymbolsData
override fun doTestByMainFile(mainFile: KtFile, mainModule: KtTestModule, testServices: TestServices) {
doTestByMainFile(mainFile, mainModule, testServices, disablePsiBasedLogic = false)
doTestByMainFile(mainFile, mainModule, testServices, disablePsiBasedLogic = true)
}
private fun doTestByMainFile(
mainFile: KtFile,
mainModule: KtTestModule,
testServices: TestServices,
disablePsiBasedLogic: Boolean,
) {
val directives = mainModule.testModule.directives
val directiveToIgnore = directives.doNotCheckNonPsiSymbolRestoreDirective()?.takeIf { disablePsiBasedLogic }
?: directives.doNotCheckSymbolRestoreDirective()
val prettyRenderer = buildList {
addIfNotNull(defaultRendererOption)
addAll(directives[PRETTY_RENDERER_OPTION])
}.fold(defaultRenderer) { acc, prettyRenderingMode ->
prettyRenderingMode.transformation(acc)
}
fun KaSession.safePointer(ktSymbol: KaSymbol): KaSymbolPointer<*>? {
if (disablePsiBasedLogic && ktSymbol is KaFileSymbol && suppressPsiBasedFilePointerCheck) return null
val result = ktSymbol.runCatching {
createPointerForTest(disablePsiBasedLogic = disablePsiBasedLogic)
}
val pointer = when {
directiveToIgnore != null -> result.getOrNull()
else -> result.getOrThrow()
} ?: return null
assertSymbolPointer(pointer, testServices)
return pointer
}
val pointersWithRendered = executeOnPooledThreadInReadAction {
analyseForTest(mainFile) {
val (symbols, symbolForPrettyRendering) = collectSymbols(mainFile, testServices).also {
if (disablePsiBasedLogic) {
it.dropBackingPsi()
}
}
checkContainingFiles(symbols, mainFile, testServices)
val pointerWithRenderedSymbol = symbols
.asSequence()
.flatMap { symbol ->
sequenceOf(symbol to true) + symbol.withImplicitSymbols().map { implicitSymbol ->
if (disablePsiBasedLogic) {
implicitSymbol.dropBackingPsi()
}
implicitSymbol to false
}
}
.distinctBy { it.first }
.map { (symbol, shouldBeRendered) ->
PointerWithRenderedSymbol(
pointer = safePointer(symbol),
rendered = renderSymbolForComparison(symbol, directives),
shouldBeRendered = shouldBeRendered,
)
}
.toList()
val pointerWithPrettyRenderedSymbol = symbolForPrettyRendering.map { symbol ->
PointerWithRenderedSymbol(
safePointer(symbol),
when (symbol) {
is KaReceiverParameterSymbol -> DebugSymbolRenderer().render(useSiteSession, symbol)
is KaDeclarationSymbol -> symbol.render(prettyRenderer)
is KaFileSymbol -> prettyPrint {
printCollection(symbol.fileScope.declarations.asIterable(), separator = "\n\n") {
append(it.render(prettyRenderer))
}
}
else -> error(symbol::class.toString())
},
)
}
SymbolPointersData(pointerWithRenderedSymbol, pointerWithPrettyRenderedSymbol)
}
}
compareResults(pointersWithRendered, testServices, disablePsiBasedLogic)
configurator.doGlobalModuleStateModification(mainFile.project)
restoreSymbolsInOtherReadActionAndCompareResults(
directiveToIgnore = directiveToIgnore,
ktFile = mainFile,
pointersWithRendered = pointersWithRendered.pointers,
testServices = testServices,
directives = directives,
disablePsiBasedLogic = disablePsiBasedLogic,
)
}
private fun KaSymbol.createPointerForTest(disablePsiBasedLogic: Boolean): KaSymbolPointer<*> =
KaPsiBasedSymbolPointer.withDisabledPsiBasedPointers(disable = disablePsiBasedLogic) { createPointer() }
private fun assertSymbolPointer(pointer: KaSymbolPointer<*>, testServices: TestServices) {
testServices.assertions.assertTrue(value = pointer.pointsToTheSameSymbolAs(pointer)) {
"The symbol is not equal to itself: ${pointer::class}"
}
}
private fun KaSession.checkContainingFiles(symbols: List<KaSymbol>, mainFile: KtFile, testServices: TestServices) {
val allowedContainingFileSymbols = getAllowedContainingFiles(mainFile, testServices).mapToSetOrEmpty { it.symbol }
for (symbol in symbols) {
if (symbol.origin != KaSymbolOrigin.SOURCE) continue
val containingFileSymbol = symbol.containingFile
when {
symbol is KaFileSymbol -> {
testServices.assertions.assertEquals(null, containingFileSymbol) {
"'containingFile' for ${KaFileSymbol::class.simpleName} should be 'null'"
}
}
containingFileSymbol !in allowedContainingFileSymbols -> {
testServices.assertions.fail {
"Invalid file for `$symbol`: Found `$containingFileSymbol`, which is not an allowed file symbol."
}
}
}
}
}
/**
* Returns the set of [KtFile]s which may contain any of the found symbols. If a symbol is not contained in one of these files, the test
* fails.
*/
open fun getAllowedContainingFiles(mainFile: KtFile, testServices: TestServices): Set<KtFile> = setOf(mainFile)
private fun RegisteredDirectives.doNotCheckSymbolRestoreDirective(): Directive? = findSpecificDirective(
commonDirective = DO_NOT_CHECK_SYMBOL_RESTORE,
k1Directive = DO_NOT_CHECK_SYMBOL_RESTORE_K1,
k2Directive = DO_NOT_CHECK_SYMBOL_RESTORE_K2,
)
private fun RegisteredDirectives.doNotCheckNonPsiSymbolRestoreDirective(): Directive? = findSpecificDirective(
commonDirective = DO_NOT_CHECK_NON_PSI_SYMBOL_RESTORE,
k1Directive = DO_NOT_CHECK_NON_PSI_SYMBOL_RESTORE_K1,
k2Directive = DO_NOT_CHECK_NON_PSI_SYMBOL_RESTORE_K2,
)
private fun compareResults(
data: SymbolPointersData,
testServices: TestServices,
disablePsiBasedLogic: Boolean,
) {
val actual = data.pointers.renderDeclarations()
compareResults(actual, testServices, disablePsiBasedLogic, extension = "txt")
val actualPretty = data.pointersForPrettyRendering.renderDeclarations()
compareResults(actualPretty, testServices, disablePsiBasedLogic, extension = "pretty.txt")
}
private fun compareResults(actual: String, testServices: TestServices, disablePsiBasedLogic: Boolean, extension: String) {
val assertions = testServices.assertions
if (!disablePsiBasedLogic) {
assertions.assertEqualsToTestDataFileSibling(actual = actual, extension = extension)
} else {
val expectedFile = getTestDataSibling(extension).toFile()
if (!assertions.doesEqualToFile(expectedFile, actual)) {
throw AssertionFailedError(
/* message = */ "Non-PSI version doesn't equal to the PSI-based variation",
/* expected = */ expectedFile.readText(),
/* actual = */ actual,
)
}
}
}
private fun List<PointerWithRenderedSymbol>.renderDeclarations(): String =
mapNotNull { it.rendered.takeIf { _ -> it.shouldBeRendered } }.renderAsDeclarations()
private fun List<String>.renderAsDeclarations(): String =
if (isEmpty()) "NO_SYMBOLS"
else joinToString(separator = "\n\n")
private fun restoreSymbolsInOtherReadActionAndCompareResults(
directiveToIgnore: Directive?,
ktFile: KtFile,
pointersWithRendered: List<PointerWithRenderedSymbol>,
testServices: TestServices,
directives: RegisteredDirectives,
disablePsiBasedLogic: Boolean,
) {
var failed = false
val restoredPointers = mutableListOf<KaSymbolPointer<*>>()
try {
val restored = analyseForTest(ktFile) {
pointersWithRendered.mapNotNull { (pointer, expectedRender, shouldBeRendered) ->
val pointer = pointer ?: error("Symbol pointer for $expectedRender was not created")
val restored = restoreSymbol(pointer, disablePsiBasedLogic) ?: error("Symbol $expectedRender was not restored")
restoredPointers += pointer
val actualRender = renderSymbolForComparison(restored, directives)
if (shouldBeRendered) {
actualRender
} else {
testServices.assertions.assertEquals(expectedRender, actualRender) { "${restored::class}" }
null
}
}
}
val actual = restored.renderAsDeclarations()
val expectedFile = getTestDataSibling().toFile()
if (!testServices.assertions.doesEqualToFile(expectedFile, actual)) {
error("Restored content is not the same. Actual:\n$actual")
}
} catch (e: Throwable) {
if (directiveToIgnore == null) throw e
failed = true
}
if (!failed) {
compareRestoredSymbols(restoredPointers, testServices, ktFile, disablePsiBasedLogic)
}
if (failed || directiveToIgnore == null) return
testServices.assertions.assertEqualsToTestDataFileSibling(
actual = ktFile.text.lines().filterNot { it == "// ${directiveToIgnore.name}" }.joinToString(separator = "\n"),
extension = ktFile.virtualFile.extension!!,
)
fail("Redundant // ${directiveToIgnore.name} directive")
}
private fun compareRestoredSymbols(
restoredPointers: List<KaSymbolPointer<*>>,
testServices: TestServices,
ktFile: KtFile,
disablePsiBasedLogic: Boolean,
) {
if (restoredPointers.isEmpty()) return
analyseForTest(ktFile) {
val symbolsToPointersMap = restoredPointers.groupByTo(mutableMapOf()) {
restoreSymbol(it, disablePsiBasedLogic) ?: error("Unexpectedly non-restored symbol pointer: ${it::class}")
}
val pointersToCheck = symbolsToPointersMap.map { (key, value) ->
value += key.createPointerForTest(disablePsiBasedLogic = disablePsiBasedLogic)
value
}
for (pointers in pointersToCheck) {
for (firstPointer in pointers) {
for (secondPointer in pointers) {
testServices.assertions.assertTrue(firstPointer.pointsToTheSameSymbolAs(secondPointer)) {
"${firstPointer::class} is not the same as ${secondPointer::class}"
}
}
}
}
}
}
protected open fun KaSession.renderSymbolForComparison(symbol: KaSymbol, directives: RegisteredDirectives): String {
val renderExpandedTypes = directives[PRETTY_RENDERER_OPTION].any { it == PrettyRendererOption.FULLY_EXPANDED_TYPES }
return with(DebugSymbolRenderer(renderExtra = true, renderExpandedTypes = renderExpandedTypes)) { render(useSiteSession, symbol) }
}
}
object SymbolTestDirectives : SimpleDirectivesContainer() {
val DO_NOT_CHECK_SYMBOL_RESTORE by directive(
description = "Symbol restoring for some symbols in current test is not supported yet",
)
val DO_NOT_CHECK_SYMBOL_RESTORE_K1 by directive(
description = "Symbol restoring for some symbols in current test is not supported yet in K1",
)
val DO_NOT_CHECK_SYMBOL_RESTORE_K2 by directive(
description = "Symbol restoring for some symbols in current test is not supported yet in K2",
)
val DO_NOT_CHECK_NON_PSI_SYMBOL_RESTORE by directive(
description = "Symbol restoring w/o psi for some symbols in current test is not supported yet",
)
val DO_NOT_CHECK_NON_PSI_SYMBOL_RESTORE_K1 by directive(
description = "Symbol restoring w/o psi for some symbols in current test is not supported yet in K1",
)
val DO_NOT_CHECK_NON_PSI_SYMBOL_RESTORE_K2 by directive(
description = "Symbol restoring w/o psi for some symbols in current test is not supported yet in K2",
)
val PRETTY_RENDERER_OPTION by enumDirective(description = "Explicit rendering mode") { PrettyRendererOption.valueOf(it) }
val TARGET_FILE_NAME by stringDirective(description = "The name of the main file")
}
enum class PrettyRendererOption(val transformation: (KaDeclarationRenderer) -> KaDeclarationRenderer) {
BODY_WITH_MEMBERS(
{ renderer ->
renderer.with {
classifierBodyRenderer = KaClassifierBodyRenderer.BODY_WITH_MEMBERS
}
}
),
FULLY_EXPANDED_TYPES(
{ renderer ->
renderer.with {
typeRenderer = typeRenderer.with {
expandedTypeRenderingMode = KaExpandedTypeRenderingMode.RENDER_EXPANDED_TYPE
functionalTypeRenderer = KaFunctionalTypeRenderer.AS_CLASS_TYPE_FOR_REFLECTION_TYPES
}
}
}
)
}
internal val KtDeclaration.isValidForSymbolCreation
get() = when (this) {
is KtBackingField -> false
is KtDestructuringDeclaration -> false
is KtPropertyAccessor -> false
is KtParameter -> !this.isFunctionTypeParameter && this.parent !is KtParameterList
is KtNamedFunction -> this.name != null
else -> true
}
data class SymbolsData(
val symbols: List<KaSymbol>,
val symbolsForPrettyRendering: List<KaSymbol> = symbols,
)
private data class SymbolPointersData(
val pointers: List<PointerWithRenderedSymbol>,
val pointersForPrettyRendering: List<PointerWithRenderedSymbol>,
)
private data class PointerWithRenderedSymbol(
val pointer: KaSymbolPointer<*>?,
val rendered: String,
val shouldBeRendered: Boolean = true,
)
private fun KaSymbol?.withImplicitSymbols(): Sequence<KaSymbol> {
val ktSymbol = this ?: return emptySequence()
return sequence {
yield(ktSymbol)
if (ktSymbol is KaDeclarationSymbol) {
for (parameter in ktSymbol.typeParameters) {
yieldAll(parameter.withImplicitSymbols())
}
}
if (ktSymbol is KaCallableSymbol) {
yieldAll(ktSymbol.receiverParameter.withImplicitSymbols())
}
if (ktSymbol is KaPropertySymbol) {
yieldAll(ktSymbol.getter.withImplicitSymbols())
yieldAll(ktSymbol.setter.withImplicitSymbols())
}
if (ktSymbol is KaFunctionSymbol) {
for (parameter in ktSymbol.valueParameters) {
yieldAll(parameter.withImplicitSymbols())
}
}
if (ktSymbol is KaValueParameterSymbol) {
yieldAll(ktSymbol.generatedPrimaryConstructorProperty.withImplicitSymbols())
}
}
}
private fun <S : KaSymbol> KaSession.restoreSymbol(pointer: KaSymbolPointer<S>, disablePsiBasedLogic: Boolean): S? {
val symbol = pointer.restoreSymbol() ?: return null
if (disablePsiBasedLogic) {
symbol.dropBackingPsi()
}
return symbol
}
private fun SymbolsData.dropBackingPsi() {
symbols.forEach(KaSymbol::dropBackingPsi)
symbolsForPrettyRendering.forEach(KaSymbol::dropBackingPsi)
}
/**
* Some K2 implementations of [KaSymbol] is backed by some [PsiElement],
* so they may implement some API on top of PSI, FirSymbols or both of them.
*
* FirSymbol-based implementation is the source of truth, so the PSI-based implementation
* exists to cover simple cases.
*
* As most of the symbols have the underlying PSI element, it is crucial to
* have consistent implementation for PSI-based and FirSymbol-based symbols.
*/
private fun KaSymbol.dropBackingPsi() {
val interfaceInstance = Class.forName("org.jetbrains.kotlin.analysis.api.fir.symbols.KaFirPsiSymbol")
val symbolType = KaSymbol::class.createType()
val thisClass = this::class
for (property in thisClass.declaredMemberProperties) {
// Some symbols may have owning symbols, so they should be invalidated as well
if (!property.name.startsWith("owning") || !property.returnType.isSubtypeOf(symbolType)) continue
val symbol = property.getter.call(this) as KaSymbol
symbol.dropBackingPsi()
}
if (!interfaceInstance.isInstance(this)) return
when (thisClass.simpleName) {
// Those classes are PSI-based only, so they have FirSymbol only for the compatibility with other classes
"KaFirPsiJavaClassSymbol",
"KaFirPsiJavaTypeParameterSymbol",
-> return
}
val property = thisClass.memberProperties.single { it.name == "backingPsi" }
val returnType = property.returnType
if (!returnType.isSubtypeOf(PsiElement::class.createType().withNullability(true))) {
error("Unexpected return type '$returnType' for '${this::class.simpleName}' class")
}
val field = property.javaField ?: error("Backing field is not found")
field.isAccessible = true
// Drop backing PSI to trigger non-psi implementation
field.set(this, null)
}
| 181 |
Kotlin
|
5748
| 49,172 |
33eb9cef3d146062c103f9853d772f0a1da0450e
| 21,719 |
kotlin
|
Apache License 2.0
|
app/src/main/java/com/utkarshsapplication/app/modules/rdviewn/data/viewmodel/RdViewNVM.kt
|
AnonymousCodes911
| 640,476,749 | false |
{"Kotlin": 99736}
|
package com.utkarshsapplication.app.modules.rdviewn.`data`.viewmodel
import android.os.Bundle
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.utkarshsapplication.app.modules.rdviewn.`data`.model.RdViewNModel
import org.koin.core.KoinComponent
class RdViewNVM : ViewModel(), KoinComponent {
val rdViewNModel: MutableLiveData<RdViewNModel> = MutableLiveData(RdViewNModel())
var navArguments: Bundle? = null
}
| 1 |
Kotlin
|
0
| 0 |
efac611ed4451f637f49608c4537e296c4d39f5e
| 455 |
Milky-Wayy
|
MIT License
|
src/test/kotlin/com/valhallagame/valhalla/recipeserviceserver/repository/RecipeRepositoryTest.kt
|
saiaku-gaming
| 148,372,560 | false | null |
package com.valhallagame.valhalla.recipeserviceserver.repository
import com.valhallagame.valhalla.recipeserviceserver.model.Recipe
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest
import org.springframework.test.context.ActiveProfiles
import org.springframework.test.context.junit.jupiter.SpringExtension
@ExtendWith(SpringExtension::class)
@DataJpaTest
@ActiveProfiles("in-memory-db", "test", "mock-client")
class RecipeRepositoryTest(@Autowired val recipeRepository: RecipeRepository) {
@Test
fun findByCharacterNameAndClaimed_ignoreUnclaimed() {
recipeRepository.save(Recipe(null, "nisse", "bed", false))
val findByCharacterNameAndClaimed = recipeRepository.findByCharacterNameAndClaimed("nisse", true)
assertThat(findByCharacterNameAndClaimed).isEmpty()
}
@Test
fun findByCharacterNameAndClaimed() {
recipeRepository.save(Recipe(null, "nisse", "bed", false))
val recipeUnclaimed = recipeRepository.findByCharacterNameAndClaimed("nisse", true)
assertThat(recipeUnclaimed).isEmpty()
val recipe = recipeRepository.findByCharacterNameAndRecipeName("nisse", "bed")
assertThat(recipe!!).isNotNull
assertThat(recipe.recipeName).isEqualTo("bed")
assertThat(recipe.characterName).isEqualTo("nisse")
recipe.claimed = true
recipeRepository.save(recipe)
val recipeClaimed = recipeRepository.findByCharacterNameAndClaimed("nisse", true)
assertThat(recipeClaimed).isNotNull
}
@Test
fun deleteByCharacterName() {
recipeRepository.save(Recipe(null, "nisse", "bed", false))
val recipeBefore = recipeRepository.findByCharacterNameAndRecipeName("nisse", "bed")!!
assertThat(recipeBefore.characterName).isEqualTo("nisse")
recipeRepository.deleteByCharacterName("nisse")
val recipeAfter = recipeRepository.findByCharacterNameAndRecipeName("nisse", "bed")
assertThat(recipeAfter).isNull()
}
}
| 0 |
Kotlin
|
0
| 0 |
9254da8dbf3f334da192eb3e56f26455909d7ef3
| 2,200 |
recipe-service-server
|
MIT License
|
src/test/kotlin/model/OrganizationTests.kt
|
ktapi
| 562,243,352 | false | null |
package model
import org.ktapi.test.DbStringSpec
import io.kotlintest.shouldBe
class OrganizationTests : DbStringSpec({
"inserting data" {
val org = Organizations.create("MyOrg")
val result = Organizations.findById(org.id)
result?.name shouldBe org.name
}
})
| 0 |
Kotlin
|
0
| 0 |
0743181261bde1f237d23deda8866d941732d6a3
| 294 |
ktapi-base
|
The Unlicense
|
app/src/main/java/com/android/saman/sample/androidmvvm/di/components/ApplicationComponent.kt
|
samesl
| 277,223,969 | false | null |
package com.android.saman.sample.androidmvvm.di.components
import com.android.saman.sample.androidmvvm.MainApplication
import com.android.saman.sample.androidmvvm.di.modules.ActivityModule
import com.android.saman.sample.androidmvvm.di.modules.ApplicationModule
import com.android.saman.sample.androidmvvm.di.modules.FragmentModule
import com.android.saman.sample.androidmvvm.di.scopes.ApplicationScope
import dagger.Component
import javax.inject.Singleton
//Sixth Step of setting up Dagger 2
@ApplicationScope
@Component(modules = [ApplicationModule::class])
interface ApplicationComponent {
fun plus(activityModule: ActivityModule) : ActivityComponent
fun plus(fragmentModule: FragmentModule) : FragmentComponent
fun inject(app: MainApplication)
}
| 1 |
Kotlin
|
1
| 0 |
d8ab01e692b285c630b5e7feca2fd01e812b3125
| 768 |
Android-MVVM
|
Apache License 2.0
|
src/main/kotlin/moe/polar/justchatting/plugins/Routing.kt
|
httpolar
| 736,405,540 | false |
{"Kotlin": 33688}
|
package moe.polar.justchatting.plugins
import io.ktor.http.HttpStatusCode
import io.ktor.server.application.Application
import io.ktor.server.application.install
import io.ktor.server.plugins.autohead.AutoHeadResponse
import io.ktor.server.plugins.doublereceive.DoubleReceive
import io.ktor.server.plugins.statuspages.StatusPages
import io.ktor.server.resources.Resources
import io.ktor.server.response.respond
import io.ktor.server.response.respondText
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.put
import moe.polar.justchatting.errors.StatusCodeError
import moe.polar.justchatting.routes.configureMessagesRoutes
import moe.polar.justchatting.routes.configureTokenRoutes
import moe.polar.justchatting.routes.configureUsersRoutes
fun Application.configureRouting() {
install(AutoHeadResponse)
install(DoubleReceive)
install(Resources)
install(StatusPages) {
exception<StatusCodeError> { call, cause ->
val body = buildJsonObject {
put("error", true)
put("message", cause.message)
}
call.respond(cause.code, body)
}
exception<Throwable> { call, cause ->
call.respondText(text = "500: $cause", status = HttpStatusCode.InternalServerError)
cause.printStackTrace()
}
}
configureUsersRoutes()
configureTokenRoutes()
configureMessagesRoutes()
}
| 0 |
Kotlin
|
0
| 0 |
d246e648f5f7140ea54e1dc75979d06ce14f6485
| 1,444 |
just-chatting-api
|
Apache License 2.0
|
app/src/main/java/com/github/wanderwise_inc/app/ui/home/SearchBar.kt
|
WanderWise-Inc
| 775,382,316 | false |
{"Kotlin": 465264}
|
package com.github.wanderwise_inc.app.ui.home
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.RangeSlider
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import com.github.wanderwise_inc.app.R
import com.github.wanderwise_inc.app.ui.TestTags
@Composable
fun SearchBar(
onSearchChange: (String) -> Unit,
onPriceChange: (Float) -> Unit,
sliderPositionPriceState: MutableState<ClosedFloatingPointRange<Float>>,
sliderPositionTimeState: MutableState<ClosedFloatingPointRange<Float>>
) {
var query by remember { mutableStateOf("") }
var isDropdownOpen by remember { mutableStateOf(false) }
OutlinedTextField(
value = query,
onValueChange = { s: String ->
query = s
onSearchChange(s)
},
placeholder = {
Text(text = "Wander where?", color = MaterialTheme.colorScheme.onPrimaryContainer)
},
leadingIcon = {
Icon(
painter = painterResource(id = R.drawable.les_controles),
contentDescription = "search icon",
tint = Color.Black,
modifier =
Modifier.clickable { isDropdownOpen = true }
.padding(2.dp)
.size(30.dp)
.testTag(TestTags.SEARCH_ICON))
},
singleLine = true,
shape = RoundedCornerShape(30.dp),
modifier =
Modifier.background(MaterialTheme.colorScheme.primaryContainer)
.fillMaxWidth()
.padding(5.dp)
.testTag(TestTags.SEARCH_BAR))
DropdownMenu(
expanded = isDropdownOpen,
onDismissRequest = { isDropdownOpen = false },
modifier = Modifier.fillMaxWidth()) {
Text("How much do I want to spend ?")
RangeSlider(
value = sliderPositionPriceState.value,
steps = 50,
onValueChange = { range -> sliderPositionPriceState.value = range },
valueRange = 0f..100f, // Adjust this range according to your needs
onValueChangeFinished = {
// launch something
},
modifier = Modifier.testTag(TestTags.FILTER_PRICE_RANGE))
Text(
text =
String.format(
"%.2f - %.2f",
sliderPositionPriceState.value.start,
sliderPositionPriceState.value.endInclusive))
// sliderPosition.contains()
Text("How Long do I want to wander ?")
RangeSlider(
value = sliderPositionTimeState.value,
steps = 24,
onValueChange = { range -> sliderPositionTimeState.value = range },
valueRange = 0f..24f, // Adjust this range according to your needs
onValueChangeFinished = {
// launch something
},
modifier = Modifier.testTag(TestTags.FILTER_TIME_RANGE))
Text(
text =
String.format(
"%.2f - %.2f",
sliderPositionTimeState.value.start,
sliderPositionTimeState.value.endInclusive))
}
}
| 23 |
Kotlin
|
0
| 1 |
ed53b045ebeee84c41ff67d73f6c8ec61e7b115e
| 4,008 |
app
|
MIT License
|
src/main/java/io/ejekta/posta/client/gui/LetterScreen.kt
|
ejektaflex
| 400,948,749 | false | null |
package io.ejekta.posta.client.gui
import io.ejekta.kambrik.KambrikHandledScreen
import io.ejekta.kambrik.ext.client.drawSimpleCenteredImage
import io.ejekta.kambrik.gui.reactor.MouseReactor
import io.ejekta.posta.PostaMod
import net.minecraft.client.util.math.MatrixStack
import net.minecraft.entity.player.PlayerInventory
import net.minecraft.screen.ScreenHandler
import net.minecraft.text.Text
import net.minecraft.util.Formatting
import net.minecraft.util.Identifier
class LetterScreen(
handler: ScreenHandler,
inventory: PlayerInventory,
title: Text
) : KambrikHandledScreen<ScreenHandler>(
handler, inventory, title
) {
init {
backgroundWidth = 176
backgroundHeight = 246
}
override fun init() {
}
override fun handledScreenTick() {
//
}
override fun onDrawBackground(matrices: MatrixStack, mouseX: Int, mouseY: Int, delta: Float) {
//TODO("Not yet implemented")
}
val textArea = KTextArea(200, 120)
val m = MouseReactor().apply {
onDragStart = { _, _ ->
println("Drag started")
}
onDragging = { x, y ->
println("Drag! $x $y $dragPos")
}
onDragModify = { x, y ->
x to 0
}
onDragEnd = { _, _ ->
println("Drag ended")
}
}
val fgGui = kambrikGui {
offset(10, 10) {
offset(m.dragPos.first, m.dragPos.second) {
area(25, 25) {
rect(Formatting.RED.colorValue!!)
reactWith(m)
}
}
}
offset(100, 100) {
widget(textArea)
}
}
override fun onDrawForeground(matrices: MatrixStack, mouseX: Int, mouseY: Int, delta: Float) {
fgGui.draw(matrices, mouseX, mouseY, delta)
}
override fun drawBackground(matrices: MatrixStack, delta: Float, mouseX: Int, mouseY: Int) {
drawSimpleCenteredImage(matrices, TEXTURE, backgroundWidth, backgroundHeight)
}
override fun render(matrices: MatrixStack, mouseX: Int, mouseY: Int, delta: Float) {
super.render(matrices, mouseX, mouseY, delta)
//textTwo.render(matrices, mouseX, mouseY, delta)
}
companion object {
private val TEXTURE = Identifier(PostaMod.ID, "textures/letter_bg.png")
}
}
| 0 |
Kotlin
|
0
| 0 |
e12489b11a37901139f5cc5e286232ee95317ae8
| 2,352 |
Posta
|
MIT License
|
app/src/main/java/com/eatssu/android/ui/main/calendar/CalendarAdapter.kt
|
EAT-SSU
| 601,871,281 | false |
{"Kotlin": 160327}
|
package com.eatssu.android.ui.main.calendar
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.eatssu.android.R
import com.eatssu.android.databinding.ItemCalendarListBinding
import com.eatssu.android.util.CalendarUtils
import java.time.LocalDate
import java.util.*
internal class CalendarAdapter(
private val days: ArrayList<LocalDate>,
private val onItemListener: OnItemListener
) :
RecyclerView.Adapter<CalendarViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CalendarViewHolder {
val binding =
ItemCalendarListBinding.inflate(LayoutInflater.from(parent.context), parent, false)
val inflater = LayoutInflater.from(parent.context)
val view: View = inflater.inflate(R.layout.item_calendar_list, parent, false)
val layoutParams = view.layoutParams
layoutParams.height = parent.height
return CalendarViewHolder(binding, view, onItemListener, days)
}
@RequiresApi(Build.VERSION_CODES.O)
override fun onBindViewHolder(holder: CalendarViewHolder, position: Int) {
val date = days[position]
holder.dayOfMonth.text = date.dayOfMonth.toString()
if (date == CalendarUtils.selectedDate) {
holder.parentView.setBackgroundResource(R.drawable.selector_background_blue)
holder.dayOfMonth.setTextColor(ContextCompat.getColor(holder.itemView.context, R.color.selector_calendar_colortext))
}
else {
holder.parentView.setBackgroundResource(R.drawable.ic_selector_background_white)
}
}
override fun getItemCount(): Int {
return days.size
}
interface OnItemListener {
fun onItemClick(position: Int, date: LocalDate?)
}
}
| 9 |
Kotlin
|
0
| 2 |
0a857abe5397b34e9bca620f2c5f9e20e1be1df6
| 1,956 |
EatSSU-Android
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.