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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
stars-core/src/main/kotlin/tools/aqua/stars/core/metric/utils/ApplicationStartTimeHolder.kt | tudo-aqua | 665,019,758 | false | null | /*
* Copyright 2023 The STARS Project 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.stars.core.metric.utils
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
/**
* This singleton holds the current date and time at the start of the application. It is used to
* persist a consistent folder name for all exported files.
*/
object ApplicationStartTimeHolder {
/** Holds the [LocalDateTime] at the start of the application. */
private val applicationStartTime: LocalDateTime = LocalDateTime.now()
/** Holds the [LocalDateTime] at the start of the application in the yyyy-MM-dd-HH-mm format. */
val applicationStartTimeString: String =
applicationStartTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm"))
}
| 3 | null | 2 | 9 | 4ec72213d2cc89d8df37ccc95b9adfdb89958e48 | 1,335 | stars | Apache License 2.0 |
src/test/kotlin/UnitTest.kt | Pascal-Institute | 730,722,004 | false | {"Kotlin": 30233} | import komat.Converter.Companion.toVect
import komat.Converter.Companion.vectToMat
import komat.Generator.Companion.mat
import komat.space.Mat.Companion.times
import komat.space.Vect
import komat.type.Axis
import komat.type.Padding
import org.junit.jupiter.api.Assertions.assertNotEquals
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import kotlin.test.assertEquals
class MatTest {
val mat1 = mat {
v(1, 2)
v(3, 4)
}
val mat2 = mat {
v(4, 3)
v(2, 1)
}
val mat3 = mat {
v(0, 0, 0, 0, 0)
v(0, 2, 3, 0, 1)
v(1, 1, 0, 1, 0)
v(0, 2, 0, 0, 0)
}
val mat4 = mat {
v(1, 0, 0, 0)
v(0, 2, 3, 0)
v(1, 1, 3, 1)
v(0, 2, 0, 4)
}
val mat5 = mat {
v(1, 3, 4, 1)
v(1, 2, -3, 2)
v(2, 6, 5, 6)
v(3, 4, 5, 9)
}
val mat6 = mat {
v(2, 1, 3)
v(-1, 0, 2)
v(4, 3, 1)
}
val mat7 = mat {
v(1, 2, 3, 4)
v(2, 4, 5, 6)
v(3, 5, 7, 8)
v(4, 6, 8, 10)
}
val mat8 = mat {
v(2, 1, -1)
v(-3, -1, 2)
v(-2, 1, 2)
}
val mat9 = mat {
v(1, 2, 3)
v(2, 4, 6)
v(3, 6, 9)
}
val mat10 = mat {
v(3.0 / 7, 2.0 / 7, 6.0 / 7)
v(-6.0 / 7, 3.0 / 7, 2.0 / 7)
v(2.0 / 7, 6.0 / 7, -3.0 / 7)
}
@Test
fun `test toMat`() {
val mutablelistVect = mutableListOf<Vect>()
mutablelistVect.add(Vect(1, 1, 1, 1, 1))
mutablelistVect.add(Vect(2, 2, 2, 2, 2))
mutablelistVect.add(Vect(3, 3, 3, 3, 3))
mutablelistVect.vectToMat().element.contentEquals(
mat {
v(1, 1, 1, 1, 1)
v(2, 2, 2, 2, 2)
v(3, 3, 3, 3, 3)
}.element
)
}
@Test
fun `test toVect`() {
val list = mat3.toVect()
println(list)
}
@Test
fun `test project`() {
val a = Vect(2, 3, 4)
val b = Vect(1, 0, 0)
a.project(b).element.contentEquals(
Vect(2, 0, 0).element
)
}
@Test
fun `test gramSchmidt`() {
/* val u1 = Vect(3,1)
val u2 = Vect(2,2)
assertEquals( u2.gramSchmidt(u1).element,
Vect(-0.4, 1.2).element)*/
}
@Test
fun `test copy`() {
val copy = mat1.copy()
assertNotEquals(
copy,
mat1
)
mat1.element.contentEquals(copy.element)
}
@Test
fun `test isOrthogonal`() {
assertEquals(mat10.isOrthogonal(), true)
}
@Test
fun `test invalid matrix size`() {
assertThrows<IllegalArgumentException> {
mat {
v(1, 2)
v(1)
}
}
}
@Test
fun `test plus`() {
mat {
v(5, 5)
v(5, 5)
}.element.contentEquals(mat1.plus(mat2).element)
}
@Test
fun `test minus`() {
mat {
v(-3, -1)
v(1, 3)
}.element.contentEquals(mat1.minus(mat2).element)
}
@Test
fun `test flip`() {
mat1.flip(Axis.HORIZONTAL).element.contentEquals(mat {
v(3, 4)
v(1, 2)
}.element)
mat {
v(1, 2)
v(3, 4)
}.flip(Axis.VERTICAL).element.contentEquals(mat {
v(2, 1)
v(4, 3)
}.element)
}
@Test
fun `test pad`() {
mat9.pad(Padding.ZERO, 1).element.contentEquals(
mat {
v(0.0, 0.0, 0.0, 0.0, 0.0)
v(0.0, 1.0, 2.0, 3.0, 0.0)
v(0.0, 4.0, 5.0, 6.0, 0.0)
v(0.0, 7.0, 8.0, 9.0, 0.0)
v(0.0, 0.0, 0.0, 0.0, 0.0)
}.element
)
}
@Test
fun `test scalar multiplication`() {
(3.0 * mat1).element.contentEquals(mat {
v(3.0, 6.0)
v(9.0, 12.0)
}.element)
}
@Test
fun `test exchange column`() {
mat1.exchangeColumn(0, 1).element.contentEquals(mat {
v(2, 1)
v(4, 3)
}.element)
}
@Test
fun `test exchange row`() {
mat {
v(3, 4)
v(1, 2)
}.element.contentEquals(
mat1.exchangeRow(0, 1).element
)
}
@Test
fun `test adjugate`() {
mat6.adjugate().element.contentEquals(mat {
v(-6, 8, 2)
v(9, -10, -7)
v(-3, -2, 1)
}.element)
}
@Test
fun `test inverse`() {
mat7.inverse().element.contentEquals(mat {
v(-1, -1, 0, 1)
v(-1, 2, -1, 0)
v(0, -1, 2, -1)
v(1, 0, -1, 0.5)
}.element)
}
@Test
fun `test transpose`() {
mat {
v(1, 2)
v(3, 4)
v(5, 6)
}.transpose().element.contentEquals(mat {
v(1, 3, 5)
v(2, 4, 6)
}.element)
}
@Test
fun `test transpose twice`() {
mat {
v(1, 2)
v(3, 4)
v(5, 6)
}.transpose().transpose().element.contentEquals(
mat {
v(1, 2)
v(3, 4)
v(5, 6)
}.element
)
}
@Test
fun `test removeColumnAt`() {
mat4.removeColumnAt(1).element.contentEquals(mat {
v(1, 0, 0)
v(0, 3, 0)
v(1, 3, 1)
v(0, 0, 4)
}.element)
}
@Test
fun `test removeRowAt`() {
mat4.removeRowAt(2).element.contentEquals(mat {
v(1, 0, 0, 0)
v(0, 2, 3, 0)
v(0, 2, 0, 4)
}.element)
}
@Test
fun `test removeAt`() {
mat4.removeAt(2, 1).element.contentEquals(mat {
v(1, 0, 0)
v(0, 3, 0)
v(0, 0, 4)
}.element)
}
@Test
fun `test concat`() {
mat1.concat(
mat { v(5, 6) }, Axis.HORIZONTAL
).element.contentEquals(
mat {
v(1, 2)
v(3, 4)
v(5, 6)
}.element
)
mat2.concat(
mat {
v(5)
v(6)
}, Axis.VERTICAL
).element.contentEquals(
mat {
v(4, 3, 5)
v(2, 1, 6)
}.element
)
}
@Test
fun `test getColsInRange`() {
mat {
v(1, 2, 3)
v(4, 5, 6)
}.getColumnsInRange(0, 2).element.contentEquals(
mat {
v(1, 2)
v(4, 5)
}.element
)
}
@Test
fun `test det`() {
assertEquals(
mat5.det(), 115.0
)
}
@Test
fun `test ref`() {
mat {
v(1, 1, 0, 1, 0)
v(0, 2, 3, 0, 1)
v(0, 0, -3, 0, -1)
v(0, 0, 0, 0, 0)
}.element.contentEquals(mat3.ref().element)
}
@Test
fun `test rref`() {
mat {
v(1, 0, 0, 1, 0)
v(0, 1, 0, 0, 0)
v(0, 0, 1, 0, 1.0 / 3)
v(0, 0, 0, 0, 0)
}.element.contentEquals(mat3.rref().element)
}
@Test
fun `test luDecompose`() {
val copy = mat9.copy()
val luDecomposeValue = copy.luDecompose()
luDecomposeValue.first.element.contentEquals(mat {
v(1, 0, 0)
v(2, 1, 0)
v(3, 0, 1)
}.element)
luDecomposeValue.second.element.contentEquals(mat {
v(1, 2, 3)
v(0, 0, 0)
v(0, 0, 0)
}.element)
val restore = (luDecomposeValue.first * luDecomposeValue.second)
restore.element.contentEquals(mat {
v(1.0, 2.0, 3.0)
v(2.0, 4.0, 6.0)
v(3.0, 6.0, 9.0)
}.element)
}
@Test
fun `test solve`() {
mat {
v(1, 0, 0)
v(0, 1, 0)
v(0, 0, 1)
}.solve(
mat
{
v(1)
v(1)
v(1)
})
}
@Test
fun `test sum`() {
assertEquals(mat1.sum(), 10.0)
}
@Test
fun `test mean`() {
assertEquals(mat1.mean(), 2.5)
}
@Test
fun `test max`() {
assertEquals(mat1.max(), 4.0)
}
@Test
fun `test min`() {
assertEquals(mat1.min(), 1.0)
}
@Test
fun `test appendCol`() {
var mat4 = mat1.copy()
mat4.appendColumn(mutableListOf(3.0, 5.0))
mat4.element.contentEquals(mat {
v(1, 2, 3)
v(3, 4, 5)
}.element)
}
@Test
fun `test print`() {
mat1.print()
}
} | 0 | Kotlin | 0 | 1 | 8ce6e418194cdce2ecffbb4ede7b2bded3c3bb3c | 8,811 | komat | MIT License |
sdk/src/main/java/network/onepay/sdk/listener/SimpleOnSuccessListener.kt | 1pay-network | 720,347,036 | false | {"Kotlin": 10564} | package network.onepay.sdk.listener
import network.onepay.sdk.dto.PaymentResponse
open class SimpleOnSuccessListener : OnOnePaySuccessListener {
override fun onSuccess(response: PaymentResponse) {
// TODO implement function
}
override fun onFailed(response: PaymentResponse) {
// TODO implement function
}
} | 0 | Kotlin | 0 | 0 | 7f98f53e6a9fa40d7f36d1fc6ed86bf6ba8d8cac | 343 | 1pay-android-sdk | Apache License 2.0 |
app/src/main/java/com/example/kbbikamusbesarbahasaindonesia/presentation/home/MainActivity.kt | arrazyfathan | 469,381,116 | false | null | package com.example.kbbikamusbesarbahasaindonesia.presentation.home
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.example.kbbikamusbesarbahasaindonesia.R
import com.example.kbbikamusbesarbahasaindonesia.databinding.ActivityMainBinding
import com.example.kbbikamusbesarbahasaindonesia.utils.viewBinding
class MainActivity : AppCompatActivity() {
private val binding by viewBinding(ActivityMainBinding::inflate)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
setupBottomNavigationView()
}
private fun setupBottomNavigationView() {
val navHostFragment =
supportFragmentManager.findFragmentById(R.id.nav_host_fragment_container) as NavHostFragment
val navController = navHostFragment.navController
binding.bottomNavigationView.apply {
setupWithNavController(navController)
itemIconTintList = null
}
}
}
| 0 | Kotlin | 1 | 5 | 52bebe8c7b86e03959cfffb66ee245ed92969e1f | 1,129 | kbbi | Apache License 2.0 |
src/main/kotlin/com/sultanofcardio/openapi/models/Response.kt | sultanofcardio | 354,597,121 | false | null | package com.sultanofcardio.openapi.models
import com.sultanofcardio.Model
import com.sultanofcardio.json
import org.json.JSONObject
class Response(
var description: String? = "null",
var content: Content? = null
) : Model {
override fun json(): JSONObject = json {
"description" to description
content?.let {
"content" to it.json()
}
}
} | 3 | Kotlin | 0 | 2 | 8e3f3d31111ada6bb7ee5cf43e30ef7961969ffe | 392 | openapi-ktor | Apache License 2.0 |
core/data/src/main/java/de/cleema/android/core/data/network/SponsorDataSource.kt | sandstorm | 840,235,083 | false | {"Kotlin": 955115, "Ruby": 1773} | package de.cleema.android.core.data.network
import de.cleema.android.core.data.network.requests.BecomeSponsorRequest
interface SponsorDataSource {
suspend fun becomeSponsor(request: BecomeSponsorRequest): Result<Unit>
}
| 0 | Kotlin | 0 | 1 | ddcb7ddedbbefb8045e7299e14a2ad47329fc53e | 226 | cleema-android | MIT License |
app/src/main/java/com/istu/schedule/ui/icons/Logo152.kt | imysko | 498,018,609 | false | null | package com.istu.schedule.ui.icons
import androidx.compose.material.icons.Icons
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.group
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
public val Icons.Logo152: ImageVector
get() {
if (_logo152 != null) {
return _logo152!!
}
_logo152 = Builder(name = "Logo152", defaultWidth = 152.0.dp, defaultHeight = 150.0.dp,
viewportWidth = 152.0f, viewportHeight = 150.0f).apply {
group {
path(fill = SolidColor(Color(0xFFF2D05C)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(148.995f, 0.696f)
curveTo(131.311f, -0.553f, 113.867f, 3.804f, 99.105f, 12.858f)
lineTo(107.108f, 44.498f)
lineTo(133.946f, 31.17f)
lineTo(151.599f, 0.88f)
lineTo(148.995f, 0.696f)
close()
}
path(fill = SolidColor(Color(0xFFF79F5E)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(151.599f, 0.88f)
lineTo(107.108f, 44.498f)
lineTo(139.381f, 52.344f)
curveTo(148.616f, 37.872f, 153.06f, 20.769f, 151.786f, 3.432f)
lineTo(151.599f, 0.88f)
close()
}
path(fill = SolidColor(Color(0xFF3D68ED)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(106.168f, 97.735f)
lineTo(105.146f, 88.847f)
lineTo(73.351f, 99.31f)
lineTo(64.195f, 128.995f)
lineTo(85.116f, 149.506f)
lineTo(89.076f, 145.623f)
curveTo(101.91f, 133.041f, 108.2f, 115.415f, 106.168f, 97.735f)
close()
}
path(fill = SolidColor(Color(0xFF3D68ED)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(52.807f, 45.42f)
curveTo(34.772f, 43.427f, 16.794f, 49.595f, 3.961f, 62.176f)
lineTo(0.0f, 66.059f)
lineTo(20.921f, 86.57f)
lineTo(51.584f, 77.393f)
lineTo(61.872f, 46.422f)
lineTo(52.807f, 45.42f)
close()
}
path(fill = SolidColor(Color(0xFFF2D05C)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(1.293f, 115.175f)
lineTo(17.304f, 99.478f)
lineTo(23.601f, 105.651f)
lineTo(7.59f, 121.349f)
lineTo(1.293f, 115.175f)
close()
}
path(fill = SolidColor(Color(0xFFF79F5E)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(28.69f, 142.041f)
lineTo(44.701f, 126.344f)
lineTo(50.998f, 132.517f)
lineTo(34.987f, 148.215f)
lineTo(28.69f, 142.041f)
close()
}
path(fill = SolidColor(Color(0xFFEB4B4B)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(99.105f, 12.858f)
curveTo(93.846f, 16.083f, 88.925f, 19.898f, 84.46f, 24.277f)
lineTo(20.921f, 86.569f)
lineTo(42.558f, 107.782f)
lineTo(110.414f, 68.835f)
lineTo(119.243f, 32.601f)
lineTo(99.105f, 12.858f)
close()
}
path(fill = SolidColor(Color(0xFFBD3C3C)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(42.558f, 107.782f)
lineTo(64.195f, 128.995f)
lineTo(127.734f, 66.702f)
curveTo(132.199f, 62.324f, 136.091f, 57.5f, 139.381f, 52.345f)
lineTo(119.243f, 32.601f)
lineTo(42.558f, 107.782f)
close()
}
path(fill = SolidColor(Color(0xFFF2D05C)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(7.095f, 136.376f)
lineTo(10.244f, 139.463f)
lineTo(23.78f, 129.279f)
lineTo(34.168f, 116.007f)
lineTo(31.019f, 112.92f)
lineTo(7.095f, 136.376f)
close()
}
path(fill = SolidColor(Color(0xFFF79F5E)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(10.229f, 139.45f)
lineTo(34.15f, 115.998f)
lineTo(37.299f, 119.085f)
lineTo(13.378f, 142.537f)
lineTo(10.229f, 139.45f)
close()
}
path(fill = SolidColor(Color(0xFF063889)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(82.277f, 48.12f)
curveTo(76.44f, 53.842f, 76.441f, 63.119f, 82.277f, 68.842f)
lineTo(98.13f, 63.661f)
lineTo(103.414f, 48.12f)
curveTo(97.577f, 42.397f, 88.114f, 42.397f, 82.277f, 48.12f)
close()
}
path(fill = SolidColor(Color(0xFF04275A)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(103.414f, 48.12f)
lineTo(82.277f, 68.842f)
curveTo(88.114f, 74.564f, 97.577f, 74.564f, 103.414f, 68.842f)
curveTo(109.251f, 63.119f, 109.251f, 53.842f, 103.414f, 48.12f)
close()
}
}
}
.build()
return _logo152!!
}
private var _logo152: ImageVector? = null
| 4 | Kotlin | 0 | 1 | e1b40ea297e93e01a4d8ec8c236378e6a3de554d | 7,940 | Schedule-ISTU | MIT License |
server/src/main/kotlin/com/xapphire13/database/FirebaseChallengeStore.kt | Xapphire13 | 448,160,864 | false | {"TypeScript": 113135, "Kotlin": 61331, "JavaScript": 4777, "Starlark": 3656, "Shell": 1070, "Batchfile": 757, "Dockerfile": 239} | package com.xapphire13.database
import com.google.cloud.Timestamp
import com.google.cloud.firestore.DocumentReference
import com.google.cloud.firestore.DocumentSnapshot
import com.google.cloud.firestore.Firestore
import com.xapphire13.extensions.asDeferred
import com.xapphire13.extensions.await
import com.xapphire13.models.Challenge
import io.github.reactivecircus.cache4k.Cache
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit
import java.time.Instant
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.util.Date
class FirebaseChallengeStore(db: Firestore) : ChallengeStore {
private val groupsCollection = db.collection("groups")
private val usersCollection = db.collection("users")
private val futureChallengeCountCache = Cache.Builder().build<String, Int>()
private val futureChallengeCountCacheSemaphore = Semaphore(1)
override suspend fun listChallenges(groupId: String): List<Challenge> {
val challengesCollection = groupsCollection.document(groupId).collection("challenges")
val documents =
challengesCollection
.listDocuments()
.map { it.get().asDeferred(Dispatchers.IO) }
.awaitAll()
return documents.map { it.toChallenge(groupId) }
}
override suspend fun getChallenge(groupId: String, id: String): Challenge? {
val challengesCollection = groupsCollection.document(groupId).collection("challenges")
val document = challengesCollection.document(id).get().await(Dispatchers.IO)
return if (document.exists()) document.toChallenge(groupId) else null
}
override suspend fun getCurrentChallenge(groupId: String): Challenge? {
val challengesCollection = groupsCollection.document(groupId).collection("challenges")
val query =
challengesCollection
.whereGreaterThan("endsAt", Timestamp.now())
.get()
.await(Dispatchers.IO)
var currentChallenge = query.firstOrNull()?.toChallenge(groupId)
if (currentChallenge == null) {
val nextChallenge =
challengesCollection
.whereEqualTo("endsAt", null)
.get()
.await(Dispatchers.IO)
.documents
.randomOrNull()
if (nextChallenge != null) {
val nextChallengeDueDate =
Instant.now()
.atZone(ZoneOffset.UTC)
.let {
if (it.hour >= 15) {
it.plusDays(1)
} else {
it
}
}
.let {
ZonedDateTime.of(
it.year,
it.monthValue,
it.dayOfMonth,
15,
0,
0,
0,
ZoneOffset.UTC
)
.toInstant()
}
nextChallenge
.reference
.update("endsAt", Timestamp.of(Date.from(nextChallengeDueDate)))
.await(Dispatchers.IO)
currentChallenge =
nextChallenge.toChallenge(groupId).copy(endsAt = nextChallengeDueDate.toString())
this.futureChallengeCountCacheSemaphore.withPermit {
this.futureChallengeCountCache.get(groupId)?.let { prev ->
this.futureChallengeCountCache.put(groupId, prev.minus(1))
}
}
}
}
return currentChallenge
}
override suspend fun getPastChallenges(groupId: String): List<Challenge> {
val challengesCollection = groupsCollection.document(groupId).collection("challenges")
val query =
challengesCollection
.whereLessThanOrEqualTo("endsAt", Timestamp.now())
.get()
.await(Dispatchers.IO)
return query.documents.map { it.toChallenge(groupId) }
}
override suspend fun getFutureChallengeCount(groupId: String): Int {
val challengesCollection = groupsCollection.document(groupId).collection("challenges")
val count = this.futureChallengeCountCacheSemaphore.withPermit {
this.futureChallengeCountCache.get(groupId) {
challengesCollection
.whereEqualTo("endsAt", null)
.get()
.await(Dispatchers.IO)
.documents
.count()
}
}
return count
}
override suspend fun addChallenge(groupId: String, challengeName: String, userId: String) {
val challengesCollection = groupsCollection.document(groupId).collection("challenges")
challengesCollection
.add(
mapOf(
"name" to challengeName,
"createdBy" to usersCollection.document(userId),
"endsAt" to null
)
)
.await(Dispatchers.IO)
this.futureChallengeCountCacheSemaphore.withPermit {
this.futureChallengeCountCache.get(groupId)?.let { prev ->
this.futureChallengeCountCache.put(groupId, prev.plus(1))
}
}
}
private fun DocumentSnapshot.toChallenge(groupId: String) =
Challenge(
id,
groupId,
name = getString("name")!!,
createdBy = (get("createdBy") as DocumentReference).id,
endsAt =
getTimestamp("endsAt")?.seconds?.let {
Instant.ofEpochSecond(it).toString()
},
)
}
| 5 | TypeScript | 0 | 1 | 614140aa16d7f711a277d79052d8bf9c84dbc71a | 6,131 | PhotoChallenge | MIT License |
sdk/src/main/java/io/wso2/android/api_authenticator/sdk/providers/util/AuthenticatorProviderUtil.kt | Achintha444 | 731,559,375 | false | {"Kotlin": 381654, "Java": 1580} | package io.wso2.android.api_authenticator.sdk.provider.util
import io.wso2.android.api_authenticator.sdk.models.autheniticator_type.AuthenticatorType
import io.wso2.android.api_authenticator.sdk.util.AuthenticatorTypeUtil
/**
* Utility class for the [AuthenticatorProvider]
*
* This class contains utility methods that are used by the [AuthenticatorProvider]
*/
object AuthenticatorProviderUtil {
/**
* Get the authenticator type from the authenticator type list
*
* @param authenticators List of authenticators
* @param authenticatorTypeString Authenticator type string
*
* @return [AuthenticatorType] object, `null` if the authenticator type is not found
* or if there are duplicates authenticators of the given authenticator type in the given step
*/
fun getAuthenticatorTypeFromAuthenticatorTypeList(
authenticators: ArrayList<AuthenticatorType>,
authenticatorTypeString: String
): AuthenticatorType? {
val authenticatorType: AuthenticatorType =
AuthenticatorTypeUtil.getAuthenticatorTypeFromAuthenticatorTypeList(
authenticators,
authenticatorTypeString
) ?: return null
val hasDuplicates: Boolean = AuthenticatorTypeUtil.hasDuplicatesAuthenticatorsInGivenStep(
authenticators,
authenticatorTypeString
)
return if (hasDuplicates) null else authenticatorType
}
/**
* Get the authenticator type from the authenticator type list
*
* @param authenticators List of authenticators
* @param authenticatorIdString Authenticator id string
*
* @return [AuthenticatorType] object, `null` if the authenticator type is not found
* or if there are duplicates authenticators of the given authenticator type in the given step
*/
fun getAuthenticatorTypeFromAuthenticatorTypeListOnAuthenticatorId(
authenticators: ArrayList<AuthenticatorType>,
authenticatorIdString: String
): AuthenticatorType? {
val authenticatorType: AuthenticatorType =
AuthenticatorTypeUtil.getAuthenticatorTypeFromAuthenticatorTypeListOnAuthenticatorId(
authenticators,
authenticatorIdString
) ?: return null
val hasDuplicates: Boolean =
AuthenticatorTypeUtil.hasDuplicatesAuthenticatorsInGivenStepOnAuthenticatorId(
authenticators,
authenticatorIdString
)
return if (hasDuplicates) null else authenticatorType
}
} | 0 | Kotlin | 0 | 0 | a4928ccd62e8ca1807e218d78c0270df65d96a5c | 2,578 | wso2-android-api-authenticator-sdk | Apache License 2.0 |
src/main/kotlin/no/nav/amt_altinn_acl/controller/RolleController.kt | navikt | 497,788,149 | false | {"Kotlin": 74889, "PLpgSQL": 635, "Dockerfile": 152} | package no.nav.amt_altinn_acl.controller
import no.nav.amt_altinn_acl.domain.RolleType
import no.nav.amt_altinn_acl.service.AuthService
import no.nav.amt_altinn_acl.service.RolleService
import no.nav.amt_altinn_acl.utils.Issuer
import no.nav.security.token.support.core.api.ProtectedWithClaims
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("/api/v1/rolle")
class RolleController(
private val authService: AuthService,
private val rolleService: RolleService
) {
@PostMapping("/tiltaksarrangor")
@ProtectedWithClaims(issuer = Issuer.AZURE_AD)
fun hentTiltaksarrangorRoller(@RequestBody hentRollerRequest: HentRollerRequest): HentRollerResponse {
authService.verifyRequestIsMachineToMachine()
hentRollerRequest.validatePersonident()
val roller = rolleService.getRollerForPerson(hentRollerRequest.personident)
return HentRollerResponse(
roller.map { rolle -> HentRollerResponse.TiltaksarrangorRoller(rolle.organisasjonsnummer, rolle.roller.map { it.rolleType }) }
)
}
data class HentRollerRequest(val personident: String) {
fun validatePersonident() {
if (personident.trim().length != 11 || !personident.trim().matches("""\d{11}""".toRegex())) {
throw IllegalArgumentException("Ugyldig personident")
}
}
}
data class HentRollerResponse(
val roller: List<TiltaksarrangorRoller>
) {
data class TiltaksarrangorRoller(
val organisasjonsnummer: String,
val roller: List<RolleType>,
)
}
}
| 0 | Kotlin | 0 | 0 | 29d2cd774c823aa9369661843b98654d797fcd93 | 1,665 | amt-altinn-acl | MIT License |
core/src/main/kotlin/live/channel/LiveVoiceChannel.kt | emrul | 338,278,659 | true | {"Kotlin": 1114973} | package dev.kord.core.live.channel
import dev.kord.common.annotation.KordPreview
import dev.kord.core.entity.KordEntity
import dev.kord.core.entity.channel.VoiceChannel
import dev.kord.core.event.Event
import dev.kord.core.event.channel.VoiceChannelCreateEvent
import dev.kord.core.event.channel.VoiceChannelDeleteEvent
import dev.kord.core.event.channel.VoiceChannelUpdateEvent
import dev.kord.core.event.guild.GuildDeleteEvent
@KordPreview
fun VoiceChannel.live() = LiveVoiceChannel(this)
@KordPreview
class LiveVoiceChannel(channel: VoiceChannel) : LiveChannel(), KordEntity by channel {
override var channel: VoiceChannel = channel
private set
override fun update(event: Event) = when (event) {
is VoiceChannelCreateEvent -> channel = event.channel
is VoiceChannelUpdateEvent -> channel = event.channel
is VoiceChannelDeleteEvent -> shutDown()
is GuildDeleteEvent -> shutDown()
else -> Unit
}
} | 0 | null | 0 | 0 | 746e04457247767d0607cd695da054dd7ccc72ad | 966 | kord | MIT License |
src/main/kotlin/com/rustyrazorblade/code2snippets/CommentMatcher.kt | rustyrazorblade | 200,167,325 | false | null | package com.rustyrazorblade.code2snippets
class CommentMatcher(extension: String) {
val regex : Regex
class UnsupportedTypeException(message: String) : Throwable()
companion object {
val types = mapOf("kt" to CommentDeliminator.DoubleSlash,
"java" to CommentDeliminator.DoubleSlash,
"fio" to CommentDeliminator.Hash,
"py" to CommentDeliminator.Hash,
"c" to CommentDeliminator.DoubleSlash,
"rb" to CommentDeliminator.Hash,
"php" to CommentDeliminator.DoubleSlash,
"erl" to CommentDeliminator.Percent,
"rs" to CommentDeliminator.DoubleSlash,
"js" to CommentDeliminator.DoubleSlash,
"cpp" to CommentDeliminator.DoubleSlash,
"swift" to CommentDeliminator.DoubleSlash)
}
init {
val delim = types.getOrElse(extension) {
throw UnsupportedTypeException("Extention $extension not supported, how did you even get here?")
}
// spaces, comment, spaces, :marker spaces
regex = """\s*${delim.s}\s+:([a-z][a-z0-9]*)\s*""".toRegex()
}
/**
* Processes a String line of code, transforming it to a Line, which may be either a special comment or a normal line
*/
fun process(line: String) : Line {
val tmp = regex.find(line)
if(tmp != null) {
return Line.CommentMarker(tmp!!.groupValues[1])
} else {
return Line.Code(line)
}
}
}
| 0 | Kotlin | 0 | 0 | f9106b4096f63e1b4f3e3d4645dd704debb847e7 | 1,548 | code2snippets | Apache License 2.0 |
kotlin/app/src/main/java/com/huawei/mapkitsample/utils/NetClient.kt | arata-1972 | 303,308,618 | true | {"Kotlin": 158516, "C#": 7513, "Java": 5989} | /*
* Copyright 2019 Square, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.huawei.mapkitsample.utils
import com.huawei.hms.maps.model.LatLng
import okhttp3.*
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.io.UnsupportedEncodingException
import java.net.URLEncoder
import java.util.concurrent.TimeUnit
/**
* NetClient
*/
class NetClient private constructor() {
// Please place your API KEY here. If the API KEY contains special characters, you need to encode it using
// encodeURI.
private val mDefaultKey = "API KEY"
private val mWalkingRoutePlanningURL =
"https://mapapi.cloud.huawei.com/mapApi/v1/routeService/walking"
private val mBicyclingRoutePlanningURL =
"https://mapapi.cloud.huawei.com/mapApi/v1/routeService/bicycling"
private val mDrivingRoutePlanningURL =
"https://mapapi.cloud.huawei.com/mapApi/v1/routeService/driving"
fun initOkHttpClient(): OkHttpClient? {
if (client == null) {
client = OkHttpClient.Builder()
.readTimeout(
10000,
TimeUnit.MILLISECONDS
) // Set the read timeout.
.connectTimeout(
10000,
TimeUnit.MILLISECONDS
) // Set the connect timeout.
.build()
}
return client
}
/**
* @param latLng1 origin latitude and longitude
* @param latLng2 destination latitude and longitude
* @param needEncode dose the api key need to be encoded
* @return
*/
fun getWalkingRoutePlanningResult(
latLng1: LatLng,
latLng2: LatLng,
needEncode: Boolean
): Response? {
var key = mDefaultKey
if (needEncode) {
try {
key = URLEncoder.encode(mDefaultKey, "UTF-8")
} catch (e: UnsupportedEncodingException) {
e.printStackTrace()
}
}
val url = "$mWalkingRoutePlanningURL?key=$key"
var response: Response? = null
val origin = JSONObject()
val destination = JSONObject()
val json = JSONObject()
try {
origin.put("lat", latLng1.latitude)
origin.put("lng", latLng1.longitude)
destination.put("lat", latLng2.latitude)
destination.put("lng", latLng2.longitude)
json.put("origin", origin)
json.put("destination", destination)
val requestBody = RequestBody.create(
JSON,
json.toString()
)
val request =
Request.Builder().url(url).post(requestBody).build()
response =
netClient!!.initOkHttpClient()!!.newCall(request).execute()
} catch (e: JSONException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
return response
}
/**
* @param latLng1 origin latitude and longitude
* @param latLng2 destination latitude and longitude
* @param needEncode dose the api key need to be encoded
* @return
*/
fun getBicyclingRoutePlanningResult(
latLng1: LatLng,
latLng2: LatLng,
needEncode: Boolean
): Response? {
var key = mDefaultKey
if (needEncode) {
try {
key = URLEncoder.encode(mDefaultKey, "UTF-8")
} catch (e: UnsupportedEncodingException) {
e.printStackTrace()
}
}
val url = "$mBicyclingRoutePlanningURL?key=$key"
var response: Response? = null
val origin = JSONObject()
val destination = JSONObject()
val json = JSONObject()
try {
origin.put("lat", latLng1.latitude)
origin.put("lng", latLng1.longitude)
destination.put("lat", latLng2.latitude)
destination.put("lng", latLng2.longitude)
json.put("origin", origin)
json.put("destination", destination)
val requestBody = RequestBody.create(
JSON,
json.toString()
)
val request =
Request.Builder().url(url).post(requestBody).build()
response =
netClient!!.initOkHttpClient()!!.newCall(request).execute()
} catch (e: JSONException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
return response
}
/**
* @param latLng1 origin latitude and longitude
* @param latLng2 destination latitude and longitude
* @param needEncode dose the api key need to be encoded
* @return
*/
fun getDrivingRoutePlanningResult(
latLng1: LatLng,
latLng2: LatLng,
needEncode: Boolean
): Response? {
var key = mDefaultKey
if (needEncode) {
try {
key = URLEncoder.encode(mDefaultKey, "UTF-8")
} catch (e: UnsupportedEncodingException) {
e.printStackTrace()
}
}
val url = "$mDrivingRoutePlanningURL?key=$key"
var response: Response? = null
val origin = JSONObject()
val destination = JSONObject()
val json = JSONObject()
try {
origin.put("lat", latLng1.latitude)
origin.put("lng", latLng1.longitude)
destination.put("lat", latLng2.latitude)
destination.put("lng", latLng2.longitude)
json.put("origin", origin)
json.put("destination", destination)
val requestBody = RequestBody.create(
JSON,
json.toString()
)
val request =
Request.Builder().url(url).post(requestBody).build()
response =
netClient!!.initOkHttpClient()!!.newCall(request).execute()
} catch (e: JSONException) {
e.printStackTrace()
} catch (e: IOException) {
e.printStackTrace()
}
return response
}
companion object {
private const val TAG = "NetClient"
@JvmStatic
var netClient: NetClient? = null
get() {
if (field == null) {
field =
NetClient()
}
return field
}
private set
private var client: OkHttpClient? = null
private val JSON =
MediaType.parse("application/json; charset=utf-8")
}
init {
client = initOkHttpClient()
}
} | 0 | null | 0 | 0 | 939a4feaa8cbf217e6932a52f433849410f0d3e9 | 7,226 | MapKit | Apache License 2.0 |
app/src/main/java/com/tugcearas/bottomnavigationview/MainActivity.kt | TugceAras | 684,245,907 | false | null | package com.tugcearas.bottomnavigationview
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.NavigationUI
import com.tugcearas.bottomnavigationview.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val navHostFragment = supportFragmentManager.findFragmentById(R.id.navHostFragment) as NavHostFragment
val navController: NavController = navHostFragment.navController
NavigationUI.setupWithNavController(binding.bottomNavView,navController)
// binding.bottomNavView.itemActiveIndicatorColor = null
}
} | 0 | Kotlin | 0 | 0 | 470cdbeb510dc028778c7b6bab018fdf6277180f | 966 | BottomNavView | MIT License |
src/main/kotlin/org/jetbrains/bio/span/fit/SpanConstants.kt | JetBrains-Research | 159,559,994 | false | {"Kotlin": 330801} | package org.jetbrains.bio.span.fit
import org.jetbrains.bio.span.peaks.ModelToPeaks.relaxedLogFdr
object SpanConstants {
/**
* Default bin size used for binned centered reads coverage aggregation.
*/
const val SPAN_DEFAULT_BIN = 200
/**
* The SPAN_DEFAULT_FDR variable represents the default value for the FDR parameter.
* The FDR is a measure of the expected proportion of false positive peaks in the peak calling results.
*/
const val SPAN_DEFAULT_FDR = 0.05
/**
* Default gap value used to merge peaks, particularly useful for broad histone marks peak calling.
*/
const val SPAN_DEFAULT_GAP = 3
/**
* The default step size used for beta values in the SPAN calculation.
* Beta value is used to minimize correlation between treatment and control track.
* Step is used to iterate in the [0, 1] interval.
*/
const val SPAN_DEFAULT_BETA_STEP = 0.01
/**
* SPAN_FIT_THRESHOLD is a constant variable that represents the threshold value used
* in the SPAN peak fitting algorithm.
*/
const val SPAN_FIT_THRESHOLD = 1.0
/**
* The maximum number of iterations to perform during the fitting process in the SPAN algorithm.
*/
const val SPAN_FIT_MAX_ITERATIONS = 20
/**
* Peak calling is done in two runs - with relaxed settings and strict user-provided strict FDR.
* This value is used to compute relaxed settings, see [relaxedLogFdr] for details.
*/
const val SPAN_RELAX_POWER_DEFAULT = 0.5
/**
* Clipping allows to fine-tune boundaries of point-wise peaks according to the local signal.
*/
const val SPAN_DEFAULT_CLIP = true
/**
* Array of steps used for reducing the range by [SPAN_CLIP_STEPS] from both sides while increasing score.
* Used together with [SPAN_MAX_CLIPPED_FRACTION].
*/
val SPAN_CLIP_STEPS = intArrayOf(1, 2, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000)
/**
* The maximum fraction of length for clipped peaks, from left and from right.
*/
const val SPAN_MAX_CLIPPED_FRACTION = 0.25
/**
* Maximum threshold value used for clipping peaks by coverage.
* Defines max score of clipped region as average_noise + MAX_CLIPPED_THRESHOLD * (average_signal - average_noise)
*/
const val SPAN_MAX_CLIPPED_THRESHOLD = 0.75
} | 3 | Kotlin | 1 | 7 | fe581a3821d7bd28bafa5b8240f7a961a4c1f291 | 2,369 | span | MIT License |
fontawesome/src/de/msrd0/fontawesome/icons/FA_LAND_MINE_ON.kt | msrd0 | 363,665,023 | false | null | /* @generated
*
* This file is part of the FontAwesome Kotlin library.
* https://github.com/msrd0/fontawesome-kt
*
* This library is not affiliated with FontAwesome.
*
* 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 de.msrd0.fontawesome.icons
import de.msrd0.fontawesome.Icon
import de.msrd0.fontawesome.Style
import de.msrd0.fontawesome.Style.SOLID
/** Land Mine-on */
object FA_LAND_MINE_ON: Icon {
override val name get() = "Land Mine-on"
override val unicode get() = "e51b"
override val styles get() = setOf(SOLID)
override fun svg(style: Style) = when(style) {
SOLID -> """<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512"><path d="M312 168C312 181.3 301.3 192 288 192C274.7 192 264 181.3 264 168V24C264 10.75 274.7 0 288 0C301.3 0 312 10.75 312 24V168zM160 320C160 302.3 174.3 288 192 288H384C401.7 288 416 302.3 416 320V352H160V320zM82.74 410.5C90.87 394.3 107.5 384 125.7 384H450.3C468.5 384 485.1 394.3 493.3 410.5L520.8 465.7C531.5 486.1 516 512 492.2 512H83.78C59.99 512 44.52 486.1 55.16 465.7L82.74 410.5zM4.269 138.3C11.81 127.4 26.77 124.7 37.66 132.3L141.7 204.3C152.6 211.8 155.3 226.8 147.7 237.7C140.2 248.6 125.2 251.3 114.3 243.7L10.34 171.7C-.5568 164.2-3.275 149.2 4.269 138.3V138.3zM538.3 132.3C549.2 124.7 564.2 127.4 571.7 138.3C579.3 149.2 576.6 164.2 565.7 171.7L461.7 243.7C450.8 251.3 435.8 248.6 428.3 237.7C420.7 226.8 423.4 211.8 434.3 204.3L538.3 132.3z"/></svg>"""
else -> null
}
}
| 0 | Kotlin | 0 | 0 | b2fdb74278104be68c95e8f083fc75ab74395112 | 1,977 | fontawesome-kt | Apache License 2.0 |
core/data/src/main/kotlin/com/skydoves/pokedex/compose/core/data/repository/details/DetailsRepository.kt | skydoves | 786,132,659 | false | {"Kotlin": 168350} | /*
* Designed and developed by 2024 skydoves (<NAME>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.pokedex.compose.core.data.repository.details
import androidx.annotation.WorkerThread
import com.skydoves.pokedex.compose.core.model.PokemonInfo
import kotlinx.coroutines.flow.Flow
interface DetailsRepository {
@WorkerThread
fun fetchPokemonInfo(
name: String,
onComplete: () -> Unit,
onError: (String?) -> Unit
): Flow<PokemonInfo>
}
| 3 | Kotlin | 93 | 705 | ee2148f0c52a3611fcbdc86849c1d39fdb0c099e | 990 | pokedex-compose | Apache License 2.0 |
core/data/src/main/kotlin/com/skydoves/pokedex/compose/core/data/repository/details/DetailsRepository.kt | skydoves | 786,132,659 | false | {"Kotlin": 168350} | /*
* Designed and developed by 2024 skydoves (<NAME>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skydoves.pokedex.compose.core.data.repository.details
import androidx.annotation.WorkerThread
import com.skydoves.pokedex.compose.core.model.PokemonInfo
import kotlinx.coroutines.flow.Flow
interface DetailsRepository {
@WorkerThread
fun fetchPokemonInfo(
name: String,
onComplete: () -> Unit,
onError: (String?) -> Unit
): Flow<PokemonInfo>
}
| 3 | Kotlin | 93 | 705 | ee2148f0c52a3611fcbdc86849c1d39fdb0c099e | 990 | pokedex-compose | Apache License 2.0 |
app/src/test/kotlin/io/github/nuhkoca/libbra/shared/LifeCycleTestOwner.kt | nuhkoca | 252,193,036 | false | {"Kotlin": 258455, "Shell": 1250, "Java": 620} | /*
* Copyright (C) 2020. <NAME>. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.nuhkoca.libbra.shared
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
/**
* A helper [LifecycleOwner] that replicates the presence of an activity or fragment in the test
* classes.
*/
class LifeCycleTestOwner : LifecycleOwner {
private val registry = LifecycleRegistry(this)
override fun getLifecycle(): Lifecycle {
return registry
}
fun onCreate() {
registry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
}
fun onResume() {
registry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
}
fun onDestroy() {
registry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
}
}
| 1 | Kotlin | 3 | 54 | ffc089cba24281a3a8a8a1991bea6d4222456a79 | 1,352 | libbra | Apache License 2.0 |
core-kotlin-modules/core-kotlin-lang/src/main/kotlin/com/baeldung/operators/Point.kt | Baeldung | 260,481,121 | false | null | package com.baeldung.operators
data class Point(val x: Int, val y: Int)
operator fun Point.unaryMinus() = Point(-x, -y)
operator fun Point.not() = Point(y, x)
operator fun Point.inc() = Point(x + 1, y + 1)
operator fun Point.dec() = Point(x - 1, y - 1)
operator fun Point.plus(other: Point): Point = Point(x + other.x, y + other.y)
operator fun Point.minus(other: Point): Point = Point(x - other.x, y - other.y)
operator fun Point.times(other: Point): Point = Point(x * other.x, y * other.y)
operator fun Point.div(other: Point): Point = Point(x / other.x, y / other.y)
operator fun Point.rem(other: Point): Point = Point(x % other.x, y % other.y)
operator fun Point.times(factor: Int): Point = Point(x * factor, y * factor)
operator fun Int.times(point: Point): Point = Point(point.x * this, point.y * this)
class Shape {
val points = mutableListOf<Point>()
operator fun Point.unaryPlus() {
points.add(this)
}
}
fun shape(init: Shape.() -> Unit): Shape {
val shape = Shape()
shape.init()
return shape
} | 14 | null | 6 | 465 | f1ef5d5ded3f7ddc647f1b6119f211068f704577 | 1,042 | kotlin-tutorials | MIT License |
analysis/low-level-api-fir/tests/org/jetbrains/kotlin/analysis/low/level/api/fir/AbstractCompilationPeerAnalysisTest.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2024 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.analysis.low.level.api.fir
import org.jetbrains.kotlin.analysis.low.level.api.fir.api.getFirResolveSession
import org.jetbrains.kotlin.analysis.low.level.api.fir.api.getOrBuildFirFile
import org.jetbrains.kotlin.analysis.low.level.api.fir.compile.CompilationPeerCollector
import org.jetbrains.kotlin.analysis.low.level.api.fir.test.configurators.AnalysisApiFirSourceTestConfigurator
import org.jetbrains.kotlin.analysis.project.structure.ProjectStructureProvider
import org.jetbrains.kotlin.analysis.test.framework.base.AbstractAnalysisApiBasedTest
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.test.model.TestModule
import org.jetbrains.kotlin.test.services.TestServices
import org.jetbrains.kotlin.test.services.assertions
abstract class AbstractCompilationPeerAnalysisTest : AbstractAnalysisApiBasedTest() {
override val configurator = AnalysisApiFirSourceTestConfigurator(analyseInDependentSession = false)
override fun doTestByMainFile(mainFile: KtFile, mainModule: TestModule, testServices: TestServices) {
val project = mainFile.project
val sourceModule = ProjectStructureProvider.getModule(project, mainFile, contextualModule = null)
val resolveSession = sourceModule.getFirResolveSession(project)
val firFile = mainFile.getOrBuildFirFile(resolveSession)
val compilationPeerData = CompilationPeerCollector.process(firFile)
val actualItems = compilationPeerData.files.map { "File " + it.name }.sorted() +
compilationPeerData.inlinedClasses.map { "Class " + it.name }
val actualText = actualItems.joinToString(separator = "\n")
testServices.assertions.assertEqualsToTestDataFileSibling(actual = actualText)
}
} | 166 | null | 5771 | 46,772 | bef0946ab7e5acd5b24b971eca532c43c8eba750 | 1,976 | kotlin | Apache License 2.0 |
samples/TestJavaKt/src/com/sample/testjava/Main.kt | earndero | 405,563,403 | false | {"Java": 16236, "Kotlin": 8067} | package com.sample.testjava
import kotlin.Throws
import java.lang.Exception
import kotlin.jvm.JvmStatic
object Main {
@Throws(Exception::class)
@JvmStatic
fun main(args: Array<String>) {
var start = System.currentTimeMillis()
TestJava.create()
var finish = System.currentTimeMillis()
var timeElapsed = finish - start
System.out.printf("time insert = %d ms\n", timeElapsed)
start = System.currentTimeMillis()
TestJava.read()
finish = System.currentTimeMillis()
timeElapsed = finish - start
System.out.printf("time read = %d ms\n", timeElapsed)
}
} | 1 | null | 1 | 1 | 1672b0a6f256d43c1498c90bf4933a8d8c8bd28d | 644 | sqlwrapper | Apache License 2.0 |
app/src/main/java/com/larrynguyen/notewall/noteslist/NotesListActivity.kt | llarrynguyen | 213,621,425 | false | null | package com.larrynguyen.notewall.noteslist
import android.content.Intent
import android.content.res.Resources
import android.graphics.Rect
import android.os.Build
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.support.v7.widget.SearchView
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.ViewTreeObserver
import android.widget.PopupMenu
import android.widget.Toast
import com.larrynguyen.notewall.*
import com.larrynguyen.notewall.addeditnote.AddEditNoteActivity
import com.larrynguyen.notewall.databinding.ActivityNoteslistBinding
import com.larrynguyen.notewall.notedetail.NoteDetailActivity
import com.larrynguyen.notewall.noteslist.NotesListViewModel.Companion.OPTION_CLOUD
import com.larrynguyen.notewall.noteslist.NotesListViewModel.Companion.OPTION_EXPORT
import com.larrynguyen.notewall.noteslist.NotesListViewModel.Companion.OPTION_FILTER
import com.larrynguyen.notewall.noteslist.NotesListViewModel.Companion.OPTION_IMPORT
import com.larrynguyen.notewall.noteslist.NotesListViewModel.Companion.OPTION_SORT
import com.larrynguyen.notewall.sortdialog.SortDialogFragment
import com.larrynguyen.notewall.topicpicker.TopicPickerActivity
import com.larrynguyen.notewall.utils.tryStartActivity
import com.firebase.ui.auth.AuthUI
import java.util.*
import kotlinx.android.synthetic.main.activity_noteslist.*
class NotesListActivity : BasicActivity<ActivityNoteslistBinding, NotesListViewModel>(),
ViewTreeObserver.OnGlobalLayoutListener, SearchView.OnQueryTextListener {
private val sreenHeight get() = Resources.getSystem().displayMetrics.heightPixels
private lateinit var searchView: SearchView
override fun onGlobalLayout() {
val maybeKeyboard = rootContainer.height < sreenHeight * 2 / 3
onKeyboardStateChanged(maybeKeyboard)
}
override fun getLayoutId() = R.layout.activity_noteslist
override fun getBindingVariable() = BR.viewModel
override fun createViewModel() = NotesListViewModel(application, getListAdapter())
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme)
super.onCreate(savedInstanceState)
}
override fun onResume() {
super.onResume()
rootContainer.viewTreeObserver.addOnGlobalLayoutListener(this)
}
override fun onPause() {
super.onPause()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
rootContainer.viewTreeObserver.removeOnGlobalLayoutListener(this)
} else rootContainer.viewTreeObserver.removeGlobalOnLayoutListener(this)
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.notes_list_menu, menu)
val searchItem = menu.findItem(R.id.miSearch)
searchView = searchItem.actionView as SearchView
searchView.setOnQueryTextListener(this)
searchView.maxWidth = Integer.MAX_VALUE
return true
}
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
R.id.filter -> viewModel.handleOptionSelection(OPTION_FILTER)
R.id.sort -> viewModel.handleOptionSelection(OPTION_SORT)
R.id.export_list -> viewModel.handleOptionSelection(OPTION_EXPORT)
R.id.import_list -> viewModel.handleOptionSelection(OPTION_IMPORT)
R.id.cloudsync -> viewModel.handleOptionSelection(OPTION_CLOUD)
else -> super.onOptionsItemSelected(item)
}
override fun onQueryTextSubmit(query: String): Boolean {
viewModel.filterNotesList(query)
return false
}
override fun onQueryTextChange(newText: String): Boolean {
viewModel.filterNotesList(newText)
return false
}
override fun setupView(savedInstanceState: Bundle?) {
super.setupView(savedInstanceState)
setupActionBar()
setupList()
}
override fun setupViewModel() {
super.setupViewModel()
subscriptions.add(viewModel.observeOpenNoteFormRequest()
.subscribe { startNoteAddition() })
subscriptions.add(viewModel.observeEditNote()
.subscribe { startNoteEditing(it) })
subscriptions.add(viewModel.observeShowNote()
.subscribe { openNoteDetails(it) })
subscriptions.add(viewModel.observeShowFilterMenu()
.subscribe { showFilterMenu() })
subscriptions.add(viewModel.observeShowSortMenu()
.subscribe { showSortMenu(it) })
subscriptions.add(viewModel.observeScrollToTopRequest()
.subscribe { notesListView.smoothScrollToPosition(0) })
subscriptions.add(viewModel.observeShowTopicPickerRequest()
.subscribe { showTopicPicker() })
subscriptions.add(viewModel.observeExportNotesRequest()
.subscribe { exportNotes() })
subscriptions.add(viewModel.observeImportNotesRequest()
.subscribe { importNotes() })
subscriptions.add(viewModel.observeCloudAuthRequest()
.subscribe { showCloudAuthForm() })
}
private fun setupList() {
notesListView.adapter = NotesListAdapter(this, mutableListOf())
notesListView.layoutManager = object: LinearLayoutManager(this) {
override fun requestChildRectangleOnScreen(parent: RecyclerView, child: View, rect: Rect, immediate: Boolean) = false
override fun requestChildRectangleOnScreen(parent: RecyclerView, child: View, rect: Rect, immediate: Boolean, focusedChildVisible: Boolean) = false
}
}
private fun getListAdapter() = notesListView.adapter as NotesListAdapter
private fun showFilterMenu() {
val popup = PopupMenu(this, findViewById(R.id.filter))
popup.menuInflater.inflate(R.menu.notes_list_filter_menu, popup.menu)
popup.setOnMenuItemClickListener { onFilterSelected(it.itemId) }
popup.show()
}
private fun onFilterSelected(itemId: Int): Boolean {
when (itemId) {
R.id.all -> viewModel.handleFilterSelection(NotesListViewModel.FILTER_ALL)
R.id.important -> viewModel.handleFilterSelection(NotesListViewModel.FILTER_IMPORTANT)
R.id.topic -> viewModel.handleFilterSelection(NotesListViewModel.FILTER_TOPIC)
else -> return false
}
return true
}
private fun startNoteAddition() {
val intent = Intent(this, AddEditNoteActivity::class.java)
startActivityForResult(intent, NotesListViewModel.INTENT_ADD_NOTE)
}
private fun startNoteEditing(id: Long) {
val intent = Intent(this, AddEditNoteActivity::class.java).apply {
putExtra(C.EXTRA_NOTE_ID, id)
}
startActivityForResult(intent, NotesListViewModel.INTENT_EDIT_NOTE)
}
private fun openNoteDetails(id: Long) {
val intent = Intent(this, NoteDetailActivity::class.java).apply {
putExtra(C.EXTRA_NOTE_ID, id)
}
startActivityForResult(intent, NotesListViewModel.INTENT_SHOW_NOTE)
}
private fun showSortMenu(@SortOrder currentSortOrder: String) {
val dialog = SortDialogFragment.newInstance(currentSortOrder)
dialog.listener = object : SortDialogFragment.Listener {
override fun onSortSelected(@SortField field: String, @SortOrder order: String) {
viewModel.sort(field, order)
}
}
dialog.show(supportFragmentManager, "SortDialog")
}
private fun showTopicPicker() {
val intent = Intent(this, TopicPickerActivity::class.java)
startActivityForResult(intent, NotesListViewModel.INTENT_SHOW_TOPIC_PICKER)
}
private fun exportNotes() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
Toast.makeText(this, R.string.warning_no_app_intent, Toast.LENGTH_SHORT).show()
return
}
val intent = Intent(Intent.ACTION_CREATE_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "*/*"
putExtra(Intent.EXTRA_TITLE, ".txt")
}
val started = tryStartActivity(intent, NotesListViewModel.INTENT_EXPORT_NOTES)
if (started.not())
Toast.makeText(this, R.string.warning_no_app_intent, Toast.LENGTH_SHORT).show()
}
private fun importNotes() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
Toast.makeText(this, R.string.warning_no_app_intent, Toast.LENGTH_SHORT).show()
return
}
val intent = Intent(Intent.ACTION_OPEN_DOCUMENT).apply {
addCategory(Intent.CATEGORY_OPENABLE)
type = "*/*"
}
val started = tryStartActivity(intent, NotesListViewModel.INTENT_IMPORT_NOTES)
if (started.not())
Toast.makeText(this, R.string.warning_no_app_intent, Toast.LENGTH_SHORT).show()
}
private fun showCloudAuthForm() {
val providers = Arrays.asList(
AuthUI.IdpConfig.EmailBuilder().build())
val intent = AuthUI.getInstance()
.createSignInIntentBuilder()
.setAvailableProviders(providers)
.build()
startActivityForResult(intent, NotesListViewModel.INTENT_CLOUD_AUTH)
}
private fun onKeyboardStateChanged(opened: Boolean) {
// switchOpenNoteFormButton(!opened)
viewModel.onKeyboardStateChanged(opened)
}
private fun switchOpenNoteFormButton(show: Boolean) {
hintFullNote.animate()
.alpha(if(show) 1f else 0f)
.translationY(if (show) 0f else -50f)
.setDuration(100)
.start()
openNoteFormButton.animate()
.alpha(if(show) 1f else 0f)
.translationY(if (show) 0f else -50f)
.setDuration(100)
.start()
}
}
| 1 | null | 1 | 1 | a106ab5e083ffd54ba727af7d61ac4b4e91394e6 | 8,843 | Stickies | MIT License |
memento/src/main/java/com/alexstyl/specialdates/upcoming/UpcomingEventRowViewModelFactory.kt | alexstyl | 66,690,455 | false | null | package com.alexstyl.specialdates.upcoming
import com.alexstyl.resources.Colors
import com.alexstyl.specialdates.date.ContactEvent
import com.alexstyl.specialdates.date.Date
import com.alexstyl.specialdates.events.bankholidays.BankHoliday
import com.alexstyl.specialdates.events.namedays.NamesInADate
class UpcomingEventRowViewModelFactory(private val today: Date,
private val colors: Colors,
private val dateCreator: UpcomingDateStringCreator,
private val contactViewModelFactory: ContactViewModelFactory) {
fun createDateHeader(date: Date): UpcomingRowViewModel {
val label = dateCreator.createLabelFor(date)
return DateHeaderViewModel(label, colorFor(date))
}
private fun colorFor(date: Date): Int {
return if (date == today) {
colors.getTodayHeaderTextColor()
} else {
colors.getDateHeaderTextColor()
}
}
fun createViewModelFor(contactEvent: ContactEvent): UpcomingRowViewModel = contactViewModelFactory.createViewModelFor(today, contactEvent)
fun createViewModelFor(bankHoliday: BankHoliday): UpcomingRowViewModel = BankHolidayViewModel(bankHoliday.holidayName)
fun createViewModelFor(namedays: NamesInADate): UpcomingRowViewModel = UpcomingNamedaysViewModel(namedays.getNames().joinToString(", "), namedays.date)
}
| 0 | null | 49 | 211 | d224f0af53ee3d4ecadad5df0a2731e2c9031a23 | 1,438 | Memento-Calendar | MIT License |
S10.04-Exercise-Notifications/app/src/main/java/com/example/android/sunshine/data/SunshinePreferences.kt | Stropek | 103,776,964 | true | {"Java": 8745366, "Kotlin": 320392, "Python": 2489} | /*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.sunshine.data
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
import com.example.android.sunshine.R
object SunshinePreferences {
/*
* In order to uniquely pinpoint the location on the map when we launch the map intent, we
* store the latitude and longitude. We will also use the latitude and longitude to create
* queries for the weather.
*/
val PREF_COORD_LAT = "coord_lat"
val PREF_COORD_LONG = "coord_long"
/**
* Helper method to handle setting location details in Preferences (city name, latitude,
* longitude)
*
*
* When the location details are updated, the database should to be cleared.
*
* @param context Context used to get the SharedPreferences
* @param lat the latitude of the city
* @param lon the longitude of the city
*/
fun setLocationDetails(context: Context, lat: Double, lon: Double) {
val sp = PreferenceManager.getDefaultSharedPreferences(context)
val editor = sp.edit()
editor.putLong(PREF_COORD_LAT, java.lang.Double.doubleToRawLongBits(lat))
editor.putLong(PREF_COORD_LONG, java.lang.Double.doubleToRawLongBits(lon))
editor.apply()
}
/**
* Resets the location coordinates stores in SharedPreferences.
*
* @param context Context used to get the SharedPreferences
*/
fun resetLocationCoordinates(context: Context) {
val sp = PreferenceManager.getDefaultSharedPreferences(context)
val editor = sp.edit()
editor.remove(PREF_COORD_LAT)
editor.remove(PREF_COORD_LONG)
editor.apply()
}
/**
* Returns the location currently set in Preferences. The default location this method
* will return is "94043,USA", which is Mountain View, California. Mountain View is the
* home of the headquarters of the Googleplex!
*
* @param context Context used to access SharedPreferences
* @return Location The current user has set in SharedPreferences. Will default to
* "94043,USA" if SharedPreferences have not been implemented yet.
*/
fun getPreferredWeatherLocation(context: Context): String {
val sp = PreferenceManager.getDefaultSharedPreferences(context)
val keyForLocation = context.getString(R.string.pref_location_key)
val defaultLocation = context.getString(R.string.pref_location_default)
return sp.getString(keyForLocation, defaultLocation)
}
/**
* Returns true if the user has selected metric temperature display.
*
* @param context Context used to get the SharedPreferences
* @return true if metric display should be used, false if imperial display should be used
*/
fun isMetric(context: Context): Boolean {
val sp = PreferenceManager.getDefaultSharedPreferences(context)
val keyForUnits = context.getString(R.string.pref_units_key)
val defaultUnits = context.getString(R.string.pref_units_metric)
val preferredUnits = sp.getString(keyForUnits, defaultUnits)
val metric = context.getString(R.string.pref_units_metric)
var userPrefersMetric = false
if (metric == preferredUnits) {
userPrefersMetric = true
}
return userPrefersMetric
}
/**
* Returns the location coordinates associated with the location. Note that there is a
* possibility that these coordinates may not be set, which results in (0,0) being returned.
* Interestingly, (0,0) is in the middle of the ocean off the west coast of Africa.
*
* @param context used to access SharedPreferences
* @return an array containing the two coordinate values for the user's preferred location
*/
fun getLocationCoordinates(context: Context): DoubleArray {
val sp = PreferenceManager.getDefaultSharedPreferences(context)
val preferredCoordinates = DoubleArray(2)
/*
* This is a hack we have to resort to since you can't store doubles in SharedPreferences.
*
* Double.doubleToLongBits returns an integer corresponding to the bits of the given
* IEEE 754 double precision value.
*
* Double.longBitsToDouble does the opposite, converting a long (that represents a double)
* into the double itself.
*/
preferredCoordinates[0] = java.lang.Double
.longBitsToDouble(sp.getLong(PREF_COORD_LAT, java.lang.Double.doubleToRawLongBits(0.0)))
preferredCoordinates[1] = java.lang.Double
.longBitsToDouble(sp.getLong(PREF_COORD_LONG, java.lang.Double.doubleToRawLongBits(0.0)))
return preferredCoordinates
}
/**
* Returns true if the latitude and longitude values are available. The latitude and
* longitude will not be available until the lesson where the PlacePicker API is taught.
*
* @param context used to get the SharedPreferences
* @return true if lat/long are saved in SharedPreferences
*/
fun isLocationLatLonAvailable(context: Context): Boolean {
val sp = PreferenceManager.getDefaultSharedPreferences(context)
val spContainLatitude = sp.contains(PREF_COORD_LAT)
val spContainLongitude = sp.contains(PREF_COORD_LONG)
var spContainBothLatitudeAndLongitude = false
if (spContainLatitude && spContainLongitude) {
spContainBothLatitudeAndLongitude = true
}
return spContainBothLatitudeAndLongitude
}
fun areNotificationsEnabled(context: Context): Boolean {
val sp = PreferenceManager.getDefaultSharedPreferences(context)
val displayNotificationsKey = context.getString(R.string.pref_enable_notifications_key)
val displayNotificationsDefault = context.resources.getBoolean(R.bool.show_notifications_by_default)
return sp.getBoolean(displayNotificationsKey, displayNotificationsDefault)
}
/**
* Returns the last time that a notification was shown (in UNIX time)
*
* @param context Used to access SharedPreferences
* @return UNIX time of when the last notification was shown
*/
fun getLastNotificationTimeInMillis(context: Context): Long {
/* Key for accessing the time at which Sunshine last displayed a notification */
val lastNotificationKey = context.getString(R.string.pref_last_notification)
/* As usual, we use the default SharedPreferences to access the user's preferences */
val sp = PreferenceManager.getDefaultSharedPreferences(context)
/*
* Here, we retrieve the time in milliseconds when the last notification was shown. If
* SharedPreferences doesn't have a value for lastNotificationKey, we return 0. The reason
* we return 0 is because we compare the value returned from this method to the current
* system time. If the difference between the last notification time and the current time
* is greater than one day, we will show a notification again. When we compare the two
* values, we subtract the last notification time from the current system time. If the
* time of the last notification was 0, the difference will always be greater than the
* number of milliseconds in a day and we will show another notification.
*/
return sp.getLong(lastNotificationKey, 0)
}
/**
* Returns the elapsed time in milliseconds since the last notification was shown. This is used
* as part of our check to see if we should show another notification when the weather is
* updated.
*
* @param context Used to access SharedPreferences as well as use other utility methods
* @return Elapsed time in milliseconds since the last notification was shown
*/
fun getEllapsedTimeSinceLastNotification(context: Context): Long {
val lastNotificationTimeMillis = SunshinePreferences.getLastNotificationTimeInMillis(context)
return System.currentTimeMillis() - lastNotificationTimeMillis
}
/**
* Saves the time that a notification is shown. This will be used to get the ellapsed time
* since a notification was shown.
*
* @param context Used to access SharedPreferences
* @param timeOfNotification Time of last notification to save (in UNIX time)
*/
fun saveLastNotificationTime(context: Context, timeOfNotification: Long) {
val sp = PreferenceManager.getDefaultSharedPreferences(context)
val editor = sp.edit()
val lastNotificationKey = context.getString(R.string.pref_last_notification)
editor.putLong(lastNotificationKey, timeOfNotification)
editor.apply()
}
} | 0 | Java | 0 | 0 | e843bc3db10a2e8c37c11f1a45d1419dd7de320f | 9,428 | ud851-Sunshine | Apache License 2.0 |
plugins/ide-features-trainer/src/training/learn/lesson/kimpl/KLesson.kt | dmochalov | 321,209,485 | true | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package training.learn.lesson.kimpl
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.NonNls
import training.learn.interfaces.Lesson
import training.learn.interfaces.Module
import training.learn.lesson.LessonListener
abstract class KLesson(@NonNls override val id: String,
@Nls override val name: String,
override var module: Module,
override val lang: String) : Lesson {
abstract val lessonContent: LessonContext.() -> Unit
override val lessonListeners: MutableList<LessonListener> = mutableListOf()
}
| 1 | null | 1 | 1 | 6f4c064caf9148f1a68e7a47c735f4a1587894f7 | 741 | intellij-community | Apache License 2.0 |
src/main/kotlin/com/eric/leetcode/ImplementStrStr.kt | wanglikun7342 | 163,727,208 | false | null | package com.eric.leetcode
class ImplementStrStr {
fun strStr(haystack: String, needle: String): Int {
if (needle.isEmpty()) {
return 0
}
loop@ for (el in haystack.withIndex()) {
if (el.value == needle[0]) {
for (index in needle.indices) {
if (el.index + index > haystack.lastIndex && needle[index] != haystack[el.index + index]) {
continue@loop
}
}
return el.index
}
}
return -1
}
} | 1 | Kotlin | 3 | 8 | ca9a8869faa90e9598eff0db756d8f9414a3d816 | 579 | Leetcode-Kotlin | Apache License 2.0 |
app/src/main/java/com/thewizrd/simpleweather/radar/rainviewer/RadarFrame.kt | bryan2894-playgrnd | 82,603,731 | false | {"Gradle": 7, "Java Properties": 2, "Shell": 1, "Ignore List": 6, "Batchfile": 1, "Text": 2, "Markdown": 1, "Proguard": 7, "JSON": 20, "Java": 288, "Kotlin": 572, "XML": 808, "Makefile": 2, "HTML": 1, "INI": 1} | package com.thewizrd.simpleweather.radar.rainviewer
data class RadarFrame(
val timeStamp: Long,
val host: String?,
val path: String?
) | 0 | Kotlin | 8 | 34 | b7c686b03f45088cc431db5e180890df18efe447 | 147 | SimpleWeather-Android | Apache License 2.0 |
repository-local/src/main/java/com/andyanika/translator/repository/local/di/koin/LocalRepositoryModule.kt | Subtle-fox | 130,334,439 | false | {"Gradle": 12, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "INI": 1, "XML": 35, "Kotlin": 78, "Java": 8, "JSON": 2, "Proguard": 5} | package com.andyanika.translator.repository.local.di.koin
import android.content.Context
import androidx.room.Room
import core.interfaces.LocalRepository
import com.andyanika.translator.repository.local.DatabaseTranslator
import com.andyanika.translator.repository.local.LocalRepositoryImpl
import com.andyanika.translator.repository.local.ModelsAdapter
import org.koin.core.qualifier.named
import org.koin.dsl.module
import org.koin.dsl.single
val localRepositoryModule = module {
single<LocalRepository> { LocalRepositoryImpl(get(), get(), get(), get(named("io"))) }
single {
Room.databaseBuilder(get(), DatabaseTranslator::class.java, "words_database")
.build()
.translatorDao()
}
single {
val ctx: Context = get()
ctx.getSharedPreferences("config", Context.MODE_PRIVATE)
}
single<ModelsAdapter>()
}
| 0 | Kotlin | 0 | 0 | d371f1a221e713a0ad34fab12afc55d8106e79f6 | 880 | translator | Apache License 2.0 |
src/support/integration/src/main/kotlin/kiit/integration/consts.kt | slatekit | 55,942,000 | false | {"Kotlin": 2295109, "Shell": 14611, "Java": 14216, "Swift": 1555} | /**
<kiit_header>
url: www.slatekit.com
git: www.github.com/slatekit/kiit
org: www.codehelix.co
author: <NAME>
copyright: 2016 CodeHelix Solutions Inc.
license: refer to website and/or github
about: A Kotlin utility library, tool-kit and server backend.
</kiit_header>
*/
/**
* Created by kishorereddy on 5/19/17.
*/
package kiit.core
object Consts {
val version = "0.9.0"
} | 3 | Kotlin | 13 | 112 | d17b592aeb28c5eb837d894e98492c69c4697862 | 386 | slatekit | Apache License 2.0 |
library/src/main/kotlin/com/twitter/meil_mitu/twitter4hk/converter/api/IStreamConverter.kt | MeilCli | 51,423,644 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Java": 3, "XML": 22, "Kotlin": 303, "Checksums": 6} | package com.twitter.meil_mitu.twitter4hk.converter.api
interface IStreamConverter<TDirectMessage, TStatus, TUser, TUserList> :
IFilterStreamConverter<TStatus>,
ISampleStreamConverter<TStatus>,
IUserStreamConverter<TDirectMessage, TStatus, TUser, TUserList> {
} | 0 | Kotlin | 0 | 0 | 818e42ea417c326e3d50024decce4c7e70641a73 | 285 | Twitter4HK | MIT License |
Problems/Algorithms/700. Search in a Binary Search Tree/SearchBST.kt | xuedong | 189,745,542 | false | {"Kotlin": 332182, "Java": 292409, "Python": 230147, "C++": 84227, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65} | /**
* Example:
* var ti = TreeNode(5)
* var v = ti.`val`
* Definition for a binary tree node.
* class TreeNode(var `val`: Int) {
* var left: TreeNode? = null
* var right: TreeNode? = null
* }
*/
class Solution {
fun searchBST(root: TreeNode?, `val`: Int): TreeNode? {
if (root == null) return null
if (root?.`val` == `val`) return root
if (root?.`val` > `val`) return searchBST(root?.left, `val`)
return searchBST(root?.right, `val`)
}
}
| 0 | Kotlin | 0 | 1 | e91deba89a708cb1bfe8e6adbde0fb585f135fad | 505 | leet-code | MIT License |
FetLifeKotlin/app/src/main/java/com/bitlove/fetlife/model/db/dao/GroupDao.kt | alphaStryke2k3 | 130,300,999 | true | {"Gradle": 9, "Ignore List": 7, "Markdown": 1, "Java Properties": 4, "Shell": 2, "Batchfile": 2, "Proguard": 6, "Kotlin": 140, "JSON": 4, "XML": 180, "Java": 268, "JavaScript": 2} | package com.bitlove.fetlife.model.db.dao
import android.arch.lifecycle.LiveData
import android.arch.paging.DataSource
import android.arch.persistence.room.Dao
import android.arch.persistence.room.Query
import android.arch.persistence.room.Transaction
import com.bitlove.fetlife.model.dataobject.entity.content.GroupEntity
import com.bitlove.fetlife.model.dataobject.entity.content.MemberEntity
import com.bitlove.fetlife.model.dataobject.entity.reference.MemberRef
import com.bitlove.fetlife.model.dataobject.wrapper.Content
import com.bitlove.fetlife.model.dataobject.wrapper.Group
import com.bitlove.fetlife.model.dataobject.wrapper.Member
@Dao
abstract class GroupDao : BaseDao<GroupEntity> {
@Query("SELECT * FROM groups WHERE dbId = :dbId")
abstract fun getEntity(dbId: String): GroupEntity?
@Query("DELETE FROM groups")
abstract fun deleteAll()
// @Query("SELECT * FROM groups ORDER BY serverOrder")
// abstract fun getGroups(): DataSource.Factory<Int, Group>
//
// @Query("SELECT * FROM groups WHERE dbId = :dbId")
// abstract fun getGroup(dbId: String): LiveData<Group>
//
// @Query("SELECT * FROM groups WHERE dbId = :dbId")
// abstract fun getEntity(dbId: String): GroupEntity?
} | 0 | Java | 0 | 2 | c6aa3bed6bf7549597b101a37ce3bb1820ad7699 | 1,229 | android | MIT License |
Android_Zone_Test/src/com/example/mylib_test/activity/three_place/LifecycleActivityCore.kt | luhaoaimama1 | 50,120,145 | false | null | package com.example.mylib_test.activity.three_place
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.LifecycleRegistry
import com.zone.lib.base.controller.activity.BaseFeatureActivity
/**
*[2019/1/3] by Zone
* 实现原理 我们可以在 不是activity fragment中去自己是实现
* https://blog.csdn.net/xiatiandefeiyu/article/details/78643482
*/
class LifecycleActivityCore : BaseFeatureActivity(), LifecycleOwner {
private lateinit var mLifecycleRegistry: LifecycleRegistry
override fun getLifecycle(): Lifecycle = mLifecycleRegistry
override fun onStart() {
super.onStart()
mLifecycleRegistry.markState(Lifecycle.State.STARTED);
}
override fun setContentView() {
mLifecycleRegistry = LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
// lifecycle.addObserver()
}
override fun initData() {
}
override fun setListener() {
}
} | 2 | null | 14 | 70 | 420b2bac6c7272997a0d95fe1ffcba7b957f7a19 | 980 | zone-sdk | MIT License |
ktx/src/main/java/luyao/util/ktx/ext/LogExt.kt | lulululbj | 221,170,029 | false | null | package pers.zander.utils.ktx.ext
import android.util.Log
import pers.zander.utils.ktx.BuildConfig
/**
* Created by zander
* on 2019/7/3 15:37
*/
const val TAG = "ktx"
var showLog = BuildConfig.DEBUG
private enum class LEVEL {
V, D, I, W, E
}
fun String.logv(tag: String = TAG) = log(LEVEL.V, tag, this)
fun String.logd(tag: String = TAG) = log(LEVEL.D, tag, this)
fun String.logi(tag: String = TAG) = log(LEVEL.I, tag, this)
fun String.logw(tag: String = TAG) = log(LEVEL.W, tag, this)
fun String.loge(tag: String = TAG) = log(LEVEL.E, tag, this)
private fun log(level: LEVEL, tag: String, message: String) {
if (!showLog) return
when (level) {
LEVEL.V -> Log.v(tag, message)
LEVEL.D -> Log.d(tag, message)
LEVEL.I -> Log.i(tag, message)
LEVEL.W -> Log.w(tag, message)
LEVEL.E -> Log.e(tag, message)
}
} | 1 | null | 4 | 31 | f323b541ac6a89b79f66a3b91bfca85a7a5cc590 | 870 | Wanandroid-Compose | Apache License 2.0 |
app/src/androidTest/java/com/ndipatri/solarmonitor/MainActivityLiveUserTest.kt | ndipatri | 93,703,045 | false | null | package com.ndipatri.solarmonitor
import android.content.Intent
import androidx.test.InstrumentationRegistry.getInstrumentation
import androidx.test.espresso.IdlingRegistry
import androidx.test.platform.app.InstrumentationRegistry
import androidx.test.rule.ActivityTestRule
import com.ndipatri.solarmonitor.activities.MainActivity
import com.ndipatri.solarmonitor.container.LiveTestObjectGraph
import com.ndipatri.solarmonitor.providers.customer.CustomerProvider
import com.ndipatri.solarmonitor.providers.panelScan.PanelProvider
import com.ndipatri.solarmonitor.utils.RxJavaUsesAsyncTaskSchedulerRule
import com.ndipatri.solarmonitor.utils.AACUsesIdlingResourceRule
import kotlinx.coroutines.runBlocking
import org.junit.After
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import javax.inject.Inject
class MainActivityLiveUserTest {
@Rule
@JvmField
var activityRule = ActivityTestRule<MainActivity>(MainActivity::class.java, true, false)
// This is the coolest thing ever. We are configuring our test thread (this thread) to block
// while the background thread is running in our target application. (only those background
// operations that are using RxJava's IO and Computation schedulers, that is)
//
// This is necessary for this test when we are 'loading' solar output using SolarOutputProvider.
// This Provider uses RxJava/Retrofit to retrieve solar output from our live RESTful endpoint.
@Rule
@JvmField
var asyncTaskSchedulerRule = RxJavaUsesAsyncTaskSchedulerRule()
@Rule
@JvmField
val executorRule = AACUsesIdlingResourceRule()
@Inject
lateinit var panelProvider: PanelProvider
@Inject
lateinit var customerProvider: CustomerProvider
lateinit var solarMonitorApp: SolarMonitorApp
@Before
@Throws(Exception::class)
fun setUp() {
// Context of the app under test.
solarMonitorApp = InstrumentationRegistry.getInstrumentation().targetContext.applicationContext as SolarMonitorApp
// We bootstrap the production ObjectGraph and inject it into this test class so we can access
// production components
val lifeTestObjectGraph = LiveTestObjectGraph.Initializer.init(solarMonitorApp)
solarMonitorApp.objectGraph = lifeTestObjectGraph
lifeTestObjectGraph.inject(this)
// For the IdlingResource feature, we need to instrument the real component, unfortunately.
// The PanelProvider actually does BLE scanning in a way that is non-blocking. Our background
// thread subscribes to hotObservable, so we need to wrap in IdlingRegistry.. RxJava thread
// trickery isn't enough.
IdlingRegistry.getInstance().register(panelProvider.idlingResource)
clearState()
}
@After
@Throws(Exception::class)
fun tearDown() {
clearState()
}
private fun clearState() {
// clear out any remaining state.
runBlocking {
panelProvider.deleteAllPanels()
customerProvider.deleteAllCustomers()
}
}
// Live Testing
//
// Here we use our production ObjectGraph with our real service and hardware layer. This service
// layer requires remote RESTful endpoints. The hardware layer requires a real Bluetooth
// stack to be present.
//
// Pros - no configuration, allows for automated 'live testing' and testing use real live system and data
// Cons - live endpoint and hardware need to be in a known state. If a test fails, your scope is so large
// it doesn't really tell you much, necessarily, about your code itself.
//
@Test
@Throws(Exception::class)
fun scanningAndLoading() {
activityRule.launchActivity(Intent())
// For Here we depend solely on the RxJavaUsesAsyncTaskSchedulerRule because our RxJava background process
// is hitting the remote RESTful endpoint. (We don't need IdlingResource)
// we know what panelId our real beacon is emitting.
assertFindingPanelViews("480557")
// we cannot predict the real solar output right now.
assertLoadingSolarOutputViews("Current \\((.*?)/hour\\)\\, Annual \\((.*?)\\)", "480557")
}
}
| 1 | Kotlin | 2 | 6 | 97a17cd3fc0475b522208ad512a0093f3006d387 | 4,244 | solarMonitor | Apache License 2.0 |
tstatus/src/main/java/com/github/john/tstatus/TStatus.kt | oOJohn6Oo | 225,583,500 | false | null | package com.github.john.tstatus
import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.PorterDuff
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.ProgressBar
import android.widget.TextView
import androidx.annotation.ArrayRes
import androidx.annotation.LayoutRes
import androidx.annotation.Size
import androidx.annotation.StringRes
import androidx.core.view.get
import androidx.fragment.app.Fragment
class TStatus private constructor(private val builder: Builder) {
private var statusViews: Array<View?>
var viewStatus:ViewType = ViewType.CONTENT
init {
statusViews = Array(builder.builderLayouts.size) { null }
}
companion object {
private var hasInitialized: Boolean = false
var globalAlerts: Array<String>? = null
var globalViews: IntArray? = null
var globalLayouts: IntArray? = null
private fun init(alerts: Array<String>) {
check(!hasInitialized) { "T_status only needs to be init once." }
hasInitialized = true
this.globalAlerts = alerts
}
/**
* 只设置
* @alerts 提示语
*/
fun init(context: Context, @Size(4) alerts: IntArray) {
init(Array(alerts.size) { pos ->
context.getString(alerts[pos])
})
}
/**
* @globalAlerts 各样式的提示语
* @resourceInt 分别为 empty图片、loading*颜色*、网络出错图片、服务器出错图片 的资源ID
*/
fun init(context: Context, @Size(4) alerts: IntArray, @Size(4) resourceInt: IntArray) {
init(context, alerts)
this.globalViews = resourceInt
}
/**
* 支持通过资源ID设置提示语
*/
fun init(context: Context, @ArrayRes alerts: Int, @Size(4) resourceInt: IntArray) {
init(context.resources.getStringArray(alerts))
this.globalViews = resourceInt
}
/**
* 直接设置view的样式
* layoutViewIds 分别对应各状态资源ID
*/
fun init(@Size(4) layoutViewIds: IntArray) {
check(!hasInitialized) { "T_status only needs to be init once." }
hasInitialized = true
globalLayouts = layoutViewIds
}
}
class Builder(val context: Context, val targetView: View) {
constructor(fragment: Fragment) : this(fragment.context!!, fragment.requireView())
constructor(activity: Activity) : this(
activity,
(activity.findViewById(android.R.id.content) as ViewGroup).getChildAt(0)
)
var netErrorClickListener: View.OnClickListener? = null
var serverErrorClickListener: View.OnClickListener? = null
val parentView: ViewGroup = targetView.parent as ViewGroup
val layoutIndex: Int = parentView.indexOfChild(targetView)
val builderAlerts: Array<String> = if (globalAlerts == null) arrayOf(
context.getString(R.string.loading_alert)
, context.getString(R.string.empty_alert)
, context.getString(R.string.network_alert)
, context.getString(R.string.server_alert)
) else globalAlerts!!
val builderViews: IntArray = if (globalViews == null) intArrayOf(
Color.RED
, R.drawable.ic_status_empty_view
, R.drawable.ic_status_network_error
, R.drawable.ic_status_server_error
) else globalViews!!
val builderLayouts: IntArray = if (globalLayouts == null) intArrayOf(
R.layout.view_status_loading,
R.layout.view_status_empty
, R.layout.view_status_net_error, R.layout.view_status_server_error
) else globalLayouts!!
fun setNetErrorClickListener(clickListener: View.OnClickListener): Builder {
this.netErrorClickListener = clickListener
return this
}
fun setServerErrorClickListener(clickListener: View.OnClickListener): Builder {
this.serverErrorClickListener = clickListener
return this
}
fun setAlertMsg(viewType: ViewType, msg: String): Builder {
check(globalLayouts == null) { "Custom layout do not permitted to invoke this func for the security" }
builderAlerts[viewType.ordinal] = msg
return this
}
fun setAlertMsg(viewType: ViewType, msg: Int): Builder {
return setAlertMsg(viewType, context.getString(msg))
}
fun setAlertView(viewType: ViewType, firstIsColorNextDrawable: Int): Builder {
check(globalLayouts == null) { "Custom layout do not permitted to invoke this func for the security" }
builderViews[viewType.ordinal] = firstIsColorNextDrawable
return this
}
fun setLayout(viewType: ViewType, @LayoutRes layoutResId: Int): Builder {
builderLayouts[viewType.ordinal] = layoutResId
return this
}
fun build(): TStatus = TStatus(this)
}
fun showLoading() = stateSwitch(ViewType.LOADING)
fun showEmpty() = stateSwitch(ViewType.EMPTY)
fun showServerError() = stateSwitch(ViewType.SERVER_ERROR)
fun showNetError() = stateSwitch(ViewType.NET_ERROR)
fun showContent() = stateSwitch(ViewType.CONTENT)
private fun stateSwitch(viewType: ViewType) {
duplicateCheck(viewType)
nullCheck(viewType)
builder.parentView.removeViewAt(builder.layoutIndex)
if (viewType == ViewType.CONTENT)
builder.parentView.addView(builder.targetView, builder.layoutIndex)
else
builder.parentView.addView(
statusViews[viewType.ordinal],
builder.layoutIndex,
builder.targetView.layoutParams
)
}
private fun duplicateCheck(viewType: ViewType) {
if(viewStatus == viewType)
return
else
viewStatus = viewType
}
private fun nullCheck(viewType: ViewType) {
val index = viewType.ordinal
if (viewType != ViewType.CONTENT && statusViews[index] == null) {
statusViews[index] = LayoutInflater.from(builder.context).inflate(
builder.builderLayouts[index],
builder.parentView,
false
)
// 用户没有自定义
if (globalLayouts == null) {
val linearLayout = (statusViews[index] as ViewGroup)[0] as ViewGroup
if (viewType == ViewType.NET_ERROR)
linearLayout.setOnClickListener(builder.netErrorClickListener)
else if (viewType == ViewType.SERVER_ERROR)
linearLayout.setOnClickListener(builder.serverErrorClickListener)
// 设置loading颜色
if (index == 0)
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP)
(linearLayout[0] as ProgressBar).indeterminateDrawable.setTint(
builder.builderViews[index]
)
else
(linearLayout[0] as ProgressBar).indeterminateDrawable.setColorFilter(
builder.builderViews[index],
PorterDuff.Mode.SRC
)
// 设置图片
else
(linearLayout[0] as ImageView).setImageResource(builder.builderViews[index])
// 设置文字
(linearLayout[1] as TextView).text = builder.builderAlerts[index]
}
}
}
} | 0 | Kotlin | 0 | 0 | 84eeebdb67b6306a7f3871200ab4949062901bf6 | 7,683 | TStatus | Apache License 2.0 |
app/src/main/java/com/samridhoverseasfsm/features/viewAllOrder/orderOptimized/OrderOptiCatagoryOnClick.kt | DebashisINT | 684,066,797 | false | null | package com.samridhoverseasfsm.features.viewAllOrder.orderOptimized
import com.samridhoverseasfsm.app.domain.NewOrderColorEntity
interface OrderOptiCatagoryOnClick {
fun catagoryListOnClick(objSel: CommonProductCatagory)
} | 0 | Kotlin | 0 | 0 | aba1d6c2accf9a800224d8b601317a8d9233ee09 | 228 | SamridhOverseas | Apache License 2.0 |
grovlin-ast/src/test/kotlin/io/gitlab/arturbosch/grovlin/ast/LoopsTest.kt | arturbosch | 80,819,243 | false | null | package io.gitlab.arturbosch.grovlin.ast
import io.gitlab.arturbosch.grovlin.ast.operations.collectByType
import org.assertj.core.api.Assertions
import org.junit.Test
/**
* @author <NAME>
*/
class LoopsTest {
@Test
fun `domain tests FOR`() {
val grovlinFile = "for x : 1..10 {}".asGrovlinFile()
val forStmt = grovlinFile.collectByType<ForStatement>()[0]
Assertions.assertThat(forStmt.varDeclaration.name).isEqualTo("x")
Assertions.assertThat(forStmt.expression).isInstanceOf(IntRangeExpression::class.java)
Assertions.assertThat(forStmt.block.statements).isEmpty()
}
@Test
fun `domain tests WHILE`() {
val grovlinFile = "while 5 < 8 {}".asGrovlinFile()
val whileStmt = grovlinFile.collectByType<WhileStatement>()[0]
Assertions.assertThat(whileStmt.condition).isInstanceOf(RelationExpression::class.java)
Assertions.assertThat(whileStmt.thenStatement.statements).isEmpty()
}
}
| 8 | null | 1 | 6 | 3bfd23cc6fd91864611e785cf2c990b3a9d83e63 | 910 | grovlin | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsrestrictedpatientsapi/services/BatchReleaseDateRemoval.kt | ministryofjustice | 377,843,107 | false | null | package uk.gov.justice.digital.hmpps.hmppsrestrictedpatientsapi.services
import com.microsoft.applicationinsights.TelemetryClient
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import uk.gov.justice.digital.hmpps.hmppsrestrictedpatientsapi.gateways.PrisonerSearchApiGateway
import uk.gov.justice.digital.hmpps.hmppsrestrictedpatientsapi.repositories.RestrictedPatientsRepository
import java.time.Clock
import java.time.LocalDate
@Service
class BatchReleaseDateRemoval(
private val restrictedPatientsRepository: RestrictedPatientsRepository,
private val prisonerSearchApiGateway: PrisonerSearchApiGateway,
private val restrictedPatientsService: RestrictedPatientsService,
private val telemetryClient: TelemetryClient,
private val domainEventPublisher: DomainEventPublisher,
private val clock: Clock,
) {
fun removeNonLifePrisonersPastRelevantDate() {
val now = LocalDate.now(clock)
val toBeDeleted = restrictedPatientsRepository.findAll()
.chunked(1000)
.flatMap { chunk ->
val results = prisonerSearchApiGateway.findByPrisonNumbers(chunk.map { it.prisonerNumber })
results.filter {
it.indeterminateSentence == false &&
(it.isNotRecallPastConditionalRelease(now) || it.isRecallPastSentenceExpiry(now))
}
.map { it.prisonerNumber }
}
if (toBeDeleted.isNotEmpty()) {
telemetryClient.trackEvent(
"restricted-patient-batch-removal",
mapOf("prisonerNumbers" to toBeDeleted.joinToString()),
null,
)
toBeDeleted.forEach {
try {
restrictedPatientsService.removeRestrictedPatient(it)
domainEventPublisher.publishRestrictedPatientRemoved(it)
} catch (ex: Exception) {
log.error("restricted-patient-batch-removal failed for offender $it", ex)
}
}
}
}
private companion object {
private val log = LoggerFactory.getLogger(this::class.java)
}
}
| 2 | Kotlin | 0 | 2 | e7a92b985013e85fcd7c92c410d0c08b57159492 | 1,981 | hmpps-restricted-patients-api | MIT License |
app/src/main/java/com/danc/watchout/presentation/screens/FilmScreen.kt | Danc-0 | 570,116,933 | false | {"Kotlin": 96005} | package com.danc.watchout.presentation.screens
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.paging.LoadState
import androidx.paging.compose.collectAsLazyPagingItems
import com.danc.watchout.domain.models.FilmsResult
import com.danc.watchout.presentation.ui.components.ErrorItemComponent
import com.danc.watchout.presentation.viewmodels.FilmsViewModel
@Composable
fun FilmScreen(navController: NavController) {
val scaffoldState = rememberScaffoldState()
val filmsViewModel: FilmsViewModel = hiltViewModel()
val films = filmsViewModel.filmPager.collectAsLazyPagingItems()
Scaffold(
scaffoldState = scaffoldState,
content = {
Box(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colors.background)
.padding(it),
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(20.dp)
) {
Text(
text = "Films",
style = TextStyle(
color = MaterialTheme.colors.onSecondary,
fontSize = 35.sp,
fontWeight = FontWeight.Bold
)
)
Text(
text = "May the Force be with you",
style = TextStyle(
color = MaterialTheme.colors.onBackground
)
)
Spacer(modifier = Modifier.height(5.dp))
LazyColumn(
modifier = Modifier.fillMaxSize(),
content = {
items(films.itemCount) { item ->
val film = films[item]
SingleFilmItem(filmResult = film)
}
when (val state = films.loadState.prepend) {
is LoadState.NotLoading -> Unit
is LoadState.Loading -> {
item {
CircularProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.wrapContentWidth(Alignment.CenterHorizontally)
)
}
}
is LoadState.Error -> {
item {
ErrorItemComponent(
message = state.error.message ?: "Unknown Error"
)
}
}
}
when (val state = films.loadState.refresh) {
is LoadState.NotLoading -> Unit
is LoadState.Loading -> {
item {
CircularProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.wrapContentWidth(Alignment.CenterHorizontally)
)
}
}
is LoadState.Error -> {
item {
ErrorItemComponent(
message = state.error.message
?: "Unknown Error Occurred"
)
}
}
}
when (val state = films.loadState.prepend) {
is LoadState.NotLoading -> Unit
is LoadState.Loading -> {
item {
CircularProgressIndicator(
modifier = Modifier
.fillMaxWidth()
.wrapContentWidth(Alignment.CenterHorizontally)
)
}
}
is LoadState.Error -> {
item {
ErrorItemComponent(
message = state.error.message
?: "Unknown Error Occurred"
)
}
}
}
})
}
}
}
)
}
@Composable
fun SingleFilmItem(filmResult: FilmsResult?) {
filmResult?.let { filmsResult ->
Box(
modifier = Modifier
.fillMaxWidth()
.padding(5.dp)
.border(
border = BorderStroke(width = 1.dp, color = MaterialTheme.colors.onSurface),
shape = RoundedCornerShape(20.dp)
)
.clickable(
onClick = {
}
),
content = {
Column(
modifier = Modifier
.padding(10.dp)
.height(150.dp),
content = {
Row(
modifier = Modifier.padding(2.dp),
content = {
Text(
text = "Film Title: ".uppercase(), style = TextStyle(
color = MaterialTheme.colors.onBackground
)
)
Text(
text = filmsResult.title.uppercase(), style = TextStyle(
color = MaterialTheme.colors.onBackground,
fontWeight = FontWeight.Bold
)
)
}
)
Row(
modifier = Modifier
.padding(2.dp)
.fillMaxWidth(),
content = {
Text(
text = "No. of Characters ".uppercase(), style = TextStyle(
color = MaterialTheme.colors.onBackground,
)
)
Text(
text = filmsResult.characters.size.toString(),
style = TextStyle(
color = MaterialTheme.colors.onBackground,
fontWeight = FontWeight.Bold
)
)
}
)
Column(
modifier = Modifier.padding(2.dp),
content = {
Text(
text = "Film Description: ".uppercase(), style = TextStyle(
color = MaterialTheme.colors.onBackground,
fontWeight = FontWeight.Bold,
textDecoration = TextDecoration.Underline
)
)
Text(
text = filmsResult.openingCrawl, style = TextStyle(
color = MaterialTheme.colors.onBackground
)
)
}
)
}
)
}
)
}
} | 0 | Kotlin | 0 | 0 | 8301e6d22e20aa3a13501700ab6bd511b2fec885 | 9,562 | WATCHOUT | MIT License |
app/src/main/java/com/example/mytripactions/data/NewsArticle.kt | tripactions | 395,483,479 | false | {"Kotlin": 9692} | package com.example.mytripactions.data
data class NewsArticle(
val title: String?,
val url: String,
val thumbnailUrl: String?,
val publishedAt: String? = null,
val isBookmarked: Boolean = false,
val updatedAt: Long = System.currentTimeMillis()
) | 0 | Kotlin | 0 | 0 | f0a6be5e4bdf06430e9b56468d184f6ee41cd113 | 270 | ta-android-code-challenge | MIT License |
composeApp/src/commonMain/kotlin/com/ideabaker/kmp/translator/core/settings/LocalSettingsRepository.kt | bidadh | 717,167,879 | false | {"Kotlin": 98552, "Swift": 595, "Shell": 228} | @file:Suppress("unused")
package com.ideabaker.kmp.translator.core.settings
import co.touchlab.kermit.Logger
import com.russhwolf.settings.Settings
class LocalSettingsRepository(
private val settings: Settings,
private val log: Logger
) {
}
| 0 | Kotlin | 0 | 0 | 964b23315b74bacf6fc778be2dd9e74308975d85 | 248 | compose-multiplatform-template | Apache License 2.0 |
sdk/src/main/kotlin/com/processout/sdk/di/ContextGraph.kt | processout | 117,821,122 | false | {"Kotlin": 541640, "Java": 85090, "Shell": 696} | package com.processout.sdk.di
import android.app.Application
import com.processout.sdk.api.model.request.DeviceData
import com.processout.sdk.core.locale.currentAppLocale
import java.util.Calendar
internal interface ContextGraph {
val application: Application
val deviceData: DeviceData
}
internal class ContextGraphImpl(override val application: Application) : ContextGraph {
override val deviceData: DeviceData
get() = provideDeviceData()
private fun provideDeviceData(): DeviceData {
val displayMetrics = application.resources.displayMetrics
val timezoneOffset = Calendar.getInstance().let {
-(it.get(Calendar.ZONE_OFFSET) + it.get(Calendar.DST_OFFSET)) / (1000 * 60)
}
return DeviceData(
application.currentAppLocale().toLanguageTag(),
displayMetrics.widthPixels,
displayMetrics.heightPixels,
timezoneOffset
)
}
}
| 0 | Kotlin | 5 | 1 | 9179baffaccd9688e9a327a9faf721c963563a59 | 951 | processout-android | MIT License |
app/src/main/java/com/project/android/app/inotes/data/model/Entity.kt | fajaragungpramana | 202,125,203 | false | null | package com.project.android.app.inotes.data.model
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import com.google.gson.annotations.SerializedName
sealed class Entity : BaseObservable() {
data class User(
@SerializedName("photoUrl") var photoUrl: String? = null,
@SerializedName("firstName") @Bindable var firstName: String? = null,
@SerializedName("lastName") @Bindable var lastName: String? = null,
@SerializedName("email") @Bindable var email: String? = null,
@SerializedName("password") @Bindable var password: String? = null
) : Entity()
} | 0 | Kotlin | 1 | 5 | 242b9c745eec9cb11c6fc8592e47dc033e2315ae | 631 | Register-Login-and-Email-Verification-use-Dagger2-MVVM-Retrofit2-Coroutine-and-DataBinding | Apache License 2.0 |
promptkt/src/main/kotlin/tri/ai/gemini/GeminiClient.kt | aplpolaris | 663,584,917 | false | {"Kotlin": 855996, "Java": 7469, "CSS": 2840} | /*-
* #%L
* tri.promptfx:promptkt
* %%
* Copyright (C) 2023 - 2024 Johns Hopkins University Applied Physics Laboratory
* %%
* 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.
* #L%
*/
package tri.ai.gemini
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.plugins.*
import io.ktor.client.plugins.contentnegotiation.*
import io.ktor.client.plugins.logging.*
import io.ktor.client.request.*
import io.ktor.http.*
import io.ktor.serialization.kotlinx.json.*
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import tri.ai.core.TextChatMessage
import tri.ai.core.TextChatRole
import tri.ai.core.VisionLanguageChatMessage
import java.io.Closeable
import java.io.File
import java.net.URI
import java.util.logging.Logger
/** General purpose client for the Gemini API. */
class GeminiClient : Closeable {
private val settings = GeminiSettings()
private val client = settings.client
/** Returns true if the client is configured with an API key. */
fun isConfigured() = settings.apiKey.isNotBlank()
//region CORE API METHODS
suspend fun listModels(): ModelsResponse {
return client.get("models")
.body<ModelsResponse>()
}
suspend fun generateContent(modelId: String, request: GenerateContentRequest): GenerateContentResponse {
return client.post("models/$modelId:generateContent") {
setBody(request)
}.body<GenerateContentResponse>()
}
//endregion
//region ALTERNATE API METHODS
suspend fun embedContent(content: String, modelId: String, outputDimensionality: Int? = null): EmbedContentResponse {
val request = EmbedContentRequest(Content(listOf(Part(content))), outputDimensionality = outputDimensionality)
return client.post("models/$modelId:embedContent") {
setBody(request)
}.body<EmbedContentResponse>()
}
suspend fun batchEmbedContents(content: List<String>, modelId: String, outputDimensionality: Int? = null): BatchEmbedContentsResponse {
val request = BatchEmbedContentRequest(
content.map { EmbedContentRequest(Content(listOf(Part(it))), model = "models/$modelId", outputDimensionality = outputDimensionality) }
)
return client.post("models/$modelId:batchEmbedContents") {
setBody(request)
}.body<BatchEmbedContentsResponse>()
}
suspend fun generateContent(prompt: String, modelId: String) =
generateContent(modelId, GenerateContentRequest(Content.text(prompt)))
suspend fun generateContent(prompt: String, image: String, modelId: String): GenerateContentResponse {
val request = GenerateContentRequest(Content(listOf(
Part(text = prompt),
Part(inlineData = Blob(image, "image/jpeg"))
)))
return generateContent(modelId, request)
}
suspend fun generateContent(messages: List<TextChatMessage>, modelId: String, config: GenerationConfig? = null): GenerateContentResponse {
val system = messages.lastOrNull { it.role == TextChatRole.System }?.content
val request = GenerateContentRequest(
messages.filter { it.role != TextChatRole.System }.map {
val role = when (it.role) {
TextChatRole.User -> "user"
TextChatRole.Assistant -> "model"
else -> error("Invalid role: ${it.role}")
}
Content(listOf(Part(it.content)), role)
},
systemInstruction = system?.let { Content(listOf(Part(it)), "system") },
generationConfig = config
)
return generateContent(modelId, request)
}
suspend fun generateContentVision(messages: List<VisionLanguageChatMessage>, modelId: String, config: GenerationConfig? = null): GenerateContentResponse {
val system = messages.lastOrNull { it.role == TextChatRole.System }?.content
val request = GenerateContentRequest(
messages.filter { it.role != TextChatRole.System }.map {
val role = when (it.role) {
TextChatRole.User -> "user"
TextChatRole.Assistant -> "model"
else -> error("Invalid role: ${it.role}")
}
Content(listOf(
Part(it.content),
Part(null, Blob.image(it.image))
), role)
},
systemInstruction = system?.let { Content(listOf(Part(it)), "system") },
generationConfig = config
)
return generateContent(modelId, request)
}
//endregion
override fun close() {
client.close()
}
companion object {
val INSTANCE by lazy { GeminiClient() }
}
}
//region API SETTINGS
/** Manages Gemini API key and client. */
@OptIn(ExperimentalSerializationApi::class)
class GeminiSettings {
companion object {
const val API_KEY_FILE = "apikey-gemini.txt"
const val API_KEY_ENV = "GEMINI_API_KEY"
const val BASE_URL = " https://generativelanguage.googleapis.com/v1beta/"
}
var baseUrl = BASE_URL
set(value) {
field = value
buildClient()
}
var apiKey = readApiKey()
set(value) {
field = value
buildClient()
}
var timeoutSeconds = 60
set(value) {
field = value
buildClient()
}
/** The HTTP client used to make requests. */
var client: HttpClient = buildClient()
/** Read API key by first checking for [API_KEY_FILE], and then checking user environment variable [API_KEY_ENV]. */
private fun readApiKey(): String {
val file = File(API_KEY_FILE)
val key = if (file.exists()) {
file.readText()
} else
System.getenv(API_KEY_ENV)
return if (key.isNullOrBlank()) {
Logger.getLogger(GeminiSettings::class.java.name).warning(
"No API key found. Please create a file named $API_KEY_FILE in the root directory, or set an environment variable named $API_KEY_ENV."
)
""
} else
key
}
@Throws(IllegalStateException::class)
private fun buildClient() = HttpClient {
install(ContentNegotiation) {
json(Json {
isLenient = true
ignoreUnknownKeys = true
explicitNulls = false
})
}
install(Logging) {
logger = io.ktor.client.plugins.logging.Logger.SIMPLE
level = LogLevel.NONE
}
install(HttpTimeout) {
socketTimeoutMillis = timeoutSeconds * 1000L
connectTimeoutMillis = timeoutSeconds * 1000L
requestTimeoutMillis = timeoutSeconds * 1000L
}
defaultRequest {
url(baseUrl)
url.parameters.append("key", apiKey)
contentType(ContentType.Application.Json)
}
}.also { client = it }
}
//endregion
//region DTO's
@Serializable
data class ModelsResponse(
val models: List<ModelInfo>
)
@Serializable
data class ModelInfo(
val name: String,
val baseModelId: String? = null,
val version: String,
val displayName: String,
val description: String,
val inputTokenLimit: Int,
val outputTokenLimit: Int,
val supportedGenerationMethods: List<String>,
val temperature: Double? = null,
val topP: Double? = null,
val topK: Int? = null
)
@Serializable
data class BatchEmbedContentRequest(
val requests: List<EmbedContentRequest>
)
@Serializable
data class BatchEmbedContentsResponse(
val embeddings: List<ContentEmbedding>
)
@Serializable
data class EmbedContentRequest(
val content: Content,
val model: String? = null,
val title: String? = null,
val outputDimensionality: Int? = null
)
@Serializable
data class EmbedContentResponse(
val embedding: ContentEmbedding
)
@Serializable
data class ContentEmbedding(
val values: List<Float>
)
@Serializable
data class GenerateContentRequest(
val contents: List<Content>,
// val safetySettings: SafetySetting? = null,
val systemInstruction: Content? = null, // this is a beta feature
val generationConfig: GenerationConfig? = null,
) {
constructor(content: Content, systemInstruction: Content? = null, generationConfig: GenerationConfig? = null) :
this(listOf(content), systemInstruction, generationConfig)
}
@Serializable
data class Content(
val parts: List<Part>,
val role: String? = null
) {
init { require(role in listOf(null, "user", "model")) { "Invalid role: $role" } }
companion object {
/** Content with a single text part. */
fun text(text: String) = Content(listOf(Part(text)), "user")
}
}
@Serializable
data class Part(
val text: String? = null,
val inlineData: Blob? = null
)
@Serializable
data class Blob(
val mimeType: String,
val data: String
) {
companion object {
/** Generate blob from image URL. */
fun image(url: URI) = image(url.toASCIIString())
/** Generate blob from image URL. */
fun image(urlStr: String): Blob {
if (urlStr.startsWith("data:image/")) {
val mimeType = urlStr.substringBefore(";base64,").substringAfter("data:")
val base64 = urlStr.substringAfter(";base64,")
return Blob(mimeType, base64)
} else {
throw UnsupportedOperationException("Only data URLs are supported for images.")
}
}
}
}
@Serializable
data class GenerationConfig(
val stopSequences: List<String>? = null,
val responseMimeType: String? = null,
val candidateCount: Int? = null,
val maxOutputTokens: Int? = null,
val temperature: Double? = null,
val topP: Double? = null,
val topK: Int? = null
) {
init {
require(responseMimeType in listOf(null, "text/plain", "application/json")) { "Invalid responseMimeType: $responseMimeType" }
}
}
@Serializable
data class GenerateContentResponse(
var error: Error? = null,
var candidates: List<Candidate>? = null
)
@Serializable
data class Candidate(
val content: Content
)
@Serializable
data class Error(
val message: String
)
//endregion | 40 | Kotlin | 1 | 16 | 0e02b4ebbf1aa6660518cd5da16f6c07271d37b4 | 10,935 | promptfx | Apache License 2.0 |
android/app/src/main/java/com/salastroya/bgandroid/services/auth/JWTService.kt | adrisalas | 780,369,375 | false | {"Kotlin": 344780, "TypeScript": 81133, "HTML": 44607, "CSS": 5704} | package com.salastroya.bgandroid.services.auth
import android.content.Context
import android.content.SharedPreferences
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
object JWTService {
private const val JWT_KEY = "jwt"
lateinit var sharedPreferences: SharedPreferences
var jwtStore by mutableStateOf("")
private set
fun getJwtFromPreferences(context: Context): String {
return sharedPreferences.getString(JWT_KEY, "") ?: ""
}
fun storeJwt(context: Context, jwt: String) {
val editor: SharedPreferences.Editor = sharedPreferences.edit()
editor.putString(JWT_KEY, jwt)
editor.apply()
jwtStore = jwt
}
fun clearJwt(context: Context) {
val editor: SharedPreferences.Editor = sharedPreferences.edit()
editor.remove(JWT_KEY)
editor.apply()
jwtStore = ""
}
fun getUserName(): String {
return "Stella"
}
} | 0 | Kotlin | 0 | 0 | afd41380db03e474bfb5650555f4831a7198852f | 1,019 | botanic-garden | MIT License |
MedJournal/app/src/main/java/com/example/medjournal/registerlogin/LoginActivity.kt | r-k-jonynas | 254,635,112 | true | {"Kotlin": 95196} | package com.example.medjournal.registerlogin
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.medjournal.home.HomeActivity
import com.example.medjournal.R
import com.google.firebase.auth.FirebaseAuth
import kotlinx.android.synthetic.main.activity_login.*
/**
* Activity that controls login
*/
class LoginActivity : AppCompatActivity() {
/**
* Instantiate login view
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
login_button_login.setOnClickListener {
performLogin()
}
back_to_register_textview.setOnClickListener {
finish()
}
}
/**
* Perform login activity, including input validation and varifying with Firebase Auth
*/
private fun performLogin() {
val email = email_edittext_login.text.toString()
val password = password_edittext_login.text.toString()
if (email.isEmpty() || password.isEmpty()) {
Toast.makeText(this, "Please fill out email/pw.", Toast.LENGTH_SHORT).show()
return
}
FirebaseAuth.getInstance().signInWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (!it.isSuccessful) return@addOnCompleteListener
Log.d("Login", "Successfully logged in: ${it.result.user.uid}")
val intent = Intent(this, HomeActivity::class.java)
intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TASK.or(Intent.FLAG_ACTIVITY_NEW_TASK)
startActivity(intent)
}
.addOnFailureListener {
Toast.makeText(this, "Failed to log in: ${it.message}", Toast.LENGTH_SHORT).show()
}
}
} | 0 | null | 0 | 0 | 03c1c7cef6b0f0cc858f1ec1f887438957d1a068 | 1,914 | medjournal | Apache License 2.0 |
checkpoint-core/src/main/kotlin/com/natigbabayev/checkpoint/core/rules/AnyRuleDsl.kt | natiginfo | 248,285,985 | false | null | @file:JvmName("AnyRuleDsl")
package com.natigbabayev.checkpoint.core.rules
import com.natigbabayev.checkpoint.core.DefaultRule
import com.natigbabayev.checkpoint.core.Rule
/**
* @param block a lambda which will be invoked when [AnyRule.canPass] returns false.
*/
inline fun <T> AnyRule.Builder<T>.whenInvalid(
crossinline block: (input: T) -> Unit
) = apply {
whenInvalid(Rule.Callback { block(it) })
}
/**
* @param whenInvalid a lambda which will be invoked, when [AnyRule.canPass] returns false.
* @return instance of [AnyRule]
*/
inline fun <T> anyRule(
vararg rules: DefaultRule<T>,
crossinline whenInvalid: (input: T) -> Unit
): AnyRule<T> {
val builder = AnyRule.Builder<T>()
.whenInvalid(Rule.Callback { whenInvalid(it) })
.addRules(rules.toList())
return builder.build()
}
/**
* @param whenInvalid a lambda which will be invoked, when [AnyRule.canPass] returns false.
* @return instance of [AnyRule]
*/
inline fun <T> anyRule(
rules: List<DefaultRule<T>>,
crossinline whenInvalid: (input: T) -> Unit
): AnyRule<T> {
val builder = AnyRule.Builder<T>()
.whenInvalid(Rule.Callback { whenInvalid(it) })
.addRules(rules)
return builder.build()
}
/**
* @return new instance of [AnyRule] without any callback.
*/
fun <T> anyRule(rules: List<DefaultRule<T>>): AnyRule<T> {
val builder = AnyRule.Builder<T>()
.addRules(rules)
return builder.build()
}
| 3 | Kotlin | 3 | 24 | 3595bb76d753c40f10478e2b9999b77332ac7704 | 1,457 | Checkpoint | Apache License 2.0 |
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/battle/AbilityArgument.kt | Anime-Game-Servers | 642,871,918 | false | {"Kotlin": 1651536} | package org.anime_game_servers.multi_proto.gi.data.battle
import org.anime_game_servers.core.base.Version.GI_CB1
import org.anime_game_servers.core.base.annotations.AddedIn
import org.anime_game_servers.core.base.annotations.proto.OneOf
import org.anime_game_servers.core.base.annotations.proto.OneOfEntry
import org.anime_game_servers.core.base.annotations.proto.OneOfType
import org.anime_game_servers.core.base.annotations.proto.ProtoModel
@AddedIn(GI_CB1)
@ProtoModel
internal interface AbilityArgument {
@OneOf(
types = [
OneOfEntry(Float::class, "float_arg"),
OneOfEntry(Int::class, "int_arg"),
OneOfEntry(String::class, "str_arg"),
]
)
var arg: OneOfType
}
| 1 | Kotlin | 3 | 6 | b342ff34dfb0f168a902498b53682c315c40d44e | 735 | anime-game-multi-proto | MIT License |
app/src/main/java/blue/aodev/animeultimetv/utils/SimpleAnimatorListener.kt | esnaultdev | 94,973,529 | false | null | package blue.aodev.animeultimetv.utils
import android.animation.Animator
interface SimpleAnimatorListener: Animator.AnimatorListener {
override fun onAnimationStart(p0: Animator) {}
override fun onAnimationEnd(p0: Animator) {}
override fun onAnimationCancel(p0: Animator) {}
override fun onAnimationRepeat(p0: Animator) {}
} | 1 | Kotlin | 1 | 1 | 481bb13907ec07226180290c5dbfc4e96284d950 | 346 | AnimeUltimeTv | MIT License |
bookpage/src/main/java/com/kai/bookpage/page/PageView.kt | pressureKai | 326,004,502 | false | null | package com.kai.bookpage.page
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.RectF
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.widget.TextView
import com.kai.bookpage.animation.*
import com.kai.bookpage.model.CoolBookBean
import com.kai.common.utils.LogUtils
import java.lang.Exception
import kotlin.math.abs
/**
* # 页面展示控件,无需关心数据来源,因为数据来源可能有多种方法。降低程序耦合度。
*/
class PageView: View{
private val TAG = "PageView"
//当前View的宽呃呃
private var mViewWidth = 0
//当前View的高
private var mViewHeight = 0
private var mStartX = 0
private var mStartY = 0
private var isMove = false
private var mBgColor = -0x313d64
private var mPageMode = PageMode.NONE
//是否允许点击
private var canTouch = true
//唤醒菜单的区域
private var mCenterRect : RectF ?= null
private var isPrepare = false
//动画类
private var mPageAnimation : PageAnimation?= null
//动画监听类
private var mPageAnimationListener : PageAnimation.OnPageChangeListener = object :PageAnimation.OnPageChangeListener{
override fun hasPrePage(): Boolean {
return [email protected]()
}
override fun hasNext(): Boolean {
return [email protected]()
}
override fun pageCancel(): Boolean {
[email protected]()
return true
}
}
//点击监听
private var mTouchListener : TouchListener ?= null
//内容加载器
private var mPageLoader : PageLoader ?= null
constructor(context: Context) : this(context, null)
constructor(context: Context, attributeSet: AttributeSet?) :this(context, attributeSet, 0)
constructor(context: Context, attributeSet: AttributeSet?, defStyleAttr: Int) :
super(context, attributeSet, defStyleAttr)
override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
super.onSizeChanged(w, h, oldw, oldh)
mViewWidth = w
mViewHeight = h
isPrepare = true
mPageLoader?.prepareDisplay(w, h)
}
override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
mPageAnimation?.abortAnimation()
mPageAnimation?.clear()
mPageLoader = null
mPageAnimation = null
}
fun hasPrePage() :Boolean{
//不做实际上的翻页操作
mTouchListener?.prePage()
var hasPre = false
mPageLoader?.let {
//实际上的翻页操作
hasPre = it.pre()
}
return hasPre
}
override fun onDraw(canvas: Canvas?) {
canvas?.let {
//绘制背景
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q) {
it.drawColor(mBgColor)
} else {
it.drawColor(context.resources.getColor(android.R.color.white))
}
//绘制动画
mPageAnimation?.draw(canvas)
}
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
super.onTouchEvent(event)
event?.let {
if(!canTouch && event.action != MotionEvent.ACTION_DOWN){
return true
}
val x = event.x.toInt()
val y = event.y.toInt()
when(event.action){
MotionEvent.ACTION_DOWN -> {
mStartX = x
mStartY = y
isMove = false
mTouchListener?.let {
canTouch = it.onTouch()
}
mPageAnimation?.onTouchEvent(event)
}
MotionEvent.ACTION_MOVE -> {
//判断是否大于最小滑动值
val slop = ViewConfiguration.get(context).scaledTouchSlop
if (!isMove) {
isMove = abs(mStartX - event.x) > slop
|| abs(mStartY - event.y) > slop
}
if (isMove) {
//如果滑动了,则进行翻页
mPageAnimation?.onTouchEvent(event)
} else {
}
// LogUtils.e("PageView", "MotionEvent.ACTION_MOVE")
}
MotionEvent.ACTION_UP -> {
if (!isMove) {
//设置中间区域范围
if (mCenterRect == null) {
mCenterRect = RectF(mViewWidth.toFloat() / 5,
mViewHeight.toFloat() / 3,
mViewHeight.toFloat() * 4 / 5,
mViewHeight.toFloat() * 2 / 3)
}
//是否点击了中间
val contains = mCenterRect?.contains(x.toFloat(), y.toFloat())
if (contains != null) {
if (contains) {
mTouchListener?.center()
return true
}
}
}
mPageAnimation?.onTouchEvent(event)
}
else -> {
return true
}
}
}
return true
}
fun hasNextPage():Boolean{
mTouchListener?.nextPage()
var hasNext = false
mPageLoader?.let {
hasNext = it.next()
}
LogUtils.e("PageView","hasNext $hasNext")
return hasNext
}
fun pageCancel(){
mTouchListener?.cancel()
mPageLoader?.pageCancel()
}
override fun computeScroll() {
//进行滑动
mPageAnimation?.scrollAnimation()
super.computeScroll()
}
fun drawCurrentPage(isUpdate: Boolean){
if(!isPrepare){
return
}
if(!isUpdate){
if(mPageAnimation is ScrollPageAnimation){
(mPageAnimation as ScrollPageAnimation).resetBitmap()
}
}
getNextBitmap()?.let {
mPageLoader?.drawPage(it, isUpdate)
}
}
fun setTouchListener(touchListener: TouchListener){
mTouchListener = touchListener
}
//设置翻页模式
fun setPageMode(pageMode: PageMode){
mPageMode = pageMode
if(mViewWidth == 0 || mViewHeight ==0){
return
}
when(mPageMode){
PageMode.SIMULATION -> {
LogUtils.e("PageView","init SimulationPageAnimation $mPageMode")
mPageAnimation = SimulationPageAnimation(mViewWidth, mViewHeight, this, mPageAnimationListener)
}
PageMode.COVER -> {
mPageAnimation = CoverAnimation(mViewWidth, mViewHeight, this, mPageAnimationListener)
}
PageMode.SLIDE -> {
mPageAnimation = SlideAnimation(mViewWidth, mViewHeight, this, mPageAnimationListener)
}
PageMode.NONE -> {
LogUtils.e("PageView","init NonePageAnimation $mPageMode")
mPageAnimation = NonePageAnimation(mViewWidth, mViewHeight, this, mPageAnimationListener)
}
PageMode.SCROLL -> {
mPageAnimation = ScrollPageAnimation(mViewWidth, mViewHeight, this, mPageAnimationListener)
}
else -> {
mPageAnimation = NonePageAnimation(mViewWidth, mViewHeight, this, mPageAnimationListener)
}
}
}
fun setBgColor(bgColor: Int){
mBgColor = bgColor
}
private fun startPageAnimation(direction: PageAnimation.Direction){
if(mTouchListener == null){
return
}
abortAnimation()
if(direction == PageAnimation.Direction.NEXT){
val x = mViewWidth
val y = mViewHeight
//初始化动画
mPageAnimation?.setStartPoint(x.toFloat(), y.toFloat())
//设置点击点
mPageAnimation?.setTouchPoint(x.toFloat(), y.toFloat())
//设置方向
mPageAnimation?.setDirection(direction)
if(!hasNextPage()){
return
}
}else{
val x = 0
val y = mViewHeight
//初始化动画
mPageAnimation?.setStartPoint(x.toFloat(), y.toFloat())
//设置点击
mPageAnimation?.setTouchPoint(x.toFloat(), y.toFloat())
mPageAnimation?.setDirection(direction)
if(!hasPrePage()){
return
}
}
mPageAnimation?.startAnimation()
postInvalidate()
}
//是否能够翻页
fun autoPrePage() :Boolean{
var auto = false
mPageAnimation?.let {
auto = it !is ScrollPageAnimation
if(auto){
startPageAnimation(PageAnimation.Direction.PRE)
}
}
return auto
}
//是否能够翻页
fun autoNextPage() :Boolean{
var auto = false
mPageAnimation?.let {
auto = it !is ScrollPageAnimation
if(auto){
startPageAnimation(PageAnimation.Direction.NEXT)
}
}
return false
}
fun isPrepare() :Boolean{
return isPrepare
}
fun isRunning() : Boolean{
if(mPageAnimation == null){
return false
}
return mPageAnimation!!.isRunning()
}
fun drawNextPage(){
if(!isPrepare){
return
}
if(mPageAnimation is BaseHorizontalPageAnimation){
(mPageAnimation as BaseHorizontalPageAnimation).changePage()
}
getNextBitmap()?.let {
mPageLoader?.drawPage(it, false)
}
}
/**
* #获取页面内容生成的Bitmap
* @return bitmap
*/
private fun getNextBitmap(): Bitmap?{
if(mPageAnimation == null){
return null
}
return mPageAnimation?.getNextBitmap()
}
/**
* # 外部调用此方法作为程序入口?
* @param [coolBookBean] 书籍实体类
* @return PageLoader 页面加载器
* @date 2021/4/14
*/
fun getPageLoader(coolBookBean: CoolBookBean,pageLoader: PageLoader): PageLoader?{
//判断是否存在,存在直接返回
if(mPageLoader != null){
return mPageLoader!!
}
//根据数据类型 coolBookBean.isLocal,获取具体加载器
mPageLoader = pageLoader
if(mViewWidth != 0 || mViewHeight != 0){
//初始化PageLoader的屏幕大小
mPageLoader?.prepareDisplay(mViewWidth, mViewHeight)
}
return mPageLoader
}
fun getBgBitmap(): Bitmap?{
if(mPageAnimation == null){
return null
}
return mPageAnimation?.getBgBitmap()
}
interface TouchListener{
fun onTouch() :Boolean
fun center()
fun prePage()
fun nextPage()
fun cancel()
}
//如果滑动状态没有停止就取消状态,重新设置Animation的触碰点
fun abortAnimation(){
mPageAnimation?.abortAnimation()
}
} | 0 | Kotlin | 1 | 1 | 73edc5e8b838f9ba89e5ac717051c15871120673 | 11,031 | FreeRead | Apache License 2.0 |
app/src/test/java/id/rizmaulana/covid19/ui/InstantTaskExecutorRule.kt | rizmaulana | 245,557,715 | false | null | package id.dtprsty.movieme
import androidx.arch.core.executor.ArchTaskExecutor
import androidx.arch.core.executor.TaskExecutor
import org.spekframework.spek2.dsl.Root
class InstantTaskExecutorRule(root: Root) {
init {
root.beforeGroup {
ArchTaskExecutor.getInstance().setDelegate(object : TaskExecutor() {
override fun isMainThread(): Boolean = true
override fun executeOnDiskIO(runnable: Runnable) = runnable.run()
override fun postToMainThread(runnable: Runnable) = runnable.run()
})
}
root.afterGroup {
ArchTaskExecutor.getInstance().setDelegate(null)
}
}
}
| 10 | null | 2 | 433 | 3e1e8027f2a5135ed72cb6aed3bc717e68bed80a | 688 | kotlin-mvvm-covid19 | Apache License 2.0 |
libs/commons-database/src/main/kotlin/gov/cdc/ocio/database/health/HealthCheckCouchbaseDb.kt | CDCgov | 679,761,337 | false | {"Kotlin": 650992, "Python": 14605, "TypeScript": 7647, "Java": 4266, "JavaScript": 2382} | package gov.cdc.ocio.database.health
import com.couchbase.client.java.Cluster
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import gov.cdc.ocio.database.couchbase.CouchbaseConfiguration
import gov.cdc.ocio.types.health.HealthCheckSystem
import gov.cdc.ocio.types.health.HealthStatusType
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
/**
* Concrete implementation of the couchbase health check.
*/
@JsonIgnoreProperties("koin")
class HealthCheckCouchbaseDb: HealthCheckSystem("Couchbase DB"), KoinComponent {
private val config by inject<CouchbaseConfiguration>()
/**
* Checks and sets couchbase status
*/
override fun doHealthCheck() {
try {
if (isCouchbaseDBHealthy()) {
status = HealthStatusType.STATUS_UP
}
} catch (ex: Exception) {
logger.error("Cosmos DB is not healthy $ex.message")
healthIssues = ex.message
}
}
/**
* Check whether couchbase is healthy.
*
* @return Boolean
*/
private fun isCouchbaseDBHealthy(): Boolean {
return if (Cluster.connect(config.connectionString, config.username, config.password) == null)
throw Exception("Failed to establish a couchbase client.")
else
true
}
} | 4 | Kotlin | 0 | 2 | 24fcd039649d7ed9fdeab5750911b1543715926a | 1,343 | data-exchange-processing-status | Apache License 2.0 |
build-tools/common/src/main/kotlin/aditogether/buildtools/utils/ExtensionUtils.kt | androiddevelopersitalia | 592,286,569 | false | null | package aditogether.buildtools.utils
import org.gradle.api.plugins.ExtensionContainer
/**
* Invokes Groovy's [ExtensionContainer.getByType] reifying the type [T].
*/
inline fun <reified T : Any> ExtensionContainer.getByType(): T = getByType(T::class.java)
/**
* Invokes Groovy's [ExtensionContainer.configure] reifying the type [T].
*/
inline fun <reified T : Any> ExtensionContainer.configure(noinline action: (T) -> Unit) {
configure(T::class.java, action)
}
| 13 | Kotlin | 0 | 17 | 94b51e5d3e108b04b5fcbca788c74d17cf455cd0 | 472 | aditogether | Apache License 2.0 |
chat/src/main/java/cn/wildfire/imshat/wallet/activity/TestNetActivity.kt | SKYNET-DAO | 470,424,807 | false | {"Java": 2293967, "Kotlin": 127502, "AIDL": 16960} | package cn.wildfire.imshat.wallet.activity
import android.content.Context
import android.content.SharedPreferences
import android.os.Build
import android.text.TextUtils
import android.view.MenuItem
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import cn.wildfire.imshat.kit.ChatManagerHolder
import cn.wildfire.imshat.kit.GlideApp
import cn.wildfire.imshat.kit.WfcBaseActivity
import com.android.base.utils.ACacheUtil
import cn.wildfire.imshat.wallet.BitUtil
import cn.wildfire.imshat.wallet.Kit
import cn.wildfire.imshat.wallet.WalletManager
import cn.wildfire.imshat.wallet.services.WalletService
import cn.wildfire.imshat.wallet.viewmodel.WalletViewModel
import cn.wildfirechat.imshat.R
import com.afollestad.materialdialogs.MaterialDialog
import com.orhanobut.logger.Logger
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_mnemonic.*
import kotlinx.android.synthetic.main.activity_net_test.*
import org.bitcoinj.crypto.MnemonicCode
import org.bitcoinj.wallet.UnreadableWalletException
class TestNetActivity : WfcBaseActivity() {
var sharedPreferences: SharedPreferences? = null
lateinit var walletViewModel:WalletViewModel
override fun contentLayout(): Int = R.layout.activity_net_test
override fun afterViews() {
walletViewModel=ViewModelProviders.of(this).get(WalletViewModel::class.java)
walletViewModel.walletLoadLiveData.observe(this, Observer {
netpeer.text=it.networkParameters.id
lastblockheight.text=it.lastBlockSeenHeight.toString()
lasthash.text=it.lastBlockSeenHash.toString()
})
walletViewModel.walletLoadLiveData.loadWallet()
}
}
| 1 | null | 1 | 1 | 905c1be47b379e87d1f5e1625841b7422c27a682 | 1,807 | SKYCHAT | MIT License |
core/src/main/kotlin/com/kurtraschke/gtfsrtarchiver/core/CustomObjectMapperSupplier.kt | kurtraschke | 467,207,020 | false | {"Kotlin": 54554} | package com.kurtraschke.gtfsrtarchiver.core
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.datatype.guava.GuavaModule
import io.hypersistence.utils.hibernate.type.util.ObjectMapperSupplier
class CustomObjectMapperSupplier : ObjectMapperSupplier {
override fun get(): ObjectMapper {
val objectMapper = ObjectMapper().findAndRegisterModules()
objectMapper.registerModule(GuavaModule())
return objectMapper
}
}
| 0 | Kotlin | 0 | 2 | 3eed893a7b8f91bbc5f1becb002f1dcd3b63a666 | 477 | gtfs-rt-archiver | Apache License 2.0 |
core/src/com/mo/stratego/model/game/GameMode.kt | GPla | 217,608,618 | false | null | package com.mo.stratego.model.game
import com.mo.stratego.model.player.PlayerType
/**
* Enum of game modes.
*/
enum class GameMode {
LOCAL,
MULTI,
AI;
/**
* @return The [PlayerType] for the second player.
*/
fun get2PType(): PlayerType =
when (this) {
LOCAL -> PlayerType.LOCAL
MULTI -> PlayerType.PROXY
AI -> PlayerType.LOCAL
}
} | 1 | Kotlin | 1 | 1 | bfcde4983771f6eabfd3060278424549d379dccf | 440 | Stratego | MIT License |
posts/src/main/java/com/addhen/checkin/posts/view/PostsFragment.kt | zularizal | 151,024,171 | false | null | /*
* Copyright (c) 2015 - 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.addhen.checkin.posts.view
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.addhen.checkin.base.Resource
import com.addhen.checkin.base.extension.snackbar
import com.addhen.checkin.base.view.BaseFragment
import com.addhen.checkin.posts.databinding.PostsFragmentBinding
class PostsFragment : BaseFragment<PostsViewModel, PostsFragmentBinding>(
clazz = PostsViewModel::class.java
) {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = PostsFragmentBinding.inflate(layoutInflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
initView()
}
private fun initView() {
val postsAdapter = PostsAdapter(requireContext())
binding.postsRecyclerView.adapter = postsAdapter
val linearLayoutManager = object : LinearLayoutManager(context) {
override fun getExtraLayoutSpace(state: RecyclerView.State) = 300
}
binding.postsRecyclerView.layoutManager = linearLayoutManager
viewModel.posts.observe(this, Observer {
when (it?.status) {
Resource.Status.SUCCESS -> {
binding.swipeRefreshLayout.isRefreshing = false
val list = viewModel.posts.value?.data ?: emptyList()
binding.emptyViewHeader.isVisible = list.isEmpty()
postsAdapter.reset(list)
}
Resource.Status.LOADING -> {
binding.swipeRefreshLayout.isRefreshing = true
binding.emptyViewHeader.isVisible = false
}
else -> {
binding.loadingProgressBar.isVisible = false
binding.emptyViewHeader.isVisible = false
binding.postRootFramelayout.snackbar(viewModel.posts.value?.message!!)
}
}
})
lifecycle.addObserver(viewModel)
}
companion object {
const val TAG: String = "PostsFragment"
fun newInstance(): PostsFragment = PostsFragment()
}
}
| 0 | Kotlin | 1 | 0 | e95e26679ee045456814155b286ae20931f12ff2 | 2,882 | checkin | MIT License |
common/src/main/java/io/homeassistant/companion/android/common/data/websocket/impl/entities/ConversationResponse.kt | home-assistant | 179,008,173 | false | {"Kotlin": 2639109, "Ruby": 3180} | package io.homeassistant.companion.android.common.data.websocket.impl.entities
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
@JsonIgnoreProperties(ignoreUnknown = true)
data class ConversationResponse(
val response: ConversationSpeechResponse,
val conversationId: String?
)
| 190 | Kotlin | 636 | 2,296 | 11367c2193316cec9579791b38006fab094293de | 299 | android | Apache License 2.0 |
shared/src/commonMain/kotlin/co/touchlab/kampkit/models/BreedModel.kt | myworkout | 360,164,604 | true | {"Kotlin": 497647, "Swift": 8040, "Ruby": 2216} | package co.touchlab.kampkit.models
import co.touchlab.kampkit.DatabaseHelper
import co.touchlab.kampkit.db.Breed
import co.touchlab.kampkit.ktor.KtorApi
import co.touchlab.stately.ensureNeverFrozen
import com.russhwolf.settings.Settings
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.datetime.Clock
import org.koin.core.component.KoinComponent
import org.koin.core.component.inject
class BreedModel : KoinComponent {
private val dbHelper: DatabaseHelper by inject()
private val settings: Settings by inject()
private val ktorApi: KtorApi by inject()
private val clock: Clock by inject()
companion object {
internal const val DB_TIMESTAMP_KEY = "DbTimestampKey"
}
init {
ensureNeverFrozen()
}
fun refreshBreedsIfStale(forced: Boolean = false): Flow<DataState<ItemDataSummary>> = flow {
emit(DataState.Loading)
val currentTimeMS = clock.now().toEpochMilliseconds()
val stale = isBreedListStale(currentTimeMS)
val networkBreedDataState: DataState<ItemDataSummary>
if (stale || forced) {
networkBreedDataState = getBreedsFromNetwork(currentTimeMS)
when (networkBreedDataState) {
DataState.Empty -> {
// Pass the empty response along
emit(networkBreedDataState)
}
is DataState.Success -> {
dbHelper.insertBreeds(networkBreedDataState.data.allItems)
}
is DataState.Error -> {
// Pass the error along
emit(networkBreedDataState)
}
DataState.Loading -> {
// Won't ever happen
}
}
}
}
fun getBreedsFromCache(): Flow<DataState<ItemDataSummary>> =
dbHelper.selectAllItems()
.mapNotNull { itemList ->
if (itemList.isEmpty()) {
null
} else {
DataState.Success(
ItemDataSummary(
itemList.maxByOrNull { it.name.length },
itemList
)
)
}
}
private fun isBreedListStale(currentTimeMS: Long): Boolean {
val lastDownloadTimeMS = settings.getLong(DB_TIMESTAMP_KEY, 0)
val oneHourMS = 60 * 60 * 1000
return lastDownloadTimeMS + oneHourMS < currentTimeMS
}
suspend fun getBreedsFromNetwork(currentTimeMS: Long): DataState<ItemDataSummary> {
return try {
val breedResult = ktorApi.getJsonFromApi()
val breedList = breedResult.message.keys.sorted().toList()
settings.putLong(DB_TIMESTAMP_KEY, currentTimeMS)
if (breedList.isEmpty()) {
DataState.Empty
} else {
DataState.Success(
ItemDataSummary(
null,
breedList.map { Breed(0L, it, 0L) }
)
)
}
} catch (e: Exception) {
DataState.Error("Unable to download breed list")
}
}
suspend fun updateBreedFavorite(breed: Breed) {
dbHelper.updateFavorite(breed.id, breed.favorite != 1L)
}
}
data class ItemDataSummary(val longestItem: Breed?, val allItems: List<Breed>)
| 0 | Kotlin | 0 | 0 | f1af526d80b1c9ff506dc9e28a1faaa8cd160f77 | 3,512 | KaMPKit | Apache License 2.0 |
plugins/github/src/org/jetbrains/plugins/github/pullrequest/ui/details/action/GHPRReopenAction.kt | hieuprogrammer | 284,920,751 | true | null | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.ui.details.action
import org.jetbrains.plugins.github.i18n.GithubBundle
import org.jetbrains.plugins.github.pullrequest.ui.details.GHPRStateModel
import java.awt.event.ActionEvent
internal class GHPRReopenAction(stateModel: GHPRStateModel)
: GHPRStateChangeAction(GithubBundle.message("pull.request.reopen.action"), stateModel) {
override fun actionPerformed(e: ActionEvent?) = stateModel.submitReopenTask()
} | 1 | null | 1 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 606 | intellij-community | Apache License 2.0 |
ui/view/src/main/kotlin/me/gegenbauer/catspy/view/table/RowNavigation.kt | Gegenbauer | 609,809,576 | false | {"Kotlin": 652879} | package me.gegenbauer.catspy.view.table
interface RowNavigation {
fun moveToNextRow()
fun moveToPreviousRow()
fun moveToFirstRow()
fun moveToLastRow()
fun moveRowToCenter(rowIndex: Int, setSelected: Boolean)
fun scrollToEnd()
fun moveToNextSeveralRows()
fun moveToPreviousSeveralRows()
} | 0 | Kotlin | 1 | 7 | 70d905761d3cb0cb2e5ee9b80ceec72fca46ee52 | 327 | CatSpy | Apache License 2.0 |
app/src/main/java/org/tokend/template/features/redeem/accept/logic/ConfirmRedemptionRequestUseCase.kt | tokend | 192,905,357 | false | null | package org.tokend.template.features.redeem.accept.logic
import io.reactivex.Completable
import io.reactivex.Single
import io.reactivex.rxkotlin.toMaybe
import io.reactivex.rxkotlin.toSingle
import io.reactivex.schedulers.Schedulers
import org.tokend.rx.extensions.toSingle
import org.tokend.sdk.api.transactions.model.SubmitTransactionResponse
import org.tokend.sdk.api.v3.accounts.params.AccountParamsV3
import org.tokend.template.di.providers.ApiProvider
import org.tokend.template.di.providers.RepositoryProvider
import org.tokend.template.di.providers.WalletInfoProvider
import org.tokend.template.features.redeem.model.RedemptionRequest
import org.tokend.template.features.systeminfo.model.SystemInfoRecord
import org.tokend.template.logic.TxManager
import org.tokend.wallet.NetworkParams
import org.tokend.wallet.Transaction
class ConfirmRedemptionRequestUseCase(
private val request: RedemptionRequest,
private val repositoryProvider: RepositoryProvider,
private val walletInfoProvider: WalletInfoProvider,
private val apiProvider: ApiProvider,
private val txManager: TxManager
) {
class RedemptionAlreadyProcessedException : Exception()
private lateinit var accountId: String
private lateinit var systemInfo: SystemInfoRecord
private lateinit var networkParams: NetworkParams
private lateinit var senderBalanceId: String
private lateinit var transaction: Transaction
private lateinit var submitTransactionResponse: SubmitTransactionResponse
fun perform(): Completable {
return getSystemInfo()
.doOnSuccess { systemInfo ->
this.systemInfo = systemInfo
this.networkParams = systemInfo.toNetworkParams()
}
.flatMap {
getSenderBalanceId()
}
.doOnSuccess { senderBalanceId ->
this.senderBalanceId = senderBalanceId
}
.flatMap {
getAccountId()
}
.doOnSuccess { accountId ->
this.accountId = accountId
}
.flatMap {
getTransaction()
}
.doOnSuccess { transaction ->
this.transaction = transaction
}
.flatMap {
submitTransaction()
}
.doOnSuccess { submitTransactionResponse ->
this.submitTransactionResponse = submitTransactionResponse
}
.flatMap {
ensureActualSubmit()
}
.doOnSuccess {
updateRepositories()
}
.ignoreElement()
}
private fun getSystemInfo(): Single<SystemInfoRecord> {
val systemInfoRepository = repositoryProvider.systemInfo()
return systemInfoRepository
.updateDeferred()
.andThen(Single.defer {
Single.just(systemInfoRepository.item!!)
})
}
private fun getSenderBalanceId(): Single<String> {
val signedApi = apiProvider.getSignedApi()
?: return Single.error(IllegalStateException("No signed API instance found"))
return signedApi.v3.accounts
.getById(request.sourceAccountId, AccountParamsV3(
listOf(AccountParamsV3.Includes.BALANCES)
))
.map { it.balances }
.toSingle()
.flatMapMaybe {
it.find { balanceResource ->
balanceResource.asset.id == request.assetCode
}?.id.toMaybe()
}
.switchIfEmpty(Single.error(
IllegalStateException("No balance ID found for ${request.assetCode}")
))
}
private fun getAccountId(): Single<String> {
return walletInfoProvider
.getWalletInfo()
?.accountId
.toMaybe()
.switchIfEmpty(Single.error(IllegalStateException("Missing account ID")))
}
private fun getTransaction(): Single<Transaction> {
return {
request.toTransaction(senderBalanceId, accountId, networkParams)
}.toSingle().subscribeOn(Schedulers.newThread())
}
private fun submitTransaction(): Single<SubmitTransactionResponse> {
return txManager.submit(transaction)
}
private fun ensureActualSubmit(): Single<Boolean> {
val latestBlockBeforeSubmit = systemInfo.latestBlock
val transactionBlock = submitTransactionResponse.ledger ?: 0
// The exactly same transaction is always accepted without any errors
// but if it wasn't the first submit the block number will be lower than the latest one.
return if (transactionBlock <= latestBlockBeforeSubmit) {
Single.error(RedemptionAlreadyProcessedException())
} else {
Single.just(true)
}
}
private fun updateRepositories() {
val balance = repositoryProvider.balances()
.itemsList
.find { it.assetCode == request.assetCode }
val balanceId = balance?.id
val asset = balance?.asset
val senderNickname = repositoryProvider.accountDetails()
.getCachedIdentity(request.sourceAccountId)
?.email
val balanceChangesRepositories = mutableListOf(repositoryProvider.balanceChanges(null))
if (balanceId != null) {
balanceChangesRepositories.add(repositoryProvider.balanceChanges(balanceId))
}
if (asset != null && balanceId != null) {
balanceChangesRepositories.forEach {
it.addAcceptedIncomingRedemption(
request = request,
asset = asset,
balanceId = balanceId,
accountId = accountId,
senderNickname = senderNickname
)
}
repositoryProvider.balances().apply {
if (!updateBalancesByTransactionResultMeta(submitTransactionResponse.resultMetaXdr!!,
networkParams))
updateBalanceByDelta(balanceId, request.amount)
}
} else {
balanceChangesRepositories.forEach { it.updateIfEverUpdated() }
repositoryProvider.balances().updateIfNotFresh()
}
}
}
| 1 | null | 1 | 6 | 05bb971859713830a9c229206dc9f525ce80f754 | 6,634 | conto-android-client | Apache License 2.0 |
data/RF04023/rnartist.kts | fjossinet | 449,239,232 | false | {"Kotlin": 8214424} | import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF04023"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
2 to 5
100 to 103
}
value = "#daeb12"
}
color {
location {
7 to 10
95 to 98
}
value = "#24d426"
}
color {
location {
12 to 16
89 to 93
}
value = "#dd78bb"
}
color {
location {
18 to 24
81 to 87
}
value = "#e9c89a"
}
color {
location {
25 to 30
74 to 79
}
value = "#28b2f1"
}
color {
location {
32 to 40
64 to 72
}
value = "#660479"
}
color {
location {
43 to 47
51 to 55
}
value = "#ca3228"
}
color {
location {
6 to 6
99 to 99
}
value = "#8d949a"
}
color {
location {
11 to 11
94 to 94
}
value = "#845928"
}
color {
location {
17 to 17
88 to 88
}
value = "#ae080e"
}
color {
location {
25 to 24
80 to 80
}
value = "#be745f"
}
color {
location {
31 to 31
73 to 73
}
value = "#9cd910"
}
color {
location {
41 to 42
56 to 63
}
value = "#448e1c"
}
color {
location {
48 to 50
}
value = "#e957aa"
}
color {
location {
1 to 1
}
value = "#963650"
}
color {
location {
104 to 104
}
value = "#c43195"
}
}
} | 0 | Kotlin | 0 | 0 | 3016050675602d506a0e308f07d071abf1524b67 | 2,521 | Rfam-for-RNArtist | MIT License |
shared/src/commonMain/kotlin/io/ktlab/bshelper/ui/components/AppDrawer.kt | ktKongTong | 694,984,299 | false | {"Kotlin": 836649, "Shell": 71} | package io.ktlab.bshelper.ui.components
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.NavigationDrawerItem
import androidx.compose.material3.NavigationDrawerItemDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import io.ktlab.bshelper.ui.route.BSHelperDestinations
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AppDrawer(
currentRoute: String,
navigateAction: (String) -> Unit,
closeDrawer: () -> Unit,
modifier: Modifier = Modifier,
) {
ModalDrawerSheet(modifier) {
// LBHelperLogo(
// modifier = Modifier.padding(horizontal = 28.dp, vertical = 24.dp)
// )
NavigationDrawerItem(
label = { Text("home") },
icon = { Icon(Icons.Filled.Home, null) },
selected = currentRoute == BSHelperDestinations.HOME_ROUTE,
onClick = {
navigateAction(BSHelperDestinations.HOME_ROUTE)
closeDrawer()
},
modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding),
)
NavigationDrawerItem(
label = { Text("beat saver") },
icon = { Icon(Icons.Filled.Home, null) },
selected = currentRoute == BSHelperDestinations.BEAT_SAVER_ROUTE,
onClick = {
navigateAction(BSHelperDestinations.BEAT_SAVER_ROUTE)
closeDrawer()
},
modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding),
)
NavigationDrawerItem(
label = { Text("toolbox") },
icon = { Icon(Icons.Filled.Settings, null) },
selected = currentRoute == BSHelperDestinations.TOOLBOX_ROUTE,
onClick = {
navigateAction(BSHelperDestinations.TOOLBOX_ROUTE)
closeDrawer()
},
modifier = Modifier.padding(NavigationDrawerItemDefaults.ItemPadding),
)
}
}
| 5 | Kotlin | 0 | 0 | ab6de84e97bcf933d034ca18788170d4ae486341 | 2,330 | cm-bs-helper | MIT License |
sora-android-sdk/src/main/kotlin/jp/shiguredo/sora/sdk/util/ByteBufferBackedInputStream.kt | shiguredo | 101,262,592 | false | null | package jp.shiguredo.sora.sdk.util
import java.io.InputStream
import java.nio.ByteBuffer
class ByteBufferBackedInputStream(private val buf: ByteBuffer) : InputStream() {
override fun read(): Int {
return if (!buf.hasRemaining()) {
-1
} else {
buf.get().toInt() and 0xFF
}
}
override fun read(bytes: ByteArray?, off: Int, len: Int): Int {
var len = len
if (!buf.hasRemaining()) {
return -1
}
len = Math.min(len, buf.remaining())
buf.get(bytes, off, len)
return len
}
}
| 0 | Kotlin | 6 | 21 | dc0da529da1b4ce9b916dcdba03f7ec7c54da6d3 | 595 | sora-android-sdk | Apache License 2.0 |
app/src/main/java/br/com/macaxeira/bookworm/models/Book.kt | SilvanoP | 102,399,559 | false | null | package br.com.macaxeira.bookworm.models
import android.os.Parcel
import android.os.Parcelable
import java.util.ArrayList
class Book(): Parcelable {
var title: String = ""
var authors: List<String> = ArrayList()
var publisher: String = ""
var description: String = ""
var averageRating: Double = 0.0
var ratingsCount: Int = 0
var imageLinks: ImageLinks? = null
var language: String = ""
var previewLink: String = ""
constructor(parcel: Parcel) : this() {
title = parcel.readString()
parcel.readStringList(authors)
publisher = parcel.readString()
description = parcel.readString()
averageRating = parcel.readDouble()
ratingsCount = parcel.readInt()
imageLinks = parcel.readTypedObject(ImageLinks.CREATOR)
language = parcel.readString()
previewLink = parcel.readString()
}
override fun writeToParcel(parcel: Parcel?, p1: Int) {
parcel?.writeString(title)
parcel?.writeStringList(authors)
parcel?.writeString(publisher)
parcel?.writeString(description)
parcel?.writeDouble(averageRating)
parcel?.writeInt(ratingsCount)
parcel?.writeTypedObject(imageLinks, Parcelable.PARCELABLE_WRITE_RETURN_VALUE)
parcel?.writeString(language)
parcel?.writeString(previewLink)
}
override fun describeContents(): Int = 0
companion object {
@JvmField val CREATOR = object : Parcelable.Creator<Book> {
override fun createFromParcel(parcel: Parcel?): Book {
if (parcel == null){
return Book()
}
return Book(parcel)
}
override fun newArray(i: Int): Array<Book> = newArray(i)
}
}
} | 0 | Kotlin | 0 | 0 | e50b2eef3615842f3315be643d033b82954261ac | 1,792 | BookWorm | MIT License |
compiler/testData/diagnostics/tests/classLiteral/genericArrays.fir.kt | android | 263,405,600 | false | null | import kotlin.reflect.KClass
fun <T> f1(): KClass<Array<T>> = Array<T>::class
fun <T> f2(): KClass<Array<Array<T>>> = Array<Array<T>>::class
inline fun <reified T> f3() = Array<T>::class
inline fun <reified T> f4() = Array<Array<T>>::class
fun f5(): KClass<Array<Any>> = Array<*>::class
fun f6(): KClass<Array<Int?>> = Array<Int?>::class
fun f7() = Array<List<String>>::class
fun f8() = Array<List<String>?>::class
fun f9() = Array<List<*>?>::class
| 0 | null | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 450 | kotlin | Apache License 2.0 |
src/main/kotlin/org/rust/lang/utils/Utils.kt | nicompte | 61,312,484 | true | {"Git Config": 1, "Gradle": 2, "Markdown": 8, "Java Properties": 2, "Shell": 1, "Text": 70, "Ignore List": 1, "Batchfile": 1, "EditorConfig": 1, "YAML": 1, "Rust": 387, "XML": 34, "HTML": 18, "RenderScript": 2, "TOML": 7, "Kotlin": 295, "Java": 5, "JFlex": 1} | package org.rust.lang.utils
import com.intellij.openapi.Disposable
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValueProvider
import com.intellij.psi.util.CachedValuesManager
import kotlin.reflect.KProperty
/**
* Helper disposing [d] upon completing the execution of the [block]
*
* @d Target `Disposable` to be disposed upon completion of the @block
* @block Target block to be run prior to disposal of @d
*/
fun <T> using(d: Disposable, block: () -> T): T {
try {
return block()
} finally {
d.dispose()
}
}
/**
* Helper disposing [d] upon completing the execution of the [block] (under the [d])
*
* @d Target `Disposable` to be disposed upon completion of the @block
* @block Target block to be run prior to disposal of @d
*/
fun <D: Disposable, T> usingWith(d: D, block: (D) -> T): T {
try {
return block(d)
} finally {
d.dispose()
}
}
/**
* Cached value invalidated on any PSI modification
*/
fun<E : PsiElement, T> psiCached(provider: E.() -> CachedValueProvider<T>): PsiCacheDelegate<E, T> = PsiCacheDelegate(provider)
class PsiCacheDelegate<E : PsiElement, T>(val provider: E.() -> CachedValueProvider<T>) {
operator fun getValue(element: E, property: KProperty<*>): T {
return CachedValuesManager.getCachedValue(element, element.provider())
}
}
| 0 | Kotlin | 0 | 0 | b9eb6161bb305800f9df43bc799872a68f9d1d1a | 1,384 | intellij-rust | MIT License |
feature/conversations/src/main/java/com/chatfire/conversations/ui/ConversationsListScreen.kt | MonicaTR06 | 846,309,512 | false | {"Kotlin": 22264} | package com.chatfire.conversations.ui
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.rounded.Menu
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import com.chatfire.conversations.R
import com.chatfire.conversations.ui.components.ConversationList
import com.chatfire.conversations.ui.components.demoFakeConversations
import com.chatfire.conversations.ui.model.generateTabs
@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterial3Api::class)
@Composable
fun ConversationsListScreen(
onNewConversationClick: () -> Unit,
onConversationClick: (chatId: String) -> Unit
) {
val tabs = generateTabs()
val selectedTabIndex = remember { mutableIntStateOf(1) }
val pagerState = rememberPagerState(initialPage = 1, pageCount = { tabs.size })
Scaffold(
topBar = {
TopAppBar(
title = { Text(text = stringResource(id = R.string.conversations_list_title)) },
actions = {
IconButton(onClick = { /*TODO Menu action */ }) {
Icon(Icons.Rounded.Menu, contentDescription = "Menu")
}
}
)
},
content = { innerPadding ->
HorizontalPager(
state = pagerState,
modifier = Modifier.padding(innerPadding)
) { index ->
when (index) {
0 -> {
//Status
}
1 -> {
ConversationList(
conversations = demoFakeConversations(),
onConversationClick = onConversationClick
)
}
2 -> {
// Calls
}
}
LaunchedEffect(key1 = selectedTabIndex.intValue) {
pagerState.animateScrollToPage(selectedTabIndex.intValue)
}
}
},
bottomBar = {
TabRow(selectedTabIndex = selectedTabIndex.intValue) {
tabs.forEachIndexed { index, _ ->
Tab(
text = { Text(text = stringResource(id = tabs[index].title)) },
selected = (index == selectedTabIndex.intValue),
onClick = {
selectedTabIndex.intValue = index
}
)
}
}
},
floatingActionButton = {
FloatingActionButton(onClick = { onNewConversationClick() }) {
Icon(imageVector = Icons.Default.Add, contentDescription = "Nuevo")
}
}
)
}
@Preview(showBackground = true)
@Composable
fun ConversationsListScreenPreview() {
ConversationsListScreen({}, {})
}
@Preview(showBackground = true, widthDp = 700, heightDp = 500)
@Composable
fun ReplyAppPreviewTablet() {
ConversationsListScreen({}, {})
}
@Preview(showBackground = true, widthDp = 500, heightDp = 700)
@Composable
fun ReplyAppPreviewTabletPortrait() {
ConversationsListScreen({}, {})
} | 0 | Kotlin | 0 | 0 | 22a18b7dc5c85e230cba91980db2a066e57785d6 | 4,137 | ChatFire | Apache License 2.0 |
src/main/java/com.android.tools.experimental/StudioKotlinVerifier.kt | gharrma | 393,155,248 | false | null | @file:JvmName("StudioKotlinVerifier")
package com.android.tools.experimental
import com.jetbrains.pluginverifier.PluginVerifierMain
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import kotlin.io.path.*
import kotlin.streams.toList
/**
* Runs the IntelliJ Plugin Verifier twice: once with the bundled Kotlin plugin,
* and again with a 'new' Kotlin plugin. The diff between the results can help
* catch binary compatibility issues (especially for plugins which depend on the
* Kotlin plugin).
*/
fun main(args: Array<String>) {
if (args.size != 3) error("Usage: run /path/to/android-studio /path/to/kotlin-plugin /path/to/output/dir")
val (idePath, newKotlinPluginPath, outDirPath) = args
val ide = Paths.get(idePath)
val newKotlinPlugin = Paths.get(newKotlinPluginPath)
val outDir = Paths.get(outDirPath)
val verifierHome = outDir.resolve("verifier-home")
val bundledPlugins = Files.list(ide.resolve("plugins")).toList()
// First run on all bundled plugins.
val reportDirBefore = outDir.resolve("verifier-report-before")
val errorsBefore = outDir.resolve("all-errors-before.txt")
runPluginVerifier(
ideHome = ide,
plugins = bundledPlugins,
reportDir = reportDirBefore,
verifierHome = verifierHome,
)
writeAllVerifierErrors(reportDirBefore, errorsBefore)
// Run again, but swap out the Kotlin plugin.
val reportDirAfter = outDir.resolve("verifier-report-after")
val errorsAfter = outDir.resolve("all-errors-after.txt")
runPluginVerifier(
ideHome = ide,
plugins = bundledPlugins.filterNot { it.name == "Kotlin" } + listOf(newKotlinPlugin),
reportDir = reportDirAfter,
verifierHome = verifierHome,
)
writeAllVerifierErrors(reportDirAfter, errorsAfter)
// Diff the results.
val diff = outDir.resolve("new-errors.txt")
val newErrors = errorsAfter.readLines().toSet() - errorsBefore.readLines()
diff.writeLines(newErrors)
}
fun runPluginVerifier(ideHome: Path, plugins: List<Path>, reportDir: Path, verifierHome: Path) {
val pluginList = plugins.joinToString("\n", postfix = "\n")
println("Verifying ${plugins.size} plugins:\n$pluginList")
val pluginListFile = createTempFile()
pluginListFile.writeText(pluginList)
val verifierArgs = arrayOf(
"check-plugin",
"@$pluginListFile",
"-offline",
"-verification-reports-dir",
reportDir.pathString,
"-runtime-dir",
ideHome.resolve("jre").pathString,
ideHome.pathString,
)
System.setProperty("plugin.verifier.home.dir", verifierHome.pathString)
PluginVerifierMain.main(verifierArgs)
}
/** Concatenates all errors found into a single file. */
fun writeAllVerifierErrors(reportDir: Path, out: Path) {
val errorFiles = Files.walk(reportDir).toList()
.filter { it.name == "compatibility-problems.txt" || it.name == "invalid-plugin.txt" }
.sortedBy { it.pathString }
println("Concatenating ${errorFiles.size} error reports")
val concatenated = buildString {
for (report in errorFiles) {
val pluginId = report.parent?.parent?.name ?: "<unknown>"
appendLine("================================================")
appendLine("Plugin: $pluginId")
appendLine("================================================")
append(report.readText())
append("\n\n\n")
}
}
out.writeText(concatenated)
}
| 0 | Kotlin | 0 | 0 | bc11742df770070d8d8ba2e011ceff99e544a2ba | 3,540 | android-studio-kotlin-verifier | MIT License |
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/datadonation/analytics/modules/usermetadata/UserMetadataDonor.kt | corona-warn-app | 268,027,139 | false | null | package de.rki.coronawarnapp.datadonation.analytics.modules.usermetadata
import de.rki.coronawarnapp.datadonation.analytics.modules.DonorModule
import de.rki.coronawarnapp.datadonation.analytics.storage.AnalyticsSettings
import de.rki.coronawarnapp.server.protocols.internal.ppdd.PpaData
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class UserMetadataDonor @Inject constructor(
private val analyticsSettings: AnalyticsSettings
) : DonorModule {
override suspend fun beginDonation(request: DonorModule.Request): DonorModule.Contribution {
val userMetadata = PpaData.PPAUserMetadata.newBuilder()
.setAgeGroup(analyticsSettings.userInfoAgeGroup.value)
.setFederalState(analyticsSettings.userInfoFederalState.value)
.setAdministrativeUnit(analyticsSettings.userInfoDistrict.value)
.build()
return UserMetadataContribution(
contributionProto = userMetadata
)
}
override suspend fun deleteData() {
analyticsSettings.apply {
userInfoAgeGroup.update {
PpaData.PPAAgeGroup.AGE_GROUP_UNSPECIFIED
}
userInfoFederalState.update {
PpaData.PPAFederalState.FEDERAL_STATE_UNSPECIFIED
}
userInfoDistrict.update {
0
}
}
}
data class UserMetadataContribution(
val contributionProto: PpaData.PPAUserMetadata
) : DonorModule.Contribution {
override suspend fun injectData(protobufContainer: PpaData.PPADataAndroid.Builder) {
protobufContainer.userMetadata = contributionProto
}
override suspend fun finishDonation(successful: Boolean) {
// No post processing needed for User Metadata
}
}
}
| 2 | null | 514 | 2,495 | d3833a212bd4c84e38a1fad23b282836d70ab8d5 | 1,815 | cwa-app-android | Apache License 2.0 |
app/src/main/java/top/topsea/simplediffusion/data/state/UIState.kt | TopSea | 712,328,719 | false | {"Kotlin": 568466} | package top.topsea.simplediffusion.data.state
import android.content.Context
import androidx.annotation.Keep
import top.topsea.simplediffusion.BaseScreen
import top.topsea.simplediffusion.SimpleDestination
import top.topsea.simplediffusion.api.dto.ActivateModel
import top.topsea.simplediffusion.api.dto.VaeModel
import top.topsea.simplediffusion.api.dto.VersionResponse
import top.topsea.simplediffusion.util.DeleteImage
sealed class UIEvent {
data class Navigate(val screen: SimpleDestination, val navOp: () -> Unit) : UIEvent()
data class UpdateVae(val vae: VaeModel, val onFailure: () -> Unit,
val onSuccess: () -> Unit) : UIEvent()
data class Display(val display: Boolean = false) : UIEvent()
data class DisplayImg(val index: Int) : UIEvent()
data class LongPressImage(val longPressImage: Boolean) : UIEvent()
data class IsSaveCapImg(val saveCapImage: Boolean = true) : UIEvent()
data class IsSaveControl(val saveControlNet: Boolean = true) : UIEvent()
data class AddGenSize(val context: Context): UIEvent()
data class MinusGenSize(val context: Context): UIEvent()
data class ShowGenOn1(val showGenOn1: Boolean): UIEvent()
// UI 相关的弹窗
data class UIWarning(val warningStr: String): UIEvent()
// SD 服务器相关
data class ServerConnected(val serverConnected: Boolean) : UIEvent()
data class SaveOnServer(val saveOnServer: Boolean) : UIEvent()
data class ModelChanging(val modelChanging: Boolean) : UIEvent()
// 是否启用 SD 插件
data class ExSettingChange(val whichOne: String, val context: Context) : UIEvent()
// SimpleDiffusion Desktop 相关
data class ConnectDesktop(val connectDesktop: Boolean): UIEvent()
data class Send2Desktop(val str: String): UIEvent()
} | 0 | Kotlin | 2 | 2 | 2e41a1a563555d23c28baaf5d235d063d1092c70 | 1,767 | SimpleDiffusion | Apache License 2.0 |
mpp/src/androidMain/kotlin/com/w10group/hertzdictionary/database/LocalWordDAORoom.kt | qiaoyuang | 119,500,508 | false | null | package com.w10group.hertzdictionary.database
import androidx.room.*
/**
* LocalWord 的 DAO
* @author Qiao
*/
@Dao
internal interface LocalWordDAORoom {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insert(vararg localWord: LocalWord)
@Delete
suspend fun delete(vararg localWord: LocalWord)
@Query("SELECT * FROM LocalWord ORDER BY count DESC")
suspend fun queryAll(): List<LocalWord>
@Update
suspend fun update(vararg localWord: LocalWord)
} | 0 | Kotlin | 2 | 10 | 46e494cd5a60e853bd49cc9b7589ac2b38ea2dab | 499 | HertzDictionary | Apache License 2.0 |
nms/1_16_R2/src/main/kotlin/me/gamercoder215/battlecards/impl/cards/INetheritePiglin.kt | GamerCoder215 | 555,359,817 | false | null | package me.gamercoder215.battlecards.impl.cards
import me.gamercoder215.battlecards.api.card.BattleCardType
import me.gamercoder215.battlecards.impl.*
import me.gamercoder215.battlecards.util.BattleSound
import org.bukkit.ChatColor
import org.bukkit.Material
import org.bukkit.enchantments.Enchantment
import org.bukkit.entity.Hoglin
import org.bukkit.entity.PiglinBrute
import org.bukkit.event.entity.EntityDamageByEntityEvent
import org.bukkit.event.entity.EntityDamageEvent
import org.bukkit.inventory.ItemStack
import org.bukkit.potion.PotionEffect
import org.bukkit.potion.PotionEffectType
@Type(BattleCardType.NETHERITE_PIGLIN)
@Attributes(400.0, 11.0, 45.0, 0.22, 60.0)
@AttributesModifier(CardAttribute.MAX_HEALTH, CardOperation.ADD, 11.5)
@AttributesModifier(CardAttribute.ATTACK_DAMAGE, CardOperation.ADD, 2.5)
@AttributesModifier(CardAttribute.DEFENSE, CardOperation.ADD, 7.5)
class INetheritePiglin(data: ICard) : IBattleCard<PiglinBrute>(data) {
override fun init() {
super.init()
entity.isImmuneToZombification = true
val equipment = entity.equipment!!
equipment.helmet = ItemStack(Material.NETHERITE_HELMET).apply {
itemMeta = itemMeta!!.apply {
isUnbreakable = true
if (level >= 15)
addEnchant(Enchantment.PROTECTION_ENVIRONMENTAL, level / 15, true)
}
}
if (level >= 45)
equipment.chestplate = ItemStack(Material.NETHERITE_CHESTPLATE).apply {
itemMeta = itemMeta!!.apply {
isUnbreakable = true
if (level >= 60)
addEnchant(Enchantment.PROTECTION_ENVIRONMENTAL, (level / 15) - 3, true)
}
}
equipment.setItemInMainHand(ItemStack(when (level) {
in 0 until 30 -> Material.NETHERITE_SWORD
else -> Material.NETHERITE_AXE
}).apply {
itemMeta = itemMeta!!.apply {
isUnbreakable = true
if (level >= 20)
addEnchant(Enchantment.DAMAGE_ALL, level / 20, true)
if (level >= 35)
addEnchant(Enchantment.KNOCKBACK, level / 35, true)
}
})
}
@CardAbility("card.netherite_piglin.ability.netherite_rage", ChatColor.RED)
@Passive(72000, CardOperation.SUBTRACT, 20, Long.MAX_VALUE, 18000)
private fun netheriteRage() {
entity.addPotionEffect(PotionEffect(PotionEffectType.INCREASE_DAMAGE, (level + 4) * 20, level / 20, true))
}
@CardAbility("card.netherite_piglin.ability.heat_shield", ChatColor.YELLOW)
@Damage
@UnlockedAt(40)
private fun heatShield(event: EntityDamageEvent) {
if (event.cause == EntityDamageEvent.DamageCause.LAVA)
event.isCancelled = true
}
@CardAbility("card.netherite_piglin.ability.hoglin", ChatColor.LIGHT_PURPLE)
@Defensive(0.1, CardOperation.ADD, 0.02, 0.25)
@UnlockedAt(55)
private fun hoglin(event: EntityDamageByEntityEvent) {
event.isCancelled = true
val sound = BattleSound.ITEM_SHIELD_BLOCK.findOrNull()
if (sound != null) world.playSound(location, sound, 3F, 1F)
minion(Hoglin::class.java) {
isImmuneToZombification = true
if (r.nextDouble() < 0.25) setBaby()
}
}
} | 0 | Kotlin | 0 | 4 | 11ef6688fe3790cb890eb2f4349485ad4d79029c | 3,367 | BattleCards | Apache License 2.0 |
nms/1_16_R2/src/main/kotlin/me/gamercoder215/battlecards/impl/cards/INetheritePiglin.kt | GamerCoder215 | 555,359,817 | false | null | package me.gamercoder215.battlecards.impl.cards
import me.gamercoder215.battlecards.api.card.BattleCardType
import me.gamercoder215.battlecards.impl.*
import me.gamercoder215.battlecards.util.BattleSound
import org.bukkit.ChatColor
import org.bukkit.Material
import org.bukkit.enchantments.Enchantment
import org.bukkit.entity.Hoglin
import org.bukkit.entity.PiglinBrute
import org.bukkit.event.entity.EntityDamageByEntityEvent
import org.bukkit.event.entity.EntityDamageEvent
import org.bukkit.inventory.ItemStack
import org.bukkit.potion.PotionEffect
import org.bukkit.potion.PotionEffectType
@Type(BattleCardType.NETHERITE_PIGLIN)
@Attributes(400.0, 11.0, 45.0, 0.22, 60.0)
@AttributesModifier(CardAttribute.MAX_HEALTH, CardOperation.ADD, 11.5)
@AttributesModifier(CardAttribute.ATTACK_DAMAGE, CardOperation.ADD, 2.5)
@AttributesModifier(CardAttribute.DEFENSE, CardOperation.ADD, 7.5)
class INetheritePiglin(data: ICard) : IBattleCard<PiglinBrute>(data) {
override fun init() {
super.init()
entity.isImmuneToZombification = true
val equipment = entity.equipment!!
equipment.helmet = ItemStack(Material.NETHERITE_HELMET).apply {
itemMeta = itemMeta!!.apply {
isUnbreakable = true
if (level >= 15)
addEnchant(Enchantment.PROTECTION_ENVIRONMENTAL, level / 15, true)
}
}
if (level >= 45)
equipment.chestplate = ItemStack(Material.NETHERITE_CHESTPLATE).apply {
itemMeta = itemMeta!!.apply {
isUnbreakable = true
if (level >= 60)
addEnchant(Enchantment.PROTECTION_ENVIRONMENTAL, (level / 15) - 3, true)
}
}
equipment.setItemInMainHand(ItemStack(when (level) {
in 0 until 30 -> Material.NETHERITE_SWORD
else -> Material.NETHERITE_AXE
}).apply {
itemMeta = itemMeta!!.apply {
isUnbreakable = true
if (level >= 20)
addEnchant(Enchantment.DAMAGE_ALL, level / 20, true)
if (level >= 35)
addEnchant(Enchantment.KNOCKBACK, level / 35, true)
}
})
}
@CardAbility("card.netherite_piglin.ability.netherite_rage", ChatColor.RED)
@Passive(72000, CardOperation.SUBTRACT, 20, Long.MAX_VALUE, 18000)
private fun netheriteRage() {
entity.addPotionEffect(PotionEffect(PotionEffectType.INCREASE_DAMAGE, (level + 4) * 20, level / 20, true))
}
@CardAbility("card.netherite_piglin.ability.heat_shield", ChatColor.YELLOW)
@Damage
@UnlockedAt(40)
private fun heatShield(event: EntityDamageEvent) {
if (event.cause == EntityDamageEvent.DamageCause.LAVA)
event.isCancelled = true
}
@CardAbility("card.netherite_piglin.ability.hoglin", ChatColor.LIGHT_PURPLE)
@Defensive(0.1, CardOperation.ADD, 0.02, 0.25)
@UnlockedAt(55)
private fun hoglin(event: EntityDamageByEntityEvent) {
event.isCancelled = true
val sound = BattleSound.ITEM_SHIELD_BLOCK.findOrNull()
if (sound != null) world.playSound(location, sound, 3F, 1F)
minion(Hoglin::class.java) {
isImmuneToZombification = true
if (r.nextDouble() < 0.25) setBaby()
}
}
} | 0 | Kotlin | 0 | 4 | 11ef6688fe3790cb890eb2f4349485ad4d79029c | 3,367 | BattleCards | Apache License 2.0 |
src/main/kotlin/com/rdb/DiscordFunctions.kt | Mark7625 | 383,185,068 | false | null | package com.rdb
import com.rdb.DiscordManager.Companion.guild
import net.dv8tion.jda.api.entities.Role
import net.dv8tion.jda.api.entities.TextChannel
import net.dv8tion.jda.api.entities.VoiceChannel
fun getTextChannel(channel: String): TextChannel {
val lookupChannel = lookupChannel(channel)
if (lookupChannel == -1L) {
println("Server Channel $channel has not been found")
return guild.getTextChannelById("NONE")!!
}
if (guild.getGuildChannelById(lookupChannel) !is TextChannel) {
println("Server Channel $channel is not text")
return guild.getTextChannelById("NONE")!!
}
return guild.getGuildChannelById(lookupChannel) as TextChannel
}
fun getVoiceChannel(channel: String): VoiceChannel {
val lookupChannel = lookupChannel(channel)
if (lookupChannel == -1L) {
println("Server Channel $channel has not been found")
return guild.getVoiceChannelById("NONE")!!
}
if (guild.getGuildChannelById(lookupChannel) !is VoiceChannel) {
println("Server Channel $channel is not voice")
return guild.getVoiceChannelById("NONE")!!
}
return guild.getGuildChannelById(lookupChannel) as VoiceChannel
}
fun lookupChannel(channel: String): Long {
if (!DiscordManager.channels.contains(channel)) return -1
return DiscordManager.channels[channel]!!
}
fun getRoleFromName(role: String): Role? = DiscordManager.roles[role]?.let { DiscordManager.jda.getRoleById(it) }
| 0 | Kotlin | 0 | 0 | 5dcc4a298e6d9e22341af93ae69a2a129536f351 | 1,471 | RsDiscordBot | MIT License |
src/main/kotlin/com/rdb/DiscordFunctions.kt | Mark7625 | 383,185,068 | false | null | package com.rdb
import com.rdb.DiscordManager.Companion.guild
import net.dv8tion.jda.api.entities.Role
import net.dv8tion.jda.api.entities.TextChannel
import net.dv8tion.jda.api.entities.VoiceChannel
fun getTextChannel(channel: String): TextChannel {
val lookupChannel = lookupChannel(channel)
if (lookupChannel == -1L) {
println("Server Channel $channel has not been found")
return guild.getTextChannelById("NONE")!!
}
if (guild.getGuildChannelById(lookupChannel) !is TextChannel) {
println("Server Channel $channel is not text")
return guild.getTextChannelById("NONE")!!
}
return guild.getGuildChannelById(lookupChannel) as TextChannel
}
fun getVoiceChannel(channel: String): VoiceChannel {
val lookupChannel = lookupChannel(channel)
if (lookupChannel == -1L) {
println("Server Channel $channel has not been found")
return guild.getVoiceChannelById("NONE")!!
}
if (guild.getGuildChannelById(lookupChannel) !is VoiceChannel) {
println("Server Channel $channel is not voice")
return guild.getVoiceChannelById("NONE")!!
}
return guild.getGuildChannelById(lookupChannel) as VoiceChannel
}
fun lookupChannel(channel: String): Long {
if (!DiscordManager.channels.contains(channel)) return -1
return DiscordManager.channels[channel]!!
}
fun getRoleFromName(role: String): Role? = DiscordManager.roles[role]?.let { DiscordManager.jda.getRoleById(it) }
| 0 | Kotlin | 0 | 0 | 5dcc4a298e6d9e22341af93ae69a2a129536f351 | 1,471 | RsDiscordBot | MIT License |
zowe-imperative/src/jsMain/kotlin/zowe/imperative/imperative/plugins/cmd/update/update.definition.kt | lppedd | 761,812,661 | false | {"Kotlin": 1887051} | @file:JsModule("@zowe/imperative")
package zowe.imperative.imperative.plugins.cmd.update
import zowe.imperative.cmd.doc.ICommandDefinition
/**
* Definition of the update command.
*/
external val updateDefinition: ICommandDefinition
| 0 | Kotlin | 0 | 3 | 0f493d3051afa3de2016e5425a708c7a9ed6699a | 237 | kotlin-externals | MIT License |
Android/app/src/main/java/com/orange/ease/dan/ui/SplashScreenActivity.kt | Romain-Rs | 469,795,451 | true | {"HTML": 483317, "Kotlin": 274017, "Swift": 254750, "Java": 64410, "CSS": 16805} | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.orange.ease.dan.ui
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.appcompat.app.AppCompatActivity
import com.orange.ease.dan.databinding.ActivitySplashscreenBinding
import com.orange.ease.dan.databinding.SplashBinding
class SplashScreenActivity : AppCompatActivity() {
private lateinit var binding: ActivitySplashscreenBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivitySplashscreenBinding.inflate(layoutInflater)
val view = binding.root
setContentView(view)
initTimer()
}
private fun startMenuActivity() {
val intent = Intent(this, MenuActivity::class.java)
startActivity(intent)
finish()
}
private fun initTimer() {
Handler(Looper.getMainLooper()).postDelayed(
{
startMenuActivity()
},
3000
)
}
}
| 0 | null | 0 | 0 | 2bdb9b569772c6f9da9bd2b6035171b79b59251c | 1,827 | m-dan-2 | Creative Commons Attribution 3.0 Unported |
app/src/main/java/com/example/noterssaver/domain/usecase/settings/GetCurrentThemeStatusUseCase.kt | Shahidzbi4213 | 613,411,095 | false | null | package com.example.noterssaver.domain.usecase.settings
import com.example.noterssaver.domain.repository.SettingRepo
import com.example.noterssaver.presentation.setting.util.ThemeStyle
import kotlinx.coroutines.flow.Flow
class GetCurrentThemeStatusUseCase(private val repo: SettingRepo) {
operator fun invoke(): Flow<ThemeStyle> {
return repo.getCurrentTheme()
}
} | 0 | Kotlin | 1 | 12 | 9ce24a429fd65ba8031abb534ebbf52610e35da7 | 383 | NotesSaver | MIT License |
sykepenger-api/src/main/kotlin/no/nav/helse/spleis/dao/PostgresProbe.kt | navikt | 193,907,367 | false | {"Kotlin": 6676387, "PLpgSQL": 2738, "Dockerfile": 168} | package no.nav.helse.spleis.dao
import io.micrometer.core.instrument.Counter.*
import io.micrometer.core.instrument.MeterRegistry
import io.micrometer.prometheusmetrics.PrometheusConfig
import io.micrometer.prometheusmetrics.PrometheusMeterRegistry
object PostgresProbe {
private val metrics: MeterRegistry = PrometheusMeterRegistry(PrometheusConfig.DEFAULT)
fun personLestFraDb() {
builder("person_lest_fra_db_totals")
.description("Antall ganger vi har lest en person fra db")
.register(metrics)
.increment()
}
fun hendelseLestFraDb() {
builder("hendelse_lest_fra_db_totals")
.description("Antall ganger vi har lest en hendelse fra db")
.register(metrics)
.increment()
}
}
| 2 | Kotlin | 7 | 3 | 7351c7849507f3baed5292e1b54c6464d5d35611 | 787 | helse-spleis | MIT License |
src/main/kotlin/com/example/parking/visit/FinishedVisitRepo.kt | johnGachihi | 365,287,855 | false | null | package com.example.parking.visit
import com.example.parking.models.FinishedVisit
import org.springframework.data.jpa.repository.JpaRepository
interface FinishedVisitRepo : JpaRepository<FinishedVisit, Long> | 0 | Kotlin | 0 | 0 | d2f1cb4af890f0e14faf57d26327115edfb73e5e | 209 | parking-spring | MIT License |
arkiverer/src/main/kotlin/no/nav/soknad/arkivering/soknadsarkiverer/service/fileservice/ResponseStatus.kt | navikt | 213,857,164 | false | {"Kotlin": 252844, "HTML": 15355, "Dockerfile": 292} | package no.nav.soknad.arkivering.soknadsarkiverer.service.fileservice
enum class ResponseStatus(val value: String) {
Ok("ok"),
NotFound("not-found"),
Deleted("deleted"),
Error("error")
}
| 0 | Kotlin | 0 | 1 | f31386607b9f9224f0798321953f211a442139a4 | 192 | soknadsarkiverer | MIT License |
app/src/main/java/nz/co/panpanini/kotlindatabinding/model/Repo.kt | panpanini | 80,402,953 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Java": 2, "XML": 9, "Kotlin": 16} | package nz.co.panpanini.kotlindatabinding.model
import com.google.gson.annotations.SerializedName
/**
* Created by matthewvern on 2017/01/30.
*/
data class Repo(
@SerializedName("full_name")
val name: String,
val description: String,
val language: String,
val fork: Boolean
) {
} | 1 | Kotlin | 0 | 0 | a7bbf07502b49d990e089d7ef5eef5465cfffe1f | 323 | KotlinWithDatabinding | The Unlicense |
main/src/main/kotlin/net/fwitz/math/main/ifs/IfsTree.kt | txshtkckr | 410,419,365 | false | null | package net.fwitz.math.main.ifs
import net.fwitz.math.fractal.ifs.Ifs
import net.fwitz.math.plot.canvas.CanvasPlot
object IfsTree {
@JvmStatic
fun main(args: Array<String>) = CanvasPlot.ifs(Ifs.TREE).render()
} | 0 | Kotlin | 1 | 0 | c6ee97ab98115e044a46490ef3a26c51752ae6d6 | 220 | fractal | Apache License 2.0 |
browser-kotlin/src/jsMain/kotlin/web/codecs/VideoFrameCopyToOptions.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6303038} | // Automatically generated - do not modify!
package web.codecs
import js.array.ReadonlyArray
import kotlinx.js.JsPlainObject
import web.geometry.DOMRectInit
import web.images.PredefinedColorSpace
@JsPlainObject
external interface VideoFrameCopyToOptions {
var colorSpace: PredefinedColorSpace?
var format: VideoPixelFormat?
var layout: ReadonlyArray<PlaneLayout>?
var rect: DOMRectInit?
}
| 0 | Kotlin | 8 | 34 | 7b4983a8951d9d135c8dbcd707012f1eb460b01a | 408 | types-kotlin | Apache License 2.0 |
app/src/main/java/org/itsman/baseandroid/viewmodel/MainActivityVM.kt | mkitcc | 631,505,045 | false | null | package org.itsman.baseandroid.viewmodel
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.itsman.network.HttpClient
import org.itsman.network.RequestResult
class MainActivityVM : ViewModel() {
var data = MutableLiveData<String?>()
fun getData() {
viewModelScope.launch {
HttpClient.request { HttpClient.getApi().getHotkey() }.collect {
when (it) {
is RequestResult.Success -> {
data.value = it.data.data.toString()
}
is RequestResult.Error -> {
data.value = it.errorMsg
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 31d847967fc89fd25d5c5a1aeb8ecc72aef6a523 | 906 | BaseAndroid | MIT License |
app/src/main/java/org/itsman/baseandroid/viewmodel/MainActivityVM.kt | mkitcc | 631,505,045 | false | null | package org.itsman.baseandroid.viewmodel
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import org.itsman.network.HttpClient
import org.itsman.network.RequestResult
class MainActivityVM : ViewModel() {
var data = MutableLiveData<String?>()
fun getData() {
viewModelScope.launch {
HttpClient.request { HttpClient.getApi().getHotkey() }.collect {
when (it) {
is RequestResult.Success -> {
data.value = it.data.data.toString()
}
is RequestResult.Error -> {
data.value = it.errorMsg
}
}
}
}
}
} | 0 | Kotlin | 0 | 0 | 31d847967fc89fd25d5c5a1aeb8ecc72aef6a523 | 906 | BaseAndroid | MIT License |
kmain/src/main/kotlin/com/zxyp/kt/app/KtApp.kt | tf2008 | 123,405,399 | false | {"Java": 340, "Kotlin": 270} | package com.zxyp.kt.app
import org.springframework.boot.SpringApplication
import org.springframework.boot.autoconfigure.SpringBootApplication
@SpringBootApplication
open class KtApp
fun main(args : Array<String>){
SpringApplication.run(KtApp::class.java,*args)
} | 1 | null | 1 | 1 | fafdf88a6b5ea6be1a26cbaa3eff25f49ce72eb1 | 270 | kspringboot | MIT License |
backend/src/main/kotlin/fr/gouv/cacem/monitorenv/infrastructure/database/repositories/interfaces/IDBSemaphoreRepository.kt | MTES-MCT | 462,794,012 | false | {"TypeScript": 1358478, "Kotlin": 815514, "Python": 209694, "Shell": 21375, "CSS": 19997, "JavaScript": 8409, "Makefile": 8169, "Dockerfile": 6554, "PLpgSQL": 4966, "HTML": 864} | package fr.gouv.cacem.monitorenv.infrastructure.database.repositories.interfaces
import fr.gouv.cacem.monitorenv.infrastructure.database.model.SemaphoreModel
import org.springframework.data.jpa.repository.JpaRepository
interface IDBSemaphoreRepository : JpaRepository<SemaphoreModel, Int>
| 190 | TypeScript | 1 | 3 | f755ce65909e473e564ff5e273b9b4930e82ad4d | 291 | monitorenv | MIT License |
domain/src/main/java/city/zouitel/domain/repository/LinkRepository.kt | City-Zouitel | 576,223,915 | false | {"Kotlin": 491074} | package city.zouitel.domain.repository
import city.zouitel.domain.model.Link
import kotlinx.coroutines.flow.Flow
interface LinkRepository {
val getAllLinks: Flow<List<Link>>
suspend fun addLink(link: Link)
suspend fun deleteLink(link: Link)
} | 37 | Kotlin | 12 | 94 | 279f774769be23f897c75028f68f93b997a86319 | 259 | JetNote | Apache License 2.0 |
src/main/kotlin/com/lounres/gradle/stal/ProjectFrame.kt | lounres | 550,215,827 | false | {"Kotlin": 29148} | /*
* Copyright © 2023 <NAME>
* All rights reserved. Licensed under the Apache License, Version 2.0. See the license in file LICENSE
*/
package com.lounres.gradle.stal
import org.gradle.api.Project
// Utils
internal fun List<String>.toGradleName(): String = joinToString(separator = "") { ":$it" }.let { if (it == "") ":" else it }
//
// region Model
public interface ProjectFrame {
// Naming
public val fullName: String get() = fullNameParts.toGradleName()
public val fullNameParts: List<String>
// Tags
public val tags: Set<String>
public fun has(soughtTag: String): Boolean = soughtTag in tags
public fun hasAnyOf(vararg soughtTags: String): Boolean = soughtTags.any { it in tags }
public fun hasAnyOf(soughtTags: Collection<String>): Boolean = soughtTags.any { it in tags }
public fun hasAllOf(vararg soughtTags: String): Boolean = soughtTags.all { it in tags }
public fun hasAllOf(soughtTags: Collection<String>): Boolean = soughtTags.all { it in tags }
public operator fun String.unaryPlus(): Boolean = this in tags
// Hierarchy
public val children: Set<ChildProjectFrame>
// Gradle API
public val project: Project
public fun project(block: Project.() -> Unit) { project.block() }
}
public interface RootProjectFrame : ProjectFrame {
override val fullNameParts: List<String> get() = emptyList()
}
public interface ChildProjectFrame : ProjectFrame {
public val name: String get() = fullNameParts.first()
// Hierarchy
public val parent: ProjectFrame
}
public fun <P> ProjectFrame.parentOrNull(): ProjectFrame? = if (this is ChildProjectFrame) parent else null
// endregion
// region Mutable model
public interface MutableProjectFrame: ProjectFrame {
// Tags
public override val tags: MutableSet<String>
}
public interface MutableRootProjectFrame : MutableProjectFrame, RootProjectFrame
public interface MutableChildProjectFrame : MutableProjectFrame, ChildProjectFrame
// endregion
// region Builders
internal interface ProjectFrameBuilder: MutableProjectFrame {
override val children: MutableSet<ChildProjectFrame>
}
internal class RootProjectFrameBuilder(
override val tags: MutableSet<String>,
override val project: Project,
override val children: MutableSet<ChildProjectFrame> = mutableSetOf(),
) : MutableRootProjectFrame, ProjectFrameBuilder
internal class ChildProjectFrameBuilder(
override val fullNameParts: List<String>,
override val tags: MutableSet<String>,
override val project: Project,
override val parent: ProjectFrame,
override val children: MutableSet<ChildProjectFrame> = mutableSetOf(),
) : MutableChildProjectFrame, ProjectFrameBuilder
// endregion | 3 | Kotlin | 0 | 1 | ed413b312739b9786821c527c3866d2c79e40d8a | 2,713 | STAL | Apache License 2.0 |
sample/src/main/kotlin/vipsffm/SampleRunner.kt | lopcode | 838,313,812 | false | null | package vipsffm
import app.photofox.vipsffm.Vips
import org.slf4j.LoggerFactory
import vipsffm.sample.VBlobByteBufferSample
import vipsffm.sample.VImageArrayJoinSample
import vipsffm.sample.VImageBlobSample
import vipsffm.sample.VImageCachingSample
import vipsffm.sample.VImageChainSample
import vipsffm.sample.VImageCopyWriteSample
import vipsffm.sample.VImageCreateThumbnailSample
import vipsffm.sample.VOptionHyphenSample
import vipsffm.sample.VSourceTargetSample
import java.nio.file.Files
import java.nio.file.Paths
import java.util.Locale
import kotlin.system.exitProcess
object SampleRunner {
private val logger = LoggerFactory.getLogger(SampleRunner::class.java)
@JvmStatic
fun main(args: Array<String>) {
val samples = listOf(
RawGetVersionSample,
HelperGetVersionSample,
VImageCreateThumbnailSample,
VImageChainSample,
VSourceTargetSample,
VImageCopyWriteSample,
VOptionHyphenSample,
VImageCachingSample,
VImageBlobSample,
VImageArrayJoinSample,
VBlobByteBufferSample,
VTargetToFileSample
)
val sampleParentRunPath = Paths.get("sample_run")
if (Files.exists(sampleParentRunPath)) {
logger.info("clearing sample run directory at path \"$sampleParentRunPath\"")
sampleParentRunPath.toFile().deleteRecursively()
}
Files.deleteIfExists(sampleParentRunPath)
Files.createDirectory(sampleParentRunPath)
Vips.init(false, true)
samples.forEach { sample ->
Vips.run { arena ->
val sampleName = sample::class.simpleName!!
logger.info("running sample \"$sampleName\"...")
val sampleDirectoryName = makeSampleDirectoryName(sampleName)
val sampleRunPath = sampleParentRunPath.resolve(sampleDirectoryName)
Files.createDirectory(sampleRunPath)
val result = sample.run(arena, sampleRunPath)
if (result.isFailure) {
logger.error("validation failed ❌", result.exceptionOrNull())
exitProcess(1)
}
logger.info("validation succeeded ✅")
}
}
logger.info("shutting down vips to check for memory leaks...")
Vips.shutdown()
logger.info("all samples ran successfully 🎉")
exitProcess(0)
}
private fun makeSampleDirectoryName(original: String): String {
return original
.replace(oldValue = " ", "_")
.lowercase(Locale.ENGLISH)
}
}
| 7 | null | 1 | 19 | 9acf6ed18aae0b076308ec97804412510e2f56ed | 2,663 | vips-ffm | Apache License 2.0 |
core/src/main/kotlin/io/holunda/connector/process/ProcessAgentFunction.kt | holunda-io | 630,812,028 | false | {"Python": 403136, "Kotlin": 57145, "Dockerfile": 1729, "Shell": 372} | package io.holunda.connector.process
import com.fasterxml.jackson.module.kotlin.*
import io.camunda.connector.api.annotation.*
import io.camunda.connector.api.outbound.*
import io.holunda.connector.common.*
import mu.*
@OutboundConnector(
name = "gpt-process",
inputVariables = [
"inputJson",
"taskDescription",
"activities",
"model"
],
type = "io.holunda:connector-process:1"
)
class ProcessAgentFunction : OutboundConnectorFunction {
override fun execute(context: OutboundConnectorContext): Any {
logger.info("Executing ProcessAgentFunction")
val connectorRequest = context.variables.readFromJson<ProcessAgentRequest>()
logger.info("ProcessAgentFunction request: $connectorRequest")
return executeRequest(connectorRequest)
}
private fun executeRequest(request: ProcessAgentRequest): ProcessAgentResult {
val result = LLMServiceClient.run("process", ProcessAgentTask.fromRequest(request))
val elements = jacksonObjectMapper().treeToValue<List<Element>>(result.get("elements"))
val flows = jacksonObjectMapper().treeToValue<List<Flow>>(result.get("flows"))
val creator = ProcessModelCreator(request.activities)
val processId = creator.createProcess(elements, flows)
logger.info("ProcessAgentFunction result: $processId")
return ProcessAgentResult(processId ?: "")
}
companion object : KLogging()
}
| 20 | Python | 0 | 24 | 655d64157bb01c247e7105118ab88d08d2ea0a11 | 1,463 | camunda-8-connector-gpt | Apache License 2.0 |
web-utils/src/main/kotlin/com/icerockdev/api/Request.kt | icerockdev | 241,792,535 | false | null | /*
* Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package com.icerockdev.api
import com.fasterxml.jackson.annotation.JsonIgnore
import com.icerockdev.exception.ValidatorException
import javax.validation.ConstraintViolation
import javax.validation.MessageInterpolator
import javax.validation.Validation
import javax.validation.Validator
import javax.validation.ValidatorFactory
import kotlin.reflect.KClass
import kotlin.reflect.full.memberProperties
/*
* Annotations docs for Kotlin - https://kotlinlang.org/docs/reference/annotations.html?_ga=2.133813446.951009214.1566383426-111422153.1543224819#annotation-use-site-targets
* Example for Javax validation annotations - https://www.baeldung.com/javax-validation
* Live example - service/tools/src/test/kotlin/ToolsTest.kt
*/
abstract class Request(
private val messageInterpolator: MessageInterpolator? = null,
validatorFactory: ValidatorFactory = Validation.byDefaultProvider()
.configure()
.messageInterpolator(messageInterpolator)
.buildValidatorFactory()
) {
private val validator: Validator? = validatorFactory.validator
private var errorList: Set<ConstraintViolation<Request>> = emptySet()
@JsonIgnore
fun validate(): Boolean {
if (validator == null) {
throw ValidatorException("Validator doesn't defined")
}
errorList = validator.validate(this)
return errorList.isEmpty()
}
@JsonIgnore
fun validateRecursive(propertyPath: String = "*"): Boolean {
validate()
val constraintSet = getErrorList().toMutableSet()
@Suppress("UNCHECKED_CAST")
val self = this::class as KClass<Request>
val kProperties = self.memberProperties
for (kProperty in kProperties) {
val property = kProperty.get(this)
val propertyName = kProperty.name
when (property) {
is Request -> {
val isValid = property.validateRecursive("$propertyPath -> $propertyName")
if (!isValid) {
constraintSet.addAll(property.getErrorList())
}
}
is List<*> -> {
property.forEach { listItem ->
if (listItem is Request) {
val isValid = listItem.validateRecursive("$propertyPath -> $propertyName")
if (!isValid) {
constraintSet.addAll(listItem.getErrorList())
}
}
}
}
}
}
errorList = constraintSet
return errorList.isEmpty()
}
@JsonIgnore
fun getErrorList(): Set<ConstraintViolation<Request>> {
return errorList
}
@JsonIgnore
fun getMembers() = this::class.memberProperties
}
| 3 | Kotlin | 0 | 2 | c3fa6aa5cb777b11bc2ad87e22efa249dab9eb5a | 2,954 | web-utils | Apache License 2.0 |
module-defender/src/main/java/com/hardlove/cl/fooddefender/di/component/LaunchComponent.kt | hardlove | 154,798,245 | true | {"Java": 620249, "Kotlin": 86570} | package com.hardlove.cl.fooddefender.di.component
import dagger.Component
import com.jess.arms.di.component.AppComponent
import com.hardlove.cl.fooddefender.di.module.LaunchModule
import com.jess.arms.di.scope.ActivityScope
import com.hardlove.cl.fooddefender.mvp.ui.activity.LaunchActivity
@ActivityScope
@Component(modules = arrayOf(LaunchModule::class), dependencies = arrayOf(AppComponent::class))
interface LaunchComponent {
fun inject(activity: LaunchActivity)
}
| 0 | Java | 0 | 0 | 732e8edf7e0046ae076cd5bd6a65630ddff8dc34 | 477 | ArmsComponent | Apache License 2.0 |
core/common/src/main/kotlin/com/azizutku/movie/core/common/extensions/FragmentExtensions.kt | azizutku | 579,143,942 | false | {"Kotlin": 265966, "Shell": 647} | package com.azizutku.movie.core.common.extensions
import androidx.fragment.app.Fragment
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
fun <T> Fragment.collectLatestLifecycleFlow(flow: Flow<T>, action: suspend (T) -> Unit) {
viewLifecycleOwner.lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
flow.collectLatest(action)
}
}
}
| 0 | Kotlin | 4 | 36 | d6e8a01a41d1f61fc1b233cb32e17505c0707a20 | 572 | Modular-Clean-Arch-Movie-App | MIT License |
cupertino-icons-extended/src/commonMain/kotlin/io/github/alexzhirkevich/cupertino/icons/outlined/Gamecontroller.kt | alexzhirkevich | 636,411,288 | false | {"Kotlin": 5215549, "Ruby": 2329, "Swift": 2101, "HTML": 2071, "Shell": 868} | package io.github.alexzhirkevich.cupertino.icons.outlined
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import io.github.alexzhirkevich.cupertino.icons.CupertinoIcons
public val CupertinoIcons.Outlined.Gamecontroller: ImageVector
get() {
if (_gamecontroller != null) {
return _gamecontroller!!
}
_gamecontroller = Builder(name = "Gamecontroller", defaultWidth = 33.832.dp, defaultHeight =
21.2461.dp, viewportWidth = 33.832f, viewportHeight = 21.2461f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(0.0f, 16.7227f)
curveTo(0.0f, 19.4648f, 1.7813f, 21.2461f, 4.4648f, 21.2461f)
curveTo(5.8242f, 21.2461f, 7.1719f, 20.6602f, 8.1563f, 19.4414f)
lineTo(10.2773f, 16.875f)
curveTo(10.582f, 16.5117f, 10.9336f, 16.3359f, 11.2852f, 16.3359f)
lineTo(22.5469f, 16.3359f)
curveTo(22.8984f, 16.3359f, 23.25f, 16.5117f, 23.5547f, 16.875f)
lineTo(25.6758f, 19.4414f)
curveTo(26.6602f, 20.6602f, 28.0078f, 21.2461f, 29.3672f, 21.2461f)
curveTo(32.0508f, 21.2461f, 33.832f, 19.4648f, 33.832f, 16.7227f)
curveTo(33.832f, 15.5508f, 33.5625f, 14.2031f, 33.1055f, 12.6914f)
curveTo(32.3906f, 10.2891f, 31.1367f, 7.0195f, 29.9414f, 4.4883f)
curveTo(28.9336f, 2.3789f, 28.418f, 1.418f, 25.9336f, 0.8555f)
curveTo(23.7305f, 0.3516f, 20.6719f, 0.0117f, 16.9219f, 0.0117f)
curveTo(13.1719f, 0.0117f, 10.1016f, 0.3516f, 7.8984f, 0.8555f)
curveTo(5.4141f, 1.418f, 4.8984f, 2.3789f, 3.8906f, 4.4883f)
curveTo(2.6953f, 7.0195f, 1.4414f, 10.2891f, 0.7266f, 12.6914f)
curveTo(0.2695f, 14.2031f, 0.0f, 15.5508f, 0.0f, 16.7227f)
close()
moveTo(1.793f, 16.793f)
curveTo(1.793f, 16.0547f, 1.957f, 15.1641f, 2.332f, 13.8867f)
curveTo(3.1172f, 11.1914f, 4.4766f, 7.6992f, 5.6602f, 5.1094f)
curveTo(6.2344f, 3.8555f, 6.5508f, 3.0938f, 8.0742f, 2.7422f)
curveTo(10.1953f, 2.2383f, 13.2188f, 1.8984f, 16.9219f, 1.8984f)
curveTo(20.6133f, 1.8984f, 23.6367f, 2.2383f, 25.7578f, 2.7422f)
curveTo(27.2812f, 3.0938f, 27.5859f, 3.8555f, 28.1719f, 5.1094f)
curveTo(29.3789f, 7.6992f, 30.6797f, 11.2031f, 31.5f, 13.8867f)
curveTo(31.8867f, 15.1641f, 32.0391f, 16.0547f, 32.0391f, 16.793f)
curveTo(32.0391f, 18.4102f, 30.9023f, 19.4297f, 29.3906f, 19.4297f)
curveTo(28.5f, 19.4297f, 27.6328f, 18.9609f, 26.9531f, 18.1289f)
lineTo(24.75f, 15.4688f)
curveTo(24.1875f, 14.7891f, 23.7188f, 14.4492f, 22.6289f, 14.4492f)
lineTo(11.2031f, 14.4492f)
curveTo(10.1133f, 14.4492f, 9.6445f, 14.7891f, 9.082f, 15.4688f)
lineTo(6.8789f, 18.1289f)
curveTo(6.1992f, 18.9609f, 5.332f, 19.4297f, 4.4414f, 19.4297f)
curveTo(2.9297f, 19.4297f, 1.793f, 18.4102f, 1.793f, 16.793f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(7.4297f, 8.2734f)
curveTo(7.4297f, 8.8828f, 7.793f, 9.2578f, 8.4023f, 9.2578f)
lineTo(10.5117f, 9.2578f)
lineTo(10.5117f, 11.3086f)
curveTo(10.5117f, 11.9062f, 10.8516f, 12.2812f, 11.4375f, 12.2812f)
curveTo(12.0117f, 12.2812f, 12.3633f, 11.9062f, 12.3633f, 11.3086f)
lineTo(12.3633f, 9.2578f)
lineTo(14.3438f, 9.2578f)
curveTo(15.0f, 9.2578f, 15.3867f, 8.8828f, 15.3867f, 8.2734f)
curveTo(15.3867f, 7.6875f, 15.0f, 7.3242f, 14.3438f, 7.3242f)
lineTo(12.3633f, 7.3242f)
lineTo(12.3633f, 5.2734f)
curveTo(12.3633f, 4.6758f, 12.0117f, 4.3125f, 11.4375f, 4.3125f)
curveTo(10.8516f, 4.3125f, 10.5117f, 4.6758f, 10.5117f, 5.2734f)
lineTo(10.5117f, 7.3242f)
lineTo(8.4023f, 7.3242f)
curveTo(7.793f, 7.3242f, 7.4297f, 7.6875f, 7.4297f, 8.2734f)
close()
moveTo(24.1992f, 8.1211f)
curveTo(25.1602f, 8.1211f, 25.8867f, 7.3945f, 25.8867f, 6.4453f)
curveTo(25.8867f, 5.4844f, 25.1602f, 4.7461f, 24.1992f, 4.7461f)
curveTo(23.2617f, 4.7461f, 22.5117f, 5.4844f, 22.5117f, 6.4453f)
curveTo(22.5117f, 7.3945f, 23.2617f, 8.1211f, 24.1992f, 8.1211f)
close()
moveTo(20.7539f, 11.6016f)
curveTo(21.7031f, 11.6016f, 22.4414f, 10.8633f, 22.4414f, 9.9141f)
curveTo(22.4414f, 8.9531f, 21.7031f, 8.2148f, 20.7539f, 8.2148f)
curveTo(19.8164f, 8.2148f, 19.0664f, 8.9531f, 19.0664f, 9.9141f)
curveTo(19.0664f, 10.8633f, 19.8164f, 11.6016f, 20.7539f, 11.6016f)
close()
}
}
.build()
return _gamecontroller!!
}
private var _gamecontroller: ImageVector? = null
| 18 | Kotlin | 31 | 848 | 54bfbb58f6b36248c5947de343567903298ee308 | 6,163 | compose-cupertino | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.