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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/example/templatebottomnavmenu/ui/notifications/NotificationsFragment.kt | pavvel42 | 247,255,932 | false | null | package com.example.templatebottomnavmenu.ui.notifications
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.templatebottomnavmenu.R
class NotificationsFragment : Fragment() {
private val TAG = NotificationsFragment::class.java.simpleName
private lateinit var notificationsViewModel: NotificationsViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
notificationsViewModel = ViewModelProvider(this).get(NotificationsViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_notifications, container, false)
val textView: TextView = root.findViewById(R.id.text_notifications)
notificationsViewModel.text.observe(viewLifecycleOwner, Observer {
textView.text = it
})
return root
}
}
| 0 | Kotlin | 0 | 2 | 207f3c8f9cacb2ba4e7c65a571b5eed0e29c9e66 | 1,073 | TemplateBottomNavigationBar | MIT License |
app/src/main/java/com/payamgr/wordchest/ui/MainActivity.kt | PayamGerackoohi | 715,554,365 | false | {"Kotlin": 197501} | package com.payamgr.wordchest.ui
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import androidx.lifecycle.lifecycleScope
import androidx.navigation.compose.rememberNavController
import com.airbnb.mvrx.Mavericks
import com.payamgr.wordchest.data.WordRepository
import com.payamgr.wordchest.ui.theme.WordChestTheme
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : ComponentActivity() {
@Inject
lateinit var repository: WordRepository
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Mavericks.initialize(this)
setContent {
WordChestTheme {
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
AppNav.Host(
navController = rememberNavController(),
push = { key -> lifecycleScope.launch { repository.push(key) } },
)
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 74a48021fcec63e0431c6cfff9e755234f121dfe | 1,336 | Word-Chest | MIT License |
kevent/src/main/java/io/github/janbarari/kevent/Observer.kt | janbarari | 258,434,229 | false | null | package io.github.janbarari.kevent
class Observer(
var observerType: Class<*>,
var guid: String,
var unit: (Any) -> Unit,
var sender: Class<*>? = null) {
override fun toString(): String {
return "Subscriber($guid, ${observerType::class.java.name})"
}
} | 0 | Kotlin | 5 | 89 | 8d8a339148b1bf44caf9a771ab1f087f2e63c912 | 286 | KEvent | Apache License 2.0 |
antlr-kotlin-runtime/src/commonTest/kotlin/StringTest.kt | Strumenta | 145,450,730 | false | {"Kotlin": 906270, "ANTLR": 3893} | import kotlin.test.Test
class StringTest : BaseTest() {
@Test
fun testAsCharArrayEmpty() {
assertArrayEquals(charArrayOf(), "".toCharArray())
}
@Test
fun testAsCharArrayEmptyLength() {
assertEquals(0, "".toCharArray().size)
}
@Test
fun testAsCharArrayEmptyEl0() {
assertEquals('a', "abc def".toCharArray()[0])
}
@Test
fun testAsCharArray() {
assertArrayEquals(charArrayOf('a', 'b', 'c', ' ', 'd', 'e', 'f'), "abc def".toCharArray())
}
}
| 30 | Kotlin | 46 | 181 | 04d77aa796c4a927a4cda29cc1afa58d8da8aa86 | 481 | antlr-kotlin | Apache License 2.0 |
app/src/main/kotlin/com/adriangl/pict2cam/ui/theme/Theme.kt | adriangl | 226,981,977 | false | null | package com.adriangl.pict2cam.ui.theme
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material.MaterialTheme
import androidx.compose.material.darkColors
import androidx.compose.material.lightColors
import androidx.compose.runtime.Composable
import androidx.compose.ui.graphics.Color
private val DarkColorPalette = darkColors(
primary = primaryColor,
primaryVariant = primaryVariantDark,
secondary = secondaryColor,
secondaryVariant = secondaryVariantDark,
background = Color.Black,
surface = Color.Black,
error = Color.Red,
onPrimary = Color.Black,
onSecondary = Color.White,
onBackground = Color.White,
onSurface = Color.White,
onError = Color.Black,
)
private val LightColorPalette = lightColors(
primary = primaryColor,
primaryVariant = primaryVariantLight,
secondary = secondaryColor,
secondaryVariant = secondaryVariantLight,
background = Color.White,
surface = Color.White,
error = Color.Red,
onPrimary = Color.White,
onSecondary = Color.Black,
onBackground = Color.Black,
onSurface = Color.Black,
onError = Color.White,
)
/**
* Main theme of the application.
*/
@Composable
fun Pict2CamTheme(darkTheme: Boolean = isSystemInDarkTheme(),
content: @Composable () -> Unit) {
val colors = if (darkTheme) {
DarkColorPalette
} else {
LightColorPalette
}
MaterialTheme(
colors = colors,
typography = Pict2CamTypography,
shapes = Shapes,
content = content
)
}
| 12 | Kotlin | 13 | 94 | aaaedca813630281fdc48e5b4c998fe6020858ae | 1,579 | pict2cam | Apache License 2.0 |
cupertino-icons-extended/src/commonMain/kotlin/io/github/alexzhirkevich/cupertino/icons/filled/HeartSlash.kt | alexzhirkevich | 636,411,288 | false | {"Kotlin": 4456601, "Ruby": 2310, "Swift": 2101, "Shell": 856, "HTML": 762} | package io.github.alexzhirkevich.cupertino.icons.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.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.path
import androidx.compose.ui.unit.dp
import io.github.alexzhirkevich.cupertino.icons.CupertinoIcons
public val CupertinoIcons.Filled.HeartSlash: ImageVector
get() {
if (_heartSlash != null) {
return _heartSlash!!
}
_heartSlash = Builder(name = "HeartSlash", defaultWidth = 24.3604.dp, defaultHeight =
24.1172.dp, viewportWidth = 24.3604f, viewportHeight = 24.1172f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(20.4463f, 17.2559f)
curveTo(22.9424f, 14.5137f, 24.3604f, 11.6426f, 24.3604f, 8.7363f)
curveTo(24.3604f, 4.5879f, 21.5127f, 1.6582f, 17.833f, 1.6582f)
curveTo(15.5479f, 1.6582f, 13.79f, 2.9238f, 12.7236f, 4.8574f)
curveTo(11.6807f, 2.9355f, 9.8994f, 1.6582f, 7.6143f, 1.6582f)
curveTo(6.794f, 1.6582f, 6.0088f, 1.7988f, 5.3057f, 2.0801f)
close()
moveTo(17.0947f, 20.3496f)
lineTo(1.9307f, 5.1738f)
curveTo(1.3916f, 6.1934f, 1.0869f, 7.4004f, 1.0869f, 8.7363f)
curveTo(1.0869f, 13.7285f, 5.2705f, 18.6387f, 11.8799f, 22.8574f)
curveTo(12.126f, 23.0098f, 12.4775f, 23.1738f, 12.7236f, 23.1738f)
curveTo(12.9697f, 23.1738f, 13.3213f, 23.0098f, 13.5791f, 22.8574f)
curveTo(14.833f, 22.0488f, 16.0166f, 21.2051f, 17.0947f, 20.3496f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.4072f, 22.6699f)
curveTo(21.7588f, 23.0332f, 22.3447f, 23.0332f, 22.6846f, 22.6699f)
curveTo(23.0244f, 22.3184f, 23.0361f, 21.7559f, 22.6846f, 21.3926f)
lineTo(1.5439f, 0.2637f)
curveTo(1.1924f, -0.0879f, 0.6064f, -0.0879f, 0.2549f, 0.2637f)
curveTo(-0.085f, 0.6035f, -0.085f, 1.2012f, 0.2549f, 1.541f)
close()
}
}
.build()
return _heartSlash!!
}
private var _heartSlash: ImageVector? = null
| 1 | Kotlin | 14 | 362 | 60fd9234eb9f2df97bc8523ea2ed344ad7f58655 | 3,086 | compose-cupertino | Apache License 2.0 |
src/main/kotlin/kjkrol/eshop/exposedcontent/castentry/CastEntryCreator.kt | freeKotlin | 356,209,177 | true | {"Kotlin": 13598, "Java": 6127} | package kjkrol.eshop.exposedcontent.castentry
import kjkrol.eshop.exposedcontent.model.CastEntry
import kjkrol.eshop.exposedcontent.model.Character
import kjkrol.eshop.exposedcontent.model.Person
import org.springframework.stereotype.Service
import java.util.UUID
@Service
internal class CastEntryCreator(val castEntryRepository: CastEntryRepository) {
fun create(person: Person,
character: Character): CastEntry {
val castEntry = CastEntry(UUID.randomUUID().toString(), person, character)
castEntryRepository.save(castEntry)
return castEntry
}
} | 0 | null | 0 | 0 | 9350261c26162c83d94f202d2569c4dc560a6cfd | 596 | exposed-content-service | MIT License |
game/plugins/src/main/kotlin/gg/rsmod/plugins/content/mechanics/equipment/equipment.plugin.kts | 2011Scape | 578,880,245 | false | null | package gg.rsmod.plugins.content.mechanics.equipment
import gg.rsmod.game.action.EquipAction
val EQUIP_ITEM_SOUND = 2238
fun bind_unequip(equipment: EquipmentType, child: Int) {
on_button(interfaceId = 387, component = child) {
val opt = player.getInteractingOpcode()
when (opt) {
61 -> {
val result = EquipAction.unequip(player, equipment.id)
if (equipment == EquipmentType.WEAPON && result == EquipAction.Result.SUCCESS) {
player.sendWeaponComponentInformation()
}
}
25 -> {
val item = player.equipment[equipment.id] ?: return@on_button
world.sendExamine(player, item.id, ExamineEntityType.ITEM)
}
else -> {
val item = player.equipment[equipment.id] ?: return@on_button
val menuOpt = opt - 1
if (!world.plugins.executeEquipmentOption(player, item.id, menuOpt) && world.devContext.debugItemActions) {
val action = item.getDef(world.definitions).equipmentMenu[menuOpt - 1]
player.message("Unhandled equipment action: [item=${item.id}, option=$menuOpt, action=$action]")
}
}
}
}
}
for (equipment in EquipmentType.values) {
on_equip_to_slot(equipment.id) {
player.playSound(EQUIP_ITEM_SOUND)
if (equipment == EquipmentType.WEAPON) {
player.sendWeaponComponentInformation()
}
}
}
bind_unequip(EquipmentType.HEAD, child = 8)
bind_unequip(EquipmentType.CAPE, child = 11)
bind_unequip(EquipmentType.AMULET, child = 14)
bind_unequip(EquipmentType.AMMO, child = 38)
bind_unequip(EquipmentType.WEAPON, child = 17)
bind_unequip(EquipmentType.CHEST, child = 20)
bind_unequip(EquipmentType.SHIELD, child = 23)
bind_unequip(EquipmentType.LEGS, child = 26)
bind_unequip(EquipmentType.GLOVES, child = 29)
bind_unequip(EquipmentType.BOOTS, child = 32)
bind_unequip(EquipmentType.RING, child = 35) | 5 | Kotlin | 8 | 13 | 11ae0b9d6f49e6580119f6f7803a01edc6673a5a | 2,041 | tek5-game | Apache License 2.0 |
feature/lists/src/main/java/com/azhapps/listapp/lists/modify/uc/GetItemCategoriesUseCase.kt | Azhrei251 | 539,352,238 | false | {"Kotlin": 239334} | package com.azhapps.listapp.lists.modify.uc
import com.azhapps.listapp.lists.data.ListsRemoteDataSource
import com.azhapps.listapp.network.Api
import com.azhapps.listapp.network.Api.callApi
import javax.inject.Inject
class GetItemCategoriesUseCase @Inject constructor(
private val remoteDataSource: ListsRemoteDataSource
) {
suspend operator fun invoke() = callApi {
remoteDataSource.getItemCategories()
}
} | 5 | Kotlin | 0 | 1 | 317804ec4047ebe3c68b29ef344d4a2e1f1010ae | 429 | list-app | MIT License |
src/main/kotlin/br/com/lucascm/mangaeasy/micro_api_monolito/features/recommendations/repositories/BucketRecommendationsRepository.kt | manga-easy | 627,169,031 | false | {"Kotlin": 154749, "Dockerfile": 912} | package br.com.lucascm.mangaeasy.micro_api_monolito.features.recommendations.repositories
import br.com.lucascm.mangaeasy.micro_api_monolito.core.entities.BusinessException
import com.oracle.bmc.ConfigFileReader
import com.oracle.bmc.auth.ConfigFileAuthenticationDetailsProvider
import com.oracle.bmc.objectstorage.ObjectStorage
import com.oracle.bmc.objectstorage.ObjectStorageClient
import com.oracle.bmc.objectstorage.requests.DeleteObjectRequest
import com.oracle.bmc.objectstorage.requests.PutObjectRequest
import org.springframework.stereotype.Repository
import org.springframework.web.multipart.MultipartFile
import java.io.InputStream
const val namespaceName = "axs7rpnviwd0"
const val bucketName = "manga-easy-banners"
const val LIMIT_FILE_SIZE_RECOMMENDATION = 2000000
val TYPE_CONTENT_IMAGE = listOf("JPG", "GIF", "PNG", "JPEG")
@Repository
class BucketRecommendationsRepository {
fun saveImage(uniqueId: String, file: MultipartFile, contentType: String) {
validateImage(file)
val configuration = getObjectStorage()
val inputStream: InputStream = file.inputStream
//build upload request
val putObjectRequest: PutObjectRequest = PutObjectRequest.builder()
.namespaceName(namespaceName)
.bucketName(bucketName)
.objectName(uniqueId)
.contentLength(file.size)
.contentType(contentType)
.putObjectBody(inputStream)
.build()
//upload the file
try {
configuration.putObject(putObjectRequest)
} catch (e: Exception) {
e.printStackTrace()
throw e
} finally {
file.inputStream.close()
configuration.close()
}
}
fun getLinkImage(uniqueId: String): String {
val configuration = getObjectStorage()
try {
// Construa a URL base do serviço Object Storage
val baseUrl = configuration.endpoint
// Combinar a URL base e a URL do objeto para obter o link final
return "${baseUrl}/n/${namespaceName}/b/${bucketName}/o/${uniqueId}"
} catch (e: Exception) {
e.printStackTrace()
throw e
} finally {
configuration.close()
}
}
private fun getObjectStorage(): ObjectStorage {
//load config file
val configFile: ConfigFileReader.ConfigFile = ConfigFileReader
.parse("src/main/resources/config", "DEFAULT")//OracleIdentityCloudService
val provider = ConfigFileAuthenticationDetailsProvider(configFile)
//build and return client
return ObjectStorageClient.builder()
.isStreamWarningEnabled(false)
.build(provider)
}
fun deleteImage(uniqueId: String) {
val configuration = getObjectStorage()
//build upload request
val putObjectRequest: DeleteObjectRequest = DeleteObjectRequest.builder()
.namespaceName(namespaceName)
.bucketName(bucketName)
.objectName(uniqueId)
.build()
//upload the file
try {
configuration.deleteObject(putObjectRequest)
} catch (e: Exception) {
e.printStackTrace()
throw e
} finally {
configuration.close()
}
}
private fun validateImage(file: MultipartFile) {
val limit = LIMIT_FILE_SIZE_RECOMMENDATION
if (file.size > limit) throw BusinessException("Imagem maior que o permitido: ${limit.toString()[0]}mb")
val typeImage = file.contentType!!.replace("image/", "").uppercase()
if (!TYPE_CONTENT_IMAGE.contains(typeImage)) throw BusinessException("Tipo de arquivo não permitido.")
}
} | 0 | Kotlin | 1 | 2 | f60a56ce888bb51d4bbf0d8b6ec1248ffd124dd5 | 3,752 | manga_easy_micro_api_monolito | MIT License |
src/main/kotlin/idea/snakeskin/lang/parser/SnakeskinParserDefinition.kt | ExactlyNoSense | 174,437,527 | false | {"Lex": 24166, "Kotlin": 15376, "Scheme": 1340} | package idea.snakeskin.lang.parser
import com.intellij.lang.ASTNode
import com.intellij.lang.ParserDefinition
import com.intellij.lang.PsiParser
import com.intellij.lexer.Lexer
import com.intellij.openapi.project.Project
import com.intellij.psi.FileViewProvider
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.tree.IFileElementType
import com.intellij.psi.tree.TokenSet
import com.intellij.psi.TokenType.WHITE_SPACE
import idea.snakeskin.lang.SsLanguage
import idea.snakeskin.lang.lexer.SsLexer
import idea.snakeskin.lang.psi.SsElementTypes
import idea.snakeskin.lang.psi.SsElementTypes.COMMENT_BLOCK
import idea.snakeskin.lang.psi.SsElementTypes.STRING_LITERAL
import idea.snakeskin.lang.psi.SsElementTypes.ML_OPEN
import idea.snakeskin.lang.psi.SsElementTypes.ML_CLOSE
import idea.snakeskin.lang.psi.SsFile
class SnakeskinParserDefinition : ParserDefinition {
companion object {
val FILE = IFileElementType(SsLanguage.INSTANCE)
}
override fun createFile(viewProvider: FileViewProvider): PsiFile = SsFile(viewProvider)
override fun getStringLiteralElements(): TokenSet = TokenSet.create(STRING_LITERAL)
override fun getFileNodeType(): IFileElementType = FILE
override fun createLexer(project: Project?): Lexer = SsLexer(false)
override fun createElement(node: ASTNode?): PsiElement = SsElementTypes.Factory.createElement(node)
override fun getCommentTokens(): TokenSet = TokenSet.create(COMMENT_BLOCK)
override fun getWhitespaceTokens(): TokenSet = TokenSet.create(WHITE_SPACE, ML_OPEN, ML_CLOSE)
override fun createParser(project: Project?): PsiParser = SnakeskinParser()
}
| 0 | Lex | 0 | 2 | 9bb2738cb96423a8926283b5b15b2c977541846a | 1,641 | snake-eater | MIT License |
app/src/main/java/kr/co/login/RingtonePlayingService.kt | hanjaegyeong | 531,970,021 | false | {"Kotlin": 82539} | package kr.co.login
import android.R
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Context
import android.content.Intent
import android.media.MediaPlayer
import android.os.Build
import android.os.IBinder
import android.util.Log
import androidx.annotation.Nullable
import androidx.core.app.NotificationCompat
class RingtonePlayingService : Service() {
var mediaPlayer: MediaPlayer? = null
var startId = 0
var isRunning = false
@Nullable
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onCreate() {
super.onCreate()
if (Build.VERSION.SDK_INT >= 26) {
val CHANNEL_ID = "default"
val channel = NotificationChannel(
CHANNEL_ID,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT
)
(getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager).createNotificationChannel(
channel
)
val notification: Notification = NotificationCompat.Builder(this, CHANNEL_ID)
.setContentTitle("알람시작")
.setContentText("알람음이 재생됩니다.")
.setSmallIcon(R.drawable.ic_btn_speak_now)
.build()
startForeground(1, notification)
}
}
override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int {
var startId = startId
val getState = intent.extras!!.getString("state")!!
startId = when (getState) {
"alarm on" -> 1
"alarm off" -> 0
else -> 0
}
// 알람음 재생 X , 알람음 시작 클릭
if (!isRunning && startId == 1) {
mediaPlayer = MediaPlayer.create(this, R.drawable.alert_dark_frame)
mediaPlayer!!.start()
isRunning = true
this.startId = 0
} else if (isRunning && startId == 0) {
mediaPlayer!!.stop()
mediaPlayer!!.reset()
mediaPlayer!!.release()
isRunning = false
this.startId = 0
} else if (!isRunning && startId == 0) {
isRunning = false
this.startId = 0
} else if (isRunning && startId == 1) {
isRunning = true
this.startId = 1
} else {
}
return START_NOT_STICKY
}
override fun onDestroy() {
super.onDestroy()
Log.d("onDestory() 실행", "서비스 파괴")
}
} | 0 | Kotlin | 0 | 0 | 5ecba6cf91e79e3135bc4d174d74da5848ff8dce | 2,590 | National-defense-App | MIT License |
library/src/main/java/com/bluesir9/asutil/library/core/coroutines/DefaultDispatcherProvider.kt | Bluesir9 | 235,258,656 | false | null | package com.bluesir9.asutil.library.core.coroutines
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
val defaultDispatcherProvider = object : DispatcherProvider {
override val main: CoroutineDispatcher = Dispatchers.Main
override val presenter: CoroutineDispatcher = Dispatchers.Default
override val io: CoroutineDispatcher = Dispatchers.IO
} | 0 | Kotlin | 0 | 0 | c555e4c87afab660ec06ac8a3c150dacf743473b | 385 | asutil | MIT License |
client-android/lib/src/main/kotlin/stasis/client_android/lib/encryption/secrets/UserPassword.kt | sndnv | 153,169,374 | false | {"Scala": 3373826, "Kotlin": 1821771, "Dart": 853650, "Python": 363474, "Shell": 70265, "CMake": 8759, "C++": 4051, "HTML": 2655, "Dockerfile": 1942, "Ruby": 1330, "C": 691, "Swift": 594, "JavaScript": 516} | package stasis.client_android.lib.encryption.secrets
import okio.ByteString
import okio.ByteString.Companion.toByteString
import stasis.client_android.lib.model.server.users.UserId
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.PBEKeySpec
data class UserPassword(
val user: UserId,
val salt: String,
private val password: CharArray,
val target: Config
) : Secret() {
fun toAuthenticationPassword(): UserAuthenticationPassword =
if (target.derivation.authentication.enabled) {
UserAuthenticationPassword.Hashed(
user = user,
hashedPassword = derivePassword(
password = <PASSWORD>,
salt = "${target.derivation.authentication.saltPrefix}-authentication-$salt",
iterations = target.derivation.authentication.iterations,
derivedKeySize = target.derivation.authentication.secretSize
)
)
} else {
UserAuthenticationPassword.Unhashed(
user = user,
rawPassword = String(password).toByteArray().toByteString()
)
}
fun toHashedEncryptionPassword(): UserHashedEncryptionPassword =
UserHashedEncryptionPassword(
user = user,
hashedPassword = derivePassword(
password = <PASSWORD>,
salt = "${target.derivation.encryption.saltPrefix}-encryption-$salt",
iterations = target.derivation.encryption.iterations,
derivedKeySize = target.derivation.encryption.secretSize
),
target = target
)
companion object {
object Defaults {
val Charset: Charset = StandardCharsets.UTF_8
const val Algorithm: String = "PBKDF2WithHmacSHA512"
}
private const val Bytes: Int = 8
fun derivePassword(
password: CharArray,
salt: String,
iterations: Int,
derivedKeySize: Int
): ByteString {
val spec = PBEKeySpec(
password,
salt.toByteArray(Defaults.Charset),
iterations,
derivedKeySize * Bytes
)
val derivedPassword = SecretKeyFactory
.getInstance(Defaults.Algorithm)
.generateSecret(spec)
.encoded
return derivedPassword.toByteString()
}
}
}
| 0 | Scala | 4 | 53 | d7b3002880814039b332b3d5373a16b57637eb1e | 2,570 | stasis | Apache License 2.0 |
sample/app/src/main/java/dev/tuongnt/tinder/presentation/ui/home/HomeViewModel.kt | alanrb | 296,359,249 | false | null | package dev.tuongnt.tinder.presentation.ui.home
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import dev.tuongnt.tinder.domain.Result
import dev.tuongnt.tinder.domain.model.UserModel
import dev.tuongnt.tinder.domain.usecase.RandomUserUseCase
import dev.tuongnt.tinder.domain.usecase.SaveFavouriteUserUseCase
import dev.tuongnt.tinder.domain.usecase.UseCase
import dev.tuongnt.tinder.presentation.common.BaseViewModel
import dev.tuongnt.tinder.presentation.common.SingleLiveEvent
import dev.tuongnt.tinder.presentation.extension.coSwitchMap
class HomeViewModel(
private val randomUserUseCase: RandomUserUseCase,
private val favouriteUserUseCase: SaveFavouriteUserUseCase
) : BaseViewModel() {
private val favouriteInvoker = MutableLiveData<UserModel>()
private val randomInvoker = SingleLiveEvent<Any>()
val randomUserResult = randomInvoker.coSwitchMap(Result.Loading) {
randomUserUseCase.invoke(viewModelScope, UseCase.None())
}
val favouriteResult = favouriteInvoker.coSwitchMap(Result.Loading) {
favouriteUserUseCase.invoke(viewModelScope, it)
}
fun randomUser() {
randomInvoker.call()
}
fun addFavourite(userModel: UserModel) {
favouriteInvoker.value = userModel
}
} | 0 | null | 0 | 0 | 4b70d16f40078747704a263b140f31fae03a5ce8 | 1,293 | Android-motion-layout | Apache License 2.0 |
SVG2ShapeShifter/src/main/kotlin/MergeShapeShifter.kt | jwill | 139,189,280 | false | {"Kotlin": 29211} | import groovy.json.JsonGenerator
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import groovyjarjarcommonscli.DefaultParser
import groovyjarjarcommonscli.HelpFormatter
import groovyjarjarcommonscli.Options
import java.io.File
import java.sql.Time
import java.util.*
fun main(args: Array<String>) {
// Call the converter from IDEA
//ConvertSVG().renderFile("examples/example.svg")
// Use from the commandline
MergeShapeShifter().merge(arrayOf("tree-base.shapeshifter", "tree-lights.shapeshifter"), "tree-all.shapeshifter")
//MergeShapeShifter().merge(args)
}
class MergeShapeShifter() {
var frameInterval = 5
var timeInterval = 50
var startId = 200
fun findReferencedPaths(oldId:String, newId:String, list:ArrayList<TimelineBlock>) {
//println()
println("Changing refs from oldId ${oldId} to ${newId}")
val foundIds = list.filter { it.layerId == oldId }
foundIds.forEach { it.layerId = newId }
}
fun walkIds(child:PathPrimitive, timelineBlocks: ArrayList<TimelineBlock>) {
val oldId = child.id
child.id = nextId().toString()
when (child) {
is Group -> {
findReferencedPaths(oldId, child.id, timelineBlocks)
if (child.children.isNotEmpty()) {
child.children.forEach { walkIds(it, timelineBlocks) }
}
}
is Path -> {
println(child.id)
findReferencedPaths(oldId, child.id, timelineBlocks)
}
}
}
fun merge(filenames: Array<String>, outFile:String) {
val outputFile = File(outFile)
val groups = arrayListOf<Group>()
val animationBlocks = arrayListOf<TimelineBlock>()
// Create skeleton file
var width: Int = -1
var height: Int = -1
var duration: Int = -1
val pathIdMap = mapOf<String, String>()
for (i in filenames) {
val file = File(i)
val f = JsonSlurper().parse(file)
val json: Map<Any, Any> = f as Map<Any, Any>
val layers = json["layers"] as Map<Any, Any>
// parse vector layer
val vectorLayer = Layer.parse(layers["vectorLayer"] as Map<Any, Any>)
vectorLayer.id = nextId().toString()
if (width == -1) {
width = vectorLayer.width
height = vectorLayer.height
}
// Use filename as group name
val groupId = vectorLayer.id
val groupName = file.name.removeSuffix(".shapeshifter").replace("-","_")
val vectorChildren = vectorLayer.children
println(vectorChildren.size)
// Append them into a new group
var group = Group(
id = groupId,
name = groupName,
children = vectorChildren
)
groups.add(group)
// Grab the animations
val timeline = json["timeline"] as Map<*, *>
val animation = AnimationTimeline.parse(timeline["animation"] as Map<*, *>)
animationBlocks.addAll(animation.blocks)
// for each group
// check timeline events for that original id
// update group id and layerId in each timeline event
// if group has children do the same
for (child: PathPrimitive in vectorLayer.children) {
//walkIds(child,animation.blocks as ArrayList<TimelineBlock>)
}
}
// walk tree and reassign ids
// for (i in animationBlocks) {
// i.id = nextId().toString()
// }
val layer = Layer(
id = nextId().toString(),
name = "vector",
width = width,
height = height,
children = groups
)
val animationTimeline = AnimationTimeline(
id = nextId().toString(), // Dummy id --- probably need to fix this later
duration = duration,
blocks = animationBlocks as List<TimelineBlock>
)
animationTimeline.fixDuration()
val jsonObject = mapOf(
"version" to 1,
"generatedby" to "GH:/jwill/android-avd-tools",
"layers" to layersToJSON(layer),
timelineToJSON(animationTimeline)
)
val customJsonOutput = JsonGenerator.Options().excludeNulls().build()
val o = customJsonOutput.toJson(jsonObject)
outputFile.writeText(JsonOutput.prettyPrint(o))
}
fun nextId() : Int {
return startId++
}
constructor(args: Array<String>) : this() {
val parser = DefaultParser()
val options = Options()
with(options) {
addOption("h", "help", false, "Print this help message")
addOption("time", "timeInterval", true, "Sets the time interval between keyframes for animations [in 1/100th of seconds]\nDefault: 20")
addOption("frame", "frameInterval", true, "Sets the number of frames to skip between keyframes when exporting.\n Default: 5")
addOption("f", "file", true, "File to convert")
}
val cmd = parser.parse(options, args)
val formatter = HelpFormatter()
if (cmd.hasOption("time")) {
val time = cmd.getOptionValue("time").toInt()
if (time > 0) timeInterval = time
}
if (cmd.hasOption("frame")) {
val frame = cmd.getOptionValue("frame").toInt()
if (frame > 0) frameInterval = frame
}
if (!cmd.hasOption("file")) {
println("You need to specify a file.")
formatter.printHelp("SVG2ShapeShifter", options)
} else {
//renderFile(cmd.getOptionValue("file"))
}
}
fun layersToJSON(layer: Layer): Map<Any, Any> {
return mapOf(
"vectorLayer" to layer
)
}
// Dupe from ConvertSVG
fun timelineToJSON(animation: AnimationTimeline): Pair<Any, Any> {
return Pair(
"timeline", mapOf(
"animation" to animation
)
)
}
}
| 1 | Kotlin | 2 | 4 | 462b9d00b52847e26100a1f862b4dd75453d8e2c | 6,269 | android-avd-tools | Apache License 2.0 |
app/src/main/java/com/realtomjoney/pyxlmoose/activities/canvas/CanvasActivity+getCoverImageBitmap.kt | realtomjoney | 419,545,692 | false | null | package com.realtomjoney.pyxlmoose.activities.canvas
import android.graphics.Bitmap
import android.graphics.Matrix
import androidx.core.view.drawToBitmap
fun getCoverImageBitmap(): Bitmap {
val bmp = outerCanvasInstance.fragmentHost.drawToBitmap()
val bmps: Bitmap?
val matrix = Matrix()
matrix.setRotate(outerCanvasInstance.getCurrentRotation())
bmps = Bitmap.createBitmap(bmp, 0, 0, bmp.width, bmp.width, matrix, false)
return bmps
} | 15 | Kotlin | 2 | 30 | ecea3c6d807483c31fa61fbf8d127e9ed92d1258 | 464 | PyxlMoose | MIT License |
reaktive/src/commonMain/kotlin/com/badoo/reaktive/utils/ThreadLocalStorage.kt | fr0l | 234,538,666 | true | {"Kotlin": 1087234, "Swift": 6264, "HTML": 1109, "Ruby": 150} | package com.badoo.reaktive.utils
import com.badoo.reaktive.disposable.Disposable
@Deprecated(
message = "Use ThreadLocalHolder from 'utils' package. This class will be removed soon.",
replaceWith = ReplaceWith("ThreadLocalHolder", "com.badoo.reaktive.utils.ThreadLocalHolder"),
level = DeprecationLevel.WARNING
)
open class ThreadLocalStorage<T : Any>(initialValue: T? = null) : ThreadLocalHolder<T>(initialValue), Disposable
| 0 | null | 0 | 0 | 5ec83b4244e25783fc70b50b547212c12b40cefc | 440 | Reaktive | Apache License 2.0 |
app/src/main/java/com/superChargedFitness/utils/CommonConstantAd.kt | praiseOjay | 870,257,631 | false | {"Kotlin": 186163, "Java": 99397, "AIDL": 17871} | package com.superChargedFitness.utils
import android.app.Activity
import android.content.Context
import android.util.Log
import android.view.View
import android.widget.LinearLayout
import android.widget.RelativeLayout
import com.facebook.ads.Ad
import com.facebook.ads.InterstitialAdListener
import com.google.android.ads.nativetemplates.TemplateView
import com.google.android.gms.ads.*
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import com.superChargedFitness.interfaces.AdsCallback
object CommonConstantAd {
private fun getAdRequest(): AdRequest {
return AdRequest.Builder().build()
}
fun loadNativeAd(context: Context, templateView: TemplateView,isViewInvisible:Boolean = false) {
if (com.superChargedFitness.utils.Utils.getPref(context, ConstantString.AD_TYPE_FB_GOOGLE, "") == ConstantString.AD_GOOGLE &&
com.superChargedFitness.utils.Utils.getPref(context, ConstantString.STATUS_ENABLE_DISABLE, "") == ConstantString.ENABLE
) {
val adLoader: AdLoader =
AdLoader.Builder(context, com.superChargedFitness.utils.Utils.getPref(context, ConstantString.GOOGLE_NATIVE, ""))
.withAdListener(object :AdListener(){
override fun onAdFailedToLoad(p0: LoadAdError) {
templateView.visibility = View.GONE
if (isViewInvisible){
templateView.visibility = View.INVISIBLE
}
Log.e("TAG", "onAdFailedToLoad:::Native Ad==>>>> "+p0.message.toString() )
}
override fun onAdLoaded() {
super.onAdLoaded()
templateView.visibility = View.VISIBLE
}
})
.forNativeAd { nativeAd ->
templateView.visibility = View.VISIBLE
templateView.setNativeAd(nativeAd)
}
.build()
adLoader.loadAd(AdRequest.Builder().build())
} else {
templateView.visibility = View.GONE
}
}
var mInterstitialAd: InterstitialAd? = null
fun googlebeforloadAd(context: Context) {
try {
InterstitialAd.load(
context, com.superChargedFitness.utils.Utils.getPref(context, ConstantString.GOOGLE_INTERSTITIAL, "")!!, getAdRequest(),
object : InterstitialAdLoadCallback() {
override fun onAdFailedToLoad(adError: LoadAdError) {
Log.e("TAG ERRRR:::: ", adError.message)
mInterstitialAd = null
}
override fun onAdLoaded(interstitialAd: InterstitialAd) {
Log.e("TAG", "Ad was loaded.")
mInterstitialAd = interstitialAd
}
}
)
} catch (e: Exception) {
e.printStackTrace()
}
}
fun showInterstitialAdsGoogle(context: Context,adsCallback: AdsCallback) {
try {
if (mInterstitialAd != null) {
mInterstitialAd?.fullScreenContentCallback = object : FullScreenContentCallback() {
override fun onAdDismissedFullScreenContent() {
Log.d("TAG", "Ad was dismissed.")
// Don't forget to set the ad reference to null so you
// don't show the ad a second time.
mInterstitialAd = null
adsCallback.startNextScreen()
}
override fun onAdFailedToShowFullScreenContent(p0: AdError) {
Log.d("TAG", "Ad failed to show.")
// Don't forget to set the ad reference to null so you
// don't show the ad a second time.
mInterstitialAd = null
adsCallback.startNextScreen()
}
override fun onAdShowedFullScreenContent() {
Log.d("TAG", "Ad showed fullscreen content.")
// Called when ad is dismissed.
adsCallback.onLoaded()
}
}
mInterstitialAd?.show(context as Activity)
} else {
Log.e("TAG", "showInterstitialAdsGoogle:::::NOT LOADED::::: " )
adsCallback.startNextScreen()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
/*Facebook Full Ad*/
var interstitialAdFb: com.facebook.ads.InterstitialAd? = null
private var adsCallbackFb: AdsCallback? = null
fun facebookbeforeloadFullAd(context: Context) {
try {
interstitialAdFb = com.facebook.ads.InterstitialAd(context, com.superChargedFitness.utils.Utils.getPref(context,ConstantString.FB_INTERSTITIAL,""))
adsCallbackFb = null
val interstitialAdListener: InterstitialAdListener = object : InterstitialAdListener {
override fun onInterstitialDisplayed(ad: Ad?) {
Log.e("TAG", "Interstitial ad displayed.")
}
override fun onInterstitialDismissed(ad: Ad?) {
Log.e("TAG", "Interstitial ad dismissed.")
adsCallbackFb!!.adClose()
}
override fun onError(ad: Ad?, adError: com.facebook.ads.AdError) {
// adsCallbackFb!!.adLoadingFailed()
Log.e("TAG", "onError:Facebook ::::::::: "+adError.errorMessage+" "+adError.errorCode )
}
override fun onAdLoaded(ad: Ad?) {
Log.e("TAG", "Interstitial ad is loaded and ready to be displayed!")
// Show the ad
}
override fun onAdClicked(ad: Ad?) {
Log.e("TAG", "Interstitial ad clicked!")
}
override fun onLoggingImpression(ad: Ad?) {
Log.e("TAG", "Interstitial ad impression logged!")
}
}
interstitialAdFb!!.loadAd(
interstitialAdFb!!.buildLoadAdConfig()
.withAdListener(interstitialAdListener)
.build()
)
} catch (e: Exception) {
e.printStackTrace()
}
}
fun showInterstitialAdsFacebook(adsCallbackFb: AdsCallback) {
this.adsCallbackFb = adsCallbackFb
try {
if (interstitialAdFb != null) {
if (interstitialAdFb!!.isAdLoaded) {
interstitialAdFb!!.show()
adsCallbackFb.onLoaded()
} else {
adsCallbackFb.startNextScreen()
}
} else {
adsCallbackFb.startNextScreen()
}
} catch (e: Exception) {
e.printStackTrace()
}
}
fun loadFacebookBannerAd(context: Context, banner_container: LinearLayout) {
Log.e("TAG", "loadFbAdFacebook::::::::::: ")
var adView: com.facebook.ads.AdView? = null
adView = com.facebook.ads.AdView(context, com.superChargedFitness.utils.Utils.getPref(context,ConstantString.FB_BANNER,""), com.facebook.ads.AdSize.BANNER_HEIGHT_50)
banner_container.addView(adView)
val adListener: com.facebook.ads.AdListener = object : com.facebook.ads.AdListener {
override fun onError(ad: Ad?, adError: com.facebook.ads.AdError) {
// Ad error callback
Log.e("TAG", "onError:Fb:::: ${adError.errorCode} ${adError.errorMessage}")
banner_container.visibility = View.GONE
}
override fun onAdLoaded(ad: Ad?) {
// Ad loaded callback
Log.e("TAG", "onAdLoaded:::::: ")
banner_container.visibility = View.VISIBLE
}
override fun onAdClicked(ad: Ad?) {
// Ad clicked callback
}
override fun onLoggingImpression(ad: Ad?) {
// Ad impression logged callback
}
}
adView!!.loadAd(adView.buildLoadAdConfig().withAdListener(adListener).build())
}
fun loadBannerGoogleAd(context: Context, llAdview: RelativeLayout, type: String) {
val adViewBottom = AdView(context)
if (type.equals("GOOGLE_BANNER_TYPE_AD")) {
//adViewBottom.adSize = AdSize.BANNER
} else if (type.equals("GOOGLE_RECTANGLE_BANNER_TYPE_AD")) {
//adViewBottom.adSize = AdSize.MEDIUM_RECTANGLE
}
adViewBottom.adUnitId = com.superChargedFitness.utils.Utils.getPref(context,ConstantString.GOOGLE_BANNER,"")
llAdview.addView(adViewBottom)
val adRequest = AdRequest.Builder().build()
adViewBottom.loadAd(adRequest)
adViewBottom.adListener = object : AdListener() {
override fun onAdLoaded() {
super.onAdLoaded()
adViewBottom.visibility = View.VISIBLE
llAdview.visibility = View.VISIBLE
}
override fun onAdFailedToLoad(p0: LoadAdError) {
super.onAdFailedToLoad(p0)
llAdview.visibility = View.GONE
Log.e("TAG", "onAdFailedToLoad:::Google Ad::: ${p0.toString()}")
}
}
}
} | 0 | Kotlin | 0 | 0 | ea7d8441f311a9053bd30d631004fceabcc18913 | 9,760 | Supercharged-Fitness | MIT License |
library/src/main/java/cloud/pace/sdk/poikit/poi/PoiKitObserverToken.kt | pace | 303,641,261 | false | null | package cloud.pace.sdk.poikit.poi
import TileQueryRequestOuterClass
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import cloud.pace.sdk.api.API
import cloud.pace.sdk.api.poi.POIAPI.gasStations
import cloud.pace.sdk.api.poi.generated.request.gasStations.GetGasStationAPI.getGasStation
import cloud.pace.sdk.poikit.database.GasStationDAO
import cloud.pace.sdk.poikit.poi.download.TileDownloader
import cloud.pace.sdk.poikit.utils.POIKitConfig
import cloud.pace.sdk.poikit.utils.addPadding
import cloud.pace.sdk.poikit.utils.toTileQueryRequest
import cloud.pace.sdk.utils.*
import com.google.android.gms.maps.model.VisibleRegion
import kotlinx.coroutines.*
import okhttp3.Call
import org.koin.core.component.inject
import java.util.*
open class PoiKitObserverToken : CloudSDKKoinComponent {
internal val tileDownloader: TileDownloader by inject()
val loading = MutableLiveData<Boolean>()
var lastRefreshTime: Date? = null
open fun refresh(zoomLevel: Int = POIKitConfig.ZOOMLEVEL) {
lastRefreshTime = Date()
}
open fun invalidate() {}
}
class VisibleRegionNotificationToken(
val visibleRegion: VisibleRegion,
padding: Double,
private val gasStationDao: GasStationDAO,
private val completion: (Completion<List<PointOfInterest>>) -> Unit
) : PoiKitObserverToken() {
private var gasStationsObserver: Observer<List<GasStation>>? = null
private var gasStations: LiveData<List<GasStation>>? = null
private var downloadTask: Call? = null
init {
// load all the points that are around a certain radius of the visible center
val regionToLoad = visibleRegion.addPadding(padding)
gasStations = gasStationDao.getInBoundingBoxLive(
minLat = regionToLoad.latLngBounds.southwest.latitude,
minLon = regionToLoad.latLngBounds.southwest.longitude,
maxLat = regionToLoad.latLngBounds.northeast.latitude,
maxLon = regionToLoad.latLngBounds.northeast.longitude
)
gasStationsObserver = Observer {
completion(Success(it))
}
gasStationsObserver?.let { gasStations?.observeForever(it) }
}
override fun refresh(zoomLevel: Int) {
if (gasStationsObserver == null) return
loading.value = true
val tileRequest = visibleRegion.toTileQueryRequest(zoomLevel)
downloadTask = tileDownloader.load(tileRequest) {
it.onSuccess { stations ->
onIOBackgroundThread {
gasStationDao.insertGasStations(stations)
withContext(Dispatchers.Main) { loading.value = false }
// Delete gas stations not reported by new tiles anymore
val persistedGasStations = gasStationDao.getInBoundingBox(
minLat = visibleRegion.latLngBounds.southwest.latitude,
minLon = visibleRegion.latLngBounds.southwest.longitude,
maxLat = visibleRegion.latLngBounds.northeast.latitude,
maxLon = visibleRegion.latLngBounds.northeast.longitude
)
val outdatedStations = persistedGasStations.filter { it.id !in stations.map { it.id } }
gasStationDao.delete(outdatedStations)
}
}
it.onFailure { error ->
completion(Failure(error))
onMainThread { loading.value = false }
}
}
super.refresh(zoomLevel)
}
override fun invalidate() {
gasStationsObserver?.let { gasStations?.removeObserver(it) }
downloadTask?.cancel()
}
}
class IDsNotificationToken(
private val ids: List<String>,
private val gasStationDao: GasStationDAO,
private val completion: (Completion<List<PointOfInterest>>) -> Unit
) : PoiKitObserverToken() {
private val gasStations = gasStationDao.getByIdsLive(ids)
private val gasStationsObserver = Observer<List<GasStation>> { completion(Success(it)) }
private var downloadTask: Call? = null
init {
gasStations.observeForever(gasStationsObserver)
}
override fun refresh(zoomLevel: Int) {
loading.value = true
CoroutineScope(Dispatchers.Default).launch {
val dbStations = gasStationDao.getByIds(ids)
// Gas station we don't have in the database
val missingStationIds = ids - dbStations.map { it.id }
// Database stations without location
val stationsWithoutLocations = dbStations.filter { it.center == null }.map { it.id }
// List of unknown gas station locations
val stationsToFetch = (missingStationIds + stationsWithoutLocations).toSet()
if (stationsToFetch.isNotEmpty()) {
// First fetch gas stations to get locations for tile request
try {
val tileRequest = stationsToFetch
.map {
async {
getGasStation(it)
}
}
.awaitAll()
.mapNotNull {
val latitude = it?.latitude?.toDouble()
val longitude = it?.longitude?.toDouble()
if (latitude != null && longitude != null) {
LocationPoint(latitude, longitude)
} else {
null
}
}
.plus(dbStations.mapNotNull { it.center }) // List of gas stations we already have in the database
.toTileQueryRequest(zoomLevel)
download(tileRequest)
} catch (e: Exception) {
completion(Failure(e))
}
} else {
// We already have all gas station locations, download the data from the tiles right now
val tileRequest = dbStations.mapNotNull { it.center }.toTileQueryRequest(zoomLevel)
download(tileRequest)
}
}
super.refresh(zoomLevel)
}
override fun invalidate() {
gasStations.removeObserver(gasStationsObserver)
downloadTask?.cancel()
}
private suspend fun download(tileRequest: TileQueryRequestOuterClass.TileQueryRequest) = withContext(Dispatchers.IO) {
downloadTask = tileDownloader.load(tileRequest) {
it.onSuccess { stations ->
onIOBackgroundThread {
gasStationDao.insertGasStations(stations)
withContext(Dispatchers.Main) { loading.value = false }
}
}
it.onFailure { error ->
completion(Failure(error))
onMainThread { loading.value = false }
}
}
}
}
class IDNotificationToken(
private val id: String,
private val gasStationDao: GasStationDAO,
private val completion: (Completion<GasStation>) -> Unit
) : PoiKitObserverToken() {
private val gasStation = gasStationDao.getByIdsLive(listOf(id))
private val gasStationObserver = Observer<List<GasStation>> { it.firstOrNull()?.let { station -> completion(Success(station)) } }
private var downloadTask: Call? = null
init {
gasStation.observeForever(gasStationObserver)
}
override fun refresh(zoomLevel: Int) {
loading.value = true
onIOBackgroundThread {
val location = gasStationDao.getByIds(listOf(id)).mapNotNull { it.center }.firstOrNull()
if (location != null) {
download(location, zoomLevel)
} else {
try {
val gasStation = getGasStation(id)
val latitude = gasStation?.latitude?.toDouble()
val longitude = gasStation?.longitude?.toDouble()
if (latitude != null && longitude != null) {
download(LocationPoint(latitude, longitude), zoomLevel)
} else {
completion(Failure(Exception("Latitude, longitude or gas station itself is null. Gas station ID: $id")))
}
} catch (e: Exception) {
completion(Failure(e))
}
}
}
super.refresh(zoomLevel)
}
override fun invalidate() {
gasStation.removeObserver(gasStationObserver)
downloadTask?.cancel()
}
private fun download(location: LocationPoint, zoomLevel: Int) {
downloadTask = tileDownloader.load(location.toTileQueryRequest(zoomLevel)) {
it.onSuccess { stations ->
onIOBackgroundThread {
gasStationDao.insertGasStations(stations)
withContext(Dispatchers.Main) { loading.value = false }
}
}
it.onFailure { error ->
completion(Failure(error))
onMainThread { loading.value = false }
}
}
}
}
class LocationsNotificationToken(
private val locations: Map<String, LocationPoint>,
private val gasStationDao: GasStationDAO,
private val completion: (Completion<List<PointOfInterest>>) -> Unit
) : PoiKitObserverToken() {
private val gasStations = gasStationDao.getByIdsLive(locations.map { it.key })
private val gasStationsObserver = Observer<List<GasStation>> { completion(Success(it)) }
private var downloadTask: Call? = null
init {
gasStations.observeForever(gasStationsObserver)
}
override fun refresh(zoomLevel: Int) {
loading.value = true
val tileRequest = locations.values.toTileQueryRequest(zoomLevel)
downloadTask = tileDownloader.load(tileRequest) {
it.onSuccess { stations ->
onIOBackgroundThread {
gasStationDao.insertGasStations(stations)
withContext(Dispatchers.Main) { loading.value = false }
}
}
it.onFailure { error ->
completion(Failure(error))
onMainThread { loading.value = false }
}
}
super.refresh(zoomLevel)
}
override fun invalidate() {
gasStations.removeObserver(gasStationsObserver)
downloadTask?.cancel()
}
}
suspend fun getGasStation(id: String) = withContext(Dispatchers.IO) {
suspendCancellableCoroutine<cloud.pace.sdk.api.poi.generated.model.GasStation?> { continuation ->
API.gasStations.getGasStation(id, false).enqueue {
onResponse = {
val body = it.body()
if (it.isSuccessful && body != null) {
continuation.resumeIfActive(body)
} else {
continuation.resumeIfActive(null)
}
}
onFailure = {
continuation.resumeIfActive(null)
}
}
}
}
| 0 | Kotlin | 1 | 5 | c459c30690f3c2c480986312a3d837698ce028bc | 11,193 | cloud-sdk-android | MIT License |
compose-multiplatform-common/src/commonMain/kotlin/com/huanshankeji/compose/foundation/ExperimentalFoundationApi.kt | huanshankeji | 570,509,992 | false | {"Kotlin": 117843} | package com.huanshankeji.compose.foundation
@RequiresOptIn(
"This foundation API is experimental and is likely to change or be removed in the " +
"future. See `androidx.compose.foundation.ExperimentalFoundationApi`."
)
@Retention(AnnotationRetention.BINARY)
annotation class ExperimentalFoundationApi
| 10 | Kotlin | 0 | 8 | eb1ada7d629f3aa8831df4588653d87530e2635b | 318 | compose-multiplatform-material | Apache License 2.0 |
app/src/test/java/ca/stefanm/mockktutorial/SecondaryRepositoryTest.kt | linster | 674,414,963 | false | null | package ca.stefanm.mockktutorial
import org.junit.Assert.*
class SecondaryRepositoryTest | 0 | Kotlin | 0 | 0 | 986c369a7c770eefbab78e5cb18299519eecc1db | 90 | android-mockk-tutorial | Apache License 2.0 |
app/src/main/java/com/example/sunnyweatherkt/logic/model/Weather.kt | Fangtian89 | 354,954,187 | false | null | package com.example.sunnyweatherkt.logic.model
import retrofit2.Call
import retrofit2.http.GET
import retrofit2.http.Path
data class Weather(val realTime:RealTimeResponse.RealTime,val dailyResponse:DailyResponse.Daily,val hourlyResponse: HourlyResponse.Hourly){
}
| 0 | Kotlin | 0 | 1 | 6d9bc89f3e42ba6e6eb61b7a566024e1352ab6a4 | 267 | weather | Apache License 2.0 |
src/main/kotlin/es/urjc/realfood/clients/infrastructure/api/rest/RegisterRestApi.kt | MasterCloudApps-Projects | 391,103,556 | false | null | package es.urjc.realfood.clients.infrastructure.api.rest
import es.urjc.realfood.clients.application.RegisterClientRequest
import es.urjc.realfood.clients.application.RegisterClientResponse
import io.swagger.v3.oas.annotations.tags.Tag
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
@Tag(name = "Register API")
@RequestMapping("/api")
interface RegisterRestApi {
@PostMapping("/clients")
fun register(@RequestBody registerClientRequest: RegisterClientRequest): RegisterClientResponse
} | 0 | Kotlin | 0 | 1 | 9f083f975051840f07b64ccc1d29302058c54302 | 631 | realfood-clients | Apache License 2.0 |
leo/src/main/kotlin/me/adkhambek/leo/recycler/LeoAdapter.kt | MrAdkhambek | 235,808,012 | false | null | package me.adkhambek.leo.recycler
import android.view.LayoutInflater
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import me.adkhambek.leo.LeoAdapter
import me.adkhambek.leo.LeoAdapterDsl
import me.adkhambek.leo.LeoItemBindListener
import me.adkhambek.leo.LeoItemBinding
import me.adkhambek.leo.core.LeoAdapterAsync
import me.adkhambek.leo.core.LeoAdapterSync
@JvmOverloads
@LeoAdapterDsl
fun <T, VB : ViewBinding> RecyclerView.setupAdapter(
getViewBinding: LeoItemBinding<VB>,
layoutManager: LinearLayoutManager = LinearLayoutManager(context),
inflater: LayoutInflater = LayoutInflater.from(context),
onBind: LeoItemBindListener<T, VB>
): LeoAdapter<T> {
val leoAdapter: LeoAdapterSync<T, VB> = LeoAdapterSync(
inflater = inflater,
getViewBinding = getViewBinding,
onBind = onBind
)
this.layoutManager = layoutManager
this.adapter = leoAdapter
return leoAdapter
}
@JvmOverloads
@LeoAdapterDsl
fun <T, VB : ViewBinding> RecyclerView.setupAdapter(
getViewBinding: LeoItemBinding<VB>,
diffUtil: DiffUtil.ItemCallback<T>,
layoutManager: LinearLayoutManager = LinearLayoutManager(context),
inflater: LayoutInflater = LayoutInflater.from(context),
onBind: LeoItemBindListener<T, VB>
): LeoAdapter<T> {
val leoAdapter: LeoAdapterAsync<T, VB> = LeoAdapterAsync(
inflater = inflater,
diffUtil = diffUtil,
getViewBinding = getViewBinding,
onBind = onBind
)
this.layoutManager = layoutManager
this.adapter = leoAdapter
return leoAdapter
} | 0 | Kotlin | 1 | 5 | d698915aef0a33312a3b5d44d8e1c7605abe00c4 | 1,712 | LeoAdapter | MIT License |
sample/src/main/java/app/starzero/navbuilder/sample/ui/list/ListNavigation.kt | STAR-ZERO | 635,777,914 | false | null | /*
* Copyright 2023 Kenji Abe
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.starzero.navbuilder.sample.ui.list
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
const val ListRoute = "list"
fun NavGraphBuilder.list(
navigateToDetail: (String, String) -> Unit
) {
composable(ListRoute) {
ListScreen(
navigateToDetail = navigateToDetail
)
}
}
| 0 | Kotlin | 0 | 4 | 0dc465fdbcb4157eb87866ee3c71e958fae359eb | 953 | navbuilder | Apache License 2.0 |
app/src/main/java/com/tzion/jetpackmovies/ui/favoriteMovies/composable/FavoriteDisplay.kt | 4mr0m3r0 | 156,536,164 | false | {"Kotlin": 158808} | package com.tzion.jetpackmovies.ui.favoriteMovies.composable
import androidx.compose.runtime.Composable
@Composable
fun FavoriteDisplay() {
} | 4 | Kotlin | 4 | 14 | 0f88ace48d438c5aa262f52cb5e70fbb8f177bc7 | 144 | movies-jetpack-sample | MIT License |
server/src/main/kotlin/com/darkrockstudios/apps/hammer/frontend/NotFound.kt | Wavesonics | 499,367,913 | false | {"Kotlin": 1290354, "Swift": 32452, "CSS": 2064, "Ruby": 1579, "Shell": 361} | package com.darkrockstudios.apps.hammer.frontend
import kweb.div
import kweb.h2
import kweb.plugins.fomanticUI.fomantic
import kweb.routing.NotFoundReceiver
val notFoundPage: NotFoundReceiver = { path ->
div(fomantic.ui.middle.aligned.center.aligned.grid) {
div(fomantic.center.aligned.column) {
div(fomantic.ui.text.message.error) {
h2().text("404 Not Found")
}
}.addClasses("medium-width")
}.addClasses("centered-container")
} | 14 | Kotlin | 7 | 99 | 2feba4da350977e6eac5fdf07b3be644ee255b7a | 446 | hammer-editor | MIT License |
downloader/app/src/main/java/com/sample/data/model/DownloadFiles.kt | tamdevs | 507,207,201 | false | null | package com.sample.data.model
data class DownloadFiles(
val url: String,
var downloadId: Int = 0,
val fileName: String
)
| 5 | Kotlin | 0 | 2 | ba873dd89811d51ab9d358820a93cfb6306ed92f | 134 | android | Apache License 2.0 |
server/src/main/kotlin/com/zana/journal/JournalApp.kt | zana-a | 631,704,620 | false | null | package com.zana.journal
import com.zana.journal.entities.posts.PostsEntity
import com.zana.journal.posts.PostsRepository
import org.springframework.boot.CommandLineRunner
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import java.time.Instant
import java.util.*
@SpringBootApplication
open class JournalApp {
@Bean
open fun onInit(postsRepository: PostsRepository): CommandLineRunner {
return CommandLineRunner {
val post = PostsEntity.builder()
.createdAt(Date.from(Instant.now()))
.updatedAt(Date.from(Instant.now()))
.build()
postsRepository.save(post.withTitle("Example One"))
postsRepository.save(post.withTitle("Example Two"))
postsRepository.save(post.withTitle("Example Three"))
}
}
}
fun main() {
runApplication<JournalApp>()
}
| 0 | Kotlin | 0 | 0 | a92565e88143889bf24f165fef00397115eb2d9e | 990 | journal | MIT License |
app/src/main/java/com/example/fusedlocationproviderclientsimpleexample/modules/location_handler/presentation/model/LocationData.kt | Passant-Hatem | 863,984,255 | false | {"Kotlin": 16991} | package com.example.fusedlocationproviderclientsimpleexample.modules.location_handler.presentation.model
import android.location.Location
data class LocationData(
val location: Location,
val name: String
)
| 0 | Kotlin | 0 | 0 | bbd08d54a18f93a0cadb2d333d89f42a7f6d9b70 | 216 | GetUserLocation | MIT License |
app/src/main/java/com/vitorpamplona/amethyst/service/NostrHashtagDataSource.kt | vitorpamplona | 587,850,619 | false | {"Kotlin": 3170921, "Shell": 1485, "Java": 921} | package com.vitorpamplona.amethyst.service
import com.vitorpamplona.amethyst.service.relays.COMMON_FEED_TYPES
import com.vitorpamplona.amethyst.service.relays.JsonFilter
import com.vitorpamplona.amethyst.service.relays.TypedFilter
import com.vitorpamplona.quartz.events.AudioHeaderEvent
import com.vitorpamplona.quartz.events.AudioTrackEvent
import com.vitorpamplona.quartz.events.ChannelMessageEvent
import com.vitorpamplona.quartz.events.ClassifiedsEvent
import com.vitorpamplona.quartz.events.HighlightEvent
import com.vitorpamplona.quartz.events.LiveActivitiesChatMessageEvent
import com.vitorpamplona.quartz.events.LongTextNoteEvent
import com.vitorpamplona.quartz.events.PollNoteEvent
import com.vitorpamplona.quartz.events.TextNoteEvent
object NostrHashtagDataSource : NostrDataSource("SingleHashtagFeed") {
private var hashtagToWatch: String? = null
fun createLoadHashtagFilter(): TypedFilter? {
val hashToLoad = hashtagToWatch ?: return null
return TypedFilter(
types = COMMON_FEED_TYPES,
filter = JsonFilter(
tags = mapOf(
"t" to listOf(
hashToLoad,
hashToLoad.lowercase(),
hashToLoad.uppercase(),
hashToLoad.capitalize()
)
),
kinds = listOf(TextNoteEvent.kind, ChannelMessageEvent.kind, LongTextNoteEvent.kind, PollNoteEvent.kind, LiveActivitiesChatMessageEvent.kind, ClassifiedsEvent.kind, HighlightEvent.kind, AudioTrackEvent.kind, AudioHeaderEvent.kind),
limit = 200
)
)
}
val loadHashtagChannel = requestNewChannel()
override fun updateChannelFilters() {
loadHashtagChannel.typedFilters = listOfNotNull(createLoadHashtagFilter()).ifEmpty { null }
}
fun loadHashtag(tag: String?) {
hashtagToWatch = tag
invalidateFilters()
}
}
| 157 | Kotlin | 141 | 981 | 2de3d19a34b97c012e39b203070d9c1c0b1f0520 | 1,965 | amethyst | MIT License |
inference/inference-core/src/commonMain/kotlin/io/kinference.core/operators/logical/Not.kt | JetBrains-Research | 244,400,016 | false | null | package io.kinference.core.operators.logical
import io.kinference.attribute.Attribute
import io.kinference.core.data.tensor.KITensor
import io.kinference.core.data.tensor.asTensor
import io.kinference.data.ONNXData
import io.kinference.graph.Contexts
import io.kinference.ndarray.arrays.MutableBooleanNDArray
import io.kinference.operator.*
import kotlin.time.ExperimentalTime
import io.kinference.protobuf.message.TensorProto
sealed class Not(info: OperatorInfo, attributes: Map<String, Attribute<Any>>, inputs: List<String>, outputs: List<String>) : Operator<KITensor, KITensor>(info, attributes, inputs, outputs) {
companion object {
private val DEFAULT_VERSION = VersionInfo(sinceVersion = 1)
operator fun invoke(version: Int?, attributes: Map<String, Attribute<Any>>, inputs: List<String>, outputs: List<String>) = when (version ?: DEFAULT_VERSION.sinceVersion) {
in NotVer1.VERSION.asRange() -> NotVer1(attributes, inputs, outputs)
else -> error("Unsupported version of Not operator: $version")
}
}
}
@ExperimentalTime
class NotVer1(attributes: Map<String, Attribute<Any>>, inputs: List<String>, outputs: List<String>) : Not(INFO, attributes, inputs, outputs) {
companion object {
private val TYPE_CONSTRAINTS = setOf(TensorProto.DataType.BOOL)
private val INPUTS_INFO = listOf(IOInfo(0, TYPE_CONSTRAINTS, "input", optional = false))
private val OUTPUTS_INFO = listOf(IOInfo(0, TYPE_CONSTRAINTS, "output", optional = false))
internal val VERSION = VersionInfo(sinceVersion = 1)
private val INFO = OperatorInfo("Not", emptyMap(), INPUTS_INFO, OUTPUTS_INFO, VERSION, OperatorInfo.DEFAULT_DOMAIN)
}
override fun <D : ONNXData<*, *>> apply(contexts: Contexts<D>, inputs: List<KITensor?>): List<KITensor?> {
val data = inputs[0]!!.data.toMutable() as MutableBooleanNDArray
return listOf(data.not().asTensor("output"))
}
}
| 1 | Kotlin | 3 | 65 | 65ac98cfcb1d9f996fc389001fc84a3536e59e28 | 1,960 | kinference | Apache License 2.0 |
PermissionHelper/src/main/java/com/mathias8dev/permissionhelper/permission/PermissionRequestEvent.kt | mathias8dev | 705,602,967 | false | {"Kotlin": 67421} | package com.mathias8dev.permissionhelper.permission
internal sealed interface PermissionRequestEvent {
class OnShowRationale(
val permission: Permission,
val onProceed: (Boolean) -> Unit
) : PermissionRequestEvent
class OnRequestPermission(
val permission: Permission,
val onProceed: (Boolean) -> Unit
) : PermissionRequestEvent
class OnPermissionGranted(
val permission: Permission,
val onProceed: () -> Unit
) : PermissionRequestEvent
class OnGotoSettings(
val permission: Permission,
val onProceed: (Boolean) -> Unit
) : PermissionRequestEvent
object Idle : PermissionRequestEvent
}
| 0 | Kotlin | 0 | 1 | 5f69792ef20dfccdd3895abf190a574e0da73851 | 689 | PermissionHelper | Apache License 2.0 |
app/src/main/java/com/huanchengfly/tieba/post/adapters/MainForumListAdapter.kt | steve02081504 | 542,136,746 | true | {"Java Properties": 2, "Gradle": 3, "Shell": 3, "Markdown": 1, "Batchfile": 1, "Text": 1, "Ignore List": 1, "INI": 1, "YAML": 1, "Proguard": 1, "Java": 240, "XML": 424, "JavaScript": 5, "JSON": 2, "Kotlin": 257, "Protocol Buffer": 2} | package com.huanchengfly.tieba.post.adapters
import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.view.View
import com.alibaba.android.vlayout.layout.GridLayoutHelper
import com.huanchengfly.tieba.post.R
import com.huanchengfly.tieba.post.adapters.base.BaseMultiTypeDelegateAdapter
import com.huanchengfly.tieba.post.api.models.ForumRecommend
import com.huanchengfly.tieba.post.components.MyViewHolder
import com.huanchengfly.tieba.post.dpToPx
import com.huanchengfly.tieba.post.ui.common.theme.utils.ColorStateListUtils
import com.huanchengfly.tieba.post.utils.*
class MainForumListAdapter(
context: Context,
span: Int = 1
) : BaseMultiTypeDelegateAdapter<ForumRecommend.LikeForum>(
context, GridLayoutHelper(span).apply { setAutoExpand(false) }
) {
companion object {
const val TYPE_LIST = 1
const val TYPE_GRID = 2
}
var spanCount = span
set(value) {
field = value
(layoutHelper as GridLayoutHelper).spanCount = value
notifyDataSetChanged()
}
override fun getItemLayoutId(itemType: Int): Int =
if (itemType == TYPE_LIST) R.layout.item_forum_list_single else R.layout.item_forum_list
override fun convert(
viewHolder: MyViewHolder,
item: ForumRecommend.LikeForum,
position: Int,
viewType: Int
) {
val cardRadius = context.resources.getDimension(R.dimen.card_radius)
val rippleColor = if (item.isFake) Color.TRANSPARENT else Util.getColorByAttr(
context,
R.attr.colorControlHighlight,
R.color.transparent
)
when {
//单列
spanCount == 1 -> {
viewHolder.itemView.background = wrapRipple(
rippleColor,
if (position == getCount() - 1) {
getRadiusDrawable(bottomLeftPx = cardRadius, bottomRightPx = cardRadius)
} else {
getRadiusDrawable()
}
)
if (context.appPreferences.listItemsBackgroundIntermixed) {
if (position % 2 == 1) {
viewHolder.itemView.backgroundTintList =
ColorStateList.valueOf(Color.TRANSPARENT)
} else {
viewHolder.itemView.backgroundTintList =
ColorStateListUtils.createColorStateList(
context,
R.color.default_color_divider
)
}
} else {
viewHolder.itemView.backgroundTintList =
ColorStateList.valueOf(Color.TRANSPARENT)
}
}
//多列第一个
position % spanCount == 0 -> {
viewHolder.itemView.backgroundTintList =
ColorStateList.valueOf(Color.TRANSPARENT)
viewHolder.itemView.background = wrapRipple(
rippleColor,
when (position) {
//最后一行,左
getCount() - spanCount -> getRadiusDrawable(bottomLeftPx = cardRadius)
//最后一项
getCount() - 1 -> getRadiusDrawable(
bottomLeftPx = cardRadius,
bottomRightPx = cardRadius
)
//其他
else -> getRadiusDrawable()
}
)
}
//多列右
else -> {
viewHolder.itemView.backgroundTintList =
ColorStateList.valueOf(Color.TRANSPARENT)
viewHolder.itemView.background = wrapRipple(
rippleColor,
if (position == getCount() - 1) {
getRadiusDrawable(bottomRightPx = cardRadius)
} else {
getRadiusDrawable()
}
)
}
}
if (viewType == TYPE_GRID) {
val visibility = if (item.isFake) View.INVISIBLE else View.VISIBLE
listOf(
R.id.forum_list_item_status,
R.id.forum_list_item_name
).forEach {
viewHolder.setVisibility(it, visibility)
}
}
if (spanCount > 1) {
ImageUtil.clear(viewHolder.getView(R.id.forum_list_item_avatar))
} else {
ImageUtil.load(
viewHolder.getView(R.id.forum_list_item_avatar),
ImageUtil.LOAD_TYPE_AVATAR,
item.avatar
)
}
ThemeUtil.setChipThemeByLevel(
item.levelId,
viewHolder.getView(R.id.forum_list_item_status),
viewHolder.getView(R.id.forum_list_item_level),
viewHolder.getView(R.id.forum_list_item_sign_status)
)
viewHolder.setText(R.id.forum_list_item_name, item.forumName)
viewHolder.setText(R.id.forum_list_item_level, item.levelId)
viewHolder.setVisibility(
R.id.forum_list_item_sign_status,
if ("1" == item.isSign) View.VISIBLE else View.GONE
)
viewHolder.getView<View>(R.id.forum_list_item_status).minimumWidth =
(if ("1" == item.isSign) 50 else 32).dpToPx()
}
override fun getViewType(position: Int, item: ForumRecommend.LikeForum): Int {
return if (spanCount == 1) TYPE_LIST else TYPE_GRID
}
} | 0 | null | 0 | 0 | afac8210329e45ddaed39675776d4f2c9e99420f | 5,668 | TiebaLite | Apache License 2.0 |
src/main/kotlin/com/koresframework/kores/type/CachedKoresTypeResolver.kt | JonathanxD | 58,418,392 | false | {"Gradle": 5, "YAML": 3, "TOML": 2, "Markdown": 7208, "INI": 2, "Shell": 1, "Text": 3, "Ignore List": 1, "Batchfile": 1, "Git Attributes": 1, "Java": 69, "Kotlin": 218, "SVG": 2, "HTML": 12, "JavaScript": 7, "CSS": 9, "JSON": 1} | /*
* Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores>
*
* The MIT License (MIT)
*
* Copyright (c) 2022 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <<EMAIL>>
* Copyright (c) contributors
*
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.koresframework.kores.type
import com.koresframework.kores.base.TypeDeclaration
import com.github.jonathanxd.iutils.`object`.Either
import com.github.jonathanxd.iutils.`object`.specialized.EitherObjBoolean
import com.github.jonathanxd.iutils.kt.right
import java.lang.reflect.Type
/**
* Caches resolutions, this class is not thread-safe and does not caches [isAssignableFrom] resolution.
*/
class CachedKoresTypeResolver<T>(private val originalResolver: KoresTypeResolver<T>) :
KoresTypeResolver<T> {
private val resolveTypes = mutableMapOf<Type, T>()
private val superClasses = mutableMapOf<Type, Type?>()
private val interfaces = mutableMapOf<Type, List<Type>>()
private val typeDeclarations = mutableMapOf<Type, TypeDeclaration>()
override fun resolve(type: Type): Either<Exception, out T> {
this.resolveTypes[type]?.let {
return right(it)
}
return this.originalResolver.resolve(type).also {
it.ifRight { this.resolveTypes[type] = it }
}
}
override fun getSuperclass(type: Type): Either<Exception, Type?> {
this.superClasses[type]?.let {
return right(it)
}
return this.originalResolver.getSuperclass(type).also {
it.ifRight { this.superClasses[type] = it }
}
}
override fun getInterfaces(type: Type): Either<Exception, List<Type>> {
this.interfaces[type]?.let {
return right(it)
}
return this.originalResolver.getInterfaces(type).also {
it.ifRight { this.interfaces[type] = it }
}
}
override fun isAssignableFrom(
type: Type,
from: Type,
resolverProvider: (Type) -> KoresTypeResolver<*>
): EitherObjBoolean<Exception> {
return this.originalResolver.isAssignableFrom(type, from, resolverProvider)
}
override fun resolveTypeDeclaration(type: Type): Either<Exception, TypeDeclaration> {
this.typeDeclarations[type]?.let {
return right(it)
}
return this.originalResolver.resolveTypeDeclaration(type).also {
it.ifRight { this.typeDeclarations[type] = it }
}
}
} | 6 | Kotlin | 0 | 4 | 236f7db6eeef7e6238f0ae0dab3f3b05fc531abb | 3,633 | CodeAPI | MIT License |
libraries/data/src/main/java/com/eunice/data/repositoryImpl/IngredientRepositoryImpl.kt | eunix56 | 466,099,049 | false | {"Kotlin": 132920} | package com.eunice.data.repositoryImpl
import com.eunice.data.contract.IngredientRemote
import com.eunice.data.handlerImpl.GeneralErrorHandler
import com.eunice.data.mapper.IngredientEntityModelMapper
import com.eunice.domain.handler.DataResult
import com.eunice.domain.model.Ingredient
import com.eunice.domain.repository.IngredientRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
/**
* Created by EUNICE BAKARE T. on 10/03/2022
* Email: [email protected]
*/
class IngredientRepositoryImpl @Inject constructor(
private val ingredientRemote: IngredientRemote,
private val ingredientEntityModelMapper: IngredientEntityModelMapper,
private val errorHandler: GeneralErrorHandler
): IngredientRepository {
override suspend fun fetchIngredients(): Flow<DataResult<List<Ingredient>>> {
var result: DataResult<List<Ingredient>>
return flow {
val ingredients = ingredientRemote.fetchIngredients()
result = DataResult.Success(ingredientEntityModelMapper.mapFromEntityList(ingredients))
emit(result)
}.catch {
result = DataResult.Error(errorHandler.getError(it))
emit(result)
}
}
} | 0 | Kotlin | 0 | 5 | ab5723d6a5777be4d600b91dd42356465f448c31 | 1,290 | Meals | Apache License 2.0 |
app/src/main/java/com/eltonkola/comfyflux/app/imageviwer/PhotoViewerScreen.kt | eltonkola | 837,643,078 | false | {"Kotlin": 274642, "Jupyter Notebook": 8656} | package com.eltonkola.comfyflux.app.imageviwer
import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import android.widget.Toast
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import coil.compose.AsyncImage
import com.eltonkola.comfyflux.R
import com.eltonkola.comfyflux.app.MainViewModel
import com.eltonkola.comfyflux.ui.theme.Ikona
import com.eltonkola.comfyflux.ui.theme.ikona.Back
import com.eltonkola.comfyflux.ui.theme.ikona.Download
import com.eltonkola.comfyflux.ui.theme.ikona.Share
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
@OptIn(ExperimentalMaterial3Api::class, ExperimentalFoundationApi::class)
@Composable
fun PhotoViewerScreen(
viewModel: MainViewModel,
navController: NavController
) {
val uiState by viewModel.imageUiState.collectAsState()
val context = LocalContext.current
val coroutineScope = rememberCoroutineScope()
var currentImageUrl by remember { mutableStateOf("") }
var showDialog by remember { mutableStateOf(false) }
if (showDialog) {
PhotoZoomDialog(photoUrl = currentImageUrl) {
showDialog = false
}
}
Scaffold(
topBar = {
TopAppBar(
title = {
Text(text = "Gallery")
},
actions = {
IconButton(onClick = {
coroutineScope.launch {
saveImageToDownloads(
context,
currentImageUrl,
"flux_image_${System.currentTimeMillis()}.png",
true
)
}
}) {
Icon(
imageVector = Ikona.Share,
contentDescription = "Share",
modifier = Modifier.size(24.dp)
)
}
IconButton(onClick = {
coroutineScope.launch {
saveImageToDownloads(
context,
currentImageUrl,
"flux_image_${System.currentTimeMillis()}.png",
false
)
}
}) {
Icon(
imageVector = Ikona.Download,
contentDescription = "Save",
modifier = Modifier.size(24.dp)
)
}
},
navigationIcon = {
IconButton(onClick = { navController.navigateUp() }) {
Icon(
imageVector = Ikona.Back,
contentDescription = "Back",
modifier = Modifier.size(24.dp)
)
}
}
)
},
) { paddingValues ->
val pagerState =
rememberPagerState(initialPage = uiState.selected, pageCount = { uiState.images.size })
HorizontalPager(
state = pagerState,
contentPadding = paddingValues,
modifier = Modifier.fillMaxSize()
) { image ->
LaunchedEffect(key1 = image) {
currentImageUrl = uiState.images[image]
}
Box(
modifier = Modifier
.fillMaxSize()
) {
AsyncImage(
model = uiState.images[image],
contentDescription = "Image ${image + 1}",
contentScale = ContentScale.Fit,
modifier = Modifier
.fillMaxSize()
.clickable { showDialog = true }
)
}
}
}
}
private fun share(context: Context, uri: Uri) {
val intent = Intent(Intent.ACTION_SEND)
intent.type = "image/*"
intent.putExtra(Intent.EXTRA_STREAM, uri)
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
context.startActivity(Intent.createChooser(intent, "Share Image"))
}
suspend fun saveImageToDownloads(
context: Context,
imageUrl: String,
filename: String,
share: Boolean = false
) {
withContext(Dispatchers.IO) {
val resolver = context.contentResolver
val contentValues = ContentValues().apply {
put(MediaStore.Images.Media.DISPLAY_NAME, filename)
put(MediaStore.Images.Media.MIME_TYPE, "image/png")
put(
MediaStore.Images.Media.RELATIVE_PATH,
"Pictures/${context.getString(R.string.app_name)}"
)
}
try {
val url = URL(imageUrl)
val connection = url.openConnection() as HttpURLConnection
connection.doInput = true
connection.connect()
val input: InputStream = connection.inputStream
val uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)
uri?.let {
resolver.openOutputStream(it)?.use { outputStream ->
input.use { inputStream ->
inputStream.copyTo(outputStream)
}
outputStream.flush()
withContext(Dispatchers.Main) {
if (share) {
share(context, uri)
}
Toast.makeText(context, "Image saved to Pictures", Toast.LENGTH_SHORT)
.show()
}
} ?: run {
withContext(Dispatchers.Main) {
Toast.makeText(context, "Failed to open output stream", Toast.LENGTH_SHORT)
.show()
}
}
} ?: run {
withContext(Dispatchers.Main) {
Toast.makeText(context, "Failed to insert image", Toast.LENGTH_SHORT).show()
}
}
} catch (e: Exception) {
e.printStackTrace()
withContext(Dispatchers.Main) {
Toast.makeText(context, "Failed to save image", Toast.LENGTH_SHORT).show()
}
}
}
} | 0 | Kotlin | 1 | 1 | c0d2a6d106ff9df1bc9cf0ddce6d92a4da1254b7 | 7,865 | ComfyFlux | Apache License 2.0 |
app/src/main/java/com/stepstone/reactiveusecasessample/domain/interactor/CheckSampleFeatureStatusUseCase.kt | stepstone-tech | 133,494,932 | false | null | /*
* Copyright (C) 2018 StepStone Services Sp. z o.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.stepstone.reactiveusecasessample.domain.interactor
import com.stepstone.reactiveusecasessample.domain.interactor.base.SynchronousUseCase
import com.stepstone.reactiveusecasessample.domain.repository.LocalPreferencesRepository
import javax.inject.Inject
class CheckSampleFeatureStatusUseCase
@Inject
constructor(
private val localPreferencesRepository: LocalPreferencesRepository
) : SynchronousUseCase<Boolean, Unit> {
override fun execute(params: Unit?): Boolean =
localPreferencesRepository.isSampleFeatureEnabled()
}
| 1 | Kotlin | 12 | 54 | 2558f3d3eabba9f1f43341a85ca11c891a93c0a4 | 1,172 | ReactiveUseCasesSample | Apache License 2.0 |
src/commonMain/kotlin/org/angproj/crypt/kp/AbstractPaulssonSponge.kt | angelos-project | 677,062,617 | false | {"Kotlin": 17587776} | /**
* Copyright (c) 2023 by Kristoffer Paulsson <[email protected]>.
*
* This software is available under the terms of the MIT license. Parts are licensed
* under different terms if stated. The legal terms are attached to the LICENSE file
* and are made available on:
*
* https://opensource.org/licenses/MIT
*
* SPDX-License-Identifier: MIT
*
* Contributors:
* Kristoffer Paulsson - initial implementation
*/
package org.angproj.crypt.kp
/**
* ===== WARNING! EXPERIMENTAL USE ONLY =====
* */
public abstract class AbstractPaulssonSponge {
protected val buffer: LongArray = LongArray(16)
protected val initVector: PaulssonSpongeInitVector = PaulssonSpongeInitVector()
protected lateinit var sponge: PaulssonSponge
} | 0 | Kotlin | 0 | 0 | e378d1dc05fc431075b1c1460b654f2fc1b9748d | 767 | angelos-project-crypt | MIT License |
solar/src/main/java/com/chiksmedina/solar/boldduotone/arrowsaction/UploadSquare.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.boldduotone.arrowsaction
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
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.path
import androidx.compose.ui.unit.dp
import com.chiksmedina.solar.boldduotone.ArrowsActionGroup
val ArrowsActionGroup.UploadSquare: ImageVector
get() {
if (_uploadSquare != null) {
return _uploadSquare!!
}
_uploadSquare = Builder(
name = "UploadSquare", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeAlpha
= 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter,
strokeLineMiter = 4.0f, pathFillType = NonZero
) {
moveTo(2.0f, 12.0f)
curveTo(2.0f, 7.286f, 2.0f, 4.9289f, 3.4645f, 3.4645f)
curveTo(4.9289f, 2.0f, 7.286f, 2.0f, 12.0f, 2.0f)
curveTo(16.714f, 2.0f, 19.0711f, 2.0f, 20.5355f, 3.4645f)
curveTo(22.0f, 4.9289f, 22.0f, 7.286f, 22.0f, 12.0f)
curveTo(22.0f, 16.714f, 22.0f, 19.0711f, 20.5355f, 20.5355f)
curveTo(19.0711f, 22.0f, 16.714f, 22.0f, 12.0f, 22.0f)
curveTo(7.286f, 22.0f, 4.9289f, 22.0f, 3.4645f, 20.5355f)
curveTo(2.0f, 19.0711f, 2.0f, 16.714f, 2.0f, 12.0f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(8.0f, 7.75f)
curveTo(7.5858f, 7.75f, 7.25f, 7.4142f, 7.25f, 7.0f)
curveTo(7.25f, 6.5858f, 7.5858f, 6.25f, 8.0f, 6.25f)
horizontalLineTo(16.0f)
curveTo(16.4142f, 6.25f, 16.75f, 6.5858f, 16.75f, 7.0f)
curveTo(16.75f, 7.4142f, 16.4142f, 7.75f, 16.0f, 7.75f)
horizontalLineTo(8.0f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(12.75f, 17.0f)
curveTo(12.75f, 17.4142f, 12.4142f, 17.75f, 12.0f, 17.75f)
curveTo(11.5858f, 17.75f, 11.25f, 17.4142f, 11.25f, 17.0f)
lineTo(11.25f, 11.8107f)
lineTo(9.5303f, 13.5303f)
curveTo(9.2374f, 13.8232f, 8.7626f, 13.8232f, 8.4697f, 13.5303f)
curveTo(8.1768f, 13.2374f, 8.1768f, 12.7626f, 8.4697f, 12.4697f)
lineTo(11.4697f, 9.4697f)
curveTo(11.6103f, 9.329f, 11.8011f, 9.25f, 12.0f, 9.25f)
curveTo(12.1989f, 9.25f, 12.3897f, 9.329f, 12.5303f, 9.4697f)
lineTo(15.5303f, 12.4697f)
curveTo(15.8232f, 12.7626f, 15.8232f, 13.2374f, 15.5303f, 13.5303f)
curveTo(15.2374f, 13.8232f, 14.7626f, 13.8232f, 14.4697f, 13.5303f)
lineTo(12.75f, 11.8107f)
verticalLineTo(17.0f)
close()
}
}
.build()
return _uploadSquare!!
}
private var _uploadSquare: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 3,875 | SolarIconSetAndroid | MIT License |
common/src/commonMain/kotlin/chat/sphinx/common/state/InviteFriendState.kt | stakwork | 457,042,828 | false | {"Kotlin": 894995} | package chat.sphinx.common.state
import chat.sphinx.response.LoadResponse
import chat.sphinx.response.ResponseError
data class InviteFriendState(
val nickname: String = "",
val welcomeMessage: String = "",
val nodePrice: String? = null,
var createInviteStatus: LoadResponse<Any, ResponseError>? = null,
)
| 31 | Kotlin | 6 | 2 | d9ba71335593e3d61da9198d4f815bf6fbef4266 | 323 | sphinx-kotlin-ui | MIT License |
app/src/main/java/com/stocksexchange/android/di/HandlersModule.kt | nscoincommunity | 277,168,471 | true | {"Kotlin": 2814235} | package com.stocksexchange.android.di
import com.stocksexchange.android.utils.ReloadProvider
import com.stocksexchange.android.utils.handlers.*
import com.stocksexchange.api.utils.CredentialsHandler
import com.stocksexchange.core.handlers.ClipboardHandler
import com.stocksexchange.core.handlers.CoroutineHandler
import com.stocksexchange.core.handlers.PreferenceHandler
import com.stocksexchange.core.handlers.QrCodeHandler
import org.koin.android.ext.koin.androidApplication
import org.koin.android.ext.koin.androidContext
import org.koin.dsl.module
val handlersModule = module {
factory { BrowserHandler(get(), get()) }
factory { ClipboardHandler(androidApplication()) }
factory { CredentialsHandler(get()) }
factory { EmailHandler(get()) }
factory { PreferenceHandler(androidContext()) }
factory { ReloadProvider(androidContext()) }
factory { UserDataClearingHandler(androidApplication(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get(), get()) }
factory { SharingHandler(get()) }
factory { ShortcutsHandler(androidApplication(), get()) }
factory { FiatCurrencyPriceHandler(get()) }
factory { IntercomHandler(get(), get()) }
factory { QrCodeHandler() }
factory { CoroutineHandler() }
} | 0 | null | 0 | 0 | 52766afab4f96506a2d9ed34bf3564b6de7af8c3 | 1,273 | Android-app | MIT License |
app-tracking-protection/vpn-impl/src/main/java/com/duckduckgo/mobile/android/vpn/feature/removal/VpnFeatureRemoverWorker.kt | hojat72elect | 822,396,044 | false | {"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784} |
package com.duckduckgo.mobile.android.vpn.feature.removal
import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.duckduckgo.anvil.annotations.ContributesWorker
import com.duckduckgo.di.scopes.AppScope
import javax.inject.Inject
import logcat.logcat
@ContributesWorker(AppScope::class)
class VpnFeatureRemoverWorker(
val context: Context,
params: WorkerParameters,
) : CoroutineWorker(context, params) {
@Inject
lateinit var vpnFeatureRemover: VpnFeatureRemover
override suspend fun doWork(): Result {
logcat { "VpnFeatureRemoverWorker, automatically removing AppTP feature" }
vpnFeatureRemover.scheduledRemoveFeature()
return Result.success()
}
companion object {
const val WORKER_VPN_FEATURE_REMOVER_TAG = "VpnFeatureRemoverTagWorker"
}
}
| 0 | Kotlin | 0 | 0 | b89591136b60933d6a03fac43a38ee183116b7f8 | 873 | DuckDuckGo | Apache License 2.0 |
app/src/main/java/com/learning/pestifyapp/ui/screen/navigation/NavigationItem.kt | C241-PS242-Pestify | 804,948,341 | false | {"Kotlin": 101102} | package com.learning.pestifyapp.ui.screen.navigation
import com.learning.pestifyapp.R
data class NavigationItem(
val title: String,
val icon: Int,
val iconSelected: Int,
val screen: Screen
)
val navigationItems = listOf(
NavigationItem(
title = Screen.Home.route,
icon = R.drawable.home_non,
iconSelected = R.drawable.home_filled,
screen = Screen.Home
),
NavigationItem(
title = Screen.Ensiklopedia.route,
icon = R.drawable.book_non,
iconSelected = R.drawable.book_filled,
screen = Screen.Ensiklopedia
),
NavigationItem(
title = Screen.Pescan.route,
icon = R.drawable.scan,
iconSelected = R.drawable.scan,
screen = Screen.Pescan
),
NavigationItem(
title = Screen.History.route,
icon = R.drawable.history_non,
iconSelected = R.drawable.history_filled,
screen = Screen.History
),
NavigationItem(
title = Screen.Profile.route,
icon = R.drawable.account_non,
iconSelected = R.drawable.account_filled,
screen = Screen.Profile
),
) | 0 | Kotlin | 0 | 0 | 025739340010f9cdf2a813c098f91c7800140d35 | 1,144 | PestifyApp | MIT License |
app/src/main/java/dev/kxxcn/maru/di/EditModule.kt | kxxcn | 281,122,468 | false | null | package dev.kxxcn.maru.di
import androidx.lifecycle.ViewModel
import dagger.Binds
import dagger.Module
import dagger.android.ContributesAndroidInjector
import dagger.multibindings.IntoMap
import dev.kxxcn.maru.view.edit.EditFragment
import dev.kxxcn.maru.view.edit.EditViewModel
@Module
abstract class EditModule {
@ContributesAndroidInjector(modules = [ViewModelBuilder::class])
internal abstract fun editFragment(): EditFragment
@Binds
@IntoMap
@ViewModelKey(EditViewModel::class)
abstract fun bindViewModel(viewModel: EditViewModel): ViewModel
}
| 0 | Kotlin | 0 | 0 | c301d8155cc13e459eb20acfc0fb89ab56d9c3dc | 577 | maru | Apache License 2.0 |
app/src/main/java/com/liflymark/normalschedule/logic/network/CheckUpdateService.kt | sasaju | 330,628,610 | false | {"Kotlin": 736981} | package com.liflymark.normalschedule.logic.network
import com.liflymark.normalschedule.logic.model.CheckUpdateResponse
import retrofit2.Call
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
interface CheckUpdateService {
@FormUrlEncoded
@POST("checkveriosn/")
fun getNewVersion(
@Field("version")versionCode:String
):Call<CheckUpdateResponse>
} | 0 | Kotlin | 3 | 14 | 616c6ba075f366e798cfccecd0369990601d1e80 | 414 | NormalSchedule | Apache License 2.0 |
feature/search/src/desktopMain/kotlin/org/michaelbel/movies/search/SearchNavigation.kt | michaelbel | 115,437,864 | false | {"Kotlin": 790428, "Java": 9611, "Swift": 342, "Shell": 235} | package org.michaelbel.movies.search
import androidx.compose.foundation.clickable
import androidx.compose.material.Text
import androidx.compose.ui.Modifier
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
fun NavController.navigateToSearch() {
navigate(SearchDestination.route)
}
fun NavGraphBuilder.searchGraph(
navigateBack: () -> Unit,
navigateToDetails: (String, Int) -> Unit,
) {
composable(
route = SearchDestination.route
) {
Text(
text = "Feed",
modifier = Modifier.clickable { navigateBack() }
)
}
} | 9 | Kotlin | 34 | 226 | 5d338324dd1e5a56c272f38bdb8fb040e6e3320f | 664 | movies | Apache License 2.0 |
app/src/main/java/com/example/androiddevchallenge/ui/ListItem.kt | HugoMatilla | 342,671,717 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.ui
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.absoluteOffset
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.androiddevchallenge.data.Dog
import com.example.androiddevchallenge.data.kelly
import com.example.androiddevchallenge.ui.common.Chip
import com.example.androiddevchallenge.ui.common.ListItemMessage
import com.example.androiddevchallenge.ui.common.ListItemSubtitle
import com.example.androiddevchallenge.ui.common.ListItemTitle
@Composable
fun ListItem(dog: Dog, onClick: () -> Unit = {}) {
BoxWithConstraints(
modifier = Modifier
.height(160.dp)
.fillMaxWidth()
.padding(8.dp)
.shadow(elevation = 8.dp, shape = RoundedCornerShape(8.dp))
.clip(RoundedCornerShape(8.dp))
.clickable(onClick = { onClick() })
.background(MaterialTheme.colors.surface)
) {
Row(verticalAlignment = Alignment.CenterVertically) {
Avatar(dog)
MainContent(dog)
}
Column(
verticalArrangement = Arrangement.Bottom,
modifier = Modifier
.fillMaxHeight()
.fillMaxWidth()
) {
Chips(dog)
}
}
}
@Composable
fun Chips(dog: Dog) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(start = 100.dp),
horizontalArrangement = Arrangement.SpaceAround
) {
for (top in dog.tops.subList(0, 3)) {
Chip(top)
}
}
}
@Composable
fun MainContent(dog: Dog) {
Column(
verticalArrangement = Arrangement.SpaceBetween,
modifier = Modifier
.fillMaxHeight()
.padding(top = 8.dp)
.absoluteOffset(x = (-10).dp)
) {
Column(
verticalArrangement = Arrangement.Top,
modifier = Modifier.fillMaxWidth()
) {
Row(
horizontalArrangement = Arrangement.SpaceBetween,
modifier = Modifier.fillMaxWidth()
) {
ListItemTitle(dog.name, modifier = Modifier.alignByBaseline())
ListItemSubtitle(dog.breed, modifier = Modifier.alignByBaseline())
}
ListItemMessage(dog.message)
}
}
}
@Preview("Light Theme", widthDp = 360)
@Composable
fun PreviewListItem() {
ListItem(kelly)
}
@Composable
fun Avatar(dog: Dog) {
Image(
painter = painterResource(dog.imageId),
contentDescription = null,
modifier = Modifier
.size(180.dp)
.fillMaxWidth()
.absoluteOffset(x = (-20).dp)
.clip(
shape = RoundedCornerShape(
topStartPercent = 0,
topEndPercent = 50,
bottomStartPercent = 0,
bottomEndPercent = 50,
)
),
contentScale = ContentScale.Crop
)
}
| 0 | Kotlin | 0 | 0 | 2cb2820e43e93c1be5e5c1fefb43438f0144a3d3 | 4,624 | android-dev-challenge-compose-puppies | Apache License 2.0 |
year2019/day01/fuel/src/test/kotlin/com/curtislb/adventofcode/year2019/day01/fuel/CalculateTotalFuelTest.kt | curtislb | 226,797,689 | false | {"Kotlin": 2074798} | package com.curtislb.adventofcode.year2019.day01.fuel
import kotlin.test.assertEquals
import org.junit.jupiter.api.Test
/**
* Tests [calculateTotalFuel].
*/
class CalculateTotalFuelTest {
@Test
fun testCalculateTotalFuel() {
assertEquals(0, calculateTotalFuel(0))
assertEquals(0, calculateTotalFuel(1))
assertEquals(0, calculateTotalFuel(2))
assertEquals(0, calculateTotalFuel(6))
assertEquals(1, calculateTotalFuel(9))
assertEquals(1, calculateTotalFuel(10))
assertEquals(1, calculateTotalFuel(11))
assertEquals(2, calculateTotalFuel(12))
assertEquals(2, calculateTotalFuel(14))
assertEquals(8, calculateTotalFuel(32))
assertEquals(10, calculateTotalFuel(33))
assertEquals(40, calculateTotalFuel(104))
assertEquals(43, calculateTotalFuel(105))
assertEquals(966, calculateTotalFuel(1969))
assertEquals(50346, calculateTotalFuel(100756))
}
}
| 0 | Kotlin | 1 | 1 | 5d28da592cfa3158ef5be6b414cf13452748ac9b | 977 | AdventOfCode | MIT License |
retrofit_lib/src/main/java/com/jesen/retrofit_lib/com/BaseMapper.kt | Jesen0823 | 432,540,052 | false | {"Kotlin": 464797, "Java": 200809} | package com.jesen.retrofit_lib.com
abstract class BaseMapper<T : Any, V : Any> {
/** Return true if this can convert [data]. */
fun handles(data: T): Boolean = true
/** Convert [data] into [V]. */
abstract fun map(data: T): V
}
| 0 | Kotlin | 2 | 9 | 39c1920c36d4fa8298f26cbefc67433f1db30a23 | 247 | Compose_bili_talk | Apache License 2.0 |
app/src/main/java/com/ams/cavus/todo/list/di/TodoModule.kt | AhmetCavus | 138,603,253 | false | {"Kotlin": 73897} | package com.ams.cavus.todo.list.di
import com.ams.cavus.todo.base.App
import com.ams.cavus.todo.helper.Settings
import com.ams.cavus.todo.list.service.TodoService
import com.ams.cavus.todo.list.viewmodel.TodoViewModel
import com.google.gson.Gson
import com.microsoft.windowsazure.mobileservices.MobileServiceClient
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class TodoModule {
@Singleton
@Provides
fun provideTodoViewModel(app: App) = TodoViewModel(app)
@Singleton
@Provides
fun provideTodoService(client: MobileServiceClient, gson: Gson, settings: Settings) = TodoService(client, gson, settings)
} | 0 | Kotlin | 0 | 0 | dc43cf8c2f94309b25e9acca769a5da82c83e91a | 665 | Food.Parser.Kotlin | MIT License |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/crypto/outline/Wanchain1.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.crypto.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
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.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.crypto.OutlineGroup
public val OutlineGroup.Wanchain1: ImageVector
get() {
if (_wanchain1 != null) {
return _wanchain1!!
}
_wanchain1 = Builder(name = "Wanchain1", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(18.7296f, 21.75f)
horizontalLineTo(12.2696f)
curveTo(11.8496f, 21.75f, 11.4596f, 21.54f, 11.2296f, 21.19f)
lineTo(8.3096f, 16.81f)
lineTo(6.0496f, 20.68f)
curveTo(5.8296f, 21.06f, 5.4396f, 21.29f, 5.0096f, 21.3f)
curveTo(4.5896f, 21.34f, 4.1696f, 21.11f, 3.9296f, 20.74f)
lineTo(0.5596f, 15.68f)
curveTo(0.2796f, 15.26f, 0.2796f, 14.71f, 0.5596f, 14.29f)
lineTo(4.2296f, 8.79f)
curveTo(4.4596f, 8.44f, 4.8496f, 8.23f, 5.2696f, 8.23f)
horizontalLineTo(10.1996f)
lineTo(7.7996f, 4.11f)
curveTo(7.5796f, 3.72f, 7.5696f, 3.24f, 7.7996f, 2.86f)
curveTo(8.0196f, 2.47f, 8.4396f, 2.23f, 8.8796f, 2.23f)
horizontalLineTo(15.7196f)
curveTo(16.1596f, 2.23f, 16.5796f, 2.47f, 16.7996f, 2.85f)
lineTo(23.4996f, 14.33f)
curveTo(23.7396f, 14.75f, 23.7296f, 15.25f, 23.4596f, 15.65f)
lineTo(19.7796f, 21.17f)
curveTo(19.5396f, 21.54f, 19.1496f, 21.75f, 18.7296f, 21.75f)
close()
moveTo(12.3996f, 20.25f)
horizontalLineTo(18.5996f)
lineTo(22.1196f, 14.97f)
lineTo(15.5696f, 3.75f)
horizontalLineTo(9.3096f)
lineTo(12.8096f, 9.75f)
lineTo(15.2096f, 13.87f)
curveTo(15.4296f, 14.25f, 15.4396f, 14.73f, 15.2096f, 15.12f)
curveTo(14.9896f, 15.51f, 14.5696f, 15.75f, 14.1296f, 15.75f)
horizontalLineTo(9.3996f)
lineTo(12.3996f, 20.25f)
close()
moveTo(1.8996f, 15.0f)
lineTo(4.9596f, 19.58f)
lineTo(7.1996f, 15.75f)
lineTo(10.6996f, 9.75f)
horizontalLineTo(5.4096f)
lineTo(1.8996f, 15.0f)
close()
moveTo(9.8096f, 14.25f)
horizontalLineTo(13.6996f)
lineTo(11.7596f, 10.92f)
lineTo(9.8096f, 14.25f)
close()
}
}
.build()
return _wanchain1!!
}
private var _wanchain1: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 3,487 | VuesaxIcons | MIT License |
domain/src/test/java/com/foobarust/domain/usecases/cart/GetUserCartUseCaseTest.kt | foobar-UST | 285,792,732 | false | null | package com.foobarust.domain.usecases.cart
import com.foobarust.domain.states.Resource
import com.foobarust.testshared.di.DependencyContainer
import com.foobarust.testshared.repositories.FakeAuthRepositoryImpl
import com.foobarust.testshared.repositories.FakeCartRepositoryImpl
import com.foobarust.testshared.utils.TestCoroutineRule
import com.foobarust.testshared.utils.coroutineScope
import com.foobarust.testshared.utils.runBlockingTest
import com.foobarust.testshared.utils.toListUntil
import org.junit.Before
import org.junit.Rule
import org.junit.Test
/**
* Created by kevin on 4/28/21
*/
class GetUserCartUseCaseTest {
private lateinit var fakeAuthRepositoryImpl: FakeAuthRepositoryImpl
private lateinit var fakeCartRepositoryImpl: FakeCartRepositoryImpl
private lateinit var dependencyContainer: DependencyContainer
@get:Rule
var coroutineRule = TestCoroutineRule()
@Before
fun init() {
dependencyContainer = DependencyContainer()
fakeAuthRepositoryImpl = FakeAuthRepositoryImpl(
idToken = dependencyContainer.fakeIdToken,
defaultAuthProfile = dependencyContainer.fakeAuthProfile,
isSignedIn = true,
coroutineScope = coroutineRule.coroutineScope()
)
fakeCartRepositoryImpl = FakeCartRepositoryImpl(
idToken = dependencyContainer.fakeIdToken,
defaultUserCart = dependencyContainer.fakeUserCart,
defaultCartItems = dependencyContainer.fakeUserCartItems
)
}
@Test
fun `test user signed out`() = coroutineRule.runBlockingTest {
fakeAuthRepositoryImpl.setUserSignedIn(false)
fakeCartRepositoryImpl.setNetworkError(false)
val getUserCartUseCase = buildGetUserCartUseCase()
val results = getUserCartUseCase(Unit).toListUntil { it is Resource.Error }
assert(results.last() is Resource.Error)
}
@Test
fun `test get cart success`() = coroutineRule.runBlockingTest {
fakeAuthRepositoryImpl.setUserSignedIn(true)
fakeCartRepositoryImpl.setNetworkError(false)
val getUserCartUseCase = buildGetUserCartUseCase()
val results = getUserCartUseCase(Unit).toListUntil { it is Resource.Success }
assert(results.last() is Resource.Success)
}
@Test
fun `test network unavailable, get cart error`() = coroutineRule.runBlockingTest {
fakeAuthRepositoryImpl.setUserSignedIn(true)
fakeCartRepositoryImpl.setNetworkError(true)
val getUserCartUseCase = buildGetUserCartUseCase()
val results = getUserCartUseCase(Unit).toListUntil { it is Resource.Error }
assert(results.last() is Resource.Error)
}
@Test
fun `test user signed out, get cart error`() = coroutineRule.runBlockingTest {
fakeAuthRepositoryImpl.setUserSignedIn(false)
fakeCartRepositoryImpl.setNetworkError(false)
val getUserCartUseCase = buildGetUserCartUseCase()
val results = getUserCartUseCase(Unit).toListUntil { it is Resource.Error }
assert(results.last() is Resource.Error)
}
private fun buildGetUserCartUseCase(): GetUserCartUseCase {
return GetUserCartUseCase(
authRepository = fakeAuthRepositoryImpl,
cartRepository = fakeCartRepositoryImpl,
coroutineDispatcher = coroutineRule.testDispatcher
)
}
} | 0 | Kotlin | 2 | 2 | b4358ef0323a0b7a95483223496164e616a01da5 | 3,398 | foobar-android | MIT License |
PineLib/src/main/java/com/blueberrysolution/pinelib19/sqlite/mylib/model/DropTableStructure.kt | leaptochina | 228,527,202 | false | null | package com.blueberrysolution.pinelib19.sqlite.mylib.model
import com.blueberrysolution.pinelib19.activity.A
import com.blueberrysolution.pinelib19.reflection.ReflectHelper
import com.blueberrysolution.pinelib19.sqlite.mylib.user_extend_models.BModel
import kotlin.reflect.KClass
import kotlin.reflect.KClassifier
import kotlin.reflect.KType
import kotlin.reflect.jvm.internal.impl.types.checker.KotlinTypeCheckerImpl
import kotlin.reflect.jvm.javaType
open class DropTableStructure<T: BModel> : TruncateStructure<T>(){
private var dropTableSql = "";
fun dropTable(){
dropTableSql = dropTableSqlTemplate;
dropTableSql = dropTableSql.replace("%TABLE_NAME%", parseTable());
A.db!!.execSQL(dropTableSql);
}
companion object {
var dropTableSqlTemplate = "DROP TABLE if exists %TABLE_NAME%;"
}
} | 0 | Kotlin | 0 | 0 | b7ccb0b4259c3e17f71a677bdbc6388bb92d9841 | 855 | celo_test | Apache License 2.0 |
app/src/main/java/dev/juanfe/instaflix/ui/serie/SerieRepository.kt | juanfec | 308,538,789 | false | null | package dev.juanfe.instaflix.ui.serie
import androidx.lifecycle.LiveData
import dev.juanfe.instaflix.data.models.Serie
import dev.juanfe.instaflix.data.remote.ApiCalls
import dev.juanfe.instaflix.repos.NetworkState
import dev.juanfe.instaflix.repos.SerieNetworkDataSource
import io.reactivex.disposables.CompositeDisposable
class SerieRepository (private val apiService : ApiCalls) {
lateinit var serieDetailsNetworkDataSource: SerieNetworkDataSource
fun fetchSingleSerieDetails (compositeDisposable: CompositeDisposable, serieId: Int) : LiveData<Serie> {
serieDetailsNetworkDataSource = SerieNetworkDataSource(apiService,compositeDisposable)
serieDetailsNetworkDataSource.fetchSerieDetails(serieId)
return serieDetailsNetworkDataSource.downloadedSerieResponse
}
fun getMovieDetailsNetworkState(): LiveData<NetworkState> {
return serieDetailsNetworkDataSource.networkState
}
} | 0 | Kotlin | 0 | 1 | 412a121e29916bb3a9f6053fe23dbcb1dcd9bf57 | 939 | INSTAFLIX | Apache License 2.0 |
app/src/main/kotlin/com/simplemobiletools/gallery/activities/PanoramaActivity.kt | spkprs | 144,426,115 | true | {"Kotlin": 416099} | package com.simplemobiletools.gallery.activities
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.Window
import android.widget.RelativeLayout
import com.google.vr.sdk.widgets.pano.VrPanoramaEventListener
import com.google.vr.sdk.widgets.pano.VrPanoramaView
import com.simplemobiletools.commons.extensions.beVisible
import com.simplemobiletools.commons.extensions.showErrorToast
import com.simplemobiletools.commons.extensions.toast
import com.simplemobiletools.commons.helpers.PERMISSION_WRITE_STORAGE
import com.simplemobiletools.gallery.R
import com.simplemobiletools.gallery.extensions.*
import com.simplemobiletools.gallery.helpers.PATH
import kotlinx.android.synthetic.main.activity_panorama.*
open class PanoramaActivity : SimpleActivity() {
private val CARDBOARD_DISPLAY_MODE = 3
private var isFullScreen = false
private var isExploreEnabled = true
private var isRendering = false
public override fun onCreate(savedInstanceState: Bundle?) {
useDynamicTheme = false
requestWindowFeature(Window.FEATURE_NO_TITLE)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_panorama)
supportActionBar?.hide()
setupButtonMargins()
cardboard.setOnClickListener {
panorama_view.displayMode = CARDBOARD_DISPLAY_MODE
}
explore.setOnClickListener {
isExploreEnabled = !isExploreEnabled
panorama_view.setPureTouchTracking(isExploreEnabled)
explore.setImageResource(if (isExploreEnabled) R.drawable.ic_explore else R.drawable.ic_explore_off)
}
handlePermission(PERMISSION_WRITE_STORAGE) {
if (it) {
checkIntent()
} else {
toast(R.string.no_storage_permissions)
finish()
}
}
}
override fun onResume() {
super.onResume()
panorama_view.resumeRendering()
isRendering = true
if (config.blackBackground) {
updateStatusbarColor(Color.BLACK)
}
}
override fun onPause() {
super.onPause()
panorama_view.pauseRendering()
isRendering = false
}
override fun onDestroy() {
super.onDestroy()
if (isRendering) {
panorama_view.shutdown()
}
}
private fun checkIntent() {
val path = intent.getStringExtra(PATH)
if (path == null) {
toast(R.string.invalid_image_path)
finish()
return
}
intent.removeExtra(PATH)
try {
val options = VrPanoramaView.Options()
options.inputType = VrPanoramaView.Options.TYPE_MONO
Thread {
val bitmap = getBitmapToLoad(path)
runOnUiThread {
panorama_view.apply {
beVisible()
loadImageFromBitmap(bitmap, options)
setFlingingEnabled(true)
setPureTouchTracking(true)
setEventListener(object : VrPanoramaEventListener() {
override fun onClick() {
handleClick()
}
})
// add custom buttons so we can position them and toggle visibility as desired
setFullscreenButtonEnabled(false)
setInfoButtonEnabled(false)
setTransitionViewEnabled(false)
setStereoModeButtonEnabled(false)
setOnClickListener {
handleClick()
}
}
}
}.start()
} catch (e: Exception) {
showErrorToast(e)
}
window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
isFullScreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0
toggleButtonVisibility()
}
}
override fun onConfigurationChanged(newConfig: Configuration?) {
super.onConfigurationChanged(newConfig)
setupButtonMargins()
}
private fun getBitmapToLoad(path: String): Bitmap? {
val options = BitmapFactory.Options()
options.inSampleSize = 1
var bitmap: Bitmap? = null
for (i in 0..10) {
try {
bitmap = BitmapFactory.decodeFile(path, options)
break
} catch (e: OutOfMemoryError) {
options.inSampleSize *= 2
}
}
return bitmap
}
private fun setupButtonMargins() {
(cardboard.layoutParams as RelativeLayout.LayoutParams).apply {
bottomMargin = navigationBarHeight
rightMargin = navigationBarWidth
}
(explore.layoutParams as RelativeLayout.LayoutParams).bottomMargin = navigationBarHeight
}
private fun toggleButtonVisibility() {
cardboard.animate().alpha(if (isFullScreen) 0f else 1f)
cardboard.isClickable = !isFullScreen
explore.animate().alpha(if (isFullScreen) 0f else 1f)
explore.isClickable = !isFullScreen
}
private fun handleClick() {
isFullScreen = !isFullScreen
toggleButtonVisibility()
if (isFullScreen) {
hideSystemUI(false)
} else {
showSystemUI(false)
}
}
}
| 0 | Kotlin | 0 | 0 | 5d1b233e4e9f3aa2c9e37fefd69d57b457746efe | 5,635 | Simple-Gallery | Apache License 2.0 |
desktop/adapters/src/main/kotlin/com/soyle/stories/scene/trackSymbolInScene/DetectUnusedSymbolsInSceneControllerImpl.kt | Soyle-Productions | 239,407,827 | false | null | package com.soyle.stories.scene.trackSymbolInScene
import com.soyle.stories.common.ThreadTransformer
import com.soyle.stories.domain.scene.Scene
import com.soyle.stories.usecase.scene.symbol.trackSymbolInScene.DetectUnusedSymbolsInScene
class DetectUnusedSymbolsInSceneControllerImpl(
private val threadTransformer: ThreadTransformer,
private val detectUnusedSymbolsInScene: DetectUnusedSymbolsInScene,
private val detectUnusedSymbolsInSceneOutput: DetectUnusedSymbolsInScene.OutputPort
) : DetectUnusedSymbolsInSceneController {
override fun detectUnusedSymbols(sceneId: Scene.Id) {
threadTransformer.async {
detectUnusedSymbolsInScene.invoke(sceneId, detectUnusedSymbolsInSceneOutput)
}
}
} | 45 | Kotlin | 0 | 9 | 1a110536865250dcd8d29270d003315062f2b032 | 743 | soyle-stories | Apache License 2.0 |
src/main/kotlin/com/ex_dock/ex_dock/frontend/home/router/homeRouter.kt | rensPols | 849,499,548 | false | {"Kotlin": 36915, "Dockerfile": 511} | package com.ex_dock.ex_dock.frontend.home.router
import io.vertx.ext.web.Router
fun Router.initHome() {
this.get("/").handler { ctx ->
ctx.end("You've successfully accessed the '/' path for the exDock server")
}
}
| 14 | Kotlin | 0 | 2 | 54268d24375a78e50a2cb78235256e391674927f | 224 | ex-dock | Apache License 2.0 |
shared/src/commonMain/kotlin/org/deafsapps/kmm/kmmplayground/character/data/datasource/CharactersDataSource.kt | pablodeafsapps | 656,122,490 | false | {"Kotlin": 25569, "Ruby": 1722, "Swift": 1525} | package org.deafsapps.kmm.kmmplayground.character.data.datasource
import org.deafsapps.kmm.kmmplayground.base.Error
import org.deafsapps.kmm.kmmplayground.base.Result
import org.deafsapps.kmm.kmmplayground.character.data.api.CharactersService
import org.deafsapps.kmm.kmmplayground.character.data.model.CharactersDto
interface CharactersDataSource {
interface Remote {
suspend fun getAllCharacters(): Result<CharactersDto, Error>
suspend fun getCharactersByPage(page: Int): Result<CharactersDto, Error>
}
}
class RickAndMortyCharactersDataSource constructor(
private val charactersService: CharactersService
) : CharactersDataSource.Remote {
override suspend fun getAllCharacters(): Result<CharactersDto, Error> = getAllCharactersByPage()
override suspend fun getCharactersByPage(page: Int): Result<CharactersDto, Error> =
getAllCharactersByPage(page = page)
private suspend fun getAllCharactersByPage(page: Int = 1): Result<CharactersDto, Error> =
charactersService.getCharactersByPage(page = page)
}
| 0 | Kotlin | 0 | 0 | 1218022c765a8dcb46f8dcd180b6a9feb9b7b61e | 1,067 | kmm-playground | MIT License |
app/src/main/java/com/example/misw4203moviles2023/domain/album/CreateAlbums.kt | Miso-Code | 620,550,868 | false | null | package com.example.misw4203moviles2023.domain.album
import android.content.Context
import com.example.misw4203moviles2023.data.AlbumRepository
import com.example.misw4203moviles2023.data.database.entities.toDatabase
import com.example.misw4203moviles2023.domain.album.model.Album
class CreateAlbums(context: Context) {
private val repository = AlbumRepository(context)
suspend operator fun invoke(album: Album) {
repository.createAlbumToToApi(album)
repository.createAlbumToDB(album.toDatabase())
}
}
| 1 | Kotlin | 2 | 0 | 6ce0e37c688ed6b8299da4351ca70c6fbe5ac24f | 533 | misw4203-moviles-2023 | MIT License |
aes-crypto/src/androidTest/java/com/tozny/crypto/android/SHA1and8bitPasswordTest.kt | JarmoKukkola | 545,185,647 | true | {"Kotlin": 46504} | package com.tozny.crypto.android
class SHA1and8bitPasswordTest:AbstractPasswordTest() {
override val pbeAlgorithm = AesCbcWithIntegrity.PbeAlgorithm.PBKDF2withHmacSHA1And8BIT
} | 0 | Kotlin | 0 | 1 | 6403f94410c3dba85470b843bfaf44a1df23ed5b | 181 | java-aes-crypto | MIT License |
09-start-async-radiobutton-application/src/main/kotlin/components/menuBar/MenuBar.kt | kotlin-es | 75,533,048 | false | null | package components.progressBar
import components.Component
import java.awt.event.ActionEvent
import javax.swing.JComponent
import javax.swing.JMenu
import javax.swing.JMenuBar
/**
* Created by vicboma on 05/12/16.
*/
interface MenuBar : Component<JMenuBar> {
fun addMenu(list: MutableList<JComponent?>): MenuBar
fun addMenu(name: JComponent?): MenuBar
fun createSubMenu(parent: JMenu?, child: JComponent?): MenuBar
fun createSubMenu(parent: JMenu?, child: MutableList<JComponent?>): MenuBar
fun createMenu(map: Map<String, Map<String, (ActionEvent) -> Unit>>): JMenu ?
fun addSeparator(menu: JMenu?): MenuBar
} | 0 | Kotlin | 0 | 2 | 28797619791209a43fbf05586e3e274e86da0133 | 638 | kotlin-JFrame-standalone | MIT License |
core/data/src/main/kotlin/com/skydoves/gemini/core/data/repository/ChatRepositoryImpl.kt | skydoves | 746,933,651 | false | {"Kotlin": 121255} | /*
* Designed and developed by 2024 skydoves (Jaewoong Eum)
*
* 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.skydoves.gemini.core.data.repository
import com.google.ai.client.generativeai.Chat
import com.google.ai.client.generativeai.GenerativeModel
import com.google.ai.client.generativeai.type.Content
import com.google.ai.client.generativeai.type.GenerateContentResponse
import com.skydoves.gemini.core.database.GeminiDao
import com.skydoves.gemini.core.database.toDomain
import com.skydoves.gemini.core.model.GeminiChannel
import com.skydoves.gemini.core.network.Dispatcher
import com.skydoves.gemini.core.network.GeminiDispatchers
import io.getstream.chat.android.client.ChatClient
import io.getstream.result.onSuccessSuspend
import javax.inject.Inject
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
/** The exposed abstraction layer of the [ChatRepository]. */
internal class ChatRepositoryImpl @Inject constructor(
@Dispatcher(GeminiDispatchers.IO) private val ioDispatcher: CoroutineDispatcher,
private val chatClient: ChatClient,
private val geminiDao: GeminiDao
) : ChatRepository {
override suspend fun summaryContent(
generativeModel: GenerativeModel,
prompt: String
): GenerateContentResponse = generativeModel.generateContent(prompt = prompt)
override suspend fun sendMessage(chat: Chat, prompt: String): GenerateContentResponse {
return chat.sendMessage(prompt = prompt)
}
override suspend fun photoReasoning(
generativeModel: GenerativeModel,
content: Content
) = generativeModel.generateContent(content)
override fun watchIsChannelMessageEmpty(cid: String): Flow<Boolean> = flow {
val result = chatClient.channel(cid).watch().await()
result.onSuccessSuspend { channel ->
val messages = channel.messages
emit(messages.isEmpty())
}
}.flowOn(ioDispatcher)
override fun getGeminiChannel(key: String): Flow<GeminiChannel> = flow {
val geminiChannel = geminiDao.getGeminiChannel(key = key).toDomain()
emit(geminiChannel)
}
}
| 11 | Kotlin | 29 | 341 | 30588637bced5bf11c22c01abdc5fa6ce963fbcd | 2,652 | gemini-android | Apache License 2.0 |
src/main/kotlin/arvem/skykid/registries/RegisterSounds.kt | ArvemW | 686,202,965 | false | {"Kotlin": 11570} | package arvem.skykid.registries
import net.minecraft.registry.Registries
import net.minecraft.registry.Registry
import net.minecraft.sound.SoundEvent
import net.minecraft.util.Identifier
object RegisterSounds {
private val CAPE_FLAP = Identifier("skykid:player.flap")
private var CAPE_FLAP_EVENT: SoundEvent = SoundEvent.of(CAPE_FLAP)
private val CAPE_BOOST = Identifier("skykid:player.boost")
private var CAPE_BOOST_EVENT: SoundEvent = SoundEvent.of(CAPE_BOOST)
private val CAPE_WHOOSH = Identifier("skykid:player.whoosh")
private var CAPE_WHOOSH_EVENT: SoundEvent = SoundEvent.of(CAPE_WHOOSH)
private val SHOUT_DEFAULT = Identifier("skykid:player.default")
private var SHOUT_DEFAULT_EVENT: SoundEvent = SoundEvent.of(SHOUT_DEFAULT)
private val SHOUT_BIRD = Identifier("skykid:player.bird")
private var SHOUT_BIRD_EVENT: SoundEvent = SoundEvent.of(SHOUT_BIRD)
private val SHOUT_CRAB = Identifier("skykid:player.crab")
private var SHOUT_CRAB_EVENT: SoundEvent = SoundEvent.of(SHOUT_CRAB)
private val SHOUT_GHOST = Identifier("skykid:player.ghost")
private var SHOUT_GHOST_EVENT: SoundEvent = SoundEvent.of(SHOUT_GHOST)
private val SHOUT_WHALE = Identifier("skykid:player.whale")
private var SHOUT_WHALE_EVENT: SoundEvent = SoundEvent.of(SHOUT_WHALE)
private val SHOUT_JELLY = Identifier("skykid:player.jelly")
private var SHOUT_JELLY_EVENT: SoundEvent = SoundEvent.of(SHOUT_JELLY)
private val SHOUT_MANTA = Identifier("skykid:player.manta")
private var SHOUT_MANTA_EVENT: SoundEvent = SoundEvent.of(SHOUT_MANTA)
private val BEAT_SLOW = Identifier("skykid:player.beatslow")
private var BEAT_SLOW_EVENT: SoundEvent = SoundEvent.of(BEAT_SLOW)
private val BEAT_MID = Identifier("skykid:player.beatmid")
private var BEAT_MID_EVENT: SoundEvent = SoundEvent.of(BEAT_MID)
private val BEAT_FAST = Identifier("skykid:player.beatfast")
private var BEAT_FAST_EVENT: SoundEvent = SoundEvent.of(BEAT_FAST)
fun init() {
Registry.register(Registries.SOUND_EVENT, CAPE_FLAP, CAPE_FLAP_EVENT)
Registry.register(Registries.SOUND_EVENT, CAPE_BOOST, CAPE_BOOST_EVENT)
Registry.register(Registries.SOUND_EVENT, CAPE_WHOOSH, CAPE_WHOOSH_EVENT)
Registry.register(Registries.SOUND_EVENT, SHOUT_DEFAULT, SHOUT_DEFAULT_EVENT)
Registry.register(Registries.SOUND_EVENT, SHOUT_BIRD, SHOUT_BIRD_EVENT)
Registry.register(Registries.SOUND_EVENT, SHOUT_CRAB, SHOUT_CRAB_EVENT)
Registry.register(Registries.SOUND_EVENT, SHOUT_GHOST, SHOUT_GHOST_EVENT)
Registry.register(Registries.SOUND_EVENT, SHOUT_WHALE, SHOUT_WHALE_EVENT)
Registry.register(Registries.SOUND_EVENT, SHOUT_JELLY, SHOUT_JELLY_EVENT)
Registry.register(Registries.SOUND_EVENT, SHOUT_MANTA, SHOUT_MANTA_EVENT)
Registry.register(Registries.SOUND_EVENT, BEAT_SLOW, BEAT_SLOW_EVENT)
Registry.register(Registries.SOUND_EVENT, BEAT_MID, BEAT_MID_EVENT)
Registry.register(Registries.SOUND_EVENT, BEAT_FAST, BEAT_FAST_EVENT)
}
}
| 0 | Kotlin | 0 | 0 | 9105ae71cfbb6791798fc1a782f4006e63387709 | 3,069 | skykid | Creative Commons Zero v1.0 Universal |
app/src/main/java/eu/yeger/r6_stats/ui/stats/StatsViewModel.kt | DerYeger | 237,462,613 | false | null | package eu.yeger.r6_stats.ui.stats
import android.app.Application
import androidx.lifecycle.*
import eu.yeger.r6_stats.repository.FavoritesRepository
import eu.yeger.r6_stats.repository.PlayerRepository
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.launch
class StatsViewModel(application: Application, val playerId: String?) : ViewModel() {
private val playerRepository = PlayerRepository(application, playerId)
private val favoritesRepository = FavoritesRepository(application)
val player = playerRepository.currentPlayer
val hasPlayer = Transformations.map(player) { it !== null }
val isFavorite = favoritesRepository.isFavorite(playerId)
private val _refreshing = MutableLiveData<Boolean>()
val refreshing: LiveData<Boolean> = Transformations.map(_refreshing) {
it && playerId !== null
}
private val _networkExceptionAction = MutableLiveData<String>()
val networkExceptionAction: LiveData<String> = _networkExceptionAction
private val networkExceptionHandler = CoroutineExceptionHandler { _, exception ->
_refreshing.value = false
_networkExceptionAction.value = exception.message ?: "Failed to fetch profile"
}
init {
refresh()
}
fun refresh() {
viewModelScope.launch(networkExceptionHandler) {
_refreshing.value = true
playerRepository.fetchPlayer()
_refreshing.value = false
}
}
fun onFavoriteToggled() {
playerId?.let {
viewModelScope.launch {
if (isFavorite.value != null) {
favoritesRepository.removeFromFavorites(playerId)
} else {
favoritesRepository.addToFavorites(playerId)
}
}
}
}
fun onNetworkExceptionActionCompleted() {
_networkExceptionAction.value = null
}
class Factory(
private val application: Application,
private val playerId: String?
) : ViewModelProvider.Factory {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(StatsViewModel::class.java)) {
@Suppress("UNCHECKED_CAST")
return StatsViewModel(application, playerId) as T
}
throw IllegalArgumentException("Unable to construct viewmodel")
}
}
} | 0 | Kotlin | 0 | 1 | 5d57fb7f07d0c93d2f17b560a278194dc318f34e | 2,426 | r6-stats | Apache License 2.0 |
device-server/src/main/kotlin/com/badoo/automation/deviceserver/data/DeviceAllocatedPorts.kt | badoo | 133,063,088 | false | {"Kotlin": 528224, "Ruby": 19586, "Shell": 7939, "Java": 956} | package com.badoo.automation.deviceserver.data
data class DeviceAllocatedPorts(
val fbsimctlPort: Int,
val wdaPort: Int,
val calabashPort: Int,
val mjpegServerPort: Int,
val appiumPort: Int
) {
fun toSet(): Set<Int> {
return setOf(fbsimctlPort, wdaPort, calabashPort, mjpegServerPort, appiumPort)
}
} | 3 | Kotlin | 11 | 42 | 5f746abbeeca944f127eeb9fb6ac7bd4b30bf913 | 337 | ios-device-server | MIT License |
roomdb/app/src/main/java/com/kimochi/note/modules/detail/viewmodel/DetailVM.kt | farhanroy | 326,154,185 | false | {"Kotlin": 128152} | package com.kimochi.note.modules.detail.viewmodel
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.kimochi.note.db.entity.NoteEntity
import com.kimochi.note.repository.LocalNoteRepository
import com.kimochi.note.utils.debug
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import org.koin.core.KoinComponent
import org.koin.core.inject
class DetailVM : ViewModel(), KoinComponent {
var title = ""
var desc = ""
private val repository by inject<LocalNoteRepository>()
fun getNoteById(id: Int) = viewModelScope.launch(Dispatchers.IO) {
try {
bindView(repository.getNoteById(id))
} catch (e: Exception) {
e.message?.let { debug(it) }
}
}
fun deleteById(note: NoteEntity) = viewModelScope.launch(Dispatchers.IO) {
try {
repository.deleteNote(note)
debug("success delete it")
} catch (e: Exception) {
e.message?.let { debug(it) }
}
}
private fun bindView(note: NoteEntity) {
title = note.title
desc = note.description
}
} | 0 | Kotlin | 0 | 0 | eb267505f33c365f110392fc19303fc9c468a075 | 1,185 | android-self-research | MIT License |
kactoos-common/src/test/kotlin/nnl/rocks/kactoos/text/SwappedCaseTextTest.kt | neonailol | 117,650,092 | false | null | package nnl.rocks.kactoos.text
import nnl.rocks.kactoos.test.AssertTextsEquals
import kotlin.test.Test
class SwappedCaseTextTest {
@Test
fun swapsCase() {
AssertTextsEquals(
SwappedCaseText(TextOf { "hELLo!" }),
TextOf { "HellO!" },
"Can't swap case"
)
}
@Test
fun swapsEmptyText() {
AssertTextsEquals(
SwappedCaseText(TextOf { "" }),
TextOf { "" },
"Can't swap case of empty text"
)
}
}
| 0 | Kotlin | 1 | 19 | ce10c0bc7e6e65076b8ace90770b9f7648facf4a | 520 | kactoos | MIT License |
app/src/main/java/dev/fanie/statefulapp/Model.kt | iFanie | 261,402,364 | false | null | package dev.fanie.statefulapp
import dev.fanie.stateful.Stateful
import dev.fanie.stateful.StatefulOptions
import dev.fanie.stateful.StatefulType
@Stateful
data class Model(
val title: String,
val titleColor: Int,
val titleFontSize: Float?,
val isTitleVisible: Boolean,
val titleAnimates: Boolean?
)
@Stateful(type = StatefulType.STACK)
data class AnotherModel(
val index: Int,
val model: Model
)
@Stateful(options = [StatefulOptions.NO_LAZY_INIT])
data class Complex(
val model: Model,
val models: List<Model>,
val anotherModel: AnotherModel,
val otherModels: Array<AnotherModel>,
val ids: List<String>,
val strs: Array<String>,
val strMatrix: Array<Array<String>>,
val ints: IntArray,
val intMatrix: Array<IntArray>
)
@Stateful(options = [StatefulOptions.WITH_LISTENER])
data class Simple(
val number: Int
)
@Stateful(options = [StatefulOptions.WITH_NON_CASCADING_LISTENER])
data class AnotherSimple(
val number: Int
)
@Stateful(type = StatefulType.LINKED_LIST)
data class TimeTraveller(
val id: String,
val uid: Long,
val name: String
)
@Stateful(options = [StatefulOptions.NO_DIFFING])
data class Effect(
val error: Throwable
)
| 1 | Kotlin | 1 | 8 | 6d864d8f852a0cc89ca216bd9b37e3cb8513fd62 | 1,228 | Stateful | Apache License 2.0 |
core/src/commonMain/kotlin/ru/pixnews/debuglayout/DisplayMetrics.kt | illarionov | 739,759,344 | false | {"Kotlin": 102703} | /*
* Copyright (c) 2024, the pixnews-debuglayout project authors and contributors.
* Please see the AUTHORS file for details.
* Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
*/
package ru.pixnews.debuglayout
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
internal data class DisplayMetrics(val density: Float, val xdpi: Float, val ydpi: Float) {
public fun withDensity(density: Float): DisplayMetrics {
return if (this.density != density) {
this.copy(density = density)
} else {
this
}
}
}
@Composable
@Suppress("ModifierComposable")
internal expect fun Modifier.getDisplayMetrics(): DisplayMetrics
| 0 | Kotlin | 0 | 0 | a8c6684fce803bb21f88fb6e3dfb90f48602e345 | 750 | pixnews-debuglayout | Apache License 2.0 |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/appmesh/CfnVirtualServiceDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.appmesh
import cloudshift.awscdk.common.CdkDslMarker
import cloudshift.awscdk.dsl.CfnTagDsl
import kotlin.String
import kotlin.Unit
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.CfnTag
import software.amazon.awscdk.IResolvable
import software.amazon.awscdk.services.appmesh.CfnVirtualService
import software.constructs.Construct
/**
* Creates a virtual service within a service mesh.
*
* A virtual service is an abstraction of a real service that is provided by a virtual node directly
* or indirectly by means of a virtual router. Dependent services call your virtual service by its
* `virtualServiceName` , and those requests are routed to the virtual node or virtual router that is
* specified as the provider for the virtual service.
*
* For more information about virtual services, see [Virtual
* services](https://docs.aws.amazon.com/app-mesh/latest/userguide/virtual_services.html) .
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.appmesh.*;
* CfnVirtualService cfnVirtualService = CfnVirtualService.Builder.create(this,
* "MyCfnVirtualService")
* .meshName("meshName")
* .spec(VirtualServiceSpecProperty.builder()
* .provider(VirtualServiceProviderProperty.builder()
* .virtualNode(VirtualNodeServiceProviderProperty.builder()
* .virtualNodeName("virtualNodeName")
* .build())
* .virtualRouter(VirtualRouterServiceProviderProperty.builder()
* .virtualRouterName("virtualRouterName")
* .build())
* .build())
* .build())
* .virtualServiceName("virtualServiceName")
* // the properties below are optional
* .meshOwner("meshOwner")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appmesh-virtualservice.html)
*/
@CdkDslMarker
public class CfnVirtualServiceDsl(
scope: Construct,
id: String,
) {
private val cdkBuilder: CfnVirtualService.Builder = CfnVirtualService.Builder.create(scope, id)
private val _tags: MutableList<CfnTag> = mutableListOf()
/**
* The name of the service mesh to create the virtual service in.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appmesh-virtualservice.html#cfn-appmesh-virtualservice-meshname)
* @param meshName The name of the service mesh to create the virtual service in.
*/
public fun meshName(meshName: String) {
cdkBuilder.meshName(meshName)
}
/**
* The AWS IAM account ID of the service mesh owner.
*
* If the account ID is not your own, then the account that you specify must share the mesh with
* your account before you can create the resource in the service mesh. For more information about
* mesh sharing, see [Working with shared
* meshes](https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html) .
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appmesh-virtualservice.html#cfn-appmesh-virtualservice-meshowner)
* @param meshOwner The AWS IAM account ID of the service mesh owner.
*/
public fun meshOwner(meshOwner: String) {
cdkBuilder.meshOwner(meshOwner)
}
/**
* The virtual service specification to apply.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appmesh-virtualservice.html#cfn-appmesh-virtualservice-spec)
* @param spec The virtual service specification to apply.
*/
public fun spec(spec: IResolvable) {
cdkBuilder.spec(spec)
}
/**
* The virtual service specification to apply.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appmesh-virtualservice.html#cfn-appmesh-virtualservice-spec)
* @param spec The virtual service specification to apply.
*/
public fun spec(spec: CfnVirtualService.VirtualServiceSpecProperty) {
cdkBuilder.spec(spec)
}
/**
* Optional metadata that you can apply to the virtual service to assist with categorization and
* organization.
*
* Each tag consists of a key and an optional value, both of which you define. Tag keys can have a
* maximum character length of 128 characters, and tag values can have a maximum length of 256
* characters.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appmesh-virtualservice.html#cfn-appmesh-virtualservice-tags)
* @param tags Optional metadata that you can apply to the virtual service to assist with
* categorization and organization.
*/
public fun tags(tags: CfnTagDsl.() -> Unit) {
_tags.add(CfnTagDsl().apply(tags).build())
}
/**
* Optional metadata that you can apply to the virtual service to assist with categorization and
* organization.
*
* Each tag consists of a key and an optional value, both of which you define. Tag keys can have a
* maximum character length of 128 characters, and tag values can have a maximum length of 256
* characters.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appmesh-virtualservice.html#cfn-appmesh-virtualservice-tags)
* @param tags Optional metadata that you can apply to the virtual service to assist with
* categorization and organization.
*/
public fun tags(tags: Collection<CfnTag>) {
_tags.addAll(tags)
}
/**
* The name to use for the virtual service.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-appmesh-virtualservice.html#cfn-appmesh-virtualservice-virtualservicename)
* @param virtualServiceName The name to use for the virtual service.
*/
public fun virtualServiceName(virtualServiceName: String) {
cdkBuilder.virtualServiceName(virtualServiceName)
}
public fun build(): CfnVirtualService {
if(_tags.isNotEmpty()) cdkBuilder.tags(_tags)
return cdkBuilder.build()
}
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 6,355 | awscdk-dsl-kotlin | Apache License 2.0 |
fluent/src/commonMain/kotlin/com/konyaco/fluent/component/SideNav.kt | Konyaco | 574,321,009 | false | {"Kotlin": 11419712, "Java": 256912} | package com.konyaco.fluent.component
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.layout
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.konyaco.fluent.FluentTheme
import com.konyaco.fluent.LocalTextStyle
import com.konyaco.fluent.animation.FluentDuration
import com.konyaco.fluent.animation.FluentEasing
import com.konyaco.fluent.background.BackgroundSizing
import com.konyaco.fluent.background.Layer
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.regular.ChevronDown
import com.konyaco.fluent.icons.regular.Navigation
import com.konyaco.fluent.icons.regular.Search
import com.konyaco.fluent.scheme.PentaVisualScheme
import com.konyaco.fluent.scheme.collectVisualState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
private val LocalExpand = compositionLocalOf { false }
private val LocalNavigationLevel = compositionLocalOf { 0 }
private val LocalSelectedItemPosition = compositionLocalOf<MutableTransitionState<Float>?> { null }
@Composable
fun SideNav(
modifier: Modifier,
expanded: Boolean,
onExpandStateChange: (Boolean) -> Unit,
title: @Composable (() -> Unit) = {},
autoSuggestionBox: (@Composable AutoSuggestionBoxScope.() -> Unit)? = null,
footer: @Composable (() -> Unit)? = null,
content: @Composable () -> Unit
) {
val width by animateDpAsState(
if (expanded) 320.dp else 48.dp,
tween(FluentDuration.ShortDuration, easing = FluentEasing.FastInvokeEasing)
)
Column(modifier.width(width)) {
Spacer(Modifier.height(8.dp))
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(horizontal = 4.dp).height(42.dp)
) {
SubtleButton(
modifier = Modifier.padding(vertical = 4.dp).size(38.dp, 34.dp),
onClick = { onExpandStateChange(!expanded) },
iconOnly = true
) {
Icon(Icons.Default.Navigation, "Expand")
}
if (expanded) {
CompositionLocalProvider(
LocalTextStyle provides FluentTheme.typography.bodyStrong
) {
title()
}
}
}
val positionState = remember {
MutableTransitionState(0f)
}
CompositionLocalProvider(
LocalExpand provides expanded,
LocalNavigationLevel provides 0,
LocalSelectedItemPosition provides positionState,
) {
autoSuggestionBox?.let {
val focusRequester = remember {
FocusRequester()
}
val autoSuggestionBoxScope = remember(focusRequester) {
AutoSuggestionBoxScopeImpl(focusRequester)
}
Box(
contentAlignment = Alignment.TopStart,
modifier = Modifier.height(48.dp)
) {
val expandedScope = rememberCoroutineScope()
if (expanded) {
Box(modifier = Modifier.padding(horizontal = 16.dp).padding(top = 2.dp)) {
autoSuggestionBoxScope.it()
}
} else {
SideNavItem(
selected = false,
onClick = {
onExpandStateChange(true)
expandedScope.launch {
delay(FluentDuration.ShortDuration.toLong())
focusRequester.requestFocus()
}
},
icon = {
Icon(Icons.Default.Search, null)
},
content = {}
)
}
}
}
val scrollState = rememberScrollState()
ScrollbarContainer(
adapter = rememberScrollbarAdapter(scrollState),
modifier = Modifier.weight(1f)
) {
Column(
modifier = Modifier.fillMaxHeight().verticalScroll(scrollState).padding(
bottom = 8.dp
)
) {
content()
}
}
footer?.let {
// Divider
NavigationItemSeparator(modifier = Modifier.padding(bottom = 4.dp))
it()
Spacer(Modifier.height(4.dp))
}
}
}
}
@Composable
fun SideNavItem(
selected: Boolean,
expand: Boolean = LocalExpand.current,
onClick: (Boolean) -> Unit,
modifier: Modifier = Modifier,
expandItems: Boolean = false,
colors: NavigationItemColorScheme = if (selected) {
NavigationDefaults.selectedSideNavigationItemColors()
} else {
NavigationDefaults.defaultSideNavigationItemColors()
},
icon: @Composable (() -> Unit)? = null,
items: @Composable (ColumnScope.() -> Unit)? = null,
indicator: @Composable IndicatorScope.() -> Unit = {
NavigationDefaults.VerticalIndicator(modifier = Modifier.indicatorOffset { selected })
},
content: @Composable RowScope.() -> Unit
) {
val interaction = remember { MutableInteractionSource() }
//TODO Enabled
val color = colors.schemeFor(interaction.collectVisualState(false))
var currentPosition by remember {
mutableStateOf(0f)
}
val selectedState = LocalSelectedItemPosition.current
LaunchedEffect(selected, currentPosition) {
if (selected) {
selectedState?.targetState = currentPosition
}
}
Column(
modifier = modifier.onGloballyPositioned {
currentPosition = it.positionInRoot().y
}
) {
Box(Modifier.height(40.dp).fillMaxWidth().padding(4.dp, 2.dp)) {
val navigationLevelPadding = 28.dp * LocalNavigationLevel.current
Layer(
modifier = Modifier.fillMaxWidth().height(36.dp),
shape = RoundedCornerShape(size = 4.dp),
color = animateColorAsState(
color.fillColor, tween(FluentDuration.QuickDuration, easing = FluentEasing.FastInvokeEasing)
).value,
contentColor = color.contentColor,
border = null,
backgroundSizing = BackgroundSizing.OuterBorderEdge
) {
Box(
Modifier.clickable(
onClick = { onClick(!selected) },
interactionSource = interaction,
indication = null
).padding(start = navigationLevelPadding),
Alignment.CenterStart
) {
if (icon != null) Box(Modifier.padding(start = 12.dp).size(18.dp), Alignment.Center) {
icon()
}
val fraction by animateFloatAsState(
targetValue = if (expand) 1f else 0f,
tween(FluentDuration.ShortDuration, easing = FluentEasing.FastInvokeEasing)
)
if (expand) {
Row(
modifier = Modifier.padding(
start = if (icon != null) 44.dp else 16.dp,
end = if (items != null) 44.dp else 0.dp
),
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
verticalAlignment = Alignment.CenterVertically,
) {
content()
}
if (items != null) {
val rotation by animateFloatAsState(
if (expandItems) {
180f
} else {
00f
}
)
Icon(
Icons.Default.ChevronDown,
null,
modifier = Modifier.width(36.dp)
.align(Alignment.CenterEnd)
.wrapContentWidth(Alignment.CenterHorizontally).size(12.dp)
.graphicsLayer {
rotationZ = rotation
alpha = if (fraction == 1f) {
1f
} else {
0f
}
}
)
}
}
}
}
Box(modifier = Modifier.align(Alignment.CenterStart).padding(start = navigationLevelPadding)) {
SideNavigationIndicatorScope.indicator()
}
}
if (items != null) {
AnimatedVisibility(
visible = expandItems && expand,
enter = fadeIn(
animationSpec = tween(FluentDuration.ShortDuration, easing = FluentEasing.FastInvokeEasing)
) + expandVertically(
animationSpec = tween(FluentDuration.ShortDuration, easing = FluentEasing.FastInvokeEasing)
),
exit = fadeOut(
animationSpec = tween(FluentDuration.ShortDuration, easing = FluentEasing.FastInvokeEasing)
) + shrinkVertically(
animationSpec = tween(FluentDuration.ShortDuration, easing = FluentEasing.FastInvokeEasing)
),
modifier = Modifier.fillMaxWidth()
) {
CompositionLocalProvider(
LocalNavigationLevel provides LocalNavigationLevel.current + 1
) {
Column {
items()
}
}
}
}
}
}
typealias NavigationItemColorScheme = PentaVisualScheme<NavigationItemColor>
@Immutable
data class NavigationItemColor(
val fillColor: Color,
val contentColor: Color
)
//TODO Common Defaults for SideNavigation and TopNavigation
object NavigationDefaults {
@Composable
@Stable
fun defaultSideNavigationItemColors(
default: NavigationItemColor = NavigationItemColor(
fillColor = FluentTheme.colors.subtleFill.transparent,
contentColor = FluentTheme.colors.text.text.primary
),
hovered: NavigationItemColor = default.copy(
fillColor = FluentTheme.colors.subtleFill.secondary
),
pressed: NavigationItemColor = default.copy(
fillColor = FluentTheme.colors.subtleFill.tertiary
),
//TODO Disabled style
disabled: NavigationItemColor = default
) = NavigationItemColorScheme(
default = default,
hovered = hovered,
pressed = pressed,
disabled = disabled
)
@Composable
@Stable
fun selectedSideNavigationItemColors(
default: NavigationItemColor = NavigationItemColor(
fillColor = FluentTheme.colors.subtleFill.secondary,
contentColor = FluentTheme.colors.text.text.primary
),
hovered: NavigationItemColor = default.copy(
fillColor = FluentTheme.colors.subtleFill.tertiary
),
pressed: NavigationItemColor = default.copy(
fillColor = FluentTheme.colors.subtleFill.tertiary
),
//TODO Disabled style
disabled: NavigationItemColor = default
) = NavigationItemColorScheme(
default = default,
hovered = hovered,
pressed = pressed,
disabled = disabled
)
@Composable
fun VerticalIndicator(
modifier: Modifier = Modifier,
color: Color = FluentTheme.colors.fillAccent.default,
shape: Shape = CircleShape,
thickness: Dp = 3.dp
) {
Box(modifier.width(thickness).background(color, shape))
}
//TODO TopNavigation
@Composable
fun HorizontalIndicator(
modifier: Modifier = Modifier,
color: Color = FluentTheme.colors.fillAccent.default,
shape: Shape = CircleShape,
thickness: Dp = 3.dp
) {
Box(modifier.height(thickness).background(color, shape))
}
}
interface IndicatorScope {
@Composable
fun Modifier.indicatorOffset(visible: () -> Boolean): Modifier
}
interface AutoSuggestionBoxScope {
fun Modifier.focusHandle(): Modifier
}
private object SideNavigationIndicatorScope: IndicatorScope {
@Composable
override fun Modifier.indicatorOffset(visible: () -> Boolean): Modifier {
val display by rememberUpdatedState(visible)
val selectionState = LocalSelectedItemPosition.current
val indicatorState = remember {
MutableTransitionState(display())
}
indicatorState.targetState = display()
val animationModifier = if (selectionState != null) {
Modifier.indicatorOffsetAnimation(16.dp, indicatorState, selectionState)
} else {
val height by updateTransition(display()).animateDp(transitionSpec = {
if (targetState) tween(FluentDuration.ShortDuration, easing = FluentEasing.FastInvokeEasing)
else tween(FluentDuration.QuickDuration, easing = FluentEasing.SoftDismissEasing)
}, targetValueByState = { if (it) 16.dp else 0.dp })
Modifier.height(height)
}
return then(animationModifier)
}
}
//TODO TopNavigationIndicatorScope
internal class AutoSuggestionBoxScopeImpl(
private val focusRequest: FocusRequester
) : AutoSuggestionBoxScope {
override fun Modifier.focusHandle() = focusRequester(focusRequest)
}
@Composable
fun NavigationItemSeparator(
isVertical: Boolean = false,
modifier: Modifier = Modifier,
color: Color = FluentTheme.colors.stroke.surface.default.copy(0.2f)
) {
val sizeModifier = if (!isVertical) {
Modifier.fillMaxWidth().height(1.dp)
} else {
Modifier.fillMaxHeight().width(1.dp)
}
Box(
Modifier
.then(modifier)
.then(sizeModifier)
.background(color)
)
}
@Composable
private fun Modifier.indicatorOffsetAnimation(
size: Dp,
indicatorState: MutableTransitionState<Boolean>,
selectedPosition: MutableTransitionState<Float>,
isVertical: Boolean = true
): Modifier {
val fraction by updateTransition(indicatorState).animateFloat(
transitionSpec = {
tween(FluentDuration.VeryLongDuration , easing = FluentEasing.PointToPointEasing)
},
targetValueByState = { if (it) 1f else 0f }
)
//Delay set selected position
if (indicatorState.isIdle && indicatorState.targetState) {
updateTransition(selectedPosition).animateFloat(transitionSpec = {
tween(
FluentDuration.QuickDuration,
easing = FluentEasing.FastInvokeEasing
)
}) { it }
}
return layout { measurable, constraints ->
val stickSize = size.toPx()
val containerSize = if (isVertical) {
constraints.maxHeight
} else {
constraints.maxWidth
}
val goBackward = selectedPosition.currentState > selectedPosition.targetState
val contentPadding = ((containerSize - stickSize) / 2).coerceAtLeast(0f)
val extendSize = containerSize - contentPadding
val currentFraction = if (indicatorState.targetState) {
fraction
} else {
1 - fraction
}
val segmentFraction = when {
currentFraction > 0.75 -> (currentFraction - 0.75f) * 4
currentFraction > 0.5 -> (currentFraction - 0.5f) * 4
currentFraction > 0.25 -> (currentFraction - 0.25f) * 4
else -> currentFraction * 4
}
val currentSize = if (!indicatorState.targetState) {
when {
currentFraction <= 0.25 -> androidx.compose.ui.util.lerp(stickSize, extendSize, segmentFraction)
currentFraction <= 0.5f -> androidx.compose.ui.util.lerp(extendSize, 0f, segmentFraction)
else -> 0f
}
} else {
when {
currentFraction > 0.75f -> androidx.compose.ui.util.lerp(
extendSize,
stickSize,
segmentFraction
)
currentFraction > 0.5f -> androidx.compose.ui.util.lerp(0f, extendSize, segmentFraction)
else -> 0f
}
}
val placeable = if (isVertical) {
measurable.measure(Constraints.fixedHeight(currentSize.roundToInt().coerceAtLeast(0)))
} else {
measurable.measure(Constraints.fixedWidth(currentSize.roundToInt().coerceAtLeast(0)))
}
layout(
width = if (isVertical) placeable.width else constraints.maxWidth,
height = if (isVertical) constraints.maxHeight else placeable.height
) {
val offset = when {
goBackward && !indicatorState.targetState && currentFraction <= 0.25f -> extendSize - currentSize
goBackward && !indicatorState.targetState -> 0f
!goBackward && !indicatorState.targetState && currentFraction <= 0.25f -> contentPadding
!goBackward && !indicatorState.targetState -> containerSize - currentSize
goBackward && currentFraction > 0.75f -> contentPadding
goBackward && currentFraction > 0.5f -> containerSize - currentSize
!goBackward && currentFraction > 0.75f -> extendSize - currentSize
!goBackward && currentFraction > 0.5f -> 0f
else -> 0f
}
if (isVertical) {
placeable.place(0, offset.roundToInt())
} else {
placeable.place(offset.roundToInt(), 0)
}
}
}
} | 8 | Kotlin | 10 | 262 | 293d7ab02d80fb9fdd372826fdc0b42b1d6e0019 | 21,379 | compose-fluent-ui | Apache License 2.0 |
fluent/src/commonMain/kotlin/com/konyaco/fluent/component/SideNav.kt | Konyaco | 574,321,009 | false | {"Kotlin": 11419712, "Java": 256912} | package com.konyaco.fluent.component
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.animateDp
import androidx.compose.animation.core.animateDpAsState
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.tween
import androidx.compose.animation.core.updateTransition
import androidx.compose.animation.expandVertically
import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.shrinkVertically
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.Immutable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.Stable
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.layout
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInRoot
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.konyaco.fluent.FluentTheme
import com.konyaco.fluent.LocalTextStyle
import com.konyaco.fluent.animation.FluentDuration
import com.konyaco.fluent.animation.FluentEasing
import com.konyaco.fluent.background.BackgroundSizing
import com.konyaco.fluent.background.Layer
import com.konyaco.fluent.icons.Icons
import com.konyaco.fluent.icons.regular.ChevronDown
import com.konyaco.fluent.icons.regular.Navigation
import com.konyaco.fluent.icons.regular.Search
import com.konyaco.fluent.scheme.PentaVisualScheme
import com.konyaco.fluent.scheme.collectVisualState
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlin.math.roundToInt
private val LocalExpand = compositionLocalOf { false }
private val LocalNavigationLevel = compositionLocalOf { 0 }
private val LocalSelectedItemPosition = compositionLocalOf<MutableTransitionState<Float>?> { null }
@Composable
fun SideNav(
modifier: Modifier,
expanded: Boolean,
onExpandStateChange: (Boolean) -> Unit,
title: @Composable (() -> Unit) = {},
autoSuggestionBox: (@Composable AutoSuggestionBoxScope.() -> Unit)? = null,
footer: @Composable (() -> Unit)? = null,
content: @Composable () -> Unit
) {
val width by animateDpAsState(
if (expanded) 320.dp else 48.dp,
tween(FluentDuration.ShortDuration, easing = FluentEasing.FastInvokeEasing)
)
Column(modifier.width(width)) {
Spacer(Modifier.height(8.dp))
Row(
horizontalArrangement = Arrangement.spacedBy(8.dp),
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(horizontal = 4.dp).height(42.dp)
) {
SubtleButton(
modifier = Modifier.padding(vertical = 4.dp).size(38.dp, 34.dp),
onClick = { onExpandStateChange(!expanded) },
iconOnly = true
) {
Icon(Icons.Default.Navigation, "Expand")
}
if (expanded) {
CompositionLocalProvider(
LocalTextStyle provides FluentTheme.typography.bodyStrong
) {
title()
}
}
}
val positionState = remember {
MutableTransitionState(0f)
}
CompositionLocalProvider(
LocalExpand provides expanded,
LocalNavigationLevel provides 0,
LocalSelectedItemPosition provides positionState,
) {
autoSuggestionBox?.let {
val focusRequester = remember {
FocusRequester()
}
val autoSuggestionBoxScope = remember(focusRequester) {
AutoSuggestionBoxScopeImpl(focusRequester)
}
Box(
contentAlignment = Alignment.TopStart,
modifier = Modifier.height(48.dp)
) {
val expandedScope = rememberCoroutineScope()
if (expanded) {
Box(modifier = Modifier.padding(horizontal = 16.dp).padding(top = 2.dp)) {
autoSuggestionBoxScope.it()
}
} else {
SideNavItem(
selected = false,
onClick = {
onExpandStateChange(true)
expandedScope.launch {
delay(FluentDuration.ShortDuration.toLong())
focusRequester.requestFocus()
}
},
icon = {
Icon(Icons.Default.Search, null)
},
content = {}
)
}
}
}
val scrollState = rememberScrollState()
ScrollbarContainer(
adapter = rememberScrollbarAdapter(scrollState),
modifier = Modifier.weight(1f)
) {
Column(
modifier = Modifier.fillMaxHeight().verticalScroll(scrollState).padding(
bottom = 8.dp
)
) {
content()
}
}
footer?.let {
// Divider
NavigationItemSeparator(modifier = Modifier.padding(bottom = 4.dp))
it()
Spacer(Modifier.height(4.dp))
}
}
}
}
@Composable
fun SideNavItem(
selected: Boolean,
expand: Boolean = LocalExpand.current,
onClick: (Boolean) -> Unit,
modifier: Modifier = Modifier,
expandItems: Boolean = false,
colors: NavigationItemColorScheme = if (selected) {
NavigationDefaults.selectedSideNavigationItemColors()
} else {
NavigationDefaults.defaultSideNavigationItemColors()
},
icon: @Composable (() -> Unit)? = null,
items: @Composable (ColumnScope.() -> Unit)? = null,
indicator: @Composable IndicatorScope.() -> Unit = {
NavigationDefaults.VerticalIndicator(modifier = Modifier.indicatorOffset { selected })
},
content: @Composable RowScope.() -> Unit
) {
val interaction = remember { MutableInteractionSource() }
//TODO Enabled
val color = colors.schemeFor(interaction.collectVisualState(false))
var currentPosition by remember {
mutableStateOf(0f)
}
val selectedState = LocalSelectedItemPosition.current
LaunchedEffect(selected, currentPosition) {
if (selected) {
selectedState?.targetState = currentPosition
}
}
Column(
modifier = modifier.onGloballyPositioned {
currentPosition = it.positionInRoot().y
}
) {
Box(Modifier.height(40.dp).fillMaxWidth().padding(4.dp, 2.dp)) {
val navigationLevelPadding = 28.dp * LocalNavigationLevel.current
Layer(
modifier = Modifier.fillMaxWidth().height(36.dp),
shape = RoundedCornerShape(size = 4.dp),
color = animateColorAsState(
color.fillColor, tween(FluentDuration.QuickDuration, easing = FluentEasing.FastInvokeEasing)
).value,
contentColor = color.contentColor,
border = null,
backgroundSizing = BackgroundSizing.OuterBorderEdge
) {
Box(
Modifier.clickable(
onClick = { onClick(!selected) },
interactionSource = interaction,
indication = null
).padding(start = navigationLevelPadding),
Alignment.CenterStart
) {
if (icon != null) Box(Modifier.padding(start = 12.dp).size(18.dp), Alignment.Center) {
icon()
}
val fraction by animateFloatAsState(
targetValue = if (expand) 1f else 0f,
tween(FluentDuration.ShortDuration, easing = FluentEasing.FastInvokeEasing)
)
if (expand) {
Row(
modifier = Modifier.padding(
start = if (icon != null) 44.dp else 16.dp,
end = if (items != null) 44.dp else 0.dp
),
horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterHorizontally),
verticalAlignment = Alignment.CenterVertically,
) {
content()
}
if (items != null) {
val rotation by animateFloatAsState(
if (expandItems) {
180f
} else {
00f
}
)
Icon(
Icons.Default.ChevronDown,
null,
modifier = Modifier.width(36.dp)
.align(Alignment.CenterEnd)
.wrapContentWidth(Alignment.CenterHorizontally).size(12.dp)
.graphicsLayer {
rotationZ = rotation
alpha = if (fraction == 1f) {
1f
} else {
0f
}
}
)
}
}
}
}
Box(modifier = Modifier.align(Alignment.CenterStart).padding(start = navigationLevelPadding)) {
SideNavigationIndicatorScope.indicator()
}
}
if (items != null) {
AnimatedVisibility(
visible = expandItems && expand,
enter = fadeIn(
animationSpec = tween(FluentDuration.ShortDuration, easing = FluentEasing.FastInvokeEasing)
) + expandVertically(
animationSpec = tween(FluentDuration.ShortDuration, easing = FluentEasing.FastInvokeEasing)
),
exit = fadeOut(
animationSpec = tween(FluentDuration.ShortDuration, easing = FluentEasing.FastInvokeEasing)
) + shrinkVertically(
animationSpec = tween(FluentDuration.ShortDuration, easing = FluentEasing.FastInvokeEasing)
),
modifier = Modifier.fillMaxWidth()
) {
CompositionLocalProvider(
LocalNavigationLevel provides LocalNavigationLevel.current + 1
) {
Column {
items()
}
}
}
}
}
}
typealias NavigationItemColorScheme = PentaVisualScheme<NavigationItemColor>
@Immutable
data class NavigationItemColor(
val fillColor: Color,
val contentColor: Color
)
//TODO Common Defaults for SideNavigation and TopNavigation
object NavigationDefaults {
@Composable
@Stable
fun defaultSideNavigationItemColors(
default: NavigationItemColor = NavigationItemColor(
fillColor = FluentTheme.colors.subtleFill.transparent,
contentColor = FluentTheme.colors.text.text.primary
),
hovered: NavigationItemColor = default.copy(
fillColor = FluentTheme.colors.subtleFill.secondary
),
pressed: NavigationItemColor = default.copy(
fillColor = FluentTheme.colors.subtleFill.tertiary
),
//TODO Disabled style
disabled: NavigationItemColor = default
) = NavigationItemColorScheme(
default = default,
hovered = hovered,
pressed = pressed,
disabled = disabled
)
@Composable
@Stable
fun selectedSideNavigationItemColors(
default: NavigationItemColor = NavigationItemColor(
fillColor = FluentTheme.colors.subtleFill.secondary,
contentColor = FluentTheme.colors.text.text.primary
),
hovered: NavigationItemColor = default.copy(
fillColor = FluentTheme.colors.subtleFill.tertiary
),
pressed: NavigationItemColor = default.copy(
fillColor = FluentTheme.colors.subtleFill.tertiary
),
//TODO Disabled style
disabled: NavigationItemColor = default
) = NavigationItemColorScheme(
default = default,
hovered = hovered,
pressed = pressed,
disabled = disabled
)
@Composable
fun VerticalIndicator(
modifier: Modifier = Modifier,
color: Color = FluentTheme.colors.fillAccent.default,
shape: Shape = CircleShape,
thickness: Dp = 3.dp
) {
Box(modifier.width(thickness).background(color, shape))
}
//TODO TopNavigation
@Composable
fun HorizontalIndicator(
modifier: Modifier = Modifier,
color: Color = FluentTheme.colors.fillAccent.default,
shape: Shape = CircleShape,
thickness: Dp = 3.dp
) {
Box(modifier.height(thickness).background(color, shape))
}
}
interface IndicatorScope {
@Composable
fun Modifier.indicatorOffset(visible: () -> Boolean): Modifier
}
interface AutoSuggestionBoxScope {
fun Modifier.focusHandle(): Modifier
}
private object SideNavigationIndicatorScope: IndicatorScope {
@Composable
override fun Modifier.indicatorOffset(visible: () -> Boolean): Modifier {
val display by rememberUpdatedState(visible)
val selectionState = LocalSelectedItemPosition.current
val indicatorState = remember {
MutableTransitionState(display())
}
indicatorState.targetState = display()
val animationModifier = if (selectionState != null) {
Modifier.indicatorOffsetAnimation(16.dp, indicatorState, selectionState)
} else {
val height by updateTransition(display()).animateDp(transitionSpec = {
if (targetState) tween(FluentDuration.ShortDuration, easing = FluentEasing.FastInvokeEasing)
else tween(FluentDuration.QuickDuration, easing = FluentEasing.SoftDismissEasing)
}, targetValueByState = { if (it) 16.dp else 0.dp })
Modifier.height(height)
}
return then(animationModifier)
}
}
//TODO TopNavigationIndicatorScope
internal class AutoSuggestionBoxScopeImpl(
private val focusRequest: FocusRequester
) : AutoSuggestionBoxScope {
override fun Modifier.focusHandle() = focusRequester(focusRequest)
}
@Composable
fun NavigationItemSeparator(
isVertical: Boolean = false,
modifier: Modifier = Modifier,
color: Color = FluentTheme.colors.stroke.surface.default.copy(0.2f)
) {
val sizeModifier = if (!isVertical) {
Modifier.fillMaxWidth().height(1.dp)
} else {
Modifier.fillMaxHeight().width(1.dp)
}
Box(
Modifier
.then(modifier)
.then(sizeModifier)
.background(color)
)
}
@Composable
private fun Modifier.indicatorOffsetAnimation(
size: Dp,
indicatorState: MutableTransitionState<Boolean>,
selectedPosition: MutableTransitionState<Float>,
isVertical: Boolean = true
): Modifier {
val fraction by updateTransition(indicatorState).animateFloat(
transitionSpec = {
tween(FluentDuration.VeryLongDuration , easing = FluentEasing.PointToPointEasing)
},
targetValueByState = { if (it) 1f else 0f }
)
//Delay set selected position
if (indicatorState.isIdle && indicatorState.targetState) {
updateTransition(selectedPosition).animateFloat(transitionSpec = {
tween(
FluentDuration.QuickDuration,
easing = FluentEasing.FastInvokeEasing
)
}) { it }
}
return layout { measurable, constraints ->
val stickSize = size.toPx()
val containerSize = if (isVertical) {
constraints.maxHeight
} else {
constraints.maxWidth
}
val goBackward = selectedPosition.currentState > selectedPosition.targetState
val contentPadding = ((containerSize - stickSize) / 2).coerceAtLeast(0f)
val extendSize = containerSize - contentPadding
val currentFraction = if (indicatorState.targetState) {
fraction
} else {
1 - fraction
}
val segmentFraction = when {
currentFraction > 0.75 -> (currentFraction - 0.75f) * 4
currentFraction > 0.5 -> (currentFraction - 0.5f) * 4
currentFraction > 0.25 -> (currentFraction - 0.25f) * 4
else -> currentFraction * 4
}
val currentSize = if (!indicatorState.targetState) {
when {
currentFraction <= 0.25 -> androidx.compose.ui.util.lerp(stickSize, extendSize, segmentFraction)
currentFraction <= 0.5f -> androidx.compose.ui.util.lerp(extendSize, 0f, segmentFraction)
else -> 0f
}
} else {
when {
currentFraction > 0.75f -> androidx.compose.ui.util.lerp(
extendSize,
stickSize,
segmentFraction
)
currentFraction > 0.5f -> androidx.compose.ui.util.lerp(0f, extendSize, segmentFraction)
else -> 0f
}
}
val placeable = if (isVertical) {
measurable.measure(Constraints.fixedHeight(currentSize.roundToInt().coerceAtLeast(0)))
} else {
measurable.measure(Constraints.fixedWidth(currentSize.roundToInt().coerceAtLeast(0)))
}
layout(
width = if (isVertical) placeable.width else constraints.maxWidth,
height = if (isVertical) constraints.maxHeight else placeable.height
) {
val offset = when {
goBackward && !indicatorState.targetState && currentFraction <= 0.25f -> extendSize - currentSize
goBackward && !indicatorState.targetState -> 0f
!goBackward && !indicatorState.targetState && currentFraction <= 0.25f -> contentPadding
!goBackward && !indicatorState.targetState -> containerSize - currentSize
goBackward && currentFraction > 0.75f -> contentPadding
goBackward && currentFraction > 0.5f -> containerSize - currentSize
!goBackward && currentFraction > 0.75f -> extendSize - currentSize
!goBackward && currentFraction > 0.5f -> 0f
else -> 0f
}
if (isVertical) {
placeable.place(0, offset.roundToInt())
} else {
placeable.place(offset.roundToInt(), 0)
}
}
}
} | 8 | Kotlin | 10 | 262 | 293d7ab02d80fb9fdd372826fdc0b42b1d6e0019 | 21,379 | compose-fluent-ui | Apache License 2.0 |
wrapper/godot-library/src/main/kotlin/godot/generated/VisualShader.kt | payload | 189,718,948 | true | {"Kotlin": 3888394, "C": 6051, "Batchfile": 714, "Shell": 574} | @file:Suppress("unused", "ClassName", "EnumEntryName", "FunctionName", "SpellCheckingInspection", "PARAMETER_NAME_CHANGED_ON_OVERRIDE", "UnusedImport", "PackageDirectoryMismatch")
package godot
import godot.gdnative.*
import godot.core.*
import godot.utils.*
import godot.icalls.*
import kotlinx.cinterop.*
// NOTE: THIS FILE IS AUTO GENERATED FROM JSON API CONFIG
open class VisualShader : Shader {
constructor() : super("VisualShader")
constructor(variant: Variant) : super(variant)
internal constructor(mem: COpaquePointer) : super(mem)
internal constructor(name: String) : super(name)
// Enums
enum class Type(val id: Long) {
TYPE_VERTEX(0),
TYPE_FRAGMENT(1),
TYPE_LIGHT(2),
TYPE_MAX(3),
;
companion object {
fun fromInt(value: Long) = values().single { it.id == value }
}
}
// Signals
class Signal {
companion object {
}
}
companion object {
infix fun from(other: Shader): VisualShader = VisualShader("").apply { setRawMemory(other.rawMemory) }
infix fun from(other: Resource): VisualShader = VisualShader("").apply { setRawMemory(other.rawMemory) }
infix fun from(other: Reference): VisualShader = VisualShader("").apply { setRawMemory(other.rawMemory) }
infix fun from(other: Object): VisualShader = VisualShader("").apply { setRawMemory(other.rawMemory) }
infix fun from(other: Variant): VisualShader = fromVariant(VisualShader(""), other)
// Constants
const val TYPE_VERTEX: Long = 0
const val TYPE_FRAGMENT: Long = 1
const val TYPE_LIGHT: Long = 2
const val TYPE_MAX: Long = 3
const val NODE_ID_INVALID: Long = -1
const val NODE_ID_OUTPUT: Long = 0
}
// Properties
open var graphOffset: Vector2
get() = _icall_Vector2(getGraphOffsetMethodBind, this.rawMemory)
set(value) = _icall_Unit_Vector2(setGraphOffsetMethodBind, this.rawMemory, value)
open fun graphOffset(shedule: (Vector2) -> Unit): Vector2 = graphOffset.apply {
shedule(this)
graphOffset = this
}
// Methods
private val setModeMethodBind: CPointer<godot_method_bind> by lazy { getMB("VisualShader", "set_mode") }
open fun setMode(mode: Long) {
_icall_Unit_Long(setModeMethodBind, this.rawMemory, mode)
}
private val addNodeMethodBind: CPointer<godot_method_bind> by lazy { getMB("VisualShader", "add_node") }
open fun addNode(type: Long, node: VisualShaderNode, position: Vector2, id: Long) {
_icall_Unit_Long_Object_Vector2_Long(addNodeMethodBind, this.rawMemory, type, node, position, id)
}
private val setNodePositionMethodBind: CPointer<godot_method_bind> by lazy { getMB("VisualShader", "set_node_position") }
open fun setNodePosition(type: Long, id: Long, position: Vector2) {
_icall_Unit_Long_Long_Vector2(setNodePositionMethodBind, this.rawMemory, type, id, position)
}
private val getNodePositionMethodBind: CPointer<godot_method_bind> by lazy { getMB("VisualShader", "get_node_position") }
open fun getNodePosition(type: Long, id: Long): Vector2 {
return _icall_Vector2_Long_Long(getNodePositionMethodBind, this.rawMemory, type, id)
}
private val getNodeMethodBind: CPointer<godot_method_bind> by lazy { getMB("VisualShader", "get_node") }
open fun getNode(type: Long, arg1: Long): VisualShaderNode {
return _icall_VisualShaderNode_Long_Long(getNodeMethodBind, this.rawMemory, type, arg1)
}
private val getNodeListMethodBind: CPointer<godot_method_bind> by lazy { getMB("VisualShader", "get_node_list") }
open fun getNodeList(type: Long): PoolIntArray {
return _icall_PoolIntArray_Long(getNodeListMethodBind, this.rawMemory, type)
}
private val getValidNodeIdMethodBind: CPointer<godot_method_bind> by lazy { getMB("VisualShader", "get_valid_node_id") }
open fun getValidNodeId(type: Long): Long {
return _icall_Long_Long(getValidNodeIdMethodBind, this.rawMemory, type)
}
private val removeNodeMethodBind: CPointer<godot_method_bind> by lazy { getMB("VisualShader", "remove_node") }
open fun removeNode(type: Long, id: Long) {
_icall_Unit_Long_Long(removeNodeMethodBind, this.rawMemory, type, id)
}
private val isNodeConnectionMethodBind: CPointer<godot_method_bind> by lazy { getMB("VisualShader", "is_node_connection") }
open fun isNodeConnection(type: Long, fromNode: Long, fromPort: Long, toNode: Long, toPort: Long): Boolean {
return _icall_Boolean_Long_Long_Long_Long_Long(isNodeConnectionMethodBind, this.rawMemory, type, fromNode, fromPort, toNode, toPort)
}
private val canConnectNodesMethodBind: CPointer<godot_method_bind> by lazy { getMB("VisualShader", "can_connect_nodes") }
open fun canConnectNodes(type: Long, fromNode: Long, fromPort: Long, toNode: Long, toPort: Long): Boolean {
return _icall_Boolean_Long_Long_Long_Long_Long(canConnectNodesMethodBind, this.rawMemory, type, fromNode, fromPort, toNode, toPort)
}
private val connectNodesMethodBind: CPointer<godot_method_bind> by lazy { getMB("VisualShader", "connect_nodes") }
open fun connectNodes(type: Long, fromNode: Long, fromPort: Long, toNode: Long, toPort: Long): GodotError {
return GodotError.fromInt(_icall_Long_Long_Long_Long_Long_Long(connectNodesMethodBind, this.rawMemory, type, fromNode, fromPort, toNode, toPort))
}
private val disconnectNodesMethodBind: CPointer<godot_method_bind> by lazy { getMB("VisualShader", "disconnect_nodes") }
open fun disconnectNodes(type: Long, fromNode: Long, fromPort: Long, toNode: Long, toPort: Long) {
_icall_Unit_Long_Long_Long_Long_Long(disconnectNodesMethodBind, this.rawMemory, type, fromNode, fromPort, toNode, toPort)
}
private val getNodeConnectionsMethodBind: CPointer<godot_method_bind> by lazy { getMB("VisualShader", "get_node_connections") }
open fun getNodeConnections(type: Long): GDArray {
return _icall_GDArray_Long(getNodeConnectionsMethodBind, this.rawMemory, type)
}
private val setGraphOffsetMethodBind: CPointer<godot_method_bind> by lazy { getMB("VisualShader", "set_graph_offset") }
open fun setGraphOffset(offset: Vector2) {
_icall_Unit_Vector2(setGraphOffsetMethodBind, this.rawMemory, offset)
}
private val getGraphOffsetMethodBind: CPointer<godot_method_bind> by lazy { getMB("VisualShader", "get_graph_offset") }
open fun getGraphOffset(): Vector2 {
return _icall_Vector2(getGraphOffsetMethodBind, this.rawMemory)
}
open fun _queue_update() {
}
open fun _update_shader() {
}
open fun _input_type_changed(arg0: Long, arg1: Long) {
}
}
| 0 | Kotlin | 1 | 2 | 70473f9b9a0de08d82222b735e7f9b07bbe91700 | 6,826 | kotlin-godot-wrapper | Apache License 2.0 |
media/src/main/java/fr/nihilus/music/media/provider/Models.kt | thibseisel | 80,150,620 | 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 fr.nihilus.music.media.provider
/**
* The metadata of a track that is saved on the device's storage.
*/
class Track(
/** The unique identifier of the track on the device media storage index. */
val id: Long,
/** The title of this track as it should be displayed to the user. */
val title: String,
/**
* The name of the artist that produced this track.
* @see Artist.name
*/
val artist: String,
/**
* The title of the album this track is part of.
* @see Album.title
*/
val album: String,
/** The playback duration of this track in milliseconds. */
val duration: Long,
/** The disc number for this track's original source. */
val discNumber: Int,
/** The position of this track from its original disc. */
val trackNumber: Int,
/** An Uri-style String pointing to the content associated with this track's metadata. */
val mediaUri: String,
/** An Uri-style String pointing to an optional artwork for this track's album. */
val albumArtUri: String?,
/**
* The time at which this track has been added to the local storage,
* expressed as the number of seconds elapsed since January 1st 1970 (Unix Epoch).
*/
val availabilityDate: Long,
/**
* The unique identifier of the artist that produced this track.
* @see Artist.id
*/
val artistId: Long,
/**
* The unique identifier of the album this track is part of.
* @see Album.id
*/
val albumId: Long,
/** The size of the file stored on the device's storage, in bytes. */
val fileSize: Long
) {
override fun toString(): String = "Track{id=$id, title=$title}"
override fun equals(other: Any?): Boolean = this === other || (other is Track && other.id == id)
override fun hashCode(): Int = id.toInt()
}
/**
* The metadata of an album whose tracks are saved on the device's storage.
*/
class Album(
/** The unique identifier of this album on the device's media storage index. */
val id: Long,
/** The title of the album as it should be displayed to the user. */
val title: String,
/**
* The name of the artist that recorded this album.
* @see Artist.name
*/
val artist: String,
/** The number of tracks that are part of this album. */
val trackCount: Int,
/** The year at which this album has been released. */
val releaseYear: Int,
/** An optional Uri-formatted String pointing to the artwork associated with this album. */
val albumArtUri: String?,
/**
* The unique identifier of the artist that recorded this album.
* @see Artist.id
*/
val artistId: Long
) {
override fun toString(): String = "Album{id=$id, title=$title, artist=$artist}"
override fun equals(other: Any?): Boolean = this === other || (other is Album && other.id == id)
override fun hashCode(): Int = id.toInt()
}
/**
* The metadata of an artist that produced tracks that are saved on the device's storage.
*/
class Artist(
/** The unique identifier of this artist on the device's media storage index. */
val id: Long,
/** The full name of this artist as it should be displayed to the user. */
val name: String,
/** The number of album this artist as recorded. */
val albumCount: Int,
/** The number of tracks that have been produced by this artist, all albums combined. */
val trackCount: Int,
/** An optional Uri-formatted String pointing to an artwork representing this artist. */
val iconUri: String?
) {
override fun toString(): String = "Artist{id=$id, name=$name}"
override fun equals(other: Any?): Boolean = this === other || (other is Album && other.id == id)
override fun hashCode(): Int = id.toInt()
} | 14 | Kotlin | 8 | 50 | d2abd7a0a83ea25e00cf1ad52ec1004478775157 | 4,378 | android-odeon | Apache License 2.0 |
app/src/main/java/com/wreckingballsoftware/fiveoclocksomewhere/database/ItsFiveOClockSomewhereDb.kt | leewaggoner | 691,900,392 | false | {"Kotlin": 68083} | package com.wreckingballsoftware.fiveoclocksomewhere.database
import androidx.room.Database
import androidx.room.RoomDatabase
@Database(
entities = [
DBCocktails::class,
DBTimeZones::class,
DBPlaces::class,
DBRegionalCocktails::class,
],
version = 3,
exportSchema = false
)
abstract class ItsFiveOClockSomewhereDb : RoomDatabase() {
abstract fun getTimeZonesDao(): TimeZonesDao
abstract fun getPlacesDao(): PlacesDao
abstract fun getRegionalCocktails(): RegionalCocktailsDao
}
| 0 | Kotlin | 0 | 0 | 9027cd1378daac84fe93ec6098414158ff876b32 | 541 | fiveoclocksomewhere | Apache License 2.0 |
examples/gold-trading/cordapp/src/main/kotlin/net/corda/gold/trading/workflows/flows/GetAllLoansOwnedByAccountFlow.kt | corda | 170,131,330 | false | {"Kotlin": 149237, "Dockerfile": 724} | package net.corda.gold.trading.workflows.flows
import co.paralleluniverse.fibers.Suspendable
import com.r3.corda.lib.accounts.contracts.states.AccountInfo
import net.corda.core.contracts.StateAndRef
import net.corda.core.flows.FlowLogic
import net.corda.core.flows.StartableByRPC
import net.corda.core.node.services.Vault
import net.corda.core.node.services.queryBy
import net.corda.core.node.services.vault.QueryCriteria
import net.corda.gold.trading.contracts.states.LoanBook
@StartableByRPC
class GetAllLoansOwnedByAccountFlow(private val account: StateAndRef<AccountInfo>) : FlowLogic<List<StateAndRef<LoanBook>>>() {
@Suspendable
override fun call(): List<StateAndRef<LoanBook>> {
val criteria = QueryCriteria.VaultQueryCriteria(
status = Vault.StateStatus.UNCONSUMED,
contractStateTypes = setOf(LoanBook::class.java),
externalIds = listOf(account.state.data.identifier.id)
)
return serviceHub.vaultService.queryBy<LoanBook>(criteria = criteria).states
}
} | 28 | Kotlin | 38 | 35 | c2428c28c341d6f9649390e202ff3b02c25cb2f3 | 1,047 | accounts | Apache License 2.0 |
domain/src/main/java/com/krakert/tracker/domain/tracker/SetAmountDaysTracking.kt | Krakert | 500,599,145 | false | {"Kotlin": 146201} | package com.krakert.tracker.domain.tracker
import javax.inject.Inject
class SetAmountDaysTracking @Inject constructor(
private val repository: PreferencesRepository,
) {
operator fun invoke(days: Int) = repository.setAmountDaysTracking(days)
} | 4 | Kotlin | 1 | 7 | 2e1a3741faa4f66d7a7b013c4544c8c7a18508c6 | 253 | Crypto-Tracker | MIT License |
buffering-event-dispatcher/src/main/kotlin/at/agsolutions/demo/SecurityUtils.kt | ajgassner | 267,076,709 | false | null | package at.agsolutions.demo
import com.vaadin.flow.server.HandlerHelper
import com.vaadin.flow.shared.ApplicationConstants
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails
import javax.servlet.http.HttpServletRequest
object SecurityUtils {
val user: UserDetails?
get() = SecurityContextHolder.getContext().authentication?.principal as? UserDetails
fun isFrameworkInternalRequest(request: HttpServletRequest): Boolean {
val parameterValue = request.getParameter(ApplicationConstants.REQUEST_TYPE_PARAMETER)
return parameterValue != null && HandlerHelper.RequestType.values().any { r -> r.identifier == parameterValue }
}
}
| 2 | Kotlin | 0 | 0 | 473b66a93c06078dffd533e5c68fa089e33d6400 | 749 | vaadin-playground | MIT License |
app/src/main/java/se/umu/ad/anpa0292/voxelsculpter/World.kt | tehAndrew | 850,690,052 | false | {"Kotlin": 31609, "GLSL": 1629} | package se.umu.ad.anpa0292.voxelsculpter
import android.util.Log
import kotlin.math.max
import kotlin.math.min
data class Ray(val origin: Vector3D, val direction: Vector3D) {
val invDirection = Vector3D(1 / direction.x, 1 / direction.y, 1 / direction.z)
}
data class AABB(val min: Vector3D, val max: Vector3D)
class World(private var viewportWidth: Int, private var viewportHeight: Int) {
val camera: PerspectiveCamera = PerspectiveCamera(
Vector3D(0f, 0f, 0f),
60f,
viewportWidth, viewportHeight
)
val voxels = arrayOf(
Voxel(Vector3D(0f, 0f, 0f)),
Voxel(Vector3D(1f, 0f, 0f)),
Voxel(Vector3D(-1f, 0f, 0f)),
Voxel(Vector3D(0f, -1f, 0f)),
Voxel(Vector3D(0f, 1f, 0f)),
)
var selectedVoxel = voxels[1]
// Updated by open gl in renderer. Spaghetti intensifies
fun setViewport(viewportWidth: Int, viewportHeight: Int) {
this.viewportWidth = viewportWidth
this.viewportHeight = viewportHeight
camera.setViewport(viewportWidth, viewportHeight)
}
fun selectVoxelAtCenter() {
val ray = camera.screenPosToWorldRay(
Vector3D(viewportWidth / 2f, viewportHeight / 2f, 0f)
)
val tVals = mutableListOf<Pair<Float, Voxel>>()
for (voxel in voxels) {
val aabb = calculateVoxelAABB(voxel)
Log.d("selectVoxelAtScreenPos", ray.origin.toString());
intersectRayAABB(ray, aabb)?.let {
tVals.add(it to voxel)
}
}
if (tVals.isNotEmpty()) {
val (value, voxel) = tVals.minBy { it.first }
selectedVoxel = voxel
}
}
fun centerCamera() {
camera.setTarget(selectedVoxel.pos)
}
// Uses the fast branchless check here: https://tavianator.com/2015/ray_box_nan.html
private fun intersectRayAABB(ray: Ray, aabb: AABB): Float? {
var tmin = Float.NEGATIVE_INFINITY
var tmax = Float.POSITIVE_INFINITY
for (i in 0 until 3) {
val t1 = (aabb.min[i] - ray.origin[i]) * ray.invDirection[i]
val t2 = (aabb.max[i] - ray.origin[i]) * ray.invDirection[i]
tmin = max(tmin, min(t1, t2))
tmax = min(tmax, max(t1, t2))
}
val isIntersecting = tmax > maxOf(tmin, 0f)
return if (isIntersecting) tmin else null
}
private fun calculateVoxelAABB(voxel: Voxel): AABB {
val center = voxel.pos
val halfSideVec = Vector3D(Voxel.HALF_SIDE, Voxel.HALF_SIDE, Voxel.HALF_SIDE)
return AABB(
center - halfSideVec,
center + halfSideVec
)
}
} | 0 | Kotlin | 0 | 0 | 6e0ef77cfd9faee4eedbe655d3d9b779aa317eb9 | 2,661 | VoxelSculpter | MIT License |
light/src/test/kotlin/net/kotlinx/aws/dynamo/DynamoQuery_쿼리테스트.kt | mypojo | 565,799,715 | false | {"Kotlin": 1118162, "Java": 9531, "Jupyter Notebook": 7080} | //package net.kotlinx.aws.dynamo
//
//import net.kotlinx.kotest.BeSpecLog
//
//
//internal class DynamoQuery_쿼리테스트 : BeSpecLog(){
//
// init {
// val aws = AwsConfig(profileName = "sin").toAwsClient1()
//
// val byStatusPk = DynamoQuery {
// indexName = "gidx-jobStatus-pk"
// scanIndexForward = false //최근 데이터 우선
// select = Select.AllProjectedAttributes
// limit = 4
// queryParam = {
// val job = it as Job
// mapOf(
// ":${DynamoDbBasic.PK}" to AttributeValue.S(job.pk),
// ":${Job::jobStatus.name}" to AttributeValue.S(job.jobStatus!!)
// )
// }
// }
//
// @TestLevel03
// fun queryAll() = runBlocking {
//
// Job.TABLE_NAME = "job-prod"
//
// val param = Job("xxEpJob", "").apply {
// jobStatus = "SUCCEEDED"
// }
// val jobs = aws.dynamo.queryAll(byStatusPk, param)
// println("jobs.size = ${jobs.size}")
// jobs.forEach {
// println("${it.sk} ")
// }
//
// }
//
// @TestLevel03
// fun query() = runBlocking {
//
// Job.TABLE_NAME = "job-prod"
//
// val param = Job("WConcepMetaEpJob", "").apply {
// jobStatus = "SUCCEEDED"
// }
// val jobs = aws.dynamo.query(byStatusPk, param)
// println("jobs.size = ${jobs.size}")
// jobs.forEach {
// println("${it.sk} ")
// }
//
// }
// }
//} | 0 | Kotlin | 0 | 1 | 7c80c11863d06c7ffea9bf6b967b875225930b54 | 1,623 | kx_kotlin_support | MIT License |
core/design/src/main/kotlin/cn/wj/android/cashbook/core/design/component/Remember.kt | WangJie0822 | 365,932,300 | false | {"Kotlin": 1658612, "Java": 1405038, "Batchfile": 535} | /*
* Copyright 2021 The Cashbook Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.wj.android.cashbook.core.design.component
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
@Composable
fun rememberSnackbarHostState(): SnackbarHostState {
return remember { SnackbarHostState() }
}
| 7 | Kotlin | 11 | 71 | 6c39b443a1e1e46cf3c4533db3ab270df1f1b9e8 | 920 | Cashbook | Apache License 2.0 |
core/src/commonMain/kotlin/dev/inmo/kmppscriptbuilder/core/ui/ListView.kt | InsanusMokrassar | 342,929,719 | false | null | package dev.inmo.kmppscriptbuilder.core.ui
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateListOf
import dev.inmo.kmppscriptbuilder.core.ui.utils.Drawer
expect class ListViewDrawer<T>() : Drawer<ListView<T>>
abstract class ListView<T>(title: String) : VerticalView(title) {
internal val itemsList = mutableStateListOf<T>()
internal open val addItemText: String = "Add"
internal open val removeItemText: String = "Remove"
internal abstract fun createItem(): T
@Composable
internal abstract fun buildView(item: T)
protected val drawer = ListViewDrawer<T>()
override val content: @Composable () -> Unit = {
with(drawer) {
draw()
}
}
}
| 2 | Kotlin | 0 | 3 | 41e8d2c54070ec28e88cbe9ecd28ebe25c141902 | 742 | KotlinPublicationScriptsBuilder | Apache License 2.0 |
MainActivity.kt | Nisha-B-Rajput | 730,577,732 | false | {"Kotlin": 1853} | package com.example.loginapplication
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.text.TextUtils
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
class MainActivity : AppCompatActivity() {
private lateinit var usernameInput: EditText
private lateinit var passwordInput: EditText
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
usernameInput = findViewById(R.id.username_input)
passwordInput = findViewById(R.id.password_input)
val username = usernameInput.text.toString()
val password = passwordInput.text.toString()
val button: Button = findViewById(R.id.login_btn)
button.setOnClickListener {
if (TextUtils.isEmpty(username)) {
Toast.makeText(this, "Please enter username", Toast.LENGTH_LONG).show()
} else if (TextUtils.isEmpty(password)) {
Toast.makeText(this, "Please enter password", Toast.LENGTH_LONG).show()
} else if ((username.toString()=="Admin") && (password.toString() == "<PASSWORD>")){
startActivity(Intent(this,MainActivity2::class.java))
}
else {
Toast.makeText(this, "Please enter correct username and password", Toast.LENGTH_LONG).show()
}
}
}
} | 0 | Kotlin | 0 | 0 | d37e0eb0e37c6ed2f09a83e5eb054f528e6fa8bd | 1,494 | SDN-Nisha-B-Rajput | MIT License |
app/src/main/java/com/example/kinetic/presentation/navigation/GenresNavGraph.kt | BENJAHJP | 593,154,677 | false | null | package com.example.kinetic.presentation.navigation
import androidx.compose.animation.AnimatedContentScope
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.tween
import androidx.compose.runtime.Composable
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.navigation
import com.example.kinetic.presentation.games_list.components.GamesListScreen
import com.example.kinetic.presentation.screen.Screens
import com.google.accompanist.navigation.animation.AnimatedNavHost
import com.google.accompanist.navigation.animation.composable
@OptIn(ExperimentalAnimationApi::class)
fun NavGraphBuilder.genresNavGraph(navHostController: NavHostController) {
navigation(
route = Graph.GENRES,
startDestination = Screens.GenreScreen.route
){
composable(
route = Screens.GenreScreen.route + "/{genre}",
enterTransition = {
when (targetState.destination.route) {
navHostController.currentDestination?.route ->
slideIntoContainer(
AnimatedContentScope.SlideDirection.Left,
initialOffset = {0},
animationSpec = tween(300)
)
else -> null
}
},
popExitTransition = {
when (targetState.destination.route) {
navHostController.currentDestination?.route ->
slideOutOfContainer(AnimatedContentScope.SlideDirection.Right, animationSpec = tween(1000))
else -> null
}
}
){
GamesListScreen(
navHostController = navHostController,
onPopBackStack = { navHostController.popBackStack() })
}
}
} | 0 | Kotlin | 0 | 1 | 56172a121b0902ad0d79521a4562fea3879beafd | 1,929 | Inverse | MIT License |
client/app/src/main/java/com/unina/natourkt/core/analytics/AnalyticsExtension.kt | archer-65 | 433,413,556 | false | null | package com.unina.natourkt.core.analytics
import android.os.Bundle
/**
* This functions provides a fast way to convert [AnalyticsEvent.params] to [Bundle], useful for
* `Firebase Analytics`
*/
fun Map<String, Any>?.toBundle(): Bundle {
val bundle = Bundle()
this?.forEach { (key, value) -> bundle.putString(key, value.toString()) }
return bundle
} | 0 | Kotlin | 0 | 1 | d0c4881e6b8432aff5cf1751d58350da2d5a4461 | 364 | natour-2122 | Apache License 2.0 |
src/main/kotlin/com/victor/example/webfluxcoroutine/handler/AbstractHandler.kt | chayu07 | 255,509,178 | false | null | package com.victor.example.webfluxcoroutine.handler
import com.victor.example.kotlinx.redirectBuilder
import com.victor.example.webfluxcoroutine.code.ErrorCd
import com.victor.example.webfluxcoroutine.exception.ApiException
import com.victor.example.kotlinx.toPrettyFormat
import com.victor.example.webfluxcoroutine.model.ErrorResponse
import com.victor.example.webfluxcoroutine.model.HeaderInfo
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.reactive.awaitSingle
import org.apache.logging.log4j.LogManager
import org.springframework.http.HttpStatus
import org.springframework.http.MediaType
import org.springframework.http.ResponseCookie
import org.springframework.util.MultiValueMap
import org.springframework.web.reactive.function.BodyInserters.fromValue
import org.springframework.web.reactive.function.server.*
import reactor.core.publisher.Mono
open class ErrorHandler {
private val log = LogManager.getLogger()!!
private fun handle(e: Throwable, serverRequest: ServerRequest, defaultErrorCd: ErrorCd = ErrorCd.INTERNAL_ERROR): Pair<Int, ErrorResponse> {
log.warn("Fail to handle ${serverRequest.uri()}", e)
return when (e) {
is ApiException -> {
val errorResponse = if (e.customMessageFlag) {
ErrorResponse(errorCd = e.errorCd, message = e.message!!)
} else {
ErrorResponse(errorCd = e.errorCd)
}
log.debug("Handling ${e.javaClass.name} Responding with $errorResponse")
Pair(e.errorCd.statusCode, errorResponse)
}
else -> {
val errorResponse = ErrorResponse(errorCd = defaultErrorCd)
log.debug("Handling ${e.javaClass.name} Responding with $errorResponse")
Pair(defaultErrorCd.statusCode, errorResponse)
}
}
}
suspend fun coHandleException(e: Throwable, serverRequest: ServerRequest, defaultErrorCd: ErrorCd = ErrorCd.INTERNAL_ERROR): ServerResponse {
val errorResponse = handle(e, serverRequest, defaultErrorCd)
return ServerResponse
.status(errorResponse.first)
.contentType(MediaType.APPLICATION_JSON)
.bodyValueAndAwait(errorResponse.second)
}
}
open class LoggingHandler {
private val log = LogManager.getLogger()!!
fun logRequest(serverRequest: ServerRequest) {
log.info("""
|Handling Request ========================================
|Method: ${serverRequest.method()}
|Uri: ${serverRequest.uri()}
|Headers:
|${serverRequest.headers().asHttpHeaders().toPrettyFormat()}
|========================================
""".trimMargin())
}
@Suppress("MemberVisibilityCanBePrivate")
fun <Res> logResponse(serverRequest: ServerRequest, serverResponse: ServerResponse, body: Res) {
log.info("""
|Responding with ========================================
|
|Handling Request ========================================
|Method: ${serverRequest.method()}
|Uri: ${serverRequest.uri()}
|Headers:
|${serverRequest.headers().asHttpHeaders().toPrettyFormat()}
|
|Response ========================================
|Status: ${serverResponse.statusCode()}
|Headers:
|${serverResponse.headers().toPrettyFormat()}
|Body:
|${body.toString()}
|========================================
""".trimMargin())
}
@Suppress("MemberVisibilityCanBePrivate")
fun logResponse(serverResponse: ServerResponse) {
log.info("""
|Responding with ========================================
|Status: ${serverResponse.statusCode()}
|Headers:
|${serverResponse.headers().toPrettyFormat()}
|Cookies:
|${serverResponse.cookies().toPrettyFormat()}
|========================================
""".trimMargin())
}
}
open class AvoidEmptyResponseHandler {
fun avoidEmptyResponse(): Mono<ServerResponse> = ServerResponse
.status(HttpStatus.INTERNAL_SERVER_ERROR)
.contentType(MediaType.APPLICATION_JSON)
.body(
fromValue(ErrorResponse(ErrorCd.INTERNAL_ERROR))
)
}
open class LoggingAndErrorHandler {
private val errorHandler: ErrorHandler = ErrorHandler()
private val loggingHandler: LoggingHandler = LoggingHandler()
private val avoidEmptyResponseHandler: AvoidEmptyResponseHandler = AvoidEmptyResponseHandler()
suspend fun coHandleException(e: Throwable, serverRequest: ServerRequest, defaultErrorCd: ErrorCd = ErrorCd.INTERNAL_ERROR): ServerResponse =
errorHandler.coHandleException(e, serverRequest, defaultErrorCd)
fun logRequest(serverRequest: ServerRequest) = loggingHandler.logRequest(serverRequest)
fun logResponse(serverResponse: ServerResponse) = loggingHandler.logResponse(serverResponse)
fun <Res> logResponse(serverRequest: ServerRequest, serverResponse: ServerResponse, body: Res) = loggingHandler.logResponse(serverRequest, serverResponse, body)
fun avoidEmptyResponse(): Mono<ServerResponse> = avoidEmptyResponseHandler.avoidEmptyResponse()
}
abstract class AbstractCoHandler : LoggingAndErrorHandler() {
data class RenderContext(val resourceName: String, val model: Map<String, Any> = mapOf(),
var cookieData: String? = "", var alreadyCookieExist: Boolean = false, var cookie: ResponseCookie? = null,
var redirect: Boolean = false, val headers: Map<String, String> = mapOf()) {
companion object {
fun redirect(redirectUrl: String): RenderContext = RenderContext(resourceName = redirectUrl, redirect = true)
}
}
protected suspend inline fun renderOrRedirectWithFormDataAndPathVariableAndHeaderInfo(
serverRequest: ServerRequest,
crossinline f: suspend (body: MultiValueMap<String, String>, pathVariables: Map<String, String>, headerInfo: HeaderInfo) -> RenderContext): ServerResponse {
return coroutineScope {
try {
logRequest(serverRequest)
val context = f(serverRequest.formData().awaitSingle(), serverRequest.pathVariables(), HeaderInfo.of(serverRequest))
if (context.redirect) {
val builder = redirectBuilder(context.resourceName)
context.headers.forEach {
builder.header(it.key, it.value)
}
val serverResponse = builder.buildAndAwait()
logResponse(serverResponse)
serverResponse
} else {
val builder = RenderingResponse.create(context.resourceName)
.modelAttributes(context.model)
context.headers.forEach {
builder.header(it.key, it.value)
}
val renderingResponse = builder.buildAndAwait()
logResponse(renderingResponse)
renderingResponse
}
} catch (e: Exception) {
coHandleException(e, serverRequest)
}
}
}
protected suspend fun renderOrRedirectWithPathVariableAndHeaderInfo(
serverRequest: ServerRequest,
f: suspend (Map<String, String>, headerInfo: HeaderInfo) -> RenderContext): ServerResponse {
return coroutineScope {
try {
logRequest(serverRequest)
val context = f(serverRequest.pathVariables(), HeaderInfo.of(serverRequest))
if (context.redirect) {
val builder = redirectBuilder(context.resourceName)
context.headers.forEach {
builder.header(it.key, it.value)
}
val serverResponse = builder.buildAndAwait()
logResponse(serverResponse)
serverResponse
} else {
val builder = RenderingResponse.create(context.resourceName)
.modelAttributes(context.model)
context.headers.forEach {
builder.header(it.key, it.value)
}
builder.buildAndAwait()
}
} catch (e: Exception) {
coHandleException(e, serverRequest)
}
}
}
protected suspend inline fun <reified Req, Res> handleWithRequestBody(serverRequest: ServerRequest,
crossinline f: suspend (Req) -> Res): ServerResponse {
return coroutineScope {
try {
logRequest(serverRequest)
val body = serverRequest.bodyToMono(Req::class.java).awaitSingle()
val res: Res = f(body)
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyValue(res!!)
.doOnNext { logResponse(serverRequest, it, res) }.awaitSingle()
} catch (e: Exception) {
coHandleException(e, serverRequest)
}
}
}
protected suspend fun <RES> handleWithQueryParams(
serverRequest: ServerRequest,
param: Map<String, Any>,
f: suspend (Map<String, Any>) -> RES): ServerResponse {
return coroutineScope {
try {
logRequest(serverRequest)
val res: RES = f(param)
ServerResponse.ok().contentType(MediaType.APPLICATION_JSON).bodyValue(res!!)
.doOnNext { logResponse(serverRequest, it, res) }.awaitSingle()
} catch (e: Exception) {
coHandleException(e, serverRequest)
}
}
}
}
| 0 | Kotlin | 0 | 3 | d276eaa0a24fbe26597511c9b9352876d201dd8e | 10,117 | webflux-coroutine | Apache License 2.0 |
server/src/main/kotlin/com/thoughtworks/archguard/code/clazz/domain/JClassRepository.kt | archguard | 460,910,110 | false | {"Kotlin": 1763628, "Java": 611399, "TypeScript": 11395, "C#": 5593, "Dockerfile": 2549, "C": 1223, "Shell": 926, "JavaScript": 400, "Go": 291, "Scala": 97, "Python": 42, "Rust": 32} | package com.thoughtworks.archguard.code.clazz.domain
import org.archguard.model.code.ClassRelation
import org.archguard.model.code.JClass
import org.archguard.model.code.JField
interface JClassRepository {
fun getJClassBy(systemId: Long, name: String, module: String?): JClass?
fun getJClassById(id: String): JClass?
fun getAllBySystemId(systemId: Long): List<JClass>
fun getJClassesHasModules(systemId: Long): List<JClass>
fun findDependencees(id: String): List<JClass>
fun findDependencers(id: String): List<JClass>
fun findClassParents(systemId: Long, module: String, name: String): List<JClass>
fun findClassImplements(systemId: Long, name: String, module: String): List<JClass>
fun findCallees(systemId: Long, name: String, module: String): List<ClassRelation>
fun findCallers(systemId: Long, name: String, module: String): List<ClassRelation>
fun findFields(id: String): List<JField>
}
| 1 | Kotlin | 89 | 575 | 049f3cc8f2c0e2c34e65bb0049f645caa5be9bf8 | 948 | archguard | MIT License |
src/Day01.kt | pmatsinopoulos | 730,162,975 | false | {"Kotlin": 4441} | val ZERO_TO_DIGITS = mapOf(
"one" to "1",
"two" to "2",
"three" to "3",
"four" to "4",
"five" to "5",
"six" to "6",
"seven" to "7",
"eight" to "8",
"nine" to "9"
)
private fun calibrate(s: String): Int = "${s.first { it.isDigit() }}${s.last { it.isDigit() }}".toInt()
private fun calibrate2(s: String): Int {
return calibrate(s.mapIndexedNotNull { index, c ->
if (c.isDigit()) {
c
} else {
s.possibleWordsAtIndex(index).firstNotNullOfOrNull { candidate ->
ZERO_TO_DIGITS[candidate]
}
}
}.joinToString())
}
private fun String.possibleWordsAtIndex(index: Int): List<String> {
return (3..5).map { len ->
substring(index, (index + len).coerceAtMost(length))
}
}
// 53551
fun main() {
fun part1(input: List<String>): Int = input.sumOf { s -> calibrate(s) }
fun part2(input: List<String>): Int = input.sumOf { s -> calibrate2(s) }
// test if implementation meets criteria from the description, like:
var testInput = readInput("Day01_test")
check(part1(testInput) == 142)
testInput = readInput("Day01_test2")
check(part2(testInput) == 281)
val input = readInput("Day01")
part1(input).println()
part2(input).println()
}
| 0 | Kotlin | 0 | 0 | 2936cd6e42bb460b722eb29797ab44470ac3d626 | 1,296 | advent-of-code-kotlin-template | Apache License 2.0 |
kaop/src/main/java/io/github/coyamo/kaop/ProxyJoinPoint.kt | Coyamo | 578,637,187 | false | null | package io.github.coyamo.kaop
import java.lang.reflect.Method
/**
* @author Coyamo
* @date 2022/12/17 00:47
* @version 1.0
*/
internal class ProxyJoinPoint(private val joinPoint: AbsJoinPoint, private val result: Any?) :
AbsJoinPoint() {
override fun proceed(): Any? {
return result
}
override val owner: Any
get() = joinPoint.owner
override val method: Method
get() = joinPoint.method
override val params: Array<Any?>
get() = joinPoint.params
} | 0 | Kotlin | 0 | 2 | 0761c724386e4dcdccadb57c2808ba9f97a01dc7 | 508 | KAop | MIT License |
login/src/main/java/com/poc/cyclone/login/LoginActivity.kt | saviolli | 590,050,106 | false | null | package com.poc.cyclone.login
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
class LoginActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
LoginScreen()
}
}
}
@Composable
fun LoginScreen() {
ConstraintLayout {
val (text) = createRefs()
Text("Hello Login", Modifier.constrainAs(text) {
top.linkTo(parent.top, margin = 16.dp)
})
}
} | 0 | Kotlin | 0 | 0 | 1c4a999c5851b7a00e976a7834cc82a87228802b | 780 | poc-cyclone | Apache License 2.0 |
src/main/kotlin/models/poke/Form.kt | bangaromaric | 370,943,027 | false | null | package models.poke
data class Form(
val name: String,
val url: String
) | 0 | Kotlin | 0 | 0 | 36fadae92cd25f3689c1e660c8915cff87be5f0c | 81 | pokedex-kotlin-js | Apache License 2.0 |
libPlugin/src/main/java/com/rk/libPlugin/client/ManagePlugin.kt | RohitKushvaha01 | 761,046,569 | false | {"Java": 1999002, "Kotlin": 439352} | package com.rk.libPlugin.client
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.rk.libPlugin.databinding.ActivityManageBinding
import com.rk.libPlugin.server.Server
import java.util.Objects
class ManagePlugin : AppCompatActivity() {
lateinit var binding: ActivityManageBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityManageBinding.inflate(layoutInflater)
val toolbar = binding.toolbar
setSupportActionBar(toolbar)
Objects.requireNonNull(supportActionBar)?.setDisplayHomeAsUpEnabled(true)
supportActionBar!!.title = "Manage Plugins"
setContentView(binding.root)
binding.listView.adapter = CustomListAdapter(this,Server.getInstalledPlugins())
}
} | 9 | Java | 13 | 234 | 5695ec9af9b7af641b68ebb5c4a44ad0f677af07 | 829 | Xed-Editor | MIT License |
simp-protocol-kt/src/main/kotlin/org/example/myhome/simp/core/SimpCodec.kt | Chantico-org | 73,012,491 | false | {"Kotlin": 25440} | package org.example.myhome.simp.core
import io.netty.buffer.ByteBuf
import io.netty.buffer.ByteBufUtil
import io.netty.channel.ChannelHandler.Sharable
import io.netty.channel.ChannelHandlerContext
import io.netty.handler.codec.MessageToMessageCodec
import java.nio.CharBuffer
import java.nio.charset.Charset
/**
* Created by alexei on 15.06.17.
*/
@Sharable
class SimpCodec(
val charset: Charset = Charset.defaultCharset()
): MessageToMessageCodec<ByteBuf, SimpMessage>() {
override fun decode(ctx: ChannelHandlerContext?, msg: ByteBuf?, out: MutableList<Any>?) {
if (msg == null || out == null || ctx == null) return
try {
val type = inferTypeFromByte(msg.readByte())
out.add(SimpMessage(type = type, body = msg.toString(charset)))
} catch(e: Error) {
ctx.close()
}
}
override fun encode(ctx: ChannelHandlerContext?, msg: SimpMessage?, out: MutableList<Any>?) {
if (ctx == null) {
return
}
if (msg == null || out == null) return
val text = msg.type.toByteString() + msg.body
out.add(ByteBufUtil.encodeString(ctx.alloc(), CharBuffer.wrap(text), charset))
}
}
| 6 | Kotlin | 0 | 3 | 2ee5bfacd6d9dafac60b2cacfe9c9daaa5926a99 | 1,134 | smart_house | MIT License |
src/main/kotlin/tech/dolch/plantarch/SequenceDiagram.kt | MrDolch | 412,704,741 | false | null | package tech.dolch.plantarch
import javassist.ClassPool
import javassist.Loader
import javassist.util.proxy.ProxyFactory
open class SequenceDiagram(
private val name: String,
private val description: String,
private val packagesToAnalyze: ArrayList<String> = ArrayList(),
) {
private var methodName: String? = null
private var methodParams: Array<Any>? = null
private var clazzName: String? = null
private var constructorParams: Array<out Any>? = null
private var participants: ArrayList<String> = ArrayList()
private var hiddenParticipants: ArrayList<String> = ArrayList()
@Suppress("UNCHECKED_CAST")
fun <T> analyzeClass(clazz: Class<T>, vararg parameters: Any): T {
clazzName = clazz.name
constructorParams = parameters
// record construction and method call
val factory = ProxyFactory()
factory.superclass = clazz
val proxiedClass =
factory.createClass { m -> !m.name.equals("finalize") }
.getDeclaredConstructor(*constructorParams?.map { it::class.java }?.toTypedArray() ?: arrayOf())
.newInstance(*constructorParams?.map { it }?.toTypedArray() ?: arrayOf()) as T
(proxiedClass as javassist.util.proxy.Proxy).setHandler { _, method, _, args ->
if (methodName == null) {
methodName = method.name
methodParams = args
} else throw IllegalStateException("Only one method call is allowed to record.")
return@setHandler null
}
return proxiedClass
}
private fun record(): String {
// build recording environment
val pool = ClassPool.getDefault()
val loader = Loader(pool)
val recorder = Recorder(packagesToAnalyze.toSet(), hiddenParticipants.toSet())
loader.addTranslator(pool, recorder)
// record calls
val clazz = loader.loadClass(clazzName)
val instance = clazz
.getDeclaredConstructor(*constructorParams?.map { it::class.java }?.toTypedArray() ?: arrayOf())
.newInstance(*constructorParams?.map { it }?.toTypedArray() ?: arrayOf())
val types = methodParams?.map { it::class.java }?.toTypedArray() ?: arrayOf()
val values = methodParams?.map { it }?.toTypedArray() ?: arrayOf()
clazz.getDeclaredMethod(methodName ?: "", *types)
.invoke(instance, *values)
// print out uml
val recorderClass = loader.loadClass("tech.dolch.plantarch.Recorder")
val recorderCompanionObject = recorderClass.getField("Companion").get(recorderClass)
return recorderCompanionObject.javaClass
.getDeclaredMethod("getData")
.invoke(recorderCompanionObject) as String
}
fun addParticipants(vararg participants: Class<*>) {
participants.map { c ->
c.name
.replaceBeforeLast('.', "").replace(".", "")
.replaceAfterLast('$', "").replace("$", "")
}
.forEach(this.participants::add)
participants.map { c -> c.packageName }.distinct().forEach(packagesToAnalyze::add)
}
fun addHiddenParticipants(vararg participants: Class<*>) {
participants.map { c -> c.name }
.forEach(this.hiddenParticipants::add)
}
fun toPlantuml(): String {
val recordedSequences = record()
return ("@startuml\n" +
"actor start\n"
+ participants.joinToString("\n") { s -> "participant $s" } + "\n"
+ recordedSequences + "\n"
+ "\ntitle\n$name\nendtitle"
+ "\ncaption\n$description\nendcaption"
+ "\nskinparam linetype polyline\n@enduml")
}
} | 0 | Kotlin | 0 | 0 | 350d5b870b52ad4d84470cd68ef2c4f55c9c6795 | 3,752 | plantarch | Apache License 2.0 |
library_swutils/src/main/java/com/swensun/http/SimpleActivityLifecycleCallbacks.kt | fighterwk | 283,684,767 | true | {"Kotlin": 330606, "Java": 106595} | package com.swensun.http
import android.app.Activity
import android.app.Application
import android.os.Bundle
import com.swensun.swutils.util.Logger
open class SimpleActivityLifecycleCallbacks : Application.ActivityLifecycleCallbacks {
override fun onActivityPaused(activity: Activity?) {
}
override fun onActivityResumed(activity: Activity?) {
Logger.d("onActivityResumed: $activity")
}
override fun onActivityStarted(activity: Activity?) {
}
override fun onActivityDestroyed(activity: Activity?) {
Logger.d("onActivityDestroyed: $activity")
}
override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {
}
override fun onActivityStopped(activity: Activity?) {
}
override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
Logger.d("onActivityCreated: $activity")
}
} | 0 | null | 0 | 0 | 85e4c8c22b148b52c9594cc41a0503c318a8cb79 | 902 | Potato | Apache License 2.0 |
src/test/java/com/example/springboot/http/甘肃/应用中台升级/大平台/UserAuthController.kt | DoubleDD | 747,076,483 | false | {"Kotlin": 302923, "Java": 116617} | package com.example.springboot.http.甘肃.应用中台升级.大平台
import com.example.springboot.http.common.BaseTest
import com.example.springboot.http.common.ServerApi
import org.junit.jupiter.api.Test
import org.springframework.http.HttpEntity
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpMethod
class UserAuthController : BaseTest() {
override fun getServer(): ServerApi {
// return ServerApi.UPDATE_PORTAL
// return ServerApi.PROD_PORTAL
// return ServerApi.LOCAL_PORTAL
return ServerApi.DEV_PORTAL
}
override fun getToken(): String {
return """
<KEY>
""".trimIndent()
}
@Test
fun 头部菜单() {
formatJson.set(true)
get("/api/auth/headers")
}
@Test
fun 查询权限() {
val header = HttpHeaders()
// header["user-agent"] = "dart:io"
header["uri"] = "#/home"
request("/api/auth/listAuth", HttpMethod.GET, HttpEntity(header))
}
@Test
fun app查询权限() {
val header = HttpHeaders()
header["user-agent"] = "dart:io"
// header["uri"] = "#/home"
request("/api/auth/listAuth/app", HttpMethod.GET, HttpEntity(header))
}
} | 0 | Kotlin | 0 | 0 | 0a7cb7c5a9241c7931dc79cef3052c5cf4cd62dd | 1,214 | api-unit-test | MIT License |
node/src/test/kotlin/net/corda/node/internal/NodeTest.kt | jjmiranda | 92,631,751 | true | {"Kotlin": 2797692, "Java": 156301, "Groovy": 26185, "Shell": 320, "Batchfile": 106} | package net.corda.node.internal
import net.corda.core.createDirectories
import net.corda.core.crypto.commonName
import net.corda.core.div
import net.corda.core.getOrThrow
import net.corda.core.utilities.ALICE
import net.corda.core.utilities.WHITESPACE
import net.corda.testing.node.NodeBasedTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
class NodeTest : NodeBasedTest() {
@Test
fun `empty plugins directory`() {
val baseDirectory = baseDirectory(ALICE.name)
(baseDirectory / "plugins").createDirectories()
startNode(ALICE.name).getOrThrow()
}
}
| 0 | Kotlin | 0 | 0 | bb0cc852954ee9eac2883e3eed3c7ce4f7d3678b | 614 | corda | Apache License 2.0 |
src/main/kotlin/com/baulsupp/okurl/authenticator/authflow/AuthOptions.kt | yschimke | 48,341,449 | false | {"Kotlin": 515385, "Shell": 843, "Smarty": 777} | package com.baulsupp.okurl.authenticator.authflow
sealed class AuthOption<T> {
abstract val param: String
}
data class Prompt(
override val param: String,
val label: String,
val default: String? = null,
val secret: Boolean = false
) :
AuthOption<String>()
data class Scopes(
override val param: String,
val label: String,
val default: List<String>? = null,
val known: List<String>
) :
AuthOption<List<String>>()
object Callback: AuthOption<String>() {
override val param = "callback"
}
object State: AuthOption<String>() {
override val param = "state"
}
| 16 | Kotlin | 15 | 126 | 32ad9f89d17500399ac16b735f1398ad6ca32f41 | 585 | okurl | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.