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/dokaLocal/ui/screens/settings/SettingsScreen.kt
|
Jocey3
| 802,480,899
| false
|
{"Kotlin": 175351}
|
package com.dokaLocal.ui.screens.settings
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.vectorResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.round
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.constraintlayout.compose.Dimension
import androidx.hilt.navigation.compose.hiltViewModel
import com.dokaLocal.MainViewModel
import com.dokaLocal.R
import com.dokaLocal.ui.theme.ButtonBackgroundColor
import com.dokaLocal.ui.theme.DOKATheme
import com.dokaLocal.ui.theme.MainBackgroundColor
import com.dokaLocal.ui.theme.BottomPanelColor
import com.dokaLocal.ui.theme.DefaultColor
import com.dokaLocal.util.rotate
@Composable
fun SettingsScreen(
modifier: Modifier = Modifier,
navigateBack: () -> Unit = {},
navigateExpTimer: () -> Unit = {},
navigateExposure: () -> Unit = {},
navigateSaturation: () -> Unit = {},
navigateContrast: () -> Unit = {},
navigateTint: () -> Unit = {},
sharedVM: MainViewModel = hiltViewModel(),
viewModel: SettingsViewModel = hiltViewModel(),
) {
ConstraintLayout(
modifier = Modifier
.fillMaxSize()
.background(MainBackgroundColor)
) {
val (mainFrame, middle, bottomPanel) = createRefs()
Spacer(modifier = Modifier
.size(1.dp)
.constrainAs(middle) {
top.linkTo(parent.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
bottom.linkTo(parent.bottom)
})
MainFrame(
modifier = Modifier
.constrainAs(mainFrame) {
top.linkTo(parent.top)
start.linkTo(parent.start)
end.linkTo(parent.end)
bottom.linkTo(middle.top)
height = Dimension.fillToConstraints
width = Dimension.fillToConstraints
}
.padding(horizontal = 32.dp)
.padding(top = 64.dp),
sharedVM = sharedVM
)
Box(
modifier = Modifier
.constrainAs(bottomPanel) {
bottom.linkTo(parent.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
height = Dimension.percent(0.25f) // Set height to 1/4 of the screen
}
) {
BottomPanel(
navigateExpTimer = navigateExpTimer,
navigateBack = navigateBack,
navigateExposure = navigateExposure,
navigateSaturation = navigateSaturation,
navigateContrast = navigateContrast,
navigateTint = navigateTint
)
}
}
}
@Composable
fun MainFrame(
modifier: Modifier = Modifier,
sharedVM: MainViewModel
) {
Box(
modifier = modifier
.clipToBounds()
) {
FrameWithImage(
modifier = Modifier
.size(
width = sharedVM.imageSize?.widthDp!!,
height = sharedVM.imageSize?.heightDp!!
)
.offset {
Offset(
sharedVM.savedImagesSettings.value.offsetX,
sharedVM.savedImagesSettings.value.offsetY
).round()
}, sharedVM = sharedVM
)
}
}
@Composable
fun FrameWithImage(
modifier: Modifier = Modifier,
sharedVM: MainViewModel
) {
Box(modifier = modifier) {
sharedVM.currentBitmap?.let {
Image(
bitmap = it.rotate(sharedVM.savedImagesSettings.value.rotation).asImageBitmap(),
modifier = Modifier
.fillMaxSize()
.graphicsLayer {
scaleX = sharedVM.savedImagesSettings.value.zoom
scaleY = sharedVM.savedImagesSettings.value.zoom
},
contentDescription = "Image for edit",
contentScale = ContentScale.Fit
)
}
}
}
@Composable
fun BottomPanel(
modifier: Modifier = Modifier,
navigateExpTimer: () -> Unit,
navigateExposure: () -> Unit,
navigateSaturation: () -> Unit,
navigateContrast: () -> Unit,
navigateTint: () -> Unit,
navigateBack: () -> Unit = {}
) {
val buttonList = remember {
listOf(
ButtonModel("Exp. timer", R.drawable.svg_timer),
ButtonModel("Exposure", R.drawable.svg_exposure),
ButtonModel("Saturation", R.drawable.svg_saturation),
ButtonModel("Contrast", R.drawable.svg_contrast),
ButtonModel("Tint", R.drawable.svg_tint)
)
}
Column(
modifier = modifier
.fillMaxSize()
.background(
color = BottomPanelColor,
shape = RoundedCornerShape(topStart = 24.dp, topEnd = 24.dp)
)
.padding(vertical = 16.dp, horizontal = 30.dp)
) {
Row {
Image(
imageVector = ImageVector.vectorResource(id = R.drawable.svg_check),
contentDescription = "Button OK",
modifier = Modifier
.clickable { navigateBack() }
)
}
Spacer(modifier = Modifier.weight(1f))
LazyRow {
itemsIndexed(buttonList) { index, _ ->
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.width(70.dp)
.clickable {
if (buttonList[index].title == "Exp. timer") navigateExpTimer()
if (buttonList[index].title == "Exposure") navigateExposure()
if (buttonList[index].title == "Saturation") navigateSaturation()
if (buttonList[index].title == "Contrast") navigateContrast()
if (buttonList[index].title == "Tint") navigateTint()
}
) {
Image(
imageVector = ImageVector.vectorResource(id = buttonList[index].image),
contentDescription = buttonList[index].title,
)
Spacer(modifier = Modifier.height(8.dp))
Text(
text = buttonList[index].title,
fontSize = 14.sp,
maxLines = 1,
color = DefaultColor,
overflow = TextOverflow.Ellipsis
)
}
}
}
Spacer(modifier = Modifier.height(15.dp))
}
}
data class ButtonModel(val title: String, val image: Int)
@Preview(
showBackground = true, showSystemUi = true,
device = "spec:width=411dp,height=711dp,dpi=420"
)
@Composable
fun GreetingPreview() {
DOKATheme {
SettingsScreen()
}
}
| 0
|
Kotlin
|
0
| 0
|
e0d4adee56e221865a2d07231b4509ef8a2bc186
| 8,467
|
DOKA
|
FSF All Permissive License
|
src/main/kotlin/io/github/mellda1024/rta/core/rofl/Rofl.kt
|
MellDa1024
| 612,876,967
| false
| null |
package io.github.mellda1024.rta.core.rofl
import java.io.File
import java.io.FileInputStream
import java.io.FileWriter
import java.io.IOException
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.attribute.BasicFileAttributes
import java.text.SimpleDateFormat
import java.util.*
import java.util.regex.Pattern
data class Rofl(
val file: File,
val name: String,
val path: String
) {
constructor(file: File) : this(file, file.name, file.path)
/**
* Rofl 파일의 ByteArray값을 가지고 와서 Version을 인식합니다.
* Rofl의 Json 메타데이터가 Hex Offset 기준 120(Decimal 288)에서 시작하므로,
* 처음 RIOT 문자열 확인으로 포인터를 4만큼 움직이니 284만큼 더 skip합니다.
* 라이엇에서 Rofl 구조를 바꾸지 않았으면 좋겠네요 ㅎㅎ;
*/
val version: String
get() {
try {
val temp = ByteArray(4)
val riotCheck = byteArrayOf(82, 73, 79, 84)
val fis = FileInputStream(file)
fis.read(temp)
if (!riotCheck.contentEquals(temp)) {
fis.close()
return "null"
}
val versionByteArray = ByteArray(64)
fis.skip(284)
fis.read(versionByteArray)
val versionRaw = String(versionByteArray, StandardCharsets.UTF_8)
val regex = Pattern.compile("\"gameVersion\":\"([0-9.]*)\",")
val match = regex.matcher(versionRaw)
if (match.find()) {
fis.close()
return match.group(1)
}
fis.close()
return "null"
} catch(e : IOException) {
return "null"
}
}
val createdDate: String
get() {
val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
return try {
val time = Files.readAttributes(this.file.toPath(), BasicFileAttributes::class.java)
.creationTime()
sdf.format(Date(time.toMillis()))
} catch (e: IOException) {
"null"
}
}
fun execute(file: File) {
val driveLetter = Paths.get(file.path).root.toString().dropLast(1)
val folder = file.parent
val command =
"cmd /c start cmd.exe /K " +
"\"cd /D $driveLetter &&" +
"cd $folder &&" +
"\"League of Legends.exe\" \"${this.path}\" -GameBaseDir=$folder -Locale=ko_KR -SkipBuild -EnableLNP -UseNewX3D=1 -UseNewX3DFramebuffers=1 &&" +
"exit\""
Runtime.getRuntime().exec(command)
}
fun saveBatchFile(file: File, saveDir: File): Boolean {
val driveLetter = Paths.get(file.path).root.toString().dropLast(1)
val folder = file.parent
val replayBatFile = File(saveDir.path + "/replay.bat")
if (!replayBatFile.exists()) replayBatFile.createNewFile()
return try {
val fw = FileWriter("replay.bat")
fw.write("cd /D $driveLetter\n")
fw.write("cd $folder\n")
fw.write("\"League of Legends.exe\" \"${this.path}\" -GameBaseDir=$folder -Locale=ko_KR -SkipBuild -EnableLNP -UseNewX3D=1 -UseNewX3DFramebuffers=1")
fw.close()
true
} catch (e: IOException) {
e.printStackTrace()
false
}
}
}
| 0
|
Kotlin
|
0
| 0
|
fe73dd9659c37881ca516e5e6ee3afe2057c6c63
| 3,412
|
ReplayToolAdvanced
|
Apache License 2.0
|
Barlom-Domain-JVM/src/main/kotlin/o/barlom/domain/metamodel/api/edges/UndirectedEdgeTypeInheritance.kt
|
martin-nordberg
| 82,682,055
| false
| null |
//
// (C) Copyright 2017-2018 <NAME>
// Apache 2.0 License
//
package o.barlom.domain.metamodel.api.edges
import o.barlom.domain.metamodel.api.vertices.AbstractElement
import o.barlom.domain.metamodel.api.vertices.UndirectedEdgeType
import x.barlom.infrastructure.uuids.Uuid
/**
* Interface for Barlom undirected edge type inheritance
*/
class UndirectedEdgeTypeInheritance internal constructor(
override val id: Uuid,
val superType: UndirectedEdgeType,
val subType: UndirectedEdgeType
) : AbstractElement() {
init {
require(!subType.isRoot) { "Root undirected edge type cannot have a super type." }
// Register both ends.
superType.addSubTypeUndirectedEdgeTypeInheritance(this)
subType.addSuperTypeUndirectedEdgeTypeInheritance(this)
}
override fun remove() {
// Unregister both ends.
superType.removeSubTypeUndirectedEdgeTypeInheritance(this)
subType.removeSuperTypeUndirectedEdgeTypeInheritance(this)
}
}
| 0
|
Kotlin
|
0
| 0
|
337b46f01f6eec6dfb3b86824c26f1c103e9d9a2
| 1,008
|
ZZ-Barlom
|
Apache License 2.0
|
sample/src/main/kotlin/com/github/elment/sample/ui/case1/Case1Screen.kt
|
ZharovVV
| 781,962,006
| false
|
{"Kotlin": 40970}
|
package com.github.elment.sample.ui.case1
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.Remove
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.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.github.elment.android.acceptDebounce
import com.github.elment.android.acceptDropOldest
import com.github.elment.android.acceptThrottle
import com.github.elment.core.store.AcceptMode
import com.github.elment.sample.ui.case1.Case1Event.Decrease
import com.github.elment.sample.ui.case1.Case1Event.Increase
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Case1Screen() {
val viewModel: Case1ViewModel = viewModel()
val state by viewModel.state.collectAsStateWithLifecycle()
Scaffold(
modifier = Modifier.fillMaxSize(),
// containerColor = MaterialTheme.colorScheme.primary
topBar = {
TopAppBar(title = { Text(text = state.counterText) })
}
) { innerPadding ->
Column(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding)
.verticalScroll(rememberScrollState()),
verticalArrangement = Arrangement.spacedBy(16.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Spacer(modifier = Modifier.height(16.dp))
Text(text = "Default Accept Mode")
Row(horizontalArrangement = Arrangement.spacedBy(32.dp)) {
IconButton(onClick = { viewModel.accept(Increase) }) {
Icon(Icons.Outlined.Add, contentDescription = "")
}
IconButton(onClick = { viewModel.accept(Decrease) }) {
Icon(Icons.Outlined.Remove, contentDescription = "")
}
}
Spacer(modifier = Modifier.height(16.dp))
Text(text = "Debounce Accept Mode")
Row(horizontalArrangement = Arrangement.spacedBy(32.dp)) {
IconButton(onClick = { viewModel.accept(Increase, AcceptMode.DEBOUNCE) }) {
Icon(Icons.Outlined.Add, contentDescription = "")
}
IconButton(onClick = { viewModel.acceptDebounce(Decrease) }) {
Icon(Icons.Outlined.Remove, contentDescription = "")
}
}
Spacer(modifier = Modifier.height(16.dp))
Text(text = "Throttle Accept Mode")
Row(horizontalArrangement = Arrangement.spacedBy(32.dp)) {
IconButton(onClick = { viewModel.accept(Increase, AcceptMode.THROTTLE) }) {
Icon(Icons.Outlined.Add, contentDescription = "")
}
IconButton(onClick = { viewModel.acceptThrottle(Decrease) }) {
Icon(Icons.Outlined.Remove, contentDescription = "")
}
}
Spacer(modifier = Modifier.height(16.dp))
Text(text = "Drop Oldest Accept Mode")
Row(horizontalArrangement = Arrangement.spacedBy(32.dp)) {
IconButton(onClick = { viewModel.accept(Increase, AcceptMode.DROP_OLDEST) }) {
Icon(Icons.Outlined.Add, contentDescription = "")
}
IconButton(onClick = { viewModel.acceptDropOldest(Decrease) }) {
Icon(Icons.Outlined.Remove, contentDescription = "")
}
}
}
}
}
| 0
|
Kotlin
|
0
| 1
|
383201372841195e6d8dcd915bc86f8d9afc5de2
| 4,419
|
Elment
|
Apache License 2.0
|
src/main/kotlin/no/nav/syfo/infrastructure/kafka/ExpiredVarselSerializer.kt
|
navikt
| 554,767,872
| false
|
{"Kotlin": 507929, "Dockerfile": 226}
|
package no.nav.syfo.infrastructure.kafka
import no.nav.syfo.infrastructure.kafka.domain.ExpiredVarsel
import no.nav.syfo.util.configuredJacksonMapper
import org.apache.kafka.common.serialization.Serializer
class ExpiredVarselSerializer : Serializer<ExpiredVarsel> {
private val mapper = configuredJacksonMapper()
override fun serialize(topic: String?, data: ExpiredVarsel?): ByteArray =
mapper.writeValueAsBytes(data)
}
| 3
|
Kotlin
|
1
| 0
|
762ed5b7d0f5ac463887c13cbe375279d79e25fb
| 438
|
isaktivitetskrav
|
MIT License
|
CustomTagView/src/main/java/amin/rz3/customtagview/Click.kt
|
aminrz3
| 454,990,610
| false
| null |
package amin.rz3.customtagview
import android.text.Spanned
import android.text.style.ClickableSpan
import android.view.View
import android.widget.TextView
class Click(val clickCallback: ClickCallback):ClickableSpan() {
override fun onClick(v: View) {
val text = (v as TextView).text
val s = text as Spanned
clickCallback.onClick(text.subSequence(s.getSpanStart(this), s.getSpanEnd(this)).toString(), s.getSpanStart(this), s.getSpanEnd(this))
}
}
| 0
|
Kotlin
|
0
| 0
|
5eb38c9bb7af9afa0295b46b590e56dbb82b258e
| 479
|
CustomTagView
|
MIT License
|
app/src/main/java/com/ybh/alarm/lostark/utils/DatabaseManager.kt
|
Hot6ix
| 160,517,270
| false
| null |
package com.ybh.alarm.lostark.utils
import android.content.Context
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
class DatabaseManager(context: Context): SQLiteOpenHelper(context, DB_NAME, null, DB_VERSION) {
override fun onCreate(db: SQLiteDatabase) {
db.execSQL("CREATE TABLE $TABLE_NAME (" +
"$COLUMN_ID INTEGER PRIMARY KEY AUTOINCREMENT," +
"$COLUMN_ISLAND TEXT NOT NULL," +
"$COLUMN_SCHEDULE TEXT," +
"$COLUMN_NOTIFICATION INTEGER," +
"$COLUMN_SWITCH INTEGER);")
}
override fun onUpgrade(db: SQLiteDatabase?, oldVersion: Int, newVersion: Int) {
}
companion object {
const val DB_NAME = "timers.db"
const val DB_VERSION = 1
const val TABLE_NAME = "timer"
const val COLUMN_ID = "id"
const val COLUMN_ISLAND = "island"
const val COLUMN_SCHEDULE = "schedule"
const val COLUMN_NOTIFICATION = "notification"
const val COLUMN_SWITCH = "switch"
}
}
| 0
|
Kotlin
|
0
| 0
|
a30d59974be9083e1a4436be1cd2d47a991babfe
| 1,075
|
IslandTimer
|
Apache License 2.0
|
src/boj_10870/Kotlin.kt
|
devetude
| 70,114,524
| false
|
{"Java": 563470, "Kotlin": 54466}
|
package boj_10870
fun main() {
val n = readln().toInt()
println(fibonacci(n))
}
fun fibonacci(n: Int): Int {
if (n <= 1) return n
return fibonacci(n = n - 2) + fibonacci(n = n - 1)
}
| 0
|
Java
|
7
| 20
|
1a42ce0351c5fbf71b14ba053978b5bb3b98e855
| 203
|
BOJ-PSJ
|
Apache License 2.0
|
ktor-http/src/io/ktor/content/IncomingContent.kt
|
tetrafolium
| 125,982,972
| false
| null |
package io.ktor.content
import io.ktor.http.*
import kotlinx.coroutines.experimental.io.*
import kotlinx.coroutines.experimental.io.jvm.javaio.*
import kotlinx.io.pool.*
import kotlinx.io.streams.*
import java.io.*
import java.nio.charset.*
@Deprecated("Use receive<ByteReadChannel>(), receive<MultiPartData>() or receive<InputStream>() instead")
interface IncomingContent : HttpMessage {
fun readChannel(): ByteReadChannel
fun multiPartData(): MultiPartData
fun inputStream(): InputStream = readChannel().toInputStream()
}
@Deprecated("Pool specification is not supported anymore", ReplaceWith("readText(charset)"))
suspend fun IncomingContent.readText(pool: ObjectPool<ByteBuffer>, charset: Charset? = null) = readText(charset ?: charset() ?: Charsets.ISO_8859_1)
suspend fun IncomingContent.readText() = readText(charset() ?: Charsets.ISO_8859_1)
suspend fun IncomingContent.readText(
charset: Charset
): String {
val channel = readChannel()
if (channel.isClosedForRead) return ""
val content = channel.readRemaining()
return try {
if (charset == Charsets.UTF_8) content.readText()
else content.inputStream().reader(charset).readText()
} finally {
content.release()
}
}
| 0
|
Kotlin
|
0
| 0
|
4d125665824f5aa41c95dee13e76e06bc87a4fb6
| 1,248
|
ktor
|
Apache License 2.0
|
core-ui/src/main/java/de/niklasbednarczyk/nbweather/core/ui/icons/NBIconButtonView.kt
|
NiklasBednarczyk
| 529,683,941
| false
|
{"Kotlin": 1265250}
|
package de.niklasbednarczyk.nbweather.core.ui.icons
import androidx.compose.material3.IconButton
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
@Composable
fun NBIconButtonView(
modifier: Modifier = Modifier,
icon: NBIconItem,
enabled: Boolean = true,
onClick: () -> Unit,
) {
IconButton(
modifier = modifier,
content = {
NBIconView(
icon = icon
)
},
enabled = enabled,
onClick = onClick
)
}
| 12
|
Kotlin
|
0
| 1
|
61c8521c434881d615d76e4f277f48d37667d50c
| 530
|
NBWeather
|
MIT License
|
app/src/main/java/com/tarapogancev/pushapp/ui/StartExerciseFragment.kt
|
tara-pogancev
| 560,429,028
| false
| null |
package com.tarapogancev.pushapp.ui
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.tarapogancev.pushapp.MainActivity
import com.tarapogancev.pushapp.databinding.FragmentStartExerciseBinding
import com.tarapogancev.pushapp.navigation.Navigation
class StartExerciseFragment : Fragment() {
private var binding: FragmentStartExerciseBinding? = null
private lateinit var navController : Navigation
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
navController = (activity as MainActivity).navController
val fragmentBinding = FragmentStartExerciseBinding.inflate(inflater, container, false)
binding = fragmentBinding
return fragmentBinding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding?.apply {
buttonStartExercise.setOnClickListener {
navController.startToInterval()
}
}
}
override fun onDestroy() {
super.onDestroy()
binding = null
}
}
| 0
|
Kotlin
|
0
| 0
|
935272275b6722f5c75b74a7d0cf4fbd6639751b
| 1,275
|
android-push-app
|
MIT License
|
app/src/main/java/com/chocolate/triviatitans/presentation/screens/quiz_screen/word_wise/view_model/BackPress.kt
|
team-chocolate-cake
| 661,943,976
| false
| null |
package com.chocolate.triviatitans.presentation.screens.quiz_screen.word_wise.view_model
sealed class BackPress {
object Idle : BackPress()
object InitialTouch : BackPress()
}
| 0
|
Kotlin
|
3
| 1
|
94e74e9943f25d94a64311d898baf4b07fabfc63
| 185
|
TriviaTitans
|
MIT License
|
shared/src/iosMain/kotlin/util/Graphic.ios.kt
|
vinceglb
| 628,619,356
| false
|
{"Kotlin": 206592, "Swift": 954, "Shell": 228}
|
package util
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.asSkiaPath
actual fun Path.asPlatformPathRewind() {
this.asSkiaPath().rewind()
}
| 2
|
Kotlin
|
2
| 93
|
7240671bdd5e6b74ff247f7443f3e996e995f634
| 177
|
ComposeAI
|
Apache License 2.0
|
androidtweaks_androidx/src/main/java/com/charlie/androidtweaks/shake/TweakShakeService.kt
|
charlie-captain
| 157,821,589
| false
| null |
package com.charlie.androidtweaks.shake
import android.app.Service
import android.content.Context
import android.content.Intent
import android.hardware.Sensor
import android.hardware.SensorEvent
import android.hardware.SensorEventListener
import android.hardware.SensorManager
import android.os.Handler
import android.os.IBinder
import android.os.Message
import android.util.Log
import com.charlie.androidtweaks.data.TAG_ANDROIDTWEAKS
import com.charlie.androidtweaks.ui.TweakActivity
import java.lang.ref.WeakReference
import kotlin.math.abs
class TweakShakeService : Service() {
private var mSensorManager: SensorManager? = null
private var mAccelerometerSensor: Sensor? = null
/**
* shake range
*/
private val SHAKE_RANGE = 25f
private var isShake = false
private var mHandler: TweakShakeHandler? = null
companion object {
private const val MSG_SHAKE_START = 1
private const val MSG_SHAKE_END = -1
}
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
mSensorManager = getSystemService(Context.SENSOR_SERVICE) as? SensorManager
mSensorManager?.let {
mAccelerometerSensor = it.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
if (mAccelerometerSensor != null) {
it.registerListener(
mShakeListener,
mAccelerometerSensor!!,
SensorManager.SENSOR_DELAY_UI
)
mHandler = TweakShakeHandler(this)
}
}
Log.d(TAG_ANDROIDTWEAKS, "shake service start command")
return super.onStartCommand(intent, flags, startId)
}
/**
* shake listener
*/
private val mShakeListener = object : SensorEventListener {
override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {
}
override fun onSensorChanged(event: SensorEvent?) {
event ?: return
val type = event?.sensor?.type ?: return
if (type == Sensor.TYPE_ACCELEROMETER) {
val values = event.values ?: FloatArray(3)
val x = values[0]
val y = values[1]
val z = values[2]
if ((abs(x) > SHAKE_RANGE || abs(y) > SHAKE_RANGE || abs(z) > SHAKE_RANGE) && !isShake) {
isShake = true
Thread {
mHandler?.sendEmptyMessage(MSG_SHAKE_START)
Thread.sleep(500)
mHandler?.sendEmptyMessage(MSG_SHAKE_END)
}.start()
}
}
}
}
override fun onDestroy() {
super.onDestroy()
mSensorManager?.unregisterListener(mShakeListener, mAccelerometerSensor)
mSensorManager = null
mAccelerometerSensor = null
mHandler?.removeCallbacksAndMessages(null)
mHandler = null
Log.d(TAG_ANDROIDTWEAKS, "shake service stop command")
}
/**
* shake handler
*/
class TweakShakeHandler(context: Context) : Handler() {
private var weakReference: WeakReference<Context>? = null
init {
weakReference = WeakReference(context)
}
override fun handleMessage(msg: Message?) {
super.handleMessage(msg)
msg ?: return
val context = weakReference?.get() as? TweakShakeService ?: return
when (msg.what) {
MSG_SHAKE_START -> {
TweakActivity.start(context)
}
MSG_SHAKE_END -> {
context.isShake = false
}
}
}
}
}
| 0
|
Kotlin
|
0
| 2
|
11706be9eb6af28e4ba3d44cd13dfad6e8a350e0
| 3,786
|
AndroidTweaks
|
MIT License
|
app/src/main/java/com/silverpants/instantaneous/di/FirebaseModule.kt
|
jeevansurendran
| 329,681,176
| false
| null |
package com.silverpants.instantaneous.di
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.ktx.auth
import com.google.firebase.crashlytics.FirebaseCrashlytics
import com.google.firebase.crashlytics.ktx.crashlytics
import com.google.firebase.dynamiclinks.FirebaseDynamicLinks
import com.google.firebase.dynamiclinks.ktx.dynamicLinks
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.ktx.firestore
import com.google.firebase.firestore.ktx.firestoreSettings
import com.google.firebase.functions.FirebaseFunctions
import com.google.firebase.functions.ktx.functions
import com.google.firebase.ktx.Firebase
import com.google.firebase.messaging.FirebaseMessaging
import com.google.firebase.messaging.ktx.messaging
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
class FirebaseModule {
@Singleton
@Provides
fun provideFirebaseFirestore(): FirebaseFirestore {
return Firebase.firestore.apply {
firestoreSettings = firestoreSettings { isPersistenceEnabled = true }
}
}
@Singleton
@Provides
fun provideFirebaseAuth(): FirebaseAuth {
return Firebase.auth
}
@Singleton
@Provides
fun provideFirebaseMessaging(): FirebaseMessaging {
return Firebase.messaging
}
@Singleton
@Provides
fun provideCrashlytics(): FirebaseCrashlytics {
return Firebase.crashlytics
}
@Singleton
@Provides
fun provideFunctions(): FirebaseFunctions {
return Firebase.functions
}
@Singleton
@Provides
fun provideDynamicLinks(): FirebaseDynamicLinks {
return Firebase.dynamicLinks
}
}
| 0
|
Kotlin
|
1
| 1
|
5c7665cb87e19a3c3c84ab046e58bbd33d21cf51
| 1,832
|
instantaneous
|
MIT License
|
src/main/kotlin/ink/ptms/ovile/api/ActiveRegionBlock.kt
|
TabooLib
| 487,524,125
| false
|
{"Kotlin": 62778}
|
package ink.ptms.ovile.api
import java.util.function.Supplier
/**
* Ovile
* ink.ptms.ovile.api.ActiveRegionBlock
*
* @author 坏黑
* @since 2022/5/2 15:42
*/
class ActiveRegionBlock(val block: RegionBlock, val originBlock: Supplier<RegionBlock>)
| 0
|
Kotlin
|
0
| 4
|
81a9b960af55c26cbf89dc3bdc6150772ec8a34a
| 250
|
ovile
|
Creative Commons Zero v1.0 Universal
|
kotlin/src/main/kotlin/net/timafe/angkor/repo/PostRepository.kt
|
tillkuhn
| 219,713,329
| false
|
{"Kotlin": 345721, "TypeScript": 332316, "Go": 129811, "HTML": 82105, "HCL": 70313, "Makefile": 50746, "Shell": 31786, "SCSS": 31379, "Dockerfile": 4350, "JavaScript": 2537, "PLpgSQL": 2280, "CSS": 1037}
|
package net.timafe.angkor.repo
import net.timafe.angkor.domain.Post
import org.springframework.data.repository.CrudRepository
import java.util.*
/**
* Crud Operations for Videos
* For complex Searches, use LocationSearch
*/
interface PostRepository : CrudRepository<Post, UUID>{
fun findOneByExternalId(externalId: String): Optional<Post>
}
| 26
|
Kotlin
|
4
| 9
|
f587e7db07f54483ce929f04391ed22f99cf97c9
| 352
|
angkor
|
Apache License 2.0
|
composeApp/src/commonMain/kotlin/MainScreen.kt
|
Buffersolve
| 798,939,755
| false
|
{"Kotlin": 95049, "Swift": 668}
|
import androidx.compose.foundation.ExperimentalFoundationApi
import utils.Gray
import utils.GrayNavNar
import utils.Main
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
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.Row
import androidx.compose.foundation.layout.WindowInsets
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.Icon
import androidx.compose.material.Scaffold
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import cafe.adriel.voyager.core.registry.ScreenRegistry
import cafe.adriel.voyager.core.screen.Screen
import cafe.adriel.voyager.navigator.tab.CurrentTab
import cafe.adriel.voyager.navigator.tab.Tab
import cafe.adriel.voyager.navigator.tab.TabNavigator
import navigation.SharedScreen
import org.jetbrains.compose.resources.ExperimentalResourceApi
import org.jetbrains.compose.resources.vectorResource
import priceninja.composeapp.generated.resources.Res
import priceninja.composeapp.generated.resources.scan
import scanner.ScannerTab
import utils.BASE_URL
import kotlin.jvm.Transient
class MainScreen(
@Transient private val writeLong: (Pair<String, Long>) -> Unit,
@Transient private val writeString: (Pair<String, String>) -> Unit,
@Transient private val readLong: (String) -> Long?,
) : Screen {
@Composable
override fun Content() {
val homeTab = ScreenRegistry.get(SharedScreen.HomeTab) as Tab
var dialogState by remember { mutableStateOf(false) }
TabNavigator(tab = homeTab) { tabNavigator ->
Scaffold(content = {
CurrentTab()
}, bottomBar = {
Box(
modifier = Modifier.fillMaxWidth()
) {
Row(
modifier = Modifier
.wrapContentHeight()
.fillMaxWidth()
.padding(
bottom = pxToDp(WindowInsets.navigationBars.getBottom(LocalDensity.current)).dp,
start = 16.dp,
end = 16.dp
)
.background(color = GrayNavNar, shape = RoundedCornerShape(64.dp))
.padding(horizontal = 24.dp, vertical = 16.dp)
.align(Alignment.BottomCenter),
horizontalArrangement = Arrangement.SpaceAround
) {
TabNavigationItem(
homeTab,
tabNavigator
) {
dialogState = true
}
ScannerNavItem(
ScreenRegistry.get(SharedScreen.ScannerTab) as Tab,
tabNavigator
)
TabNavigationItem(ScreenRegistry.get(SharedScreen.CardsTab {
tabNavigator.current = ScannerTab(writeString, readLong)
}) as Tab, tabNavigator)
}
}
})
}
if (dialogState) {
OpenIpDialog(writeString) {
dialogState = false
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
private fun TabNavigationItem(
screenTab: Tab,
tabNavigator: TabNavigator,
onLongPress: () -> Unit = {}
) {
val selected = tabNavigator.current == screenTab
val interactionSource = remember { MutableInteractionSource() }
var iconColor by rememberSaveable { mutableIntStateOf(Gray.toArgb()) }
var textColor by rememberSaveable { mutableIntStateOf(Gray.toArgb()) }
iconColor = if (selected) Main.toArgb() else Gray.toArgb()
textColor = if (selected) Main.toArgb() else Gray.toArgb()
Box(
modifier = Modifier.combinedClickable(
interactionSource = interactionSource,
indication = null,
onClick = {
tabNavigator.current = screenTab
},
onLongClick = { onLongPress() }
)
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(horizontal = 16.dp, vertical = 8.dp)
) {
screenTab.options.icon?.let {
Icon(
painter = it,
contentDescription = screenTab.options.title,
tint = Color(iconColor)
)
}
Text(
text = screenTab.options.title,
color = Color(textColor),
maxLines = 1
)
}
}
}
@OptIn(ExperimentalResourceApi::class)
@Composable
fun ScannerNavItem(screenTab: Tab, tabNavigator: TabNavigator) {
Box(
modifier = Modifier.size(56.dp).background(Main, shape = RoundedCornerShape(28.dp))
.clickable(
interactionSource = remember { MutableInteractionSource() },
indication = null,
onClick = {
tabNavigator.current = screenTab
})
) {
Icon(
imageVector = vectorResource(Res.drawable.scan),
contentDescription = "Scan",
tint = Color.White,
modifier = Modifier.size(24.dp).align(Alignment.Center)
)
}
}
@Composable
fun OpenIpDialog(
writeString: (Pair<String, String>) -> Unit,
onDismiss: () -> Unit
) {
var ipToSave by remember { mutableStateOf("") }
Dialog(onDismissRequest = onDismiss) {
Column(modifier = Modifier.padding(16.dp).background(Color.White)) {
TextField(
value = ipToSave,
onValueChange = { ipToSave = it },
label = { Text("Enter IP") },
modifier = Modifier.padding(16.dp)
)
Button(
modifier = Modifier.fillMaxWidth()
.padding(horizontal = 12.dp)
.padding(bottom = 16.dp),
onClick = {
println(ipToSave)
writeString(BASE_URL to ipToSave)
}) {
Text(text = "Save")
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c4eb08daf6be65a08c11db1450d6fc6675144cb0
| 7,937
|
PriceNinja
|
MIT License
|
common/src/main/kotlin/tech/figure/aggregate/common/models/AmountDenom.kt
|
FigureTechnologies
| 395,683,487
| false
| null |
package tech.figure.aggregate.common.models
data class AmountDenom (
val amount: String,
val denom: String
)
| 1
|
Kotlin
|
0
| 5
|
b6a2d477567507e048953728b315276b45dfd4da
| 118
|
aggregate-service
|
Apache License 2.0
|
modules/nbt/src/main/kotlin/io/heartpattern/spikot/nbt/NBTWrappers.kt
|
Spikot
| 262,074,229
| false
| null |
/*
* Copyright (c) 2020 HeartPattern and Spikot authors
*
* 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 io.heartpattern.spikot.nbt
import java.util.*
public interface Tag<T : Any> {
public val rawTag: Any
public val type: TagType<T>
public val value: T
public fun isEmpty(): Boolean = false
public fun copy(): Tag<T>
}
public interface NumericTag<T : Number> : Tag<T> {
public val long: Long
get() = value.toLong()
public val int: Int
get() = value.toInt()
public val short: Short
get() = value.toShort()
public val byte: Byte
get() = value.toByte()
public val double: Double
get() = value.toDouble()
public val float: Float
get() = value.toFloat()
}
public interface EndTag : Tag<Unit> {
override val type: TagType<Unit>
get() = TagType.END
override fun copy(): EndTag
}
public interface ByteTag : NumericTag<Byte> {
override val type: TagType<Byte>
get() = TagType.BYTE
override fun copy(): ByteTag
}
public interface ShortTag : NumericTag<Short> {
override val type: TagType<Short>
get() = TagType.SHORT
override fun copy(): ShortTag
}
public interface IntTag : NumericTag<Int> {
override val type: TagType<Int>
get() = TagType.INT
override fun copy(): IntTag
}
public interface LongTag : NumericTag<Long> {
override val type: TagType<Long>
get() = TagType.LONG
override fun copy(): LongTag
}
public interface FloatTag : NumericTag<Float> {
override val type: TagType<Float>
get() = TagType.FLOAT
override fun copy(): FloatTag
}
public interface DoubleTag : NumericTag<Double> {
override val type: TagType<Double>
get() = TagType.DOUBLE
override fun copy(): DoubleTag
}
public interface ByteArrayTag : Tag<ByteArray> {
override val type: TagType<ByteArray>
get() = TagType.BYTE_ARRAY
override fun copy(): ByteArrayTag
}
public interface StringTag : Tag<String> {
public override val type: TagType<String>
get() = TagType.STRING
public override fun copy(): StringTag
}
public interface ListTag : Tag<List<Tag<*>>> {
public override val type: TagType<List<Tag<*>>>
get() = TagType.LIST
override fun copy(): ListTag
override fun isEmpty(): Boolean = size == 0
public operator fun get(index: Int): Tag<*>
public fun add(element: Tag<*>)
public fun add(index: Int, element: Tag<*>)
public fun remove(index: Int): Tag<*>
public fun getCompound(index: Int): CompoundTag
public fun getInt(index: Int): Int
public fun getIntArray(index: Int): IntArray
public fun getDouble(index: Int): Double
public fun getFloat(index: Int): Float
public fun getString(index: Int): String
public val elementType: TagType<*>
public val size: Int
}
public interface CompoundTag : Tag<Map<String, Tag<*>>> {
public override val type: TagType<Map<String, Tag<*>>>
get() = TagType.COMPOUND
public override fun copy(): CompoundTag
public fun getAllKeys(): Set<String>
public val size: Int
public operator fun set(key: String, value: Tag<*>)
public fun putByte(key: String, value: Byte)
public fun putShort(key: String, value: Short)
public fun putInt(key: String, value: Int)
public fun putLong(key: String, value: Long)
public fun putUUID(key: String, value: UUID)
public fun putFloat(key: String, value: Float)
public fun putDouble(key: String, value: Double)
public fun putString(key: String, value: String)
public fun putByteArray(key: String, value: ByteArray)
public fun putIntArray(key: String, value: IntArray)
public fun putIntArray(key: String, value: List<Int>)
public fun putLongArray(key: String, value: LongArray)
public fun putLongArray(key: String, value: List<Long>)
public fun putBoolean(key: String, value: Boolean)
public fun getTagType(key: String): TagType<*>
public operator fun contains(key: String): Boolean
public fun contains(key: String, type: TagType<*>): Boolean
public fun hasUUID(key: String): Boolean
public fun get(key: String): Tag<*>
public fun getByte(key: String): Byte
public fun getShort(key: String): Short
public fun getInt(key: String): Int
public fun getLong(key: String): Long
public fun getUUID(key: String): UUID
public fun getFloat(key: String): Float
public fun getDouble(key: String): Double
public fun getString(key: String): String
public fun getByteArray(key: String): ByteArray
public fun getIntArray(key: String): IntArray
public fun getLongArray(key: String): LongArray
public fun getCompound(key: String): CompoundTag
public fun getList(key: String, type: TagType<*>): ListTag
public fun getBoolean(key: String): Boolean
public fun remove(key: String)
override fun isEmpty(): Boolean
public fun merge(compound: CompoundTag)
}
public interface IntArrayTag : Tag<IntArray> {
override val type: TagType<IntArray>
get() = TagType.INT_ARRAY
override fun copy(): IntArrayTag
}
public interface LongArrayTag : Tag<LongArray> {
override val type: TagType<LongArray>
get() = TagType.LONG_ARRAY
override fun copy(): LongArrayTag
}
| 0
|
Kotlin
|
0
| 14
|
ea00c92973dea15175c42336ec059389655499d7
| 6,338
|
Spikot
|
MIT License
|
app/src/main/java/com/kire/audio/presentation/ui/player_screen_ui/dialog/dialog_info/DialogInfo.kt
|
KiREHwYE
| 674,992,893
| false
|
{"Kotlin": 297464}
|
package com.kire.audio.presentation.ui.player_screen_ui.dialog.dialog_info
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.GridItemSpan
import androidx.compose.foundation.lazy.grid.LazyGridItemScope
import androidx.compose.foundation.lazy.grid.LazyGridScope
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Edit
import androidx.compose.material.icons.rounded.Save
import androidx.compose.material3.BasicAlertDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.kire.audio.R
import com.kire.audio.presentation.util.bounceClick
import com.kire.audio.presentation.model.Track
import com.kire.audio.presentation.model.TrackUiState
import com.kire.audio.presentation.ui.player_screen_ui.dialog.DialogGalleryOrPhoto
import com.kire.audio.presentation.ui.theme.AudioExtendedTheme
import com.kire.audio.presentation.util.nonScaledSp
import com.kire.audio.screen.functional.convertLongToTime
import com.kire.audio.screen.functional.getContext
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.util.concurrent.TimeUnit
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun DialogInfo(
trackUiState: TrackUiState,
changeTrackUiState: (TrackUiState) -> Unit,
changeOpenDialog: (Boolean) -> Unit,
upsertTrack: suspend (Track) -> Unit,
) {
val context = getContext()
var openDialog by remember {
mutableStateOf(false)
}
val coroutineScope = rememberCoroutineScope()
val minutesAll = TimeUnit.MILLISECONDS.toMinutes(trackUiState.currentTrackPlaying?.duration ?: 0L)
val secondsAll = TimeUnit.MILLISECONDS.toSeconds(trackUiState.currentTrackPlaying?.duration ?: 0L) % 60
val map = mapOf(
stringResource(id = R.string.info_dialog_title) to trackUiState.currentTrackPlaying?.title,
stringResource(id = R.string.info_dialog_artist) to trackUiState.currentTrackPlaying?.artist,
stringResource(id = R.string.info_dialog_album) to (trackUiState.currentTrackPlaying?.album ?: "0"),
stringResource(id = R.string.info_dialog_duration) to "$minutesAll:$secondsAll",
stringResource(id = R.string.info_dialog_favourite) to if (trackUiState.currentTrackPlaying?.isFavourite == true) "Yes" else "No",
stringResource(id = R.string.info_dialog_date_added) to convertLongToTime(trackUiState.currentTrackPlaying?.dateAdded?.toLong() ?: 0),
stringResource(id = R.string.info_dialog_album_id) to trackUiState.currentTrackPlaying?.albumId.toString(),
stringResource(id = R.string.info_dialog_image_uri) to trackUiState.currentTrackPlaying?.imageUri.toString(),
stringResource(id = R.string.info_dialog_path) to trackUiState.currentTrackPlaying?.path
)
var isEnabled by rememberSaveable { mutableStateOf(false) }
var newTitle by rememberSaveable { mutableStateOf(trackUiState.currentTrackPlaying?.title) }
var newArtist by rememberSaveable { mutableStateOf(trackUiState.currentTrackPlaying?.artist) }
var newAlbum by rememberSaveable { mutableStateOf(trackUiState.currentTrackPlaying?.album) }
BasicAlertDialog(
onDismissRequest = {
changeOpenDialog(false)
}
) {
LazyVerticalGrid(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight(0.5f)
.background(
color = AudioExtendedTheme.extendedColors.controlElementsBackground,
shape = RoundedCornerShape(size = dimensionResource(id = R.dimen.app_universal_rounded_corner))
),
columns = GridCells.Fixed(count = 2),
verticalArrangement = Arrangement.spacedBy(10.dp),
horizontalArrangement = Arrangement.spacedBy(12.dp),
contentPadding = PaddingValues(
start = 32.dp,
end = 32.dp,
top = 28.dp,
bottom = 28.dp
)
) {
item(span = { GridItemSpan(this.maxLineSpan) }) {
Column(
modifier = Modifier
.fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(10.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
Row(
modifier = Modifier
.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.SpaceBetween
){
Box(modifier = Modifier.size(20.dp)) { }
Text(
text = stringResource(id = R.string.info_dialog_header),
fontWeight = FontWeight.W700,
fontSize = 28.sp.nonScaledSp,
fontFamily = FontFamily.SansSerif,
color = AudioExtendedTheme.extendedColors.primaryText
)
Icon(
imageVector = if (!isEnabled) Icons.Rounded.Edit else Icons.Rounded.Save,
contentDescription = "",
tint = AudioExtendedTheme.extendedColors.orangeAccents,
modifier = Modifier
.size(dimensionResource(id = R.dimen.app_universal_icon_size))
.bounceClick {
isEnabled = !isEnabled.also {
trackUiState.currentTrackPlaying?.apply {
if (
title != newTitle ||
artist != newArtist ||
!album.equals(newAlbum)
)
coroutineScope.launch(Dispatchers.Default) {
upsertTrack(this@apply
.copy(
title = newTitle ?: "Null",
artist = newArtist ?: "Null",
album = newAlbum ?: "Null"
)
.also {
changeTrackUiState(
trackUiState.copy(
currentTrackPlaying = it
)
)
}
)
}
}
}
}
)
}
HorizontalDivider(
modifier = Modifier
.fillMaxWidth(0.25f)
.clip(
RoundedCornerShape(dimensionResource(id = R.dimen.app_universal_rounded_corner))
),
thickness = 4.dp,
color = AudioExtendedTheme.extendedColors.divider
)
}
}
for(element in map){
item {
GridElement(
text = element.key,
switcher = true,
isFirst = element.key == stringResource(id = R.string.info_dialog_title)
)
}
item {
GridElement(
text = element.value ?: "Null",
switcher = false,
isEnabled = isEnabled,
isImageURI = element.key == stringResource(id = R.string.info_dialog_image_uri),
isEditable = element.key in arrayOf(
stringResource(id = R.string.info_dialog_title),
stringResource(id = R.string.info_dialog_artist),
stringResource(id = R.string.info_dialog_album),
stringResource(id = R.string.info_dialog_image_uri)
),
updateText = { newText ->
when(element.key){
context.getString(R.string.info_dialog_title) -> newTitle = newText
context.getString(R.string.info_dialog_artist) -> newArtist = newText
context.getString(R.string.info_dialog_album) -> newAlbum = newText
}
},
isFirst = element.key == stringResource(id = R.string.info_dialog_title),
changeOpenDialog = {isIt ->
openDialog = isIt
}
)
}
}
}
}
trackUiState.currentTrackPlaying?.apply {
if (openDialog) {
DialogGalleryOrPhoto(
imageUri = imageUri,
defaultImageUri = defaultImageUri,
changeOpenDialog = {isIt ->
openDialog = isIt
},
updateUri = { imageUri ->
coroutineScope.launch(Dispatchers.Default) {
upsertTrack(copy(imageUri = imageUri)
.also {
changeTrackUiState(trackUiState.copy(currentTrackPlaying = it))
}
)
}
},
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
2c9a85d3a10d06b7c5ffd058d60faca91211498f
| 11,725
|
Meowdio
|
Apache License 2.0
|
core-api/src/main/java/com/gifft/core/api/di/FragmentKey.kt
|
SIDOVSKY
| 265,333,377
| false
| null |
package com.gifft.core.api.di
import androidx.fragment.app.Fragment
import dagger.MapKey
import kotlin.reflect.KClass
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
@Retention(value = AnnotationRetention.RUNTIME)
@MapKey
annotation class FragmentKey(val value: KClass<out Fragment>)
| 0
|
Kotlin
|
0
| 1
|
890f89317d59dff6dac6435fe1aaf26637ad2f29
| 341
|
Gifft
|
Apache License 2.0
|
app/src/main/java/pointlessgroup/pointless/wifi/WifiScanReceiver.kt
|
brunodles
| 110,770,735
| false
| null |
package pointlessgroup.pointless.wifi
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.wifi.WifiManager
import android.util.Log
class WifiScanReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != ACTION)
return
Log.d(TAG, "onReceive: " + intent.extras)
intent.extras.keySet().forEach {
Log.d(TAG, "onReceive: -key: " + it)
Log.d(TAG, "onReceive: - " + intent.extras[it])
}
val scanResults = WifiManagerCompat.from(context).scanResults
Log.d(TAG, "onReceive: scanResults " + scanResults.size)
scanResults.forEach {
Log.d(TAG, "onReceive: result - " + it)
}
// Preferences(context).
}
fun register(context: Context) {
context.registerReceiver(this, IntentFilter(ACTION))
}
fun unregister(context: Context) {
context.unregisterReceiver(this)
}
companion object {
val TAG = "WifiScanReceiver"
const val ACTION = WifiManager.SCAN_RESULTS_AVAILABLE_ACTION
}
}
| 0
|
Kotlin
|
0
| 0
|
501c26dee22f527c5113d36daf483a1582ad3209
| 1,216
|
pointless
|
MIT License
|
Todo app/app/src/main/java/com/android/todoapp/ui/add/AddFragment.kt
|
NishadiSS
| 729,465,945
| false
|
{"Kotlin": 22414}
|
package com.android.todoapp.ui.add
import android.os.Bundle
import android.text.TextUtils
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ArrayAdapter
import android.widget.Toast
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.android.todoapp.R
import com.android.todoapp.data.local.TaskEntry
import com.android.todoapp.databinding.FragmentAddBinding
import com.android.todoapp.ui.task.TaskViewModel
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class AddFragment : Fragment() {
private val viewModel: TaskViewModel by viewModels()
private var _binding: FragmentAddBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentAddBinding.inflate(inflater, container, false)
val myAdapter = ArrayAdapter(
requireContext(),
android.R.layout.simple_spinner_dropdown_item,
resources.getStringArray(R.array.priorities)
)
binding.apply {
spinner.adapter = myAdapter
btnAdd.setOnClickListener {
if(TextUtils.isEmpty((edtTask.text))){
Toast.makeText(requireContext(), "It's empty!", Toast.LENGTH_SHORT).show()
return@setOnClickListener
}
val titleTitle = edtTask.text.toString()
val priority = spinner.selectedItemPosition
val taskEntry = TaskEntry(
0,
titleTitle,
priority,
System.currentTimeMillis()
)
viewModel.insert(taskEntry)
Toast.makeText(requireContext(), "Successfully added!", Toast.LENGTH_SHORT).show()
findNavController().navigate(R.id.action_addFragment_to_taskFragment)
}
}
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
}
| 0
|
Kotlin
|
0
| 0
|
c432cb06dea89d89913791ef56d87cb7ef248777
| 2,239
|
TODO-Application-Android-studio-Kotlin
|
MIT License
|
kotlin-mui-icons/src/main/generated/mui/icons/material/CorporateFareSharp.kt
|
JetBrains
| 93,250,841
| false
| null |
// Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/CorporateFareSharp")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val CorporateFareSharp: SvgIconComponent
| 10
|
Kotlin
|
145
| 983
|
7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35
| 218
|
kotlin-wrappers
|
Apache License 2.0
|
src/main/kotlin/me/jraynor/Bpm.kt
|
MrManiacc
| 349,858,377
| false
| null |
package me.jraynor
import me.jraynor.internal.Listeners
import me.jraynor.internal.Registry
import net.minecraftforge.fml.common.Mod
import org.apache.logging.log4j.LogManager
import thedarkcolour.kotlinforforge.forge.FORGE_BUS
import thedarkcolour.kotlinforforge.forge.MOD_BUS
/**
* Main mod class. Should be an `object` declaration annotated with `@Mod`.
* The modid should be declared in this object and should match the modId entry
* in mods.toml.
*/
@Mod(Bpm.ID)
object Bpm {
const val ID: String = "bpm"
/**We should only create this once, not per call.**/
internal val logger = LogManager.getLogger(ID)
/**
* This will setup everything first initializing out event callbacks,
* then initializing our blocks and other objects.
*/
init {
Listeners.register(MOD_BUS, FORGE_BUS)
Registry.register(MOD_BUS)
}
}
| 8
|
Kotlin
|
3
| 15
|
4334badd181215dccecb4f62be1f565ad8af5b09
| 877
|
Blueprints
|
MIT License
|
tracy/src/main/kotlin/io/polyakov/tracy/action/TraceAction.kt
|
p01yak0v
| 596,203,365
| false
| null |
package io.polyakov.tracy.action
internal enum class TraceAction {
START, STOP, CANCEL, ENRICH
}
| 0
|
Kotlin
|
0
| 0
|
cfc9818b55b154cff29c716dcd4184d306bbd817
| 102
|
tracy
|
Apache License 2.0
|
app/src/main/java/com/breezebengaldetergentproducts/features/leaveapplynew/ClickonStatus.kt
|
DebashisINT
| 863,405,964
| false
|
{"Kotlin": 15991783, "Java": 1032672}
|
package com.breezebengaldetergentproducts.features.leaveapplynew
import com.breezebengaldetergentproducts.features.addAttendence.model.Leave_list_Response
interface ClickonStatus {
fun OnApprovedclick(obj: Leave_list_Response)
fun OnRejectclick(obj: Leave_list_Response)
}
| 0
|
Kotlin
|
0
| 0
|
0cd8b29158b494893e3d7be77b87a725e3d49abf
| 283
|
BengalDetergentProducts
|
Apache License 2.0
|
src/main/kotlin/no/nav/sosialhjelp/avtaler/kommune/KommuneApi.kt
|
navikt
| 538,959,615
| false
|
{"Kotlin": 82993, "Dockerfile": 184}
|
package no.nav.sosialhjelp.avtaler.kommune
import io.ktor.http.HttpStatusCode
import io.ktor.http.auth.HttpAuthHeader
import io.ktor.server.application.ApplicationCall
import io.ktor.server.application.call
import io.ktor.server.auth.parseAuthorizationHeader
import io.ktor.server.response.respond
import io.ktor.server.routing.Route
import io.ktor.server.routing.get
import io.ktor.server.routing.route
import mu.KotlinLogging
import no.nav.sosialhjelp.avtaler.altinn.Avgiver
import no.nav.sosialhjelp.avtaler.avtaler.AvtaleService
import no.nav.sosialhjelp.avtaler.extractFnr
private val log = KotlinLogging.logger { }
fun Route.kommuneApi(avtaleService: AvtaleService) {
route("/kommuner") {
get {
val kommuner =
avtaleService.hentAvtaler(
fnr = call.extractFnr(),
tjeneste = Avgiver.Tjeneste.AVTALESIGNERING,
this.context.getAccessToken(),
)
call.respond(HttpStatusCode.OK, kommuner)
}
}
}
private fun ApplicationCall.getAccessToken(): String? {
val authorizationHeader = request.parseAuthorizationHeader()
if (authorizationHeader is HttpAuthHeader.Single && authorizationHeader.authScheme == "Bearer") {
log.info { "returning authheader" }
return authorizationHeader.blob
}
return null
}
| 6
|
Kotlin
|
1
| 1
|
8203455fb387af8c570786e2037c2d0808ef07a1
| 1,370
|
sosialhjelp-avtaler-api
|
MIT License
|
app/src/main/java/com/jocoos/flipflop/media/sample/ReceiverActivity.kt
|
jocoos-dev
| 274,056,833
| false
| null |
package com.jocoos.flipflop.media.sample
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.jocoos.flipflop.media.FlipFlopMedia
import com.jocoos.flipflop.media.api.FFRTC
import com.jocoos.flipflop.media.api.FFRTCListener
import kotlinx.android.synthetic.main.activity_rtc.*
class ReceiverActivity : AppCompatActivity(), FFRTCListener {
private val rtc = FlipFlopMedia.getRTC()
private val myID = System.currentTimeMillis()
private var roomID: Long = 0 // 방송하기에서 만들어진 roomID로 바꿔준다.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rtc)
rtc.listener = this
// 준비
rtc.prepare(this, preview, null)
}
override fun onStop() {
super.onStop()
rtc.reset()
}
// prepare 성공 후
override fun onPrepared(rtc: FFRTC) {
//서버에 접속
rtc.connect()
}
// 서버와 접속이 성공 했을때
override fun onConnected(rtc: FFRTC) {
// 방에 접속한다.
rtc.join(roomID, myID)
}
// 서버 접속이 끊어 졌을때
override fun onDisconnected(rtc: FFRTC) {
}
// 방 생성이 성공 했을때
override fun onRoomCreated(rtc: FFRTC, roomID: Long) {
}
// 방 삭제가 성공 했을때
override fun onRoomDeleted(rtc: FFRTC, roomID: Long) {
}
// 에러가 났을때
override fun onError(rtc: FFRTC, errorCode: Int, error: String) {
Toast.makeText(this, "errorCode: $errorCode error: $error", Toast.LENGTH_LONG).show()
}
}
| 0
|
Kotlin
|
0
| 0
|
827c48a35b3d0e6f2b3000c40ab07f8de8c154ff
| 1,538
|
FlipFlopMediaSDKSample-Android
|
MIT License
|
libdatabase/src/main/java/ru/example/libdatabase/sqlite/WorkDao.kt
|
elronsmith
| 317,674,896
| false
| null |
package ru.example.libdatabase.sqlite
import android.content.ContentValues
import android.database.Cursor
import android.database.DatabaseUtils
import android.database.sqlite.SQLiteOpenHelper
class WorkDao(private val database: SQLiteOpenHelper): IWorkDao {
private val projection = arrayOf(
WorkEntity.COLUMN__ID,
WorkEntity.COLUMN_TITLE,
WorkEntity.COLUMN_DESCRIPTION
)
override fun getWorks(): List<WorkEntity> {
val result = ArrayList<WorkEntity>()
val cursor = database.writableDatabase.query(WorkEntity.TABLE_NAME, null, null, null, null, null, null)
if (cursor.moveToFirst())
do {
result.add(obtainWorkEntity(cursor))
} while (cursor.moveToNext())
cursor.close()
return result
}
override fun getWork(id: Long): WorkEntity? {
val db = database.readableDatabase
val selection = "${WorkEntity.COLUMN__ID} = ?"
val selectionArgs = arrayOf("$id")
val cursor = db.query(
WorkEntity.TABLE_NAME, // The table to query
projection, // The array of columns to return (pass null to get all)
selection, // The columns for the WHERE clause
selectionArgs, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
)
var entity: WorkEntity? = null
if (cursor.moveToFirst()) {
entity = WorkEntity(
cursor.getLong(cursor.getColumnIndex(WorkEntity.COLUMN__ID)),
cursor.getString(cursor.getColumnIndex(WorkEntity.COLUMN_TITLE)),
cursor.getString(cursor.getColumnIndex(WorkEntity.COLUMN_DESCRIPTION)))
}
cursor.close()
return entity
}
override fun setWork(work: WorkEntity) {
val contentValues = obtainContentValues(work)
val rows = database.writableDatabase.update(
WorkEntity.TABLE_NAME,
contentValues,
"${WorkEntity.COLUMN__ID}=?",
arrayOf(work.id.toString()))
if (rows == 0)
database.writableDatabase.insert(
WorkEntity.TABLE_NAME,
null,
contentValues)
}
override fun deleteWork(work: WorkEntity) {
deleteWork(work.id)
}
override fun deleteWork(id: Long) {
database.writableDatabase.delete(
WorkEntity.TABLE_NAME,
"${WorkEntity.COLUMN__ID}=?",
arrayOf(id.toString())
)
}
override fun deleteAll() {
database.writableDatabase.delete(WorkEntity.TABLE_NAME, null, null)
}
override fun getSize(): Long {
return DatabaseUtils.queryNumEntries(database.readableDatabase, WorkEntity.TABLE_NAME)
}
private fun obtainContentValues(work: WorkEntity): ContentValues {
val result = ContentValues()
result.put(WorkEntity.COLUMN__ID, work.id)
result.put(WorkEntity.COLUMN_TITLE, work.title)
result.put(WorkEntity.COLUMN_DESCRIPTION, work.description)
return result
}
private fun obtainWorkEntity(cursor: Cursor): WorkEntity {
return WorkEntity(
cursor.getLong(cursor.getColumnIndex(WorkEntity.COLUMN__ID)),
cursor.getString(cursor.getColumnIndex(WorkEntity.COLUMN_TITLE)),
cursor.getString(cursor.getColumnIndex(WorkEntity.COLUMN_DESCRIPTION))
)
}
}
| 0
|
Kotlin
|
0
| 0
|
1d5eff3afb6123727db0ff28547f7365c79caf9b
| 3,578
|
ExampleRoom
|
Apache License 2.0
|
app/src/main/java/com/example/fragment/project/data/Login.kt
|
miaowmiaow
| 364,865,870
| false
|
{"Kotlin": 896094, "Java": 31064, "JavaScript": 10814, "HTML": 5449, "CSS": 60}
|
package com.example.fragment.project.data
import com.example.fragment.project.database.user.User
import com.example.miaow.base.http.HttpResponse
data class Login(
val data: User? = null
) : HttpResponse()
data class Register(
val data: User? = null
) : HttpResponse()
| 0
|
Kotlin
|
233
| 1,313
|
7e75e6c6738b6bbcf1cead9dfe6e7e2bf86ab6b1
| 278
|
fragmject
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/BaseballAlt.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.bold
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 me.localx.icons.straight.Icons
public val Icons.Bold.BaseballAlt: ImageVector
get() {
if (_baseballAlt != null) {
return _baseballAlt!!
}
_baseballAlt = Builder(name = "BaseballAlt", defaultWidth = 512.0.dp, defaultHeight =
512.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(22.616f, 8.067f)
arcToRelative(4.726f, 4.726f, 0.0f, false, false, -6.683f, -6.683f)
lineTo(12.891f, 4.427f)
arcToRelative(32.691f, 32.691f, 0.0f, false, false, -4.7f, 5.939f)
arcTo(18.967f, 18.967f, 0.0f, false, false, 7.028f, 12.7f)
arcToRelative(10.3f, 10.3f, 0.0f, false, true, -0.692f, 1.415f)
lineToRelative(-3.3f, 3.3f)
lineTo(2.119f, 16.5f)
lineTo(0.0f, 18.618f)
lineTo(5.382f, 24.0f)
lineTo(7.5f, 21.882f)
lineToRelative(-0.919f, -0.92f)
lineTo(9.742f, 17.8f)
arcToRelative(11.434f, 11.434f, 0.0f, false, true, 1.6f, -0.8f)
arcToRelative(20.311f, 20.311f, 0.0f, false, false, 2.49f, -1.258f)
arcToRelative(32.643f, 32.643f, 0.0f, false, false, 5.6f, -4.494f)
close()
moveTo(12.232f, 13.206f)
arcToRelative(10.526f, 10.526f, 0.0f, false, true, -1.05f, 0.567f)
lineToRelative(-0.927f, -0.928f)
arcToRelative(9.765f, 9.765f, 0.0f, false, true, 0.484f, -0.9f)
arcToRelative(29.7f, 29.7f, 0.0f, false, true, 4.273f, -5.394f)
lineToRelative(3.042f, -3.043f)
arcTo(1.726f, 1.726f, 0.0f, false, true, 20.5f, 5.946f)
lineToRelative(-3.181f, 3.18f)
arcTo(29.576f, 29.576f, 0.0f, false, true, 12.232f, 13.206f)
close()
moveTo(24.0f, 21.0f)
arcToRelative(3.0f, 3.0f, 0.0f, true, true, -3.0f, -3.0f)
arcTo(3.0f, 3.0f, 0.0f, false, true, 24.0f, 21.0f)
close()
}
}
.build()
return _baseballAlt!!
}
private var _baseballAlt: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 2,985
|
icons
|
MIT License
|
compiler-plugin-ksp/src/main/kotlin/com/ing/zkflow/ksp/Util.kt
|
ing-bank
| 550,239,957
| false
|
{"Kotlin": 1610321, "Shell": 1609}
|
@file:Suppress("TooManyFunctions")
package com.ing.zkflow.ksp
import com.google.devtools.ksp.getAllSuperTypes
import com.google.devtools.ksp.isAbstract
import com.google.devtools.ksp.processing.Resolver
import com.google.devtools.ksp.symbol.ClassKind
import com.google.devtools.ksp.symbol.KSAnnotated
import com.google.devtools.ksp.symbol.KSAnnotation
import com.google.devtools.ksp.symbol.KSClassDeclaration
import com.google.devtools.ksp.symbol.KSType
import com.google.devtools.ksp.symbol.KSTypeReference
import com.ing.zkflow.Surrogate
import com.ing.zkflow.Via
import com.ing.zkflow.annotations.ZKPSurrogate
import com.ing.zkflow.annotations.corda.Algorithm
import com.ing.zkflow.annotations.corda.SignatureSpec
import com.ing.zkflow.util.buildFullyDistinguishableClassName
import com.squareup.kotlinpoet.AnnotationSpec
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.TypeName
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.ksp.toClassName
import kotlinx.serialization.Contextual
import kotlin.reflect.KClass
private val implementedInterfacesCache: MutableMap<KSClassDeclaration, Sequence<KSClassDeclaration>> = mutableMapOf()
private val implementedDirectInterfacesCache: MutableMap<KSClassDeclaration, Sequence<KSClassDeclaration>> = mutableMapOf()
fun KSClassDeclaration.getAllImplementedInterfaces(): Sequence<KSClassDeclaration> = implementedInterfacesCache.getOrPut(this) {
getAllSuperTypes()
.map { it.declaration }
.filterIsInstance<KSClassDeclaration>()
.filter { it.classKind == ClassKind.INTERFACE }
}
fun KSClassDeclaration.getAllDirectlyImplementedInterfaces(): Sequence<KSClassDeclaration> =
implementedDirectInterfacesCache.getOrPut(this) {
superTypes
.map { it.resolve().declaration }
.filterIsInstance<KSClassDeclaration>()
.filter { it.classKind == ClassKind.INTERFACE }
}
/**
* Returns true if the receiver implements the interfaceClass either directly or indirectly
*/
fun KSClassDeclaration.implementsInterface(interfaceClass: KClass<*>): Boolean =
getAllImplementedInterfaces().any {
it.qualifiedName?.asString() == interfaceClass.qualifiedName
}
/**
* Returns true only if the receiver implements the interfaceClass directly
*/
fun KSClassDeclaration.implementsInterfaceDirectly(interfaceClass: KClass<*>): Boolean =
getAllDirectlyImplementedInterfaces().any {
it.qualifiedName?.asString() == interfaceClass.qualifiedName
}
/**
* Returns true only if the receiver implements the interfaceClass directly
*/
fun KSClassDeclaration.implementsInterfaceDirectly(interfaceClass: KSClassDeclaration): Boolean =
getAllDirectlyImplementedInterfaces().any {
it.qualifiedName?.asString() == interfaceClass.qualifiedName?.asString()
}
fun KSAnnotated.getAnnotationsByType(annotationKClass: KClass<out Annotation>): Sequence<KSAnnotation> {
return this.annotations.filter {
it.shortName.getShortName() == annotationKClass.simpleName &&
it.annotationType.resolve().declaration.qualifiedName?.asString() == annotationKClass.qualifiedName
}
}
fun KSClassDeclaration.getSurrogateTargetClass(): KSClassDeclaration {
val type = getSurrogateTargetType()
return type
.declaration as? KSClassDeclaration
?: error("$type is not a KSClassDeclaration.")
}
fun KSClassDeclaration.getSurrogateTargetType(): KSType {
val surrogateArgument = superTypes.single {
it.resolve().declaration.qualifiedName?.asString() == Surrogate::class.qualifiedName
}.resolve().arguments.single()
return surrogateArgument
.type
?.resolve()
?: error("Could not resolve type of $surrogateArgument.")
}
fun Sequence<KSClassDeclaration>.filterConcreteClassesOrObjects(): Sequence<KSClassDeclaration> =
filter { it.classKind in listOf(ClassKind.ENUM_CLASS, ClassKind.CLASS, ClassKind.OBJECT) && !it.isAbstract() }
/**
* Surrogates are classes that are annotated with @ZKPSurrogate *and* implement [Surrogate].
* Classes with only the annotation cause an error, classes only implementing the interface will be ignored.
*/
fun Resolver.getAllSurrogates(): Sequence<KSClassDeclaration> {
val annotated = this.findClassesOrObjectsWithAnnotation(ZKPSurrogate::class)
val implementing = annotated.filter { it.implementsInterface(Surrogate::class) }
require(annotated.count() == implementing.count()) {
"All @${ZKPSurrogate::class.simpleName}-annotated classes should implement the ${Surrogate::class.simpleName} interface. " +
"The following do not: ${(annotated - implementing).map { it.qualifiedName?.asString() }.joinToString(", ")}"
}
return implementing
}
fun Resolver.findClassesOrObjectsWithAnnotation(annotationKClass: KClass<out Annotation>): Sequence<KSClassDeclaration> {
return getSymbolsWithAnnotation(annotationKClass.qualifiedName!!)
.filterIsInstance<KSClassDeclaration>()
.filterConcreteClassesOrObjects()
}
fun KSAnnotated.getSingleArgumentOfSingleAnnotationByType(annotationKClass: KClass<out Annotation>): Any {
return this.getAnnotationsByType(annotationKClass).single().arguments.single().value!!
}
fun KSTypeReference.getNonRepeatableAnnotationByType(annotationKClass: KClass<out Annotation>): KSAnnotation {
return annotations
.single {
it.shortName.getShortName() == annotationKClass.simpleName &&
it.annotationType.resolve().declaration.qualifiedName?.asString() == annotationKClass.qualifiedName
}
}
fun KSTypeReference.getCordaSignatureId(): Int {
return getSingleMetaAnnotationByType(SignatureSpec::class)
.arguments
.single()
.value!!
.toString()
.toInt()
}
fun KSTypeReference.getDigestAlgorithm(): KSType {
return getSingleMetaAnnotationByType(Algorithm::class)
.arguments
.single()
.value!! as KSType
}
/**
* Inspects every annotation (let's call it) `A` of a [KSType] and selects
* an [annotationKClass] of `A`, e.g., in the following piece
*
* ```
* val value: @A @B Int
*
* @[annotationKClass]
* annotation class A
*
* annotation class B
* ```
*
* @[annotationKClass] will be selected.
*/
fun KSTypeReference.getSingleMetaAnnotationByType(annotationKClass: KClass<out Annotation>): KSAnnotation {
return annotations.mapNotNull {
try {
it.annotationType.resolve().declaration.getAnnotationsByType(annotationKClass).single()
} catch (_: Exception) {
null
}
}.single()
}
fun KSClassDeclaration.getSurrogateClassName(isEnum: Boolean): ClassName {
return if (isEnum) {
toClassName().buildFullyDistinguishableClassName(
Surrogate.GENERATED_SURROGATE_POSTFIX,
Surrogate.GENERATED_SURROGATE_ENUM_POSTFIX
)
} else {
toClassName().buildFullyDistinguishableClassName(
Surrogate.GENERATED_SURROGATE_POSTFIX
)
}
}
fun KSClassDeclaration.getSurrogateSerializerClassName(): ClassName {
return toClassName().buildFullyDistinguishableClassName(Surrogate.GENERATED_SURROGATE_SERIALIZER_POSTFIX)
}
fun KSAnnotation.getSurrogateFromViaAnnotation(): KSClassDeclaration {
require(annotationType.resolve().declaration.qualifiedName?.asString() == Via::class.qualifiedName) {
"Can't get Surrogate from $this, it is not a @${Via::class.simpleName} annotation."
}
return annotationType.element?.typeArguments?.singleOrNull()?.type?.resolve()?.declaration as? KSClassDeclaration
?: error("@${Via::class.simpleName} annotation's argument is not a class.")
}
/**
* Prepends every type with @[Contextual] annotation.
*/
fun KSType.toContextualTypeName() =
toTypeNameWithAnnotation(listOf(Contextual::class))
/**
* Removes all annotations from the type declaration.
*/
fun KSType.toCleanTypeName() =
toTypeNameWithAnnotation(emptyList())
/**
* Recursively walks the type tree and attaches ALL given annotations on ALL levels.
*/
private fun KSType.toTypeNameWithAnnotation(annotations: List<KClass<out Annotation>>): TypeName {
if (arguments.isEmpty()) {
return toClassName()
.copy(
annotations = annotations.map {
AnnotationSpec.builder(it.asClassName()).build()
},
nullable = isMarkedNullable
)
}
val typeArguments = arguments.map { it.type!!.resolve().toTypeNameWithAnnotation(annotations) }
return toClassName()
.parameterizedBy(typeArguments)
.copy(
annotations = annotations.map {
AnnotationSpec.builder(it.asClassName()).build()
},
nullable = isMarkedNullable
)
}
| 0
|
Kotlin
|
4
| 9
|
f6e2524af124c1bdb2480f03bf907f6a44fa3c6c
| 8,913
|
zkflow
|
MIT License
|
app/src/main/java/com/bengisusahin/cryptocrazy/model/CryptoItem.kt
|
bengisusaahin
| 832,308,437
| false
|
{"Kotlin": 25486}
|
package com.bengisusahin.cryptocrazy.model
data class CryptoItem(
val id: String,
val logo_url: String,
val name: String
)
| 0
|
Kotlin
|
0
| 0
|
9e29c2307ae1e04835676793862f5d085bb3036b
| 135
|
CryptoCrazy
|
Apache License 2.0
|
src/main/kotlin/trik/testsys/gradingsystem/enums/TRIKCommands.kt
|
Pupsen-Vupsen
| 441,453,585
| false
|
{"Kotlin": 64463, "Qt Script": 2966, "Dockerfile": 2450, "HTML": 399}
|
package trik.testsys.gradingsystem.enums
enum class TRIKCommands(val command: String) {
TWO_D_MODEL("./TRIKStudio/bin/2D-model -platform offscreen --close -r"),
PATCHER("./TRIKStudio/bin/patcher -f")
}
| 1
|
Kotlin
|
1
| 1
|
e8c7a6c2a309c2c006470ab562dc4bd883224a71
| 212
|
trik-testsys-grading-system
|
Apache License 2.0
|
app/src/main/java/com/tzapps/calculator/HistoryAdapter.kt
|
JohnX4321
| 448,324,079
| false
|
{"Kotlin": 57087}
|
package com.tzapps.calculator
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.tzapps.calculator.db.Record
class HistoryAdapter(var recordsList: List<Record>): RecyclerView.Adapter<HistoryAdapter.HistoryViewHolder>() {
override fun getItemCount(): Int {
return recordsList.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): HistoryViewHolder {
val v = LayoutInflater.from(parent.context).inflate(R.layout.item_expression,null)
//xml encoding didn't worked. this did.
v.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT)
return HistoryViewHolder(v)
}
override fun onBindViewHolder(holder: HistoryViewHolder, position: Int) {
holder.exprTV.text=recordsList[position].exprName
holder.resTV.text=recordsList[position].exp
}
inner class HistoryViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
val exprTV = itemView.findViewById<TextView>(R.id.txtExpr)!!
val resTV = itemView.findViewById<TextView>(R.id.txtResult)!!
}
}
| 0
|
Kotlin
|
0
| 0
|
a7e798dec410ec7dfce2fded64d6f713baf03100
| 1,304
|
Calculator
|
Apache License 2.0
|
Week3/src/main/kotlin/main.kt
|
EdmundoSanchezM
| 354,481,310
| false
| null |
/*fun isFoo1(n: Name) = n.value == "foo"
fun isFoo2(n: Name?) = n.value == "foo"
fun isFoo3(n: Name?) = n != null && n.value == "foo"
fun isFoo4(n: Name?) = n?.value == "foo"*/
fun NullableTypes() {
val s1: String = "always not null"
val s2: String? = "can be null or non-null"
val s: String? = null
if(s != null){
s.length
}//Replace if expression with safe access as follows
s?.length
val length: Int? = s?.length
//or
val length1: Int = s?.length ?:0
println(length1)
val a: Int? = null
val b: Int? = 1
val c: Int = 2
val sum1 = (a ?: 0) + c
val sum2 = (b ?: 0) + c
println("$sum1$sum2")//Output: 23
/*
isFoo1(null) //Function ok, but the invocation We not expected a null parameter
isFoo2(null) //Ok but in invocation but we need use '?.value'
isFoo3(null) //Ok
isFoo4(null) //Ok
*/
val x: Int? = 1
val y: Int = 2
val sum = x ?: 0 + y // x ?: (0 + y)
println(sum)
/*
* fun foo(list1: List<Int?>, list2: List<Int>?) {
list1.size
list2.size
val i: Int = list1.get(0)
val j: Int = list2.get(0)
}
* */
fun foo(list1: List<Int?>, list2: List<Int>?) {
list1.size
list2?.size
val i: Int? = list1.get(0)
val j: Int? = list2?.get(0)
}
}
fun SafeCast(){
val any: String="Any"
if(any is String){
val s = any as String
s.toUpperCase()
}
//or
if(any is String){
any.toUpperCase()
}
(any as? String)?.toUpperCase()//Null if it cant be converted
}
fun main(){
//NullableTypes()
SafeCast()
}
| 0
|
Kotlin
|
0
| 0
|
a671a9b35eeae1f56ee1ad448347d9df5e583c9d
| 1,672
|
Kotlin-for-Java-Developers
|
MIT License
|
features/home/src/main/kotlin/app/dapk/st/home/HomeScreen.kt
|
ShadowJonathan
| 471,471,233
| true
|
{"Kotlin": 586327, "Java": 13756, "Shell": 763, "Prolog": 113}
|
package app.dapk.st.home
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import app.dapk.st.core.components.CenteredLoading
import app.dapk.st.design.components.CircleishAvatar
import app.dapk.st.design.components.SmallTalkTheme
import app.dapk.st.directory.DirectoryScreen
import app.dapk.st.home.HomeScreenState.*
import app.dapk.st.home.HomeScreenState.Page.Directory
import app.dapk.st.home.HomeScreenState.Page.Profile
import app.dapk.st.login.LoginScreen
import app.dapk.st.profile.ProfileScreen
@Composable
fun HomeScreen(homeViewModel: HomeViewModel) {
SmallTalkTheme {
Surface(Modifier.fillMaxSize()) {
LaunchedEffect(true) {
homeViewModel.start()
}
when (val state = homeViewModel.state) {
Loading -> CenteredLoading()
is SignedIn -> {
Scaffold(
bottomBar = {
BottomBar(state, homeViewModel)
},
content = { innerPadding ->
Box(modifier = Modifier.padding(innerPadding)) {
when (state.page) {
Directory -> DirectoryScreen(homeViewModel.directory())
Profile -> {
ProfileScreen(homeViewModel.profile()) {
homeViewModel.changePage(Directory)
}
}
}
}
}
)
}
SignedOut -> {
LoginScreen(homeViewModel.login()) {
homeViewModel.loggedIn()
}
}
}
}
}
}
@Composable
private fun BottomBar(state: SignedIn, homeViewModel: HomeViewModel) {
Column {
Divider(modifier = Modifier.fillMaxWidth(), color = Color.Black.copy(alpha = 0.2f), thickness = 0.5.dp)
BottomNavigation(elevation = 0.dp, backgroundColor = Color.Transparent, modifier = Modifier.height(IntrinsicSize.Min)) {
Page.values().forEach { page ->
when (page) {
Directory -> BottomNavigationItem(
icon = { Icon(page.icon, contentDescription = null) },
selected = state.page == page,
onClick = { homeViewModel.changePage(page) },
)
Profile -> BottomNavigationItem(
icon = {
Box(modifier = Modifier.fillMaxHeight()) {
CircleishAvatar(state.me.avatarUrl?.value, state.me.displayName ?: state.me.userId.value, size = 25.dp)
}
},
selected = state.page == page,
onClick = { homeViewModel.changePage(page) },
)
}
}
}
}
}
| 0
| null |
0
| 0
|
2ab2253e7a1335f8c25b5e69be0dc1ec9c254958
| 3,376
|
small-talk
|
Apache License 2.0
|
cinema-server/src/main/kotlin/io/github/ermadmi78/kobby/cinema/server/resolvers/ActorResolver.kt
|
ermadmi78
| 323,070,076
| false
| null |
package io.github.ermadmi78.kobby.cinema.server.resolvers
import io.github.ermadmi78.kobby.cinema.api.kobby.kotlin.dto.ActorDto
import io.github.ermadmi78.kobby.cinema.api.kobby.kotlin.dto.CountryDto
import io.github.ermadmi78.kobby.cinema.api.kobby.kotlin.dto.FilmDto
import io.github.ermadmi78.kobby.cinema.api.kobby.kotlin.dto.Genre
import io.github.ermadmi78.kobby.cinema.api.kobby.kotlin.resolver.CinemaActorResolver
import io.github.ermadmi78.kobby.cinema.server.jooq.Tables.*
import io.github.ermadmi78.kobby.cinema.server.security.hasAnyRole
import org.jooq.DSLContext
import org.jooq.impl.DSL.trueCondition
import org.springframework.stereotype.Component
/**
* Created on 03.03.2021
*
* @author <NAME> (<EMAIL>)
*/
@Component
class ActorResolver(private val dslContext: DSLContext) : CinemaActorResolver {
companion object {
private val ALL_FIELDS = setOf("id", "firstName", "lastName", "birthday", "gender")
}
override suspend fun fields(
actor: ActorDto,
keys: List<String>?
): Map<String, Any?> {
val result = mutableMapOf<String, Any?>()
(keys?.toSet() ?: ALL_FIELDS).forEach {
when (it) {
"id" -> result[it] = actor.id
"firstName" -> result[it] = actor.firstName
"lastName" -> result[it] = actor.lastName
"birthday" -> result[it] = actor.birthday
"gender" -> result[it] = actor.gender
}
}
return result
}
override suspend fun country(actor: ActorDto): CountryDto = hasAnyRole("USER", "ADMIN") {
dslContext.selectFrom(COUNTRY)
.where(COUNTRY.ID.eq(actor.countryId))
.fetchAny { it.toDto() }!!
}
override suspend fun films(
actor: ActorDto,
title: String?,
genre: Genre?,
limit: Int,
offset: Int
): List<FilmDto> = hasAnyRole("USER", "ADMIN") {
dslContext.select(FILM.asterisk())
.from(FILM)
.join(FILM_ACTOR)
.onKey()
.where(FILM_ACTOR.ACTOR_ID.eq(actor.id))
.and(trueCondition().andFilms(title, genre))
.limit(offset.prepare(), limit.prepare())
.fetch {
it.into(FILM).toDto()
}
}
}
| 0
|
Kotlin
|
1
| 5
|
5fd5808e9d2b5c0912d0196116ab622ff580d35c
| 2,297
|
kobby-gradle-example
|
Apache License 2.0
|
sources/js/values/AnimationPlayState.kt
|
cybernetics
| 323,978,300
| true
|
{"Kotlin": 245088}
|
@file:Suppress("NOTHING_TO_INLINE")
package io.fluidsonic.css
// FIXME support multiple values
public external interface AnimationPlayState : CssValue {
@Suppress("INLINE_EXTERNAL_DECLARATION", "NESTED_CLASS_IN_EXTERNAL_INTERFACE", "WRONG_BODY_OF_EXTERNAL_DECLARATION")
public companion object {
@CssDsl
public inline val paused: AnimationPlayState
get() = unsafe("paused")
@CssDsl
public inline val running: AnimationPlayState
get() = unsafe("running")
public inline fun unsafe(value: String): AnimationPlayState =
CssValue.unsafe(value)
public inline fun variable(name: String): Variable =
CssVariable.unsafe(name)
}
public interface Variable : AnimationPlayState, CssVariable<AnimationPlayState>
}
@CssDsl
public inline fun CssDeclarationBlockBuilder.animationPlayState(value: AnimationPlayState) {
property(animationPlayState, value)
}
@Suppress("unused")
public inline val CssProperties.animationPlayState: CssProperty<AnimationPlayState>
get() = CssProperty.unsafe("animation-play-state")
| 0
| null |
0
| 0
|
65b9463c57be79f8fcb5e5083df6907340388826
| 1,042
|
fluid-css
|
Apache License 2.0
|
app/src/main/java/com/b_lam/resplash/provider/ResplashMuzeiArtProvider.kt
|
b-lam
| 69,628,893
| false
| null |
package com.b_lam.resplash.provider
import com.b_lam.resplash.data.download.DownloadService
import com.b_lam.resplash.util.safeApiCall
import com.b_lam.resplash.util.warn
import com.b_lam.resplash.worker.MuzeiWorker
import com.google.android.apps.muzei.api.provider.Artwork
import com.google.android.apps.muzei.api.provider.MuzeiArtProvider
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import org.koin.android.ext.android.get
import org.koin.android.ext.android.inject
import java.io.InputStream
class ResplashMuzeiArtProvider : MuzeiArtProvider() {
override fun onLoadRequested(initial: Boolean) {
val context = context ?: return
MuzeiWorker.enqueueWork(context, get())
}
override fun openFile(artwork: Artwork): InputStream {
return super.openFile(artwork).also {
artwork.token?.run {
try {
val downloadService: DownloadService by inject()
CoroutineScope(Job() + Dispatchers.IO).launch {
safeApiCall(Dispatchers.IO) { downloadService.trackDownload(this@run) }
}
} catch (e: Exception) {
warn("Error reporting download to Unsplash", e)
}
}
}
}
}
| 33
|
Kotlin
|
105
| 569
|
4b13d31134d1c31bd331e92ffe8d410984529212
| 1,371
|
Resplash
|
The Unlicense
|
Code/CurrencyConversionApp/app-core/models/src/main/kotlin/com/istudio/models/custom/CurrencyValidationInput.kt
|
devrath
| 708,793,882
| false
|
{"Kotlin": 421506}
|
package com.istudio.models.custom
import com.istudio.models.local.CurrencyAndRates
import com.istudio.models.local.RatesEntity
data class CurrencyValidationInput(
val userEnteredCurrencyValueInput : String,
val userEnteredCurrencyTypeInput : String,
val userSelectedCurrencyConversionTypeInput : List<CurrencyAndRates>
)
| 0
|
Kotlin
|
0
| 0
|
43e1b2d0f4b275f1aa3f74f2be536d9bc2575b3e
| 335
|
DroidCurrencyConverter
|
Apache License 2.0
|
core/core/src/commonMain/kotlin/zakadabar/core/comm/CommConfig.kt
|
spxbhuhb
| 290,390,793
| false
|
{"Kotlin": 2390839, "HTML": 2835, "JavaScript": 1021, "Dockerfile": 269, "Shell": 253}
|
/*
* Copyright © 2020-2021, Simplexion, Hungary and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package zakadabar.core.comm
import kotlinx.serialization.Serializable
import zakadabar.core.business.BusinessLogicCommon
import zakadabar.core.business.EntityBusinessLogicCommon
import zakadabar.core.data.BaseBo
import zakadabar.core.data.EntityBo
import zakadabar.core.module.modules
import zakadabar.core.util.Lock
import zakadabar.core.util.use
/**
* Specifies the URL or part of the URL for communication.
*
* @property baseUrl Base url of the communication, keeps the `/api/${namespace}/${operation}` part intact.
* @property namespace Use this namespace instead of the one from the BO.
* @property fullUrl Use this URL without adding/removing anything. For queries the query is appended.
* @property local Locate and use a local Business Logic for the call, do not go over HTTP.
*
*/
@Serializable
data class CommConfig(
val baseUrl: String? = null,
val namespace: String? = null,
val fullUrl: String? = null,
val local: Boolean = false
) {
companion object {
/**
* Coroutine scope for comm coroutines.
*/
var commScope = makeCommScope()
/**
* This lock is used when comm config instances are replaced. The reason
* for the lock is to make sure that multithreaded platforms perform the
* necessary synchronization.
*/
var configLock = Lock()
/**
* A global communication configuration.
*
* Access to this variable is thread safe, [configLock] is used to
* synchronize get and set.
*/
var global = CommConfig()
get() = configLock.use { field }
set(value) = configLock.use { field = value }
/**
* Checks if a call should be shortcut locally, calling the BL directly.
* Javascript does not support local calls at the moment, only JVM does.
*/
fun isLocal(call: CommConfig?, bo: CommConfig?): Boolean {
if (call != null) return call.local
if (bo != null) return bo.local
return global.local
}
/**
* Finds an entity BL for the given namespace.
*
* @throws NoSuchElementException when there is no module for the given namespace
*/
fun <T : EntityBo<T>> localEntityBl(namespace: String, call: CommConfig?, bo: CommConfig?): EntityBusinessLogicCommon<T>? {
if (! isLocal(call, bo)) return null
val callNamespace = call?.namespace ?: bo?.namespace ?: namespace
return modules.first { it.namespace == callNamespace }
}
/**
* Finds a common BL for the given namespace. Common BL covers action and query, for entities
* use [localEntityBl] instead.
*
* @throws NoSuchElementException when there is no module for the given namespace
*/
fun localCommonBl(namespace: String, call: CommConfig?, bo: CommConfig?): BusinessLogicCommon<BaseBo>? {
if (! isLocal(call, bo)) return null
val callNamespace = call?.namespace ?: bo?.namespace ?: namespace
return modules.first { it.namespace == callNamespace }
}
/**
* Merges [CommConfig]s with request specific parts to create the URL for a comm call.
*/
fun merge(function: String, namespace: String, call: CommConfig?, bo: CommConfig?): String {
val callBase = call?.baseUrl ?: bo?.baseUrl ?: global.baseUrl ?: ""
val callNamespace = call?.namespace ?: bo?.namespace ?: namespace
return "${callBase}/api/${callNamespace}$function"
}
}
}
| 12
|
Kotlin
|
3
| 24
|
00859b62570bf455addc9723015ba2c48b77028b
| 3,809
|
zakadabar-stack
|
Apache License 2.0
|
app/src/main/java/com/jrektor/skripsi/product/items/checkout/PayOptionActivity.kt
|
ichwansh03
| 600,659,408
| false
| null |
package com.jrektor.skripsi.product.items.checkout
import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import com.android.volley.Response
import com.android.volley.toolbox.JsonObjectRequest
import com.android.volley.toolbox.StringRequest
import com.android.volley.toolbox.Volley
import com.jrektor.skripsi.GlobalData
import com.jrektor.skripsi.MainActivity
import com.jrektor.skripsi.R
import com.jrektor.skripsi.verification.LoginActivity
import kotlinx.android.synthetic.main.activity_pay_option.*
import com.midtrans.sdk.corekit.core.MidtransSDK
import com.midtrans.sdk.corekit.core.UIKitCustomSetting
import com.midtrans.sdk.corekit.models.ItemDetails
import com.midtrans.sdk.uikit.api.model.SnapTransactionDetail
import com.midtrans.sdk.uikit.internal.util.UiKitConstants.STATUS_CANCELED
import com.midtrans.sdk.uikit.internal.util.UiKitConstants.STATUS_FAILED
import com.midtrans.sdk.uikit.internal.util.UiKitConstants.STATUS_INVALID
import com.midtrans.sdk.uikit.internal.util.UiKitConstants.STATUS_PENDING
import com.midtrans.sdk.uikit.internal.util.UiKitConstants.STATUS_SUCCESS
import com.midtrans.sdk.uikit.api.model.CustomColorTheme
import com.midtrans.sdk.uikit.external.UiKitApi
import com.midtrans.sdk.uikit.internal.util.UiKitConstants
import java.text.NumberFormat
import java.util.*
import kotlin.collections.HashMap
class PayOptionActivity : AppCompatActivity() {
private var status: String = ""
private val launcher =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
if (result?.resultCode == RESULT_OK) {
result.data?.let {
val transactionResult = it.getParcelableExtra<com.midtrans.sdk.uikit.api.model.TransactionResult>(UiKitConstants.KEY_TRANSACTION_RESULT)
deleteItem()
getPaymentStatus(transactionResult?.transactionId)
Toast.makeText(this, "Transaksi Berhasil ${transactionResult?.transactionId}", Toast.LENGTH_LONG).show()
insertPaymentStatus(transactionResult?.transactionId)
}
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
if (resultCode == RESULT_OK) {
val transactionResult = data?.getParcelableExtra<com.midtrans.sdk.uikit.api.model.TransactionResult>(UiKitConstants.KEY_TRANSACTION_RESULT)
if (transactionResult != null) {
when (transactionResult.status) {
STATUS_SUCCESS -> {
Toast.makeText(this, "Transaction Finished. ID: " + transactionResult.transactionId, Toast.LENGTH_LONG).show()
}
STATUS_PENDING -> {
Toast.makeText(this, "Transaction Pending. ID: " + transactionResult.transactionId, Toast.LENGTH_LONG).show()
}
STATUS_FAILED -> {
Toast.makeText(this, "Transaction Failed. ID: " + transactionResult.transactionId, Toast.LENGTH_LONG).show()
}
STATUS_CANCELED -> {
Toast.makeText(this, "Transaction Cancelled", Toast.LENGTH_LONG).show()
}
STATUS_INVALID -> {
Toast.makeText(this, "Transaction Invalid. ID: " + transactionResult.transactionId, Toast.LENGTH_LONG).show()
}
else -> {
Toast.makeText(this, "Transaction ID: " + transactionResult.transactionId + ". Message: " + transactionResult.status, Toast.LENGTH_LONG).show()
}
}
} else {
Toast.makeText(this, "Transaction Invalid", Toast.LENGTH_LONG).show()
}
}
super.onActivityResult(requestCode, resultCode, data)
}
private fun deleteItem() {
val queue = Volley.newRequestQueue(this)
val stringRequest =
object : StringRequest(Method.DELETE, GlobalData.BASE_URL+"item/deleteitemall.php", Response.Listener { _ ->
startActivity(Intent(this, MainActivity::class.java))
}, { _ ->
Toast.makeText(this, "Terjadi kesalahan saat menghapus produk", Toast.LENGTH_SHORT)
.show()
}) {}
queue.add(stringRequest)
}
private var itemDetails = listOf(ItemDetails("id-11", GlobalData.totalBayar.toDouble(), 1, "id-11"))
private fun initTransactionDetails() : SnapTransactionDetail {
val orderID = UUID.randomUUID().toString()
return SnapTransactionDetail(
orderId = orderID,
grossAmount = GlobalData.totalBayar.toDouble()
)
}
@SuppressLint("SetTextI18n")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_pay_option)
val customerDetails = com.midtrans.sdk.uikit.api.model.CustomerDetails(
"pembayaran",
"${GlobalData.namaPelanggan} dari ${LoginActivity.OutletData.namaOutlet}",
" No.HP: ${GlobalData.nohpPelanggan}",
"ichwansholihin03@gmail.com"
)
val total = GlobalData.totalBayar
val formatRp = NumberFormat.getCurrencyInstance(Locale("id","ID"))
formatRp.minimumFractionDigits = 0
val totalFormatted = formatRp.format(total)
total_bayar.text = totalFormatted
buildUiKit()
tunai.setOnClickListener {
val intent = Intent(this, CashPaymentActivity::class.java)
intent.putExtra("total",GlobalData.totalBayar.toString())
startActivity(intent)
}
transfer.setOnClickListener {
UiKitApi.getDefaultInstance().startPaymentUiFlow(
this@PayOptionActivity,
launcher,
initTransactionDetails(),
customerDetails,
itemDetails,
)
}
}
private fun insertPaymentStatus(transactionId: String?) {
val url = GlobalData.BASE_URL + "order/midtrans_status.php"
val request = Volley.newRequestQueue(applicationContext)
val stringRequest = object : StringRequest(
Method.GET,
"$url?order_id=$transactionId&name=${GlobalData.namaPelanggan}&phone=${GlobalData.nohpPelanggan}&payment_status=$status",
{ response ->
if (response == "1") {
//success
}
},
{ error ->
Toast.makeText(this, "Error inserting payment status: ${error.toString()}", Toast.LENGTH_LONG).show()
Log.d("Error insert payment status", error.toString())
}) {}
request.add(stringRequest)
}
private fun getPaymentStatus(transactionId: String?) {
val url = "https://api.sandbox.midtrans.com/v2/$transactionId/status"
val headers = HashMap<String, String>()
headers["Accept"] = "application/json"
headers["Content-Type"] = "application/json"
headers["Authorization"] = "Basic U0ItTWlkLXNlcnZlci1BVHhkbmowM1Q0bGRmQ3c1TGI1bkVUMkM6"
val request = object : JsonObjectRequest(
Method.GET, url, null,
{ response ->
val transactionStatus = response.getString("transaction_status")
status = transactionStatus
},
{ error ->
Log.d("Error to get payment status", error.toString())
}) {
override fun getHeaders(): MutableMap<String, String> {
return headers
}
}
// Create a request queue
val requestQueue = Volley.newRequestQueue(this)
requestQueue.add(request)
}
private fun buildUiKit() {
UiKitApi.Builder()
.withContext(this.applicationContext)
.withMerchantUrl("http://192.168.43.8/charge/midtrans.php/")
.withMerchantClientKey("SB-Mid-client-UZ9Yl7aefQos1858")
.enableLog(true)
.withColorTheme(CustomColorTheme("#FFE51255", "#B61548", "#FFE51255"))
.build()
uiKitCustomSetting()
}
private fun uiKitCustomSetting() {
val uIKitCustomSetting = UIKitCustomSetting()
uIKitCustomSetting.setSaveCardChecked(true)
MidtransSDK.getInstance().setUiKitCustomSetting(uIKitCustomSetting)
}
}
| 0
|
Kotlin
|
0
| 3
|
47d3654008b154de124fc80d0801f4c962b928c9
| 8,708
|
android-pos
|
Apache License 2.0
|
src/main/kotlin/com/beepsoft/hasuraconf/HasuraConfiguratorException.kt
|
dsd-sztaki-hu
| 228,703,596
| false
|
{"Kotlin": 453969, "Java": 10449, "PLpgSQL": 1024}
|
package com.beepsoft.hasuraconf
import kotlin.Exception
class HasuraConfiguratorException(message: String, cause: Throwable? = null) : Exception(message, cause) {
}
| 6
|
Kotlin
|
1
| 17
|
ce2ef250beeec46bcfa615b243e9c356cc13429f
| 166
|
hasuraconf
|
MIT License
|
vk-api-generated/src/main/kotlin/name/anton3/vkapi/generated/photos/methods/PhotosSaveWallPhoto.kt
|
Anton3
| 159,801,334
| true
|
{"Kotlin": 1382186}
|
@file:Suppress("unused", "MemberVisibilityCanBePrivate", "SpellCheckingInspection")
package name.anton3.vkapi.generated.photos.methods
import com.fasterxml.jackson.module.kotlin.jacksonTypeRef
import name.anton3.vkapi.generated.photos.objects.Photo
import name.anton3.vkapi.method.UserMethod
import name.anton3.vkapi.method.VkMethod
/**
* [https://vk.com/dev/photos.saveWallPhoto]
*
* Saves a photo to a user's or community's wall after being uploaded.
*
* @property userId ID of the user on whose wall the photo will be saved.
* @property groupId ID of community on whose wall the photo will be saved.
* @property photo Parameter returned when the the photo is [vk.com/dev/upload_files|uploaded to the server].
* @property server No description
* @property hash No description
* @property latitude Geographical latitude, in degrees (from '-90' to '90').
* @property longitude Geographical longitude, in degrees (from '-180' to '180').
* @property caption Text describing the photo. 2048 digits max.
*/
data class PhotosSaveWallPhoto(
var userId: Long? = null,
var groupId: Long? = null,
var photo: String,
var server: Long? = null,
var hash: String? = null,
var latitude: Double? = null,
var longitude: Double? = null,
var caption: String? = null
) : VkMethod<List<Photo>, UserMethod>("photos.saveWallPhoto", jacksonTypeRef())
| 2
|
Kotlin
|
0
| 8
|
773c89751c4382a42f556b6d3c247f83aabec625
| 1,376
|
kotlin-vk-api
|
MIT License
|
android/app/src/main/java/cloud/multipos/pos/views/PosControlSwipeLayout.kt
|
multipos-app
| 773,180,579
| false
|
{"Kotlin": 548453, "Java": 306036}
|
/**
* Copyright (C) 2023 multiPOS, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cloud.multipos.pos.views
import cloud.multipos.pos.*
import cloud.multipos.pos.util.*
import android.content.Context
import android.util.AttributeSet
import android.view.View
import android.view.Gravity
open class PosControlSwipeLayout (context: Context, attrs: AttributeSet): PosSwipeLayout (context, attrs) {
val listeners = mutableListOf <SwipeListener> ()
val dialogs = mutableListOf <DialogView> ()
val MAX_DIALOGS = 10
init {
Pos.app.controlLayout = this
}
fun push (dialog: DialogView) {
dialogs.add (0, dialog)
swipeLeft ()
if (dialog is SwipeListener) {
listeners.add (dialog as SwipeListener)
}
if (dialogs.size == MAX_DIALOGS) {
dialogs.removeAt (MAX_DIALOGS - 1)
}
}
fun pop (dialog: DialogView) {
swipeRight ()
if (!dialog.sticky ()) {
dialogs.remove (dialog)
}
if (listeners.contains (dialog)) {
listeners.remove (dialog)
}
}
override fun swipeLeft () {
if (dialogs.size > 0) {
swiper = this
dir = Gravity.END
edge = Gravity.START
swipe (dialogs [0])
notifyListeners (SwipeDir.Left)
}
else {
Logger.w ("wha... no dialgos...")
}
}
override fun swipeRight () {
dir = Gravity.START
edge = Gravity.END
swipe (Pos.app.controlHomeLayout)
notifyListeners (SwipeDir.Right)
if ((dialogs.size > 0) && !dialogs [0].sticky ()) {
dialogs.removeAt (0);
}
}
override fun swipeUp () {
notifyListeners (SwipeDir.Up)
}
override fun swipeDown () {
notifyListeners (SwipeDir.Down)
}
fun notifyListeners (dir: SwipeDir) {
for (listener in listeners) {
listener.onSwipe (dir)
}
}
}
| 0
|
Kotlin
|
1
| 7
|
119bb0c86a5f9589e0219249b02f0f56d43120f7
| 2,360
|
pos
|
Apache License 2.0
|
src/main/kotlin/ninja/sakib/pultusorm/core/PultusORMCondition.kt
|
JensAstrup
| 76,914,436
| true
|
{"Kotlin": 46086}
|
package ninja.sakib.pultusorm.core
/**
* := Coded with love by <NAME> on 10/3/16.
* := <EMAIL>
* := www.sakib.ninja
* := Coffee : Dream : Code
*/
/**
* PultusORMCondition
* Class used to provide condition on queries
*/
class PultusORMCondition private constructor(builder: Builder) {
private var rawQuery: String = ""
init {
rawQuery = builder.rawQuery()
}
/**
* Method to get query as String
* @return String
*/
fun rawQuery(): String {
return rawQuery
}
/**
* Builder class used to
* create condition query
*/
class Builder {
private var conditionQuery: StringBuilder = StringBuilder() // Condition Queries
private var sortQuery: StringBuilder = StringBuilder() // Sort Queries
private var groupQuery: StringBuilder = StringBuilder() // Group Queries
/**
* Method to add equal condition
* @param key field name
* @param value field value
* @return Builder with contacted current condition
*/
fun eq(key: String, value: Any): Builder {
addSeparator()
if (value is String)
conditionQuery.append("$key = '$value'")
else conditionQuery.append("$key = $value")
return this
}
/**
* Method to add not equal condition
* @param key field name
* @param value field value
* @return Builder with contacted current condition
*/
fun notEq(key: String, value: Any): Builder {
addSeparator()
if (value is String)
conditionQuery.append("$key != '$value'")
else conditionQuery.append("$key != $value")
return this
}
/**
* Method to add between condition
* @param begin start value
* @param end end value
* @return Builder with contacted current condition
*/
fun between(begin: Int, end: Int): Builder {
addSeparator()
conditionQuery.append("BETWEEN $begin AND $end")
return this
}
/**
* Method to add in condition
* @param begin start value
* @param end end value
* @return Builder with contacted current condition
*/
fun In(begin: Int, end: Int): Builder {
addSeparator()
conditionQuery.append("IN($begin,$end)")
return this
}
/**
* Method to add between condition
* @param begin start value
* @param end end value
* @return Builder with contacted current condition
*/
fun notIn(begin: Int, end: Int): Builder {
addSeparator()
conditionQuery.append("NOT IN($begin,$end)")
return this
}
/**
* Method to add and clause
* @return Builder with contacted current condition
*/
fun and(): Builder {
addSeparator()
conditionQuery.append("AND")
return this
}
/**
* Method to add or clause
* @return Builder with contacted current condition
*/
fun or(): Builder {
addSeparator()
conditionQuery.append("OR")
return this
}
/**
* Method to concat condition with first bracket using OR
* @param condition
* @return Builder with contacted current condition
*/
fun or(condition: Builder): Builder {
addSeparator()
conditionQuery.append("OR (${condition.conditionQuery.toString()})")
return this
}
/**
* Method to concat condition with first bracket using AND
* @param condition
* @return Builder with contacted current condition
*/
fun and(condition: Builder): Builder {
addSeparator()
conditionQuery.append("AND (${condition.conditionQuery.toString()})")
return this
}
/**
* Method to add greater condition
* @param key field name
* @param value field value
* @return Builder with contacted current condition
*/
fun greater(key: String, value: Int): Builder {
addSeparator()
conditionQuery.append("$key > $value")
return this
}
/**
* Method to add less condition
* @param key field name
* @param value field value
* @return Builder with contacted current condition
*/
fun less(key: String, value: Int): Builder {
addSeparator()
conditionQuery.append("$key < $value")
return this
}
/**
* Method to add greater or equal condition
* @param key field name
* @param value field value
* @return Builder with contacted current condition
*/
fun greaterEq(key: String, value: Int): Builder {
addSeparator()
conditionQuery.append("$key >= $value")
return this
}
/**
* Method to add less or equal condition
* @param key field name
* @param value field value
* @return Builder with contacted current condition
*/
fun lessEq(key: String, value: Int): Builder {
addSeparator()
conditionQuery.append("$key <= $value")
return this
}
/**
* Method to add sort condition
* @param fieldName field name
* @param order ordering type
* @return Builder with contacted current condition
*/
fun sort(fieldName: String, order: PultusORMQuery.Sort): Builder {
if (sortQuery.isNotEmpty())
sortQuery.append(",")
when (order) {
PultusORMQuery.Sort.ASCENDING -> {
addSeparator()
sortQuery.append("$fieldName ASC")
}
PultusORMQuery.Sort.DESCENDING -> {
addSeparator()
sortQuery.append("$fieldName DESC")
}
}
return this
}
/**
* Method to add group by condition
* @param fieldName field name
* @return Builder with contacted current condition
*/
fun group(fieldName: String): Builder {
if (groupQuery.isNotEmpty())
groupQuery.append(",")
groupQuery.append(fieldName)
return this
}
/**
* Method to add search condition
* @param fieldName field name
* @param value field value
* @return Builder with contacted current condition
*/
fun startsWith(fieldName: String, value: Any): Builder {
addSeparator()
conditionQuery.append("$fieldName LIKE '$value%'")
return this
}
/**
* Method to add search condition
* @param fieldName field name
* @param value field value
* @return Builder with contacted current condition
*/
fun endsWith(fieldName: String, value: Any): Builder {
addSeparator()
conditionQuery.append("$fieldName LIKE '%$value'")
return this
}
/**
* Method to add search condition
* @param fieldName field name
* @param value field value
* @return Builder with contacted current condition
*/
fun contains(fieldName: String, value: Any): Builder {
addSeparator()
conditionQuery.append("$fieldName LIKE '%$value%'")
return this
}
/**
* Method to create final query as String
* @return String
*/
fun rawQuery(): String {
val query: StringBuilder = StringBuilder()
if (conditionQuery.isNotEmpty())
query.append("WHERE ${conditionQuery.toString()}")
if (query.isNotEmpty())
query.append(" ")
if (groupQuery.isNotEmpty())
query.append("GROUP BY ${groupQuery.toString()}")
if (query.isNotEmpty())
query.append(" ")
if (sortQuery.isNotEmpty())
query.append("ORDER BY ${sortQuery.toString()}")
return query.toString()
}
/**
* Method build condition and
* return it
*/
fun build(): PultusORMCondition {
return PultusORMCondition(this)
}
private fun addSeparator() {
if (conditionQuery.isNotEmpty())
conditionQuery.append(" ")
}
}
}
| 0
|
Kotlin
|
1
| 2
|
bb31e00a02b8ec5a77d30f9db36d080a8afea333
| 8,922
|
PultusORM
|
MIT License
|
src/test/kotlin/com/github/furubarug/intellij/external/binary/viewer/utils/ExtensionsSplitterTest.kt
|
furubarug
| 463,926,581
| false
| null |
package com.github.furubarug.intellij.external.binary.viewer.utils
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder
/**
* test class for [ExtensionsSplitter]
*/
class ExtensionsSplitterTest : StringSpec() {
init {
"split: valid" {
val result = ExtensionsSplitter.split(";a;bc;;def")
result shouldContainExactlyInAnyOrder listOf("a", "bc", "def")
}
"split: invalid" {
shouldThrow<RuntimeException> {
ExtensionsSplitter.split("")
}
shouldThrow<RuntimeException> {
ExtensionsSplitter.split(";;;")
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ba3c26087326618c329ab6905064afd503037d37
| 766
|
intellij-external-binary-viewer
|
MIT License
|
library/src/commonMain/kotlin/datingcomponents/stack/StackBackgroundCard.kt
|
numq
| 619,221,709
| false
|
{"Kotlin": 12830}
|
package datingcomponents.stack
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.Card
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
import datingcomponents.swipeable.SwipeableState
@Composable
fun StackBackgroundCard(
modifier: Modifier = Modifier,
state: SwipeableState,
content: @Composable () -> Unit,
) = with(state) {
Card(modifier.graphicsLayer {
scaleX = animatedScale.value
scaleY = animatedScale.value
}) {
Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
content()
}
}
}
| 0
|
Kotlin
|
1
| 2
|
3455a718d90e9a740ef7512f6543d3e3a0df7994
| 771
|
dating-components
|
MIT License
|
core/ui-kmp/src/commonMain/kotlin/org/michaelbel/movies/ui/compose/page/PageLoading.kt
|
michaelbel
| 115,437,864
| false
|
{"Kotlin": 680733, "Java": 10013, "Swift": 342, "Shell": 235}
|
@file:Suppress("EXPECT_AND_ACTUAL_IN_THE_SAME_MODULE")
package org.michaelbel.movies.ui.compose.page
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import org.michaelbel.movies.common.appearance.FeedView
@Composable
expect fun PageLoading(
feedView: FeedView,
modifier: Modifier = Modifier,
paddingValues: PaddingValues = PaddingValues()
)
| 5
|
Kotlin
|
31
| 186
|
e7b74544e4951a2fd49cc02d7858fb8df89c0eae
| 442
|
movies
|
Apache License 2.0
|
todomvrx/src/main/java/com/airbnb/mvrx/todomvrx/di/ViewModelKey.kt
|
luozejiaqun
| 157,853,404
| true
|
{"Kotlin": 141016, "Java": 140}
|
package com.airbnb.mvrx.todomvrx.di
import android.arch.lifecycle.ViewModel
import dagger.MapKey
import kotlin.reflect.KClass
@Target(AnnotationTarget.FUNCTION)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)
| 0
|
Kotlin
|
0
| 2
|
68957133773ca8d32bfa5ff6438b7862cacf28f1
| 235
|
DiMvRx
|
Apache License 2.0
|
app/src/main/java/com/habitsapp/home/data/repository/HomeRepositoryImpl.kt
|
ByteSurferX
| 839,968,824
| false
|
{"Kotlin": 116886}
|
package com.habitsapp.home.data.repository
import androidx.work.BackoffPolicy
import androidx.work.Constraints
import androidx.work.ExistingWorkPolicy
import androidx.work.NetworkType
import androidx.work.OneTimeWorkRequestBuilder
import androidx.work.WorkManager
import com.habitsapp.home.data.extension.toStartOfDateTimestamp
import com.habitsapp.home.data.local.HomeDao
import com.habitsapp.home.data.maper.toDomain
import com.habitsapp.home.data.maper.toDto
import com.habitsapp.home.data.maper.toEntity
import com.habitsapp.home.data.maper.toSyncEntity
import com.habitsapp.home.data.remote.HomeApi
import com.habitsapp.home.data.remote.util.resultOf
import com.habitsapp.home.data.sync.HabitSyncWorker
import com.habitsapp.home.domain.alarm.AlarmHandler
import com.habitsapp.home.domain.models.Habit
import com.habitsapp.home.domain.repository.HomeRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onStart
import java.time.Duration
import java.time.ZonedDateTime
class HomeRepositoryImpl(
private val dao: HomeDao,
private val api: HomeApi,
private val alarmHandler: AlarmHandler,
private val workManager: WorkManager
) : HomeRepository {
override fun getAllHabitsForSelectedDate(date: ZonedDateTime): Flow<List<Habit>> {
val localFlow = dao.getAllHabitsForSelectedDate(date.toStartOfDateTimestamp())
.map { it.map { it.toDomain() } }
val apiFlow = getHabitsFromApi()
return localFlow.combine(apiFlow) { db, _ ->
db
}
}
private fun getHabitsFromApi(): Flow<List<Habit>> {
return flow {
resultOf {
val habits = api.getAllHabits().toDomain()
insertHabits(habits)
}
emit(emptyList<Habit>())
}.onStart {
emit(emptyList())
}
}
override suspend fun insertHabit(habit: Habit) {
handleAlarm(habit)
dao.insertHabit(habit.toEntity())
resultOf {
api.insertHabit(habit.toDto())
}.onFailure {
dao.insertHabitSync(habit.toSyncEntity())
}
}
private suspend fun insertHabits(habits: List<Habit>) {
habits.forEach {
handleAlarm(it)
dao.insertHabit(it.toEntity())
}
}
private suspend fun handleAlarm(habit: Habit) {
try {
val previous = dao.getHabitById(habit.id)
alarmHandler.cancel(previous.toDomain())
} catch (e: Exception) { /* Habit doesn't exist */
}
alarmHandler.setRecurringAlarm(habit)
}
override suspend fun getHabitById(id: String): Habit {
return dao.getHabitById(id).toDomain()
}
override suspend fun syncHabit() {
val worker = OneTimeWorkRequestBuilder<HabitSyncWorker>().setConstraints(
Constraints.Builder().setRequiredNetworkType(
NetworkType.CONNECTED
).build()
).setBackoffCriteria(BackoffPolicy.EXPONENTIAL, Duration.ofMinutes(5)).build()
workManager.beginUniqueWork("sync_habit_id", ExistingWorkPolicy.REPLACE, worker).enqueue()
}
}
| 0
|
Kotlin
|
0
| 0
|
54b317dd0000ea9fe7eb8cd09c4ec19d1c4f7b7f
| 3,254
|
habits-app
|
MIT License
|
app/src/main/java/com/gitzblitz/locationviewerkotlin/di/AppComponent.kt
|
gitzblitz
| 191,737,820
| false
| null |
package com.gitzblitz.locationviewerkotlin.di
import com.gitzblitz.locationviewerkotlin.LocationApplication
import dagger.BindsInstance
import dagger.Component
import dagger.android.AndroidInjectionModule
import javax.inject.Singleton
@Singleton
@Component(modules = [(AndroidInjectionModule::class), (AppModule::class), (DataModule::class), (ActivityBuilder::class), (ViewModelModule::class)])
interface AppComponent {
@Component.Builder
interface Builder {
@BindsInstance
fun application(application: LocationApplication): Builder
fun appModule(appModule: AppModule): Builder
fun dataModule(dataModule: DataModule): Builder
fun build(): AppComponent
}
fun inject(locationApplication: LocationApplication)
}
| 0
|
Kotlin
|
0
| 4
|
5652cd5e05888ef9c18f01c6387c97964b4c34ad
| 770
|
LocationViewerKotlin
|
Apache License 2.0
|
app/src/main/java/com/akinci/moneybox/feature/login/data/input/LoginServiceRequest.kt
|
AttilaAKINCI
| 333,097,438
| false
| null |
package com.akinci.moneybox.feature.login.data.input
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class LoginServiceRequest(
val Email: String,
val Password: String,
val Idfa: String
)
| 0
|
Kotlin
|
1
| 2
|
b1f306bc45059134157326d90f872bb95f624e87
| 229
|
MoneyBox
|
Apache License 2.0
|
domain/src/test/java/studio/lunabee/onesafe/domain/usecase/SearchIndexManagerTest.kt
|
LunabeeStudio
| 624,544,471
| false
| null |
/*
* Copyright (c) 2023 Lunabee Studio
*
* 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.
*
* Created by Lunabee Studio / Date - 4/7/2023 - for the oneSafe6 SDK.
* Last modified 4/7/23, 12:24 AM
*/
package studio.lunabee.onesafe.domain.usecase
import com.lunabee.lbcore.model.LBFlowResult
import com.lunabee.lbextensions.lazyFast
import io.mockk.MockKAnnotations
import io.mockk.coEvery
import io.mockk.every
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.test.TestResult
import kotlinx.coroutines.test.advanceTimeBy
import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import studio.lunabee.onesafe.domain.manager.SearchIndexManager
import studio.lunabee.onesafe.domain.model.search.ClearIndexWordEntry
import studio.lunabee.onesafe.domain.model.search.IndexWordEntry
import studio.lunabee.onesafe.domain.repository.MainCryptoRepository
import studio.lunabee.onesafe.domain.repository.IndexWordEntryRepository
import studio.lunabee.onesafe.test.assertSuccess
import studio.lunabee.onesafe.test.testUUIDs
import kotlin.test.assertContentEquals
import kotlin.test.assertIs
import kotlin.test.assertNotNull
import kotlin.test.assertNull
@OptIn(ExperimentalCoroutinesApi::class)
class SearchIndexManagerTest {
private val indexManager: SearchIndexManager by lazyFast {
SearchIndexManager(cryptoRepository, indexWordEntryRepository)
}
@MockK lateinit var cryptoRepository: MainCryptoRepository
@MockK lateinit var indexWordEntryRepository: IndexWordEntryRepository
private val indexList: List<IndexWordEntry> = listOf(IndexWordEntry(byteArrayOf(), testUUIDs[0], null))
private val clearIndexWordEntries = listOf(ClearIndexWordEntry("word", testUUIDs[0], null))
@BeforeEach
fun setup() {
MockKAnnotations.init(this)
every { indexWordEntryRepository.getAll() } returns flowOf(indexList)
coEvery { cryptoRepository.decryptIndexWord(indexList) } returns clearIndexWordEntries
}
@Test
fun initStoreIndex_test(): TestResult = runTest {
assertIs<LBFlowResult.Loading<List<ClearIndexWordEntry>>>(indexManager.decryptedIndex.value)
assertNull(indexManager.decryptedIndex.value.data)
indexManager.initStoreIndex(this)
runCurrent()
assertSuccess(indexManager.decryptedIndex.value)
assertContentEquals(clearIndexWordEntries, indexManager.decryptedIndex.value.data)
}
@Test
fun clear_index_after_delay_test(): TestResult = runTest {
indexManager.initStoreIndex(this)
advanceTimeBy(SearchIndexManager.DELAY_CLEAR_DECRYPTED_INDEX)
assertSuccess(indexManager.decryptedIndex.value)
assertNotNull(indexManager.decryptedIndex.value.data)
runCurrent()
assertIs<LBFlowResult.Loading<List<ClearIndexWordEntry>>>(indexManager.decryptedIndex.value)
assertNull(indexManager.decryptedIndex.value.data)
}
@Test
fun collect_new_item_when_index_is_decrypted_test(): TestResult = runTest {
val expectedIndex = listOf(
ClearIndexWordEntry("word", testUUIDs[0], null),
ClearIndexWordEntry("word2", testUUIDs[1], null),
)
val indexList2 = listOf(
IndexWordEntry(byteArrayOf(), testUUIDs[0], null),
IndexWordEntry(byteArrayOf(), testUUIDs[1], null),
)
val indexFlow = MutableStateFlow(indexList)
every { indexWordEntryRepository.getAll() } returns indexFlow
coEvery { cryptoRepository.decryptIndexWord(indexList2) } returns expectedIndex
indexManager.initStoreIndex(this)
runCurrent()
assertContentEquals(clearIndexWordEntries, indexManager.decryptedIndex.value.data!!.toList())
indexFlow.value = indexList2
runCurrent()
assertContentEquals(expectedIndex, indexManager.decryptedIndex.value.data!!.toList())
}
}
| 0
|
Kotlin
|
0
| 0
|
37ba3d1618945078d40d1ce1d32b184ae647643d
| 4,624
|
oneSafe6_SDK_Android
|
Apache License 2.0
|
app/src/main/java/com/thk/sevendays/data/StampViewModel.kt
|
taehee28
| 453,343,657
| false
| null |
package com.thk.sevendays.data
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.thk.data.logd
import com.thk.data.model.Stamp
import com.thk.data.repository.StampRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class StampViewModel @Inject constructor(
private val repository: StampRepository
) : ViewModel() {
val uiState = MutableStateFlow<UiState<List<Stamp>>>(UiState.Loading)
fun getStamps(id: Long) = viewModelScope.launch {
repository.getStamps(id).collectLatest {
uiState.value = UiState.Success(it)
}
}
fun setStampChecked(stamp: Stamp) = viewModelScope.launch {
repository.setStampChecked(stamp)
}
fun clearUiState() {
uiState.value = UiState.Loading
}
}
| 0
|
Kotlin
|
0
| 0
|
2dcc6f3ecb83b7fdefed6a110ea20e96c65eb623
| 1,109
|
SevenDays
|
MIT License
|
src/main/kotlin/no/nav/toi/kandidatsøk/filter/InnsatsgruppeFilter.kt
|
navikt
| 732,052,226
| false
|
{"Kotlin": 250789, "Dockerfile": 234}
|
package no.nav.toi.kandidatsøk.filter
import no.nav.toi.kandidatsøk.FilterParametre
import no.nav.toi.must_
import no.nav.toi.terms
fun List<Filter>.medInnsatsgruppeFilter() = this + InnsatsgruppeFilter()
private val lovligeVerdier = listOf("ANDRE","IKVAL","VARIG","BFORM","BATT","IVURD","BKART","OPPFI","VURDI","VURDU")
private val defaultInnsatsgrupper = listOf("BATT","BFORM","IKVAL","VARIG")
private class InnsatsgruppeFilter: Filter {
private lateinit var innsatsgrupper: List<String>
override fun berikMedParameter(filterParametre: FilterParametre) {
val innkommendeParameter = filterParametre.innsatsgruppe?.filter { it in lovligeVerdier }?.flatMap { if(it=="ANDRE") listOf(it,"IVURD","BKART","OPPFI","VURDI","VURDU") else listOf(it) }
innsatsgrupper = if(innkommendeParameter?.isNotEmpty() == true) innkommendeParameter else defaultInnsatsgrupper
}
override fun erAktiv() = true
override fun lagESFilterFunksjon(): FilterFunksjon = {
must_ {
terms("kvalifiseringsgruppekode" to innsatsgrupper)
}
}
}
| 1
|
Kotlin
|
0
| 0
|
8fc25415ccb30c8802d51766abc36fff645a24b4
| 1,082
|
rekrutteringsbistand-kandidatsok-api
|
MIT License
|
server-base-local/src/main/kotlin/ai/dstack/server/local/JerseyApplicationProvider.kt
|
latticetower
| 315,119,574
| true
|
{"JavaScript": 397840, "Kotlin": 336820, "CSS": 147028, "Python": 5184, "HTML": 4199, "Shell": 34}
|
package ai.dstack.server.local
import ai.dstack.server.local.jersey.FilesResources
import ai.dstack.server.jersey.JerseyApplication
import ai.dstack.server.jersey.guice.SpringAwareHK2ServiceLocatorFeature
import org.glassfish.jersey.server.ResourceConfig
import org.glassfish.jersey.servlet.ServletProperties
import org.springframework.beans.factory.BeanFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Bean
import org.springframework.stereotype.Component
@Component
open class JerseyApplicationProvider {
@Bean
open fun resourceConfig(@Autowired beanFactory: BeanFactory): ResourceConfig {
val config = JerseyApplication.resourceConfig
.registerClasses(FilesResources::class.java)
.property(ServletProperties.FILTER_FORWARD_ON_404, true)
config.register(SpringAwareHK2ServiceLocatorFeature(beanFactory))
return config
}
}
| 0
| null |
0
| 0
|
81fa7873bbd851b474e7d49cd69087f204bd2171
| 951
|
dstack
|
Apache License 2.0
|
src/main/kotlin/model/paging/PagedResponse.kt
|
Ather
| 161,568,528
| false
| null |
/*
* Copyright 2018 Michael Haas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package app.ather.radarr.model.paging
data class PagedResponse<RecordType : Any, SortKeyType: SortKey>(
val page: Int,
val pageSize: Int,
val sortKey: SortKeyType,
val sortDirection: SortDirection,
val totalRecords: Int,
val records: List<RecordType>
)
| 0
|
Kotlin
|
0
| 0
|
7313476abe3a0a2db135ffce1c91b3a5f206b74e
| 898
|
radarr-kotlin
|
Apache License 2.0
|
android/shared/src/androidMain/kotlin/io/rebble/cobble/shared/domain/notifications/calls/WhatsAppCallNotificationInterpreter.kt
|
pebble-dev
| 295,813,856
| false
|
{"Kotlin": 770908, "Dart": 604224, "Java": 261839, "Objective-C": 165254, "Swift": 110627, "JavaScript": 23686, "Ruby": 1469, "HTML": 305, "C": 211, "Shell": 29}
|
package io.rebble.cobble.shared.domain.notifications.calls
import android.service.notification.StatusBarNotification
class WhatsAppCallNotificationInterpreter: CallNotificationInterpreter {
override fun processCallNotification(sbn: StatusBarNotification): CallNotification? {
val acceptAction = sbn.notification.actions?.firstOrNull { it.title.toString().contains("Answer", true) }
val declineAction = sbn.notification.actions?.firstOrNull { it.title.toString().contains("Decline", true) }
val hangUpAction = sbn.notification.actions?.firstOrNull { it.title.toString().contains("Hang up", true) }
if (acceptAction != null && declineAction != null) {
val contactName = sbn.notification.extras.getCharSequence("android.title")?.toString()?.let {
"WhatsApp\n$it"
}
return CallNotification(
sbn.packageName,
acceptAction.actionIntent,
declineAction.actionIntent,
null,
CallNotificationType.RINGING,
"WhatsApp",
contactName ?: "WhatsApp Call"
)
} else if (hangUpAction != null) {
val contactName = sbn.notification.extras.getCharSequence("android.title")?.toString()?.let {
"WhatsApp\n$it"
}
return CallNotification(
sbn.packageName,
null,
null,
hangUpAction.actionIntent,
CallNotificationType.ONGOING,
"WhatsApp",
contactName ?: "WhatsApp Call"
)
} else {
return null
}
}
}
| 57
|
Kotlin
|
24
| 147
|
111c30b0a6e2e6682b35b6e86dd2982ea27ab89f
| 1,756
|
mobile-app
|
Apache License 2.0
|
src/commonMain/kotlin/websocket/Message.kt
|
tradeJmark
| 432,544,195
| false
| null |
package ca.tradejmark.jbind.websocket
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import kotlinx.serialization.modules.PolymorphicModuleBuilder
import kotlinx.serialization.modules.SerializersModule
import kotlinx.serialization.modules.polymorphic
import kotlinx.serialization.modules.subclass
sealed interface Message
sealed interface ClientMessage: Message
sealed interface ServerMessage: Message
object Serialization {
private val json = Json {
serializersModule = SerializersModule {
fun PolymorphicModuleBuilder<ServerMessage>.registerServerMessages() {
subclass(WSProviderResponse::class)
subclass(WSProviderError::class)
}
fun PolymorphicModuleBuilder<ClientMessage>.registerClientMessages() {
subclass(WSProviderRequest::class)
subclass(WSProviderError::class)
}
polymorphic(Message::class) {
registerServerMessages()
registerClientMessages()
}
polymorphic(ServerMessage::class) {
registerServerMessages()
}
polymorphic(ClientMessage::class) {
registerClientMessages()
}
}
}
fun serializeMessage(message: Message): String = json.encodeToString(message)
fun deserializeClientMessage(message: String): ClientMessage = json.decodeFromString(message)
fun deserializeServerMessage(message: String): ServerMessage = json.decodeFromString(message)
}
| 3
|
Kotlin
|
0
| 0
|
18cdecd8353345905012eb128ca1f7910623a43f
| 1,622
|
jBind
|
MIT License
|
src/player/main/sp/it/pl/layout/Layout.kt
|
sghpjuikit
| 18,862,317
| false
| null |
package sp.it.pl.layout
import javafx.scene.Node
import javafx.scene.layout.AnchorPane
import sp.it.util.conf.cv
import sp.it.util.conf.def
import sp.it.util.conf.readOnly
class Layout: ContainerUni {
/** Name of this container. */
override val name = "Layout"
/** Whether this container is designed as a root and overrides its ui decorations. Default `false`. */
val isStandalone by cv(false).readOnly().def(name = "Standalone", info = "Whether this container is designed as a root and overrides its ui decorations.")
@JvmOverloads
constructor(state: RootContainerDb = RootContainerDb()): super(state.toUni())
/**
* @param parentPane root node to load the layout into.
* @return root node of the layout
*/
override fun load(parentPane: AnchorPane?): Node {
setParentRec()
val n = super.load(parentPane)
return n
}
override fun toString() = "${Layout::class} name=$name"
override fun toDb() = RootContainerDb(id, loadType.value, locked.value, child?.toDb(), properties)
companion object {
fun openStandalone(root: AnchorPane): Layout {
val l = Layout()
l.isStandalone.value = true
l.load(root)
return l
}
}
}
| 12
|
Kotlin
|
2
| 17
|
d8fab86c7e7e3a2fee02eb0099a1e3e25e74794d
| 1,234
|
player
|
X.Net License
|
permissions/src/main/java/com/piroworkz/composeandroidpermissions/Permissions.kt
|
piroworkz
| 802,955,723
| false
|
{"Kotlin": 2705}
|
package com.piroworkz.composeandroidpermissions
import androidx.activity.compose.ManagedActivityResultLauncher
import androidx.compose.runtime.MutableState
class Permissions(
private val _state: MutableState<PermissionsState>,
private val launcher: ManagedActivityResultLauncher<Array<String>, Map<String, Boolean>>,
private val _requested: MutableState<Boolean>,
) {
val requestedAtLeastOnce: Boolean get() = _requested.value
val state: PermissionsState get() = _state.value
fun launchRequestFor(vararg permissions: String) {
launcher.launch(arrayOf(*permissions))
}
fun onDismissRationale() {
_requested.value = true
_state.value = PermissionsState.DENIED
}
}
| 0
|
Kotlin
|
0
| 1
|
3d8b4f47c24cfecf8c850b16a2be13b99f3ec5bc
| 726
|
ComposeAndroidPermissions
|
MIT License
|
app/src/main/java/zengqiang/composestudy/module/custom_view/CustomIntrinsicPage.kt
|
qiangzengli
| 629,271,848
| false
|
{"Kotlin": 170040, "Java": 689}
|
package zengqiang.composestudy.module.custom_view
import androidx.compose.foundation.layout.*
import androidx.compose.material.Divider
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.*
import androidx.compose.ui.unit.Constraints
import androidx.compose.ui.unit.dp
@Composable
fun CustomIntrinsicPage() {
IntrinsicRow(
modifier = Modifier
.height(IntrinsicSize.Min)
.fillMaxWidth()
) {
Text(
text = "Left",
modifier = Modifier
.wrapContentWidth(Alignment.Start)
.layoutId("main")
)
Divider(
modifier = Modifier
.fillMaxHeight()
.width(4.dp)
.layoutId("divider")
)
Text(
text = "Right",
modifier = Modifier
.wrapContentWidth(Alignment.End)
.layoutId("main")
)
}
}
@Composable
fun IntrinsicRow(
modifier: Modifier, content: @Composable () -> Unit
) {
Layout(
modifier = modifier,
content = content,
measurePolicy = object : MeasurePolicy {
override fun MeasureScope.measure(
measurables: List<Measurable>,
constraints: Constraints
): MeasureResult {
val dividerConstraints = constraints.copy(minWidth = 0)
val mainPlaceableList = measurables.filter {
it.layoutId == "main"
}.map {
it.measure(constraints)
}
val devicePlaceable =
measurables.first { it.layoutId == "divider" }.measure(dividerConstraints)
val midPos = constraints.maxWidth / 2
return layout(constraints.maxWidth, constraints.maxHeight) {
mainPlaceableList.forEach { placeable ->
placeable.placeRelative(0, 0)
}
devicePlaceable.placeRelative(midPos, 0)
}
}
override fun IntrinsicMeasureScope.minIntrinsicHeight(
measurables: List<IntrinsicMeasurable>, width: Int
): Int {
var maxHeight = 0
measurables.forEach {
maxHeight = it.minIntrinsicHeight(width).coerceAtLeast(maxHeight)
}
return maxHeight
}
// override fun IntrinsicMeasureScope.maxIntrinsicHeight(
// measurable: List<IntrinsicMeasurable>,
// width: Int
// ): Int {
// }
//
// override fun IntrinsicMeasureScope.minIntrinsicWidth(
// measurable: List<IntrinsicMeasurable>,
// height: Int
// ): Int {
// }
//
// override fun IntrinsicMeasureScope.maxIntrinsicWidth(
// measurable: List<IntrinsicMeasurable>,
// height: Int
// ): Int {
// }
})
}
| 0
|
Kotlin
|
0
| 0
|
e7117e0ec1fe19f1ae285f7945e36985e1369b22
| 3,179
|
ComposeStudy
|
MIT License
|
app/src/main/java/pini/mattia/coachtimer/Destinations.kt
|
martirius
| 559,459,763
| false
| null |
package pini.mattia.coachtimer
object Destinations {
const val MAIN_SCREEN = "main"
const val SESSION_SCREEN = "session/{playerId}/{lapDistance}"
const val LEADERBOARD_SCREEN = "leaderboard"
fun prepareSessionScreenNavigation(playerId: String, lapDistance: Int): String {
return SESSION_SCREEN
.replace("{playerId}", playerId)
.replace("{lapDistance}", lapDistance.toString())
}
}
| 0
|
Kotlin
|
0
| 0
|
7853e31b3a436087e79690a9abbd652f20d47856
| 435
|
coach-timer
|
MIT License
|
app/src/main/java/com/example/arvoice/VoiceApplication.kt
|
catalinghita8
| 277,572,435
| false
| null |
package com.example.arvoice
import android.app.Application
import android.content.Context
class VoiceApplication : Application() {
init { instance = this }
companion object {
var instance: VoiceApplication? = null
fun applicationContext(): Context {
return instance!!.applicationContext
}
}
}
| 0
|
Kotlin
|
1
| 2
|
d3de1ec7cdc774618eca08119f87d495c4466d05
| 347
|
voice-text-nlp-stanford
|
MIT License
|
appsub/app_ktv/src/main/java/com/niucube/app/ktv/StartActivity.kt
|
pili-engineering
| 468,291,874
| false
|
{"Kotlin": 1046570, "Java": 735296, "GLSL": 430}
|
package com.niucube.app.ktv
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.launcher.ARouter
import com.qiniu.router.RouterConstant
import com.qiniudemo.baseapp.BaseStartActivity
class StartActivity : BaseStartActivity() {
override fun getDefaultImg(): Int {
return R.drawable.spl_bg
}
override val onLoginFinishPostcard: Postcard
get() = ARouter.getInstance().build(RouterConstant.KTV.KTVList)
}
| 0
|
Kotlin
|
2
| 8
|
b6c29394e2f28e05236c9a36d16dc7e94ff06f54
| 468
|
QNCube_Android
|
Apache License 2.0
|
mineinabyss-systems/src/main/kotlin/com/mineinabyss/enchants/FrostAspectListener.kt
|
MineInAbyss
| 115,279,675
| false
| null |
package com.mineinabyss.enchants
import com.mineinabyss.idofront.time.TimeSpan
import com.mineinabyss.mineinabyss.core.mineInAbyss
import com.okkero.skedule.schedule
import org.bukkit.entity.LivingEntity
import org.bukkit.entity.Player
import org.bukkit.event.EventHandler
import org.bukkit.event.Listener
import org.bukkit.event.entity.EntityDamageByEntityEvent
class FrostAspectListener : Listener {
@EventHandler
fun EntityDamageByEntityEvent.onFrostAspectHit() {
val damager = damager as? Player ?: return
val item = damager.inventory.itemInMainHand
val enchantLvl = item.getEnchantmentLevel(CustomEnchants.FROST_ASPECT)
val length = TimeSpan(10000).inSeconds.times(enchantLvl) // Multiplied duration by level.
val damageTimer = TimeSpan(10000).inSeconds
var timePassed = 0L
var freezeTimePassed = 0L
val lastTime = System.currentTimeMillis()
if (item.containsEnchantment(CustomEnchants.FROST_ASPECT)) {
mineInAbyss.schedule {
do {
val lastFreezeTime = System.currentTimeMillis()
do {
entity.freezeTicks = entity.maxFreezeTicks
freezeTimePassed += System.currentTimeMillis() - lastFreezeTime
waitFor(1)
} while ((freezeTimePassed < damageTimer) &&
((entity.freezeTicks == entity.maxFreezeTicks) ||
(entity.freezeTicks in (1 until entity.maxFreezeTicks)))
)
freezeTimePassed = 0L
(entity as LivingEntity).damage(1.0)
entity.freezeTicks = entity.maxFreezeTicks
timePassed += System.currentTimeMillis() - lastTime
if ((entity as LivingEntity).health == 0.0) timePassed = length.toLong()
} while (timePassed < length)
}
}
}
}
| 12
|
Kotlin
|
23
| 45
|
3bcae467fd80dba68f5083ddd0d1711f7052fc50
| 1,986
|
MineInAbyss
|
MIT License
|
app/src/main/kotlin/net/primal/android/core/compose/icons/primaliconpack/FeedReplies.kt
|
PrimalHQ
| 639,579,258
| false
| null |
package net.primal.android.core.compose.icons.primaliconpack
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
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 net.primal.android.core.compose.icons.PrimalIcons
public val PrimalIcons.FeedReplies: ImageVector
get() {
if (_feedReplies != null) {
return _feedReplies!!
}
_feedReplies = Builder(name = "Feedreplies", defaultWidth = 18.0.dp, defaultHeight =
18.0.dp, viewportWidth = 18.0f, viewportHeight = 18.0f).apply {
path(fill = SolidColor(Color(0xFF666666)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd) {
moveTo(5.8f, 11.1953f)
verticalLineTo(13.5911f)
curveTo(5.8f, 13.7988f, 6.0154f, 13.9029f, 6.1414f, 13.756f)
lineTo(8.3373f, 11.1953f)
horizontalLineTo(14.8f)
curveTo(15.6837f, 11.1953f, 16.4f, 10.3599f, 16.4f, 9.3294f)
verticalLineTo(4.7318f)
curveTo(16.4f, 3.7013f, 15.6837f, 2.8659f, 14.8f, 2.8659f)
horizontalLineTo(4.2f)
curveTo(3.3163f, 2.8659f, 2.6f, 3.7013f, 2.6f, 4.7318f)
verticalLineTo(9.3294f)
curveTo(2.6f, 10.3599f, 3.3163f, 11.1953f, 4.2f, 11.1953f)
horizontalLineTo(5.8f)
close()
moveTo(4.8828f, 17.8624f)
curveTo(4.6309f, 18.1563f, 4.2f, 17.9482f, 4.2f, 17.5326f)
lineTo(4.2f, 13.0611f)
curveTo(2.4327f, 13.0611f, 1.0f, 11.3904f, 1.0f, 9.3294f)
verticalLineTo(4.7318f)
curveTo(1.0f, 2.6708f, 2.4327f, 1.0f, 4.2f, 1.0f)
horizontalLineTo(14.8f)
curveTo(16.5673f, 1.0f, 18.0f, 2.6708f, 18.0f, 4.7318f)
verticalLineTo(9.3294f)
curveTo(18.0f, 11.3904f, 16.5673f, 13.0611f, 14.8f, 13.0611f)
horizontalLineTo(9.0f)
lineTo(4.8828f, 17.8624f)
close()
}
}
.build()
return _feedReplies!!
}
private var _feedReplies: ImageVector? = null
| 0
|
Kotlin
|
0
| 7
|
fd815cd9a771c1b110e0e12ceca1012201d8e9dc
| 2,659
|
primal-android-app
|
MIT License
|
app/src/main/java/com/digging/coroutine/ui/request/NewsViewHolder.kt
|
thiagodmont
| 358,086,711
| false
|
{"Kotlin": 41064}
|
package com.digging.coroutine.ui.request
import com.digging.coroutine.base.BaseViewHolder
import com.digging.coroutine.databinding.ItemNewsBinding
import com.digging.coroutine.domain.model.NewsModel
internal class NewsViewHolder(private val viewBinding: ItemNewsBinding):
BaseViewHolder(viewBinding) {
fun binding(news: NewsModel) {
viewBinding.mtvTitleNews.text = news.title
viewBinding.mtvContentNews.text = news.content
}
}
| 0
|
Kotlin
|
0
| 0
|
cfd2c8b22b786c34ccb191729a3ca4c5f0d20198
| 457
|
digging-coroutine
|
MIT License
|
app/src/main/java/com/breezefieldsalesprashant/features/nearbyuserlist/api/NearbyUserRepo.kt
|
DebashisINT
| 855,017,070
| false
|
{"Kotlin": 15873987, "Java": 1028328}
|
package com.breezefieldsalesprashant.features.nearbyuserlist.api
import com.breezefieldsalesprashant.app.Pref
import com.breezefieldsalesprashant.features.nearbyuserlist.model.NearbyUserResponseModel
import com.breezefieldsalesprashant.features.newcollection.model.NewCollectionListResponseModel
import com.breezefieldsalesprashant.features.newcollection.newcollectionlistapi.NewCollectionListApi
import io.reactivex.Observable
class NearbyUserRepo(val apiService: NearbyUserApi) {
fun nearbyUserList(): Observable<NearbyUserResponseModel> {
return apiService.getNearbyUserList(Pref.session_token!!, Pref.user_id!!)
}
}
| 0
|
Kotlin
|
0
| 0
|
a281633009426017c9d16dd760f69f6f6496c34e
| 637
|
PRASHANT
|
Apache License 2.0
|
src/main/kotlin/dreifa/app/opentelemetry/AttributesHelper.kt
|
dreifadotapp
| 478,598,303
| false
| null |
package dreifa.app.opentelemetry
import dreifa.app.types.CorrelationContext
import dreifa.app.types.CorrelationContexts
import io.opentelemetry.api.common.AttributeKey
import io.opentelemetry.api.common.Attributes
object AttributesHelper {
fun fromCorrelation(correlation: CorrelationContext): Attributes {
return Attributes.of(AttributeKey.stringKey(correlation.openTelemetryAttrName), correlation.id.id)
}
fun fromCorrelations(correlations: CorrelationContexts): Attributes {
val builder = Attributes.builder()
correlations.forEach {
builder.put(it.openTelemetryAttrName, it.id.id)
}
return builder.build()
}
fun stringAttr(key: String, value: String): Attributes {
return Attributes.of(AttributeKey.stringKey(key), value)
}
fun longAttr(key: String, value: Long): Attributes {
return Attributes.of(AttributeKey.longKey(key), value)
}
}
| 0
|
Kotlin
|
0
| 0
|
a31809cc91858259d1e48d109c3743762dca28a5
| 943
|
open-telemetry
|
MIT License
|
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/Keyboard.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.filled
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 me.localx.icons.straight.Icons
public val Icons.Filled.Keyboard: ImageVector
get() {
if (_keyboard != null) {
return _keyboard!!
}
_keyboard = Builder(name = "Keyboard", defaultWidth = 512.0.dp, defaultHeight = 512.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(21.0f, 6.0f)
lineTo(13.0f, 6.0f)
lineTo(13.0f, 2.0f)
lineTo(11.0f, 2.0f)
lineTo(11.0f, 6.0f)
lineTo(3.0f, 6.0f)
arcTo(3.0f, 3.0f, 0.0f, false, false, 0.0f, 9.0f)
lineTo(0.0f, 20.0f)
lineTo(24.0f, 20.0f)
lineTo(24.0f, 9.0f)
arcTo(3.0f, 3.0f, 0.0f, false, false, 21.0f, 6.0f)
close()
moveTo(9.0f, 10.0f)
horizontalLineToRelative(3.0f)
verticalLineToRelative(2.0f)
lineTo(9.0f, 12.0f)
close()
moveTo(6.0f, 16.0f)
lineTo(4.0f, 16.0f)
lineTo(4.0f, 14.0f)
lineTo(6.0f, 14.0f)
close()
moveTo(7.0f, 12.0f)
lineTo(4.0f, 12.0f)
lineTo(4.0f, 10.0f)
lineTo(7.0f, 10.0f)
close()
moveTo(16.0f, 16.0f)
lineTo(8.0f, 16.0f)
lineTo(8.0f, 14.0f)
horizontalLineToRelative(8.0f)
close()
moveTo(20.0f, 16.0f)
lineTo(18.0f, 16.0f)
lineTo(18.0f, 14.0f)
horizontalLineToRelative(2.0f)
close()
moveTo(20.0f, 12.0f)
lineTo(14.0f, 12.0f)
lineTo(14.0f, 10.0f)
horizontalLineToRelative(6.0f)
close()
}
}
.build()
return _keyboard!!
}
private var _keyboard: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 2,759
|
icons
|
MIT License
|
src/jsMain/kotlin/domain/use_case/user/UserGetByIdUseCase.kt
|
Tanexc
| 667,134,735
| false
| null |
package domain.use_case.user
import domain.model.User
import domain.repository.UserRepository
import kotlinx.coroutines.flow.Flow
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
import util.State
class UserGetByIdUseCase: KoinComponent {
private val repository: UserRepository by inject()
suspend operator fun invoke(id: Long): Flow<State<User>> = repository.getById(id)
}
| 0
|
Kotlin
|
0
| 3
|
27bc23f5ab9dbc8ec7da5fc7812555bbbcaeb0a7
| 418
|
ComposeWebCakes
|
Apache License 2.0
|
spring-boot-demo/src/main/java/moe/bit/ignotusdemo/model/table/UserTable.kt
|
ParaParty
| 430,148,230
| false
|
{"Kotlin": 173423, "Java": 30623}
|
package moe.bit.ignotusdemo.model.table
import com.tairitsu.ignotus.database.exposed.model.table.BaseLongIdWithUUIDTable
import org.jetbrains.exposed.sql.Column
import org.jetbrains.exposed.sql.javatime.datetime
import java.time.LocalDateTime
object UserTable : BaseLongIdWithUUIDTable("users") {
val username: Column<String> = varchar("username", 256)
val password: Column<String> = varchar("password", 256)
val lastLoginAt: Column<LocalDateTime?> = datetime("last_login_at").nullable()
}
| 1
|
Kotlin
|
0
| 22
|
0937ec102c9da4df6c39ee8bd1832402ec9cd1e8
| 504
|
Ignotus
|
MIT License
|
app/src/main/java/com/example/wordapp/DictionaryFragment.kt
|
erenozdemr
| 651,890,308
| false
| null |
package com.example.wordapp
import android.media.AudioManager
import android.media.MediaPlayer
import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.util.Log
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.ImageButton
import android.widget.MediaController
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.DialogFragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.Navigation
import androidx.navigation.fragment.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.wordapp.MVVM.WordMeaningsRecyclerAdapter
import com.example.wordapp.MVVM.WordMeaningsWievModel
import com.example.wordapp.databinding.FragmentDictionaryBinding
import kotlinx.android.synthetic.main.fragment_dictionary.*
import kotlinx.coroutines.flow.callbackFlow
import java.lang.Exception
import java.util.Locale
class DictionaryFragment : Fragment(),TextToSpeech.OnInitListener {
lateinit var binding: FragmentDictionaryBinding
private lateinit var viewModel: WordMeaningsWievModel
private var adapter= WordMeaningsRecyclerAdapter(arrayListOf())
lateinit var recyclerDictionary: RecyclerView
private lateinit var tts:TextToSpeech
val args: DictionaryFragmentArgs by navArgs()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
binding= FragmentDictionaryBinding.inflate(inflater,container,false)
tts=TextToSpeech(requireContext(),this)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
recyclerDictionary=view.findViewById(R.id.dictionaryRecycler)
recyclerDictionary.layoutManager= LinearLayoutManager(view.context)
recyclerDictionary.adapter=adapter
viewModel= ViewModelProvider(this).get(WordMeaningsWievModel::class.java)
viewModel.inTheBeginning()
if(arguments?.isEmpty == false){
var id=args.id.toString()
if(!id.equals("noid")){
binding.etSearchBox.visibility=View.GONE
binding.btnSearch.visibility=View.GONE
viewModel.getWordWithID(id!!)
/*
btnSave.setImageResource(R.drawable.img_1)
btnNote.visibility=View.VISIBLE
tvGhost.setText("saved")*/
}
else{
binding.etSearchBox.visibility=View.VISIBLE
binding.btnSearch.visibility=View.VISIBLE
}
}
binding.btnSearch.setOnClickListener {
var wordSearch=binding.etSearchBox.text.toString().trim()
wordSearch?.let {
println("word ${wordSearch} is being searched")
viewModel.getWord(wordSearch,requireContext())
observeLiveData()
adapter.notifyDataSetChanged()
}
}
binding.btnSave.setOnClickListener {
viewModel.saveWord()
observeLiveData()
}
binding.btnNote.setOnClickListener{
if(viewModel.meaningsSaved.value == true){
var action = DictionaryFragmentDirections.actionDictionaryFragmentToNoteFragment(viewModel.meanings.value!!.id)
Navigation.findNavController(it).navigate(action)
}
}
binding.btnSpeak.setOnClickListener{
tts.speak(viewModel.meanings.value!!.word,TextToSpeech.QUEUE_FLUSH,null,"")
}
observeLiveData()
}
fun observeLiveData(){
viewModel.meanings.observe(viewLifecycleOwner, Observer {
if(it!=null){
binding.LinearLayoutDictionary.visibility=View.VISIBLE
binding.LinearLayoutTextview.visibility=View.GONE
recyclerDictionary.visibility=View.VISIBLE
var word=it
binding.etWord.setText(word.word)
binding.etPronunce.setText(word.phonetic.get(0).text)
adapter.refreshMeanings(word.meanings)
}
else{
binding.LinearLayoutDictionary.visibility=View.GONE
}
})
viewModel.meaningsErrors.observe(viewLifecycleOwner, Observer {
it?.let {
if(it){
binding.LinearLayoutTextview.visibility=View.VISIBLE
//buraya daha sonra hata mesajı ekelenbilir
}else{
binding.LinearLayoutTextview.visibility=View.GONE
}
}
})
viewModel.meaningsLoading.observe(viewLifecycleOwner, Observer {
if(it){
binding.LinearLayoutProgressbar.visibility=View.VISIBLE
}else{
binding.LinearLayoutProgressbar.visibility=View.GONE
}
})
viewModel.meaningsSaved.observe(viewLifecycleOwner, Observer {
if(it){
binding.btnSave.setImageResource(R.drawable.img_1)
binding.btnNote.visibility=View.VISIBLE
}else{
binding.btnSave.setImageResource(R.drawable.img)
binding.btnNote.visibility=View.GONE
}
})
}
override fun onInit(status: Int) {
if(status==TextToSpeech.SUCCESS){
val result=tts.setLanguage(Locale.UK)
if(result==TextToSpeech.LANG_MISSING_DATA||result==TextToSpeech.LANG_NOT_SUPPORTED){
Log.e("TTS","Laguage is not supported")
}
}else{
Log.e("TTS","Initalization failed")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3c4f4ae964521f3508e94883f630acf1721cf50d
| 6,136
|
WordApp
|
MIT License
|
src/main/kotlin/ru/biluta/memes/service/persistence/model/ChatSettings.kt
|
antonbiluta
| 755,326,602
| false
|
{"Kotlin": 48349, "Dockerfile": 1079}
|
package ru.biluta.memes.service.persistence.model
import jakarta.persistence.*
@Entity
@Table(name="chat_settings")
class ChatSettings(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0,
@Column(name = "chat_id", nullable = false, unique = true)
val chatId: Long,
@Column(name = "chat_prefix")
var chatPrefix: String? = null,
@OneToMany(mappedBy = "chatSettings", fetch = FetchType.LAZY)
val memes: List<Memes> = mutableListOf()
)
| 0
|
Kotlin
|
0
| 0
|
c0d60762beb2af2ef9d66fbc32fe1d7f039ebde4
| 496
|
memes-backend
|
MIT License
|
app/src/main/java/com/gdsc/bbsbec/gbooks/activity/BookDao.kt
|
gdsc-bbsbec
| 441,695,228
| false
|
{"Kotlin": 52052}
|
/*
* Copyright (C) 2022 Google Developer Student Clubs BBSBEC
*
* 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.gdsc.bbsbec.gbooks.activity
import androidx.lifecycle.LiveData
import androidx.room.*
import com.gdsc.bbsbec.gbooks.model.BookSearchResultData
@Dao
interface BookDao {
@Insert(onConflict = OnConflictStrategy.IGNORE)
suspend fun addBook(books: BookSearchResultData)
@Query("SELECT * FROM book_data ORDER BY id ASC")
fun readAllData(): LiveData<List<BookSearchResultData>>
@Delete
suspend fun deleteBook(book: BookSearchResultData)
}
| 0
|
Kotlin
|
7
| 13
|
ac1f49ce0a3df5a57c325509cc4c179be2ced4fd
| 1,099
|
GBooks
|
Apache License 2.0
|
koral-algorithms/src/test/kotlin/tools/aqua/koral/util/MutableCanonicalSetTest.kt
|
tudo-aqua
| 472,398,902
| false
| null |
/*
* Copyright 2022 The Koral Authors
* SPDX-License-Identifier: Apache-2.0
*
* 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 tools.aqua.koral.util
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
internal class MutableCanonicalSetTest {
@Test
fun `size is correct`() {
val set = MutableCanonicalSet<Int>().also { it += 1 }
assertEquals(1, set.size)
}
@Test
fun `size ignores duplicates`() {
val set =
MutableCanonicalSet<Int>().also {
it += 1
it += 1
}
assertEquals(1, set.size)
}
@Test
fun `re-interning yields original object`() {
val canonical = listOf(1)
val set = MutableCanonicalSet<List<Int>>().also { it.intern(canonical) }
assertSame(canonical, set.intern(listOf(1)))
}
@Test
fun `interning adds to set`() {
val set = MutableCanonicalSet<Int>().also { it.intern(1) }
assertEquals(setOf(1), set)
}
@Test
fun `adding interns`() {
val canonical = listOf(1)
val set = MutableCanonicalSet<List<Int>>().also { it.add(canonical) }
assertSame(canonical, set.intern(listOf(1)))
}
@Test
fun `adding works`() {
val set = MutableCanonicalSet<Int>().also { it.add(1) }
assertEquals(setOf(1), set)
}
@Test
fun `clearing works`() {
val set =
MutableCanonicalSet<Int>().also {
it += 1
it.clear()
}
assertEquals(emptySet<Int>(), set)
}
@Test
fun `contains works`() {
val set = MutableCanonicalSet<Int>().also { it += 1 }
assertTrue(set.contains(1))
assertFalse(set.contains(2))
}
@Test
fun `contains all works`() {
val set =
MutableCanonicalSet<Int>().also {
it += 1
it += 2
}
assertTrue(set.containsAll(listOf(1)))
assertTrue(set.containsAll(listOf(1, 2)))
assertFalse(set.containsAll(listOf(1, 2, 3)))
}
@Test
fun `iterator works`() {
val iterator =
MutableCanonicalSet<Int>()
.also {
it += 1
it += 2
}
.iterator()
val first = iterator.next()
val second = iterator.next()
assertEquals(setOf(1, 2), setOf(first, second))
assertFalse(iterator.hasNext())
}
@Test
fun `remove works`() {
val set =
MutableCanonicalSet<Int>().also {
it += 1
it += 2
it.remove(1)
}
assertEquals(setOf(2), set)
}
@Test
fun `remove ignores missing`() {
val set =
MutableCanonicalSet<Int>().also {
it += 1
it += 2
}
assertDoesNotThrow { set.remove(3) }
assertEquals(setOf(1, 2), set)
}
@Test
fun `retainAll works`() {
val set =
MutableCanonicalSet<Int>().also {
it += 1
it += 2
it += 3
it.retainAll(listOf(1, 3))
}
assertEquals(setOf(1, 3), set)
}
@Test
fun `retainAll ignores missing`() {
val set =
MutableCanonicalSet<Int>().also {
it += 1
it += 2
it.retainAll(listOf(1, 3))
}
assertEquals(setOf(1), set)
}
}
| 0
|
Kotlin
|
0
| 0
|
c5e8c3374ace1a84f60f50c74b17505b9c0952e5
| 3,641
|
koral
|
Apache License 2.0
|
domain/src/main/kotlin/com/yossisegev/domain/usecases/SearchMovie.kt
|
hbrtose
| 156,258,366
| true
|
{"Kotlin": 137058}
|
package com.yossisegev.domain.usecases
import com.yossisegev.domain.MoviesRepository
import com.yossisegev.domain.common.Transformer
import com.yossisegev.domain.entities.MovieEntity
import io.reactivex.Single
/**
* Created by <NAME> on 11/02/2018.
*/
class SearchMovie(transformer: Transformer<List<MovieEntity>>,
private val moviesRepository: MoviesRepository) : UseCase<String, List<MovieEntity>>(transformer) {
fun search(query: String): Single<List<MovieEntity>> {
return observable(query)
}
override fun createObservable(data: String?): Single<List<MovieEntity>> {
data?.let {
return moviesRepository.search(it)
} ?: return Single.just(emptyList())
}
}
| 0
|
Kotlin
|
0
| 0
|
7c6d2e444862f6bc21205b80dd68b5a44b70c73d
| 735
|
MovieNight
|
Apache License 2.0
|
library/src/main/java/com/d10ng/compose/ui/form/DatePicker.kt
|
D10NGYANG
| 445,078,597
| false
|
{"Kotlin": 380265}
|
package com.d10ng.compose.ui.form
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.text.TextStyle
import com.d10ng.compose.ui.AppText
import com.d10ng.datelib.curTime
import com.d10ng.datelib.getDateDay
import com.d10ng.datelib.getDateMonth
import com.d10ng.datelib.getDateYear
import com.d10ng.datelib.getDaysOfMonth
import com.d10ng.datelib.setDateDay
import com.d10ng.datelib.setDateMonth
import com.d10ng.datelib.setDateYear
/**
* 日期选择器
* @Author d10ng
* @Date 2023/9/11 17:16
*/
enum class DatePickerMode(
val getItems: (Set<String>, Set<String>, Set<String>) -> List<Set<String>>,
val getSelectedItems: (String, String, String) -> List<String>,
val getDate: (Long, List<String>) -> Long,
) {
// 年月日
YMD(
{ y, m, d -> listOf(y, m, d) },
{ y, m, d -> listOf(y, m, d) },
{ v, l -> v.setDateYear(l[0].toInt()).setDateMonth(l[1].toInt()).setDateDay(l[2].toInt()) }
),
// 年月
YM(
{ y, m, _ -> listOf(y, m) },
{ y, m, _ -> listOf(y, m) },
{ v, l -> v.setDateYear(l[0].toInt()).setDateMonth(l[1].toInt()) }),
// 年
Y({ y, _, _ -> listOf(y) }, { y, _, _ -> listOf(y) }, { v, l -> v.setDateYear(l[0].toInt()) }),
// 月日
MD(
{ _, m, d -> listOf(m, d) },
{ _, m, d -> listOf(m, d) },
{ v, l -> v.setDateMonth(l[0].toInt()).setDateDay(l[1].toInt()) }),
// 月
M({ _, m, _ -> listOf(m) }, { _, m, _ -> listOf(m) }, { v, l -> v.setDateMonth(l[0].toInt()) }),
}
/**
* 日期选择器
* @param value Long 选中的日期
* @param onValueChange Function1<Long, Unit> 选中日期改变事件
* @param start Long 开始日期
* @param endInclude Long 结束日期,包含
* @param textStyle TextStyle 文本样式
* @param mode DatePickerMode 选择器模式
* @param itemText Function2<Int, Int, String> 选项文本
*/
@Composable
fun DatePicker(
value: Long,
onValueChange: (Long) -> Unit,
start: Long = 0,
endInclude: Long = curTime,
textStyle: TextStyle = AppText.Normal.Title.default,
mode: DatePickerMode = DatePickerMode.YMD,
itemText: (Int, String) -> String = { _, item -> item },
) {
// 年份列表
val years = remember(start, endInclude) {
(start.getDateYear()..endInclude.getDateYear()).map { it.toString() }.toSet()
}
// 选择的年份
val year = remember(value) {
value.getDateYear()
}
// 月份列表
val months = remember(year, start, endInclude) {
val startMonth = if (year == start.getDateYear()) start.getDateMonth() else 1
val endMonth = if (year == endInclude.getDateYear()) endInclude.getDateMonth() else 12
(startMonth..endMonth).map { it.toString().padStart(2, '0') }.toSet()
}
// 选择的月份
val month = remember(value) {
value.getDateMonth()
}
// 日期列表
val days = remember(year, month, start, endInclude, value) {
val startDay =
if (year == start.getDateYear() && month == start.getDateMonth()) start.getDateDay() else 1
val endDay =
if (year == endInclude.getDateYear() && month == endInclude.getDateMonth()) endInclude.getDateDay()
else getDaysOfMonth(value.getDateYear(), value.getDateMonth())
(startDay..endDay).map { it.toString().padStart(2, '0') }.toSet()
}
// 选择的日期
val day = remember(value) {
value.getDateDay()
}
val items = remember(mode, years, months, days) {
mode.getItems(years, months, days)
}
val selectedItems = remember(mode, year, month, day) {
mode.getSelectedItems(
year.toString(),
month.toString().padStart(2, '0'),
day.toString().padStart(2, '0')
)
}
MultiPicker(
items = items,
itemText = itemText,
textStyle = textStyle,
selectedItems = selectedItems,
onValueChange = {
onValueChange(mode.getDate(value, it).coerceAtLeast(start).coerceAtMost(endInclude))
}
)
}
| 0
|
Kotlin
|
1
| 9
|
490be74ad152b83648d1fb6fe6a665f75596b0d6
| 3,953
|
DLJetpackComposeUtil
|
MIT License
|
lib/src/main/java/com/thenewboston/data/dto/common/response/ValidatorDetails.kt
|
thenewboston-developers
| 300,752,823
| false
| null |
package com.thenewboston.data.dto.common.response
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class ValidatorDetails(
@SerialName("primary_validator")
val primaryValidator: Validator,
@SerialName("account_number")
val accountNumber: String,
@SerialName("ip_address")
val ipAddress: String,
@SerialName("node_identifier")
val nodeIdentifier: String,
@SerialName("port")
val port: Int? = null,
@SerialName("protocol")
val protocol: String,
@SerialName("version")
val version: String,
@SerialName("default_transaction_fee")
val defaultTransactionFee: Int,
@SerialName("root_account_file")
val rootAccountFile: String,
@SerialName("root_account_file_hash")
val rootAccountFileHash: String,
@SerialName("seed_block_identifier")
val seedBlockIdentifier: String,
@SerialName("daily_confirmation_rate")
val dailyConfirmationRate: Int,
@SerialName("node_type")
val nodeType: String,
)
| 1
|
Kotlin
|
19
| 42
|
97f5b462d2179aa65dc8e35828eef39ba791c0ac
| 1,039
|
Kotlin-SDK
|
MIT License
|
netk_okhttp3_interceptor/src/main/java/com/mozhimen/netk/okhttp3/interceptor/impls/InterceptorCacheOnline.kt
|
mozhimen
| 556,827,365
| false
|
{"Kotlin": 231548, "Java": 28281}
|
package com.mozhimen.netk.okhttp3.interceptor.impls
import com.mozhimen.netk.okhttp3.interceptor.annors.AInterceptor
import com.mozhimen.netk.okhttp3.interceptor.annors.ANetworkInterceptor
import com.mozhimen.netk.okhttp3.interceptor.commons.IInterceptor
import okhttp3.Interceptor
import okhttp3.Response
/**
* @ClassName InterceptorCache
* @Description TODO
* @Author mozhimen
* @Date 2024/7/30
* @Version 1.0
*/
@ANetworkInterceptor
class InterceptorCacheOnline(private val _cacheSeconds: Long = 120) : IInterceptor {
override fun intercept(chain: Interceptor.Chain): Response =
chain.proceed(
chain
.request().newBuilder()
.removeHeader("Pragma")
// .removeHeader("Cache-Control")
.header("Cache-Control", "public, max-age=${_cacheSeconds}")
.build()
)
}
| 0
|
Kotlin
|
0
| 0
|
32416e82013d40dee62c2c79d2f886fe348f828c
| 878
|
ANetKit
|
Apache License 2.0
|
app/src/main/java/com/fernandofgallego/demo/data/DataItem.kt
|
ferdy182
| 340,445,317
| false
| null |
package com.fernandofgallego.demo.data
sealed class DataItem {
data class Section(val title: String): DataItem()
data class Item(val title: String, val checked: Boolean): DataItem()
}
| 0
|
Kotlin
|
0
| 0
|
bb3aede2a2bf342141d703344cfe81a4ff94f730
| 192
|
DemoApp
|
Apache License 2.0
|
core/src/main/java/de/markusressel/kutepreferences/core/preference/color/KuteColorPreference.kt
|
markusressel
| 129,962,741
| false
| null |
package de.markusressel.kutepreferences.core.preference.color
import android.graphics.drawable.Drawable
import androidx.annotation.ColorInt
import androidx.compose.ui.graphics.Color
import de.markusressel.kutepreferences.core.persistence.KutePreferenceDataProvider
import de.markusressel.kutepreferences.core.preference.KutePreferenceItem
import de.markusressel.kutepreferences.core.preference.KutePreferenceListItem
import de.markusressel.kutepreferences.core.search.SearchUtils.containsAnyWord
/**
* Preference item for a 4 channel color (rgba).
* The color is stored as an integer.
*/
open class KuteColorPreference(
override val key: Int,
override val icon: Drawable? = null,
override val title: String,
@ColorInt
private val defaultValue: Int,
override val dataProvider: KutePreferenceDataProvider,
override val onPreferenceChangedListener: ((oldValue: Int, newValue: Int) -> Unit)? = null,
override val onClick: (() -> Unit)? = null,
override val onLongClick: (() -> Unit)? = null,
) : KutePreferenceItem<Int>, KutePreferenceListItem {
override val persistedValue by lazy { getPersistedValueFlow() }
override fun getDefaultValue(): Int = defaultValue
override fun createDescription(currentValue: Int): String {
val color = Color(currentValue)
return color.toHexString()
}
override fun search(searchTerm: String) =
listOf(title, description).containsAnyWord(searchTerm)
}
private fun Color.toHexString(): String {
val a = (alpha * 255).toInt().toString(16).padStart(2, '0')
val r = (red * 255).toInt().toString(16).padStart(2, '0')
val g = (green * 255).toInt().toString(16).padStart(2, '0')
val b = (blue * 255).toInt().toString(16).padStart(2, '0')
return "#$a$r$g$b"
}
| 5
|
Kotlin
|
0
| 9
|
6d8d2e86f46808a376355f54f82c2f4878834e24
| 1,789
|
KutePreferences
|
The Unlicense
|
common/common.consul/common.consul.client/src/main/java/org/eclipse/slm/common/consul/client/requests/ConsulRequest.kt
|
sriluxman
| 655,789,230
| true
|
{"Maven POM": 61, "Markdown": 25, "Git Attributes": 1, "Text": 2, "Ignore List": 4, "XML": 7, "Java": 299, "Kotlin": 201, "YAML": 91, "HTTP": 9, "JSON": 21, "JavaScript": 59, "Dotenv": 6, "JSON with Comments": 2, "Dockerfile": 21, "Browserslist": 1, "HTML": 1, "Vue": 117, "SCSS": 2, "Sass": 15, "SVG": 2, "Shell": 12, "Nginx": 3, "SQL": 1, "Python": 1, "Java Properties": 1, "CSS": 3, "INI": 5, "Fluent": 1, "PowerShell": 1, "Stylus": 2, "OASv3-yaml": 1}
|
package org.eclipse.slm.common.consul.client.requests
import org.eclipse.slm.common.consul.client.requests.parameters.UrlParameters
interface ConsulRequest {
fun asUrlParameters(): List<UrlParameters?>?
}
| 0
|
Java
|
0
| 0
|
7f78aba76cbfe051af60dbee118bcc9a5fda139c
| 211
|
slm
|
Apache License 2.0
|
idea/testData/completion/class/InExtendTypeAnnotation.kt
|
interestingforked
| 6,451,772
| true
|
{"Markdown": 17, "XML": 122, "Ant Build System": 7, "Ignore List": 3, "Maven POM": 23, "Kotlin": 3122, "Java": 2286, "CSS": 10, "JavaScript": 47, "HTML": 16, "Text": 885, "Shell": 5, "Java Properties": 4, "INI": 1, "JFlex": 2, "Makefile": 1, "JAR Manifest": 1, "Batchfile": 2}
|
class Test : <caret> {
fun test() {
}
}
// RUNTIME: 1
// EXIST: Any, Nothing, Tuple0, Int, Number
// EXIST: Array, Math, Hashable, OutputStream
| 0
|
Java
|
0
| 0
|
130cbff966c7bb6ba8f6206aa87530b58c01f41b
| 152
|
kotlin
|
Apache License 2.0
|
app/src/main/java/at/specure/androidX/Application.kt
|
specure
| 114,878,528
| false
|
{"Java": 3220084, "Kotlin": 233019, "HTML": 32323}
|
package at.specure.androidX
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.util.Log
import androidx.multidex.MultiDexApplication
import at.specure.android.util.location.GeoLocationX
import at.specure.android.util.net.NetworkInfoCollector
import at.specure.androidX.logging.timber.LoggingTree
import at.specure.di.AppComponent
import at.specure.di.DaggerAppComponent
import com.facebook.FacebookSdk
import com.facebook.appevents.AppEventsLogger
import com.facebook.stetho.Stetho
import com.google.firebase.FirebaseApp
import com.hypertrack.hyperlog.HyperLog
import com.specure.opennettest.BuildConfig
import timber.log.Timber
class Application : MultiDexApplication() {
private var mNetworkStateIntentReceiver: BroadcastReceiver? = null
private var mNetworkStateChangedFilter: IntentFilter? = null
private var networkInfoCollector: NetworkInfoCollector? = null
val coreComponent: AppComponent
get() = Injector.component
override fun onCreate() {
FirebaseApp.initializeApp(this)
super.onCreate()
FacebookSdk.sdkInitialize(applicationContext)
Stetho.initializeWithDefaults(this)
AppEventsLogger.activateApp(this)
Timber.e("CREATE")
if (!BuildConfig.DEBUG) {
Timber.plant(LoggingTree())
} else {
Timber.plant(LoggingTree())
}
HyperLog.initialize(this)
HyperLog.setLogLevel(Log.VERBOSE)
Injector.component = DaggerAppComponent.builder()
.context(this)
.build()
Injector.component = Injector.component
Injector.inject(this)
val instance = GeoLocationX.getInstance(this)
instance.getLastKnownLocation(this, null)
mNetworkStateChangedFilter = IntentFilter()
mNetworkStateChangedFilter!!.addAction(ConnectivityManager.CONNECTIVITY_ACTION)
networkInfoCollector = NetworkInfoCollector.getInstance(applicationContext)
mNetworkStateIntentReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.action != null && intent.action == ConnectivityManager.CONNECTIVITY_ACTION) {
val connected = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false)
val isFailOver = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false)
if (connected) {
if (networkInfoCollector != null) {
networkInfoCollector!!.setHasConnectionFromAndroidApi(true)
}
} else {
if (networkInfoCollector != null) {
networkInfoCollector!!.setHasConnectionFromAndroidApi(false)
}
}
Timber.i(" %s CONNECTED: %s FAILOVER: %s", "application", connected, isFailOver)
}
}
}
}
}
| 1
| null |
1
| 1
|
a2cf04e1a92a0accd53a3d62ab65542ee249314a
| 3,145
|
ont-android-client
|
Apache License 2.0
|
remote-server/src/test/kotlin/RemoteFormTest.kt
|
CLOVIS-AI
| 464,628,603
| false
| null |
package opensavvy.formulaide.remote.server
import kotlinx.coroutines.ExperimentalCoroutinesApi
import opensavvy.formulaide.fake.FakeDepartments
import opensavvy.formulaide.fake.FakeForms
import opensavvy.formulaide.fake.FakeTemplates
import opensavvy.formulaide.fake.spies.SpyDepartments.Companion.spied
import opensavvy.formulaide.fake.spies.SpyForms.Companion.spied
import opensavvy.formulaide.fake.spies.SpyTemplates.Companion.spied
import opensavvy.formulaide.remote.client.Forms
import opensavvy.formulaide.remote.server.utils.TestClient
import opensavvy.formulaide.remote.server.utils.createTestServer
import opensavvy.formulaide.test.FormTestData
import opensavvy.formulaide.test.execution.Executor
import opensavvy.formulaide.test.execution.Suite
import opensavvy.formulaide.test.formTestSuite
import opensavvy.formulaide.test.utils.TestClock.Companion.testClock
class RemoteFormTest : Executor() {
@OptIn(ExperimentalCoroutinesApi::class)
override fun Suite.register() {
formTestSuite {
val clock = testClock()
val departments = FakeDepartments().spied()
val templates = FakeTemplates(clock).spied()
val application = backgroundScope.createTestServer {
routing {
forms(departments, templates, FakeForms(clock).spied())
}
}
FormTestData(
departments,
templates,
Forms(
TestClient(application.client),
departments,
templates,
backgroundScope.coroutineContext,
)
)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
aa086b58e67a1cc0ae0fb5a936fe661b46646419
| 1,460
|
Formulaide
|
Apache License 2.0
|
app/src/main/java/com/softcross/moviedetective/core/domain/repository/FirebaseRepository.kt
|
ErenMlg
| 796,625,412
| false
|
{"Kotlin": 131785}
|
package com.softcross.moviedetective.core.domain.repository
import com.softcross.moviedetective.core.common.Resource
import com.softcross.moviedetective.core.domain.model.UserModel
import kotlinx.coroutines.flow.Flow
interface FirebaseRepository {
fun loginUser(email: String, password: String): Flow<Resource<UserModel>>
fun registerUser(email: String,password: String,name: String,surname: String): Flow<Resource<UserModel>>
suspend fun addUserDetailsToFirestore(userModel: UserModel): UserModel
suspend fun getUserDetailFromFirestore(userID: String): UserModel
}
| 0
|
Kotlin
|
0
| 0
|
b29cf54e7a8e8b3f218da85045ffc5b08acde98a
| 585
|
MovieDetective
|
Apache License 2.0
|
app/src/main/java/com/test/zh/videoandaudio/codec/Frame.kt
|
XWS
| 252,695,628
| false
| null |
package com.test.zh.videoandaudio.codec
import android.media.MediaCodec
import java.nio.ByteBuffer
/**
* 单帧数据类型(封装类,用以数据处理方便)
*/
class Frame {
var buffer: ByteBuffer? = null
var bufferInfo = MediaCodec.BufferInfo()
private set
fun setBufferInfo(info: MediaCodec.BufferInfo) {
bufferInfo.set(info.offset, info.size, info.presentationTimeUs, info.flags)
}
}
| 0
|
Kotlin
|
0
| 0
|
979ab6cc0b568eda086def41d95f5ab43a7381b7
| 393
|
VideoAndAudio
|
Apache License 2.0
|
src/test/java/playground/BackpressureExercisesTest.kt
|
ExpensiveBelly
| 104,675,798
| false
| null |
package playground
import io.reactivex.schedulers.Schedulers
import org.junit.Ignore
class BackpressureExercisesTest {
private val backpressureExercises: BackpressureExercises = BackpressureExercises()
@Ignore
fun range_on_same_thread_should_not_throw_backpressure_error() {
backpressureExercises.dishesRange.subscribe {
System.out.println("Range Washing: $it")
Thread.sleep(50)
}
}
@Ignore
fun range_on_io_thread_should_not_throw_backpressure_exception() {
backpressureExercises.dishesRange.observeOn(Schedulers.io()).blockingSubscribe {
System.out.println("Range with concurrency Washing: $it")
Thread.sleep(50)
}
}
@Ignore
fun interval_should_throw_backpressure_exception_but_it_doesnt() {
backpressureExercises.dishesInterval.observeOn(Schedulers.newThread()).blockingSubscribe {
System.out.println("Interval Washing: $it")
Thread.sleep(150000)
}
}
@Ignore
fun zip_should_throw_backpressure_exception() {
backpressureExercises.dishesZip.blockingSubscribe {
System.out.println("Interval Washing: $it")
}
}
}
| 0
|
Kotlin
|
11
| 19
|
e07a3aea09f9235077d6d0dd553af2cfe782b393
| 1,217
|
RxKata
|
MIT License
|
libraries/audio/src/common/AudioDelegate.kt
|
featurea
| 407,517,337
| false
| null |
package featurea.audio
import featurea.runtime.Component
import featurea.runtime.Module
expect class AudioDelegate(module: Module) : Component {
fun newAudioTrack(filePath: String): AudioTrack
fun newAudioEffect(filePath: String): AudioEffect
}
| 24
|
Kotlin
|
1
| 6
|
07074dc37a838f16ece90c19a4e8d45e743013d3
| 255
|
engine
|
MIT License
|
app/src/main/kotlin/com/mgorski/articles/view/ArticleCategoriesActivity.kt
|
mgorski-mg
| 71,564,062
| false
|
{"Kotlin": 8262, "Java": 447, "IDL": 339}
|
package com.mgorski.articles.view
import android.databinding.DataBindingUtil
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import com.mgorski.articles.R
import com.mgorski.articles.databinding.ActivityArticleCategoriesBinding
import com.mgorski.articles.viewmodel.ArticleCategoriesViewModel
class ArticleCategoriesActivity : AppCompatActivity() {
private val viewModel = ArticleCategoriesViewModel()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
DataBindingUtil.setContentView<ActivityArticleCategoriesBinding>(this, R.layout.activity_article_categories).viewModel = viewModel
}
}
| 0
|
Kotlin
|
0
| 0
|
86d9415210d2b0e58c3f5debaf11c1c29282f152
| 681
|
articles
|
Apache License 2.0
|
src/main/kotlin/day07/solution.kt
|
bukajsytlos
| 433,979,778
| false
|
{"Kotlin": 63913}
|
package day07
import java.io.File
import kotlin.math.abs
import kotlin.math.roundToInt
fun main() {
val crabSubmarinePositions =
File("src/main/kotlin/day07/input.txt").readLines().first().split(",").map { it.toInt() }
val medianDistance = crabSubmarinePositions.sorted()[crabSubmarinePositions.size / 2]
println(calculateFuelSpent(crabSubmarinePositions, medianDistance) { it })
val meanDistance = crabSubmarinePositions.average().roundToInt()
val minFuelSpent = ((meanDistance - 1)..(meanDistance + 1)) //correct answer should be around mean
.map { position -> calculateFuelSpent(crabSubmarinePositions, position) { it * (it + 1) / 2 } }
.minOf { it }
println(minFuelSpent)
}
private fun calculateFuelSpent(crabSubmarinePositions: List<Int>, position: Int, fuelFormula: (Int) -> Int): Int =
crabSubmarinePositions.sumOf { fuelFormula(abs(it - position)) }
| 0
|
Kotlin
|
0
| 0
|
f47d092399c3e395381406b7a0048c0795d332b9
| 914
|
aoc-2021
|
MIT License
|
sdk/src/test/java/com/exponea/sdk/FlushManagerTest.kt
|
yegorsch
| 138,986,195
| true
|
{"Kotlin": 211964, "Java": 719}
|
package com.exponea.sdk
import com.exponea.sdk.manager.ExponeaMockServer
import com.exponea.sdk.manager.FlushManager
import com.exponea.sdk.models.ExponeaConfiguration
import com.exponea.sdk.models.FlushMode
import com.exponea.sdk.repository.EventRepository
import okhttp3.mockwebserver.MockWebServer
import org.junit.AfterClass
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import kotlin.test.assertEquals
@RunWith(RobolectricTestRunner::class)
class FlushManagerTest {
companion object {
val configuration = ExponeaConfiguration()
val server = MockWebServer()
@BeforeClass @JvmStatic
fun setup() {
configuration.baseURL = server.url("/").toString()
configuration.projectToken = "projectToken"
configuration.authorization = "projectAuthorization"
}
@AfterClass
fun tearDown() {
server.shutdown()
}
}
lateinit var manager: FlushManager
lateinit var repo: EventRepository
@Before
fun init() {
val context = RuntimeEnvironment.application
Exponea.init(context, configuration)
Exponea.flushMode = FlushMode.MANUAL
repo = Exponea.component.eventRepository
manager = Exponea.component.flushManager
}
@Test
fun flushEvents_ShouldPass() {
ExponeaMockServer.setResponseSuccess(server,"tracking/track_event_success.json")
manager.flushData()
manager.onFlushFinishListener = {
assertEquals(0, repo.all().size)
}
}
@Test
fun flushEvents_ShouldFail() {
ExponeaMockServer.setResponseError(server,"tracking/track_event_failed.json")
manager.flushData()
manager.onFlushFinishListener = {
assertEquals(1, repo.all().size)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
6a5420bb73cf4abe3a2bd76c2ccfae123dbe3902
| 1,963
|
exponea-android-sdk
|
Apache License 2.0
|
src/main/kotlin/com/github/secretx33/whisperjsontosrt/Util.kt
|
SecretX33
| 640,121,315
| false
| null |
package com.github.secretx33.whisperjsontosrt
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.databind.DeserializationFeature
import com.fasterxml.jackson.databind.ObjectMapper
import com.github.secretx33.whisperjsontosrt.exception.QuitApplicationException
import java.io.InputStream
import java.nio.file.Path
import java.time.LocalTime
import java.time.format.DateTimeFormatter
import java.util.Locale
import kotlin.io.path.ExperimentalPathApi
import kotlin.io.path.createDirectories
import kotlin.io.path.createFile
import kotlin.io.path.deleteIfExists
import kotlin.io.path.deleteRecursively
import kotlin.io.path.exists
import kotlin.io.path.isDirectory
import kotlin.io.path.outputStream
import kotlin.reflect.KProperty0
import kotlin.reflect.jvm.isAccessible
import kotlin.time.Duration.Companion.seconds
val jackson: ObjectMapper by lazy(LazyThreadSafetyMode.NONE) {
ObjectMapper().findAndRegisterModules().apply {
setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL)
disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
}
}
fun Path.createFileIfNotExists(): Path {
if (exists()) return this
parent?.createDirectories()
return createFile()
}
val formatter: DateTimeFormatter = DateTimeFormatter.ofPattern("HH:mm:ss,SSS", Locale.US)
fun Double.formatSeconds(): String {
val time = LocalTime.ofNanoOfDay(seconds.inWholeNanoseconds)
return formatter.format(time)
}
fun printError(message: String) = System.err.println(message)
fun exitWithMessage(message: String): Nothing = throw QuitApplicationException(message)
fun InputStream.copyTo(file: Path) {
require(!file.isDirectory()) { "file must not be a directory, file = $file" }
file.createFileIfNotExists()
buffered().use { inputStream ->
file.outputStream().buffered().use(inputStream::copyTo)
}
}
fun Path.deleteIfExistsSilently() = try {
deleteIfExists()
} catch (_: Exception) {
}
@OptIn(ExperimentalPathApi::class)
fun Path.deleteRecursivelySilently() = try {
deleteRecursively()
deleteIfExists()
} catch (_: Exception) {
}
/**
* Returns true if a lazy property reference has been initialized, or if the property is not lazy.
*/
val KProperty0<*>.isLazyInitialized: Boolean
get() {
if (this !is Lazy<*>) return true
isAccessible = true
return (getDelegate() as Lazy<*>).isInitialized()
}
| 0
|
Kotlin
|
0
| 1
|
99f0fafe0419c6be8c39e5d1fed9c024200299f9
| 2,417
|
WhisperJsonToSrt
|
MIT License
|
src/main/kotlin/com/github/gbrowser/services/providers/CachingFavIconLoader.kt
|
edgafner
| 294,787,892
| false
|
{"Kotlin": 185262}
|
package com.github.gbrowser.services.providers
import com.github.benmanes.caffeine.cache.Caffeine
import com.intellij.openapi.Disposable
import com.intellij.openapi.components.Service
import com.intellij.util.ImageLoader
import java.net.URI
import java.net.URL
import java.util.concurrent.CompletableFuture
import java.util.concurrent.TimeUnit
import javax.swing.Icon
import javax.swing.ImageIcon
@Service(Service.Level.APP)
class CachingFavIconLoader : Disposable {
private val favIconCache = Caffeine.newBuilder()
.expireAfterWrite(5, TimeUnit.MINUTES)
.build<String, CompletableFuture<Icon?>>()
fun loadFavIcon(url: String, size: Int = 32, targetSize: Int = 16): CompletableFuture<Icon?> {
return favIconCache.get(url) { loadImageAsync(url, size, targetSize) }
}
private fun loadImageAsync(url: String, size: Int, targetSize: Int): CompletableFuture<Icon?> {
return CompletableFuture.supplyAsync {
try {
val domain = getDomainName(url.trim())
val iconUrl = URL("https://www.google.com/s2/favicons?domain=$domain&sz=$size")
ImageLoader.loadFromUrl(iconUrl)?.let { iconImage ->
val iconScaled = ImageLoader.scaleImage(iconImage, targetSize)
ImageIcon(iconScaled)
}
} catch (e: Exception) {
null
}
}
}
//private fun getDomainName(url: String): String {
// // Implement this function to extract the domain from the URL if not already done.
// return URL(url).host
//}
private fun getDomainName(url: String): String {
return try {
URI(url).host?.removePrefix("www.")?.removeSuffix("/") ?: url
} catch (e: Exception) {
url.removePrefix("www.").removeSuffix("/")
}
}
override fun dispose() {
favIconCache.cleanUp()
}
}
| 2
|
Kotlin
|
16
| 59
|
79243ea42866da447d790af2653763fed3fc9eaf
| 1,777
|
GBrowser
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.