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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
helper/src/main/java/archtree/helper/binding/CommonAdapter.kt
|
TrendingTechnology
| 146,884,571
| true
|
{"Kotlin": 56289}
|
package archtree.helper.binding
import android.content.res.Resources
import android.databinding.BindingAdapter
import android.os.Build
import android.support.v4.content.ContextCompat
import android.support.v4.content.res.ResourcesCompat
import android.text.Html
import android.view.View
import android.widget.ImageView
import android.widget.TextView
@Suppress("DEPRECATION")
@BindingAdapter("archtree_setHtml")
fun setHtml(textView: TextView, html: String?) {
if (html != null) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
textView.text = Html.fromHtml(html, Html.FROM_HTML_MODE_LEGACY)
} else {
textView.text = Html.fromHtml(html)
}
}
}
@BindingAdapter("archtree_custom_font")
fun setFont(view: TextView, value: Int?) {
value?.run {
val typeface = try {
ResourcesCompat.getFont(view.context, value)
} catch (e: Resources.NotFoundException) {
null
}
typeface?.run {
view.typeface = typeface
}
}
}
@BindingAdapter("archtree_icon_src")
fun setIcon(view: ImageView, icon: Int?) {
icon?.run {
val drawable = try {
ContextCompat.getDrawable(view.context, icon)
} catch (e: Resources.NotFoundException) {
null
}
view.setImageDrawable(drawable)
} ?: view.setImageBitmap(null)
}
@BindingAdapter("archtree_textRes")
fun setTextRes(view: TextView, value: Int?) {
value?.run {
view.text = try {
view.resources.getString(value)
} catch (e: Resources.NotFoundException) {
""
}
}
}
@BindingAdapter("archtree_textColorRes")
fun setTextColorRes(view: TextView, value: Int?) {
value?.run {
try {
ContextCompat.getColor(view.context, value)
} catch (e: Resources.NotFoundException) {
null
}?.let { textColor ->
view.setTextColor(textColor)
}
}
}
@BindingAdapter("archtree_backgroundRes")
fun setBackgroundRes(view: View, value: Int?) {
value?.run {
view.setBackgroundResource(value)
} ?: view.setBackgroundResource(0)
}
| 0
|
Kotlin
|
0
| 0
|
9a1c6263148978676ab3d1a5b93aeef6ae4ff7f0
| 2,171
|
archtree
|
Apache License 2.0
|
jujubasvg/src/test/kotlin/com/gabrielbmoro/jujubasvg/core/commander/JujubaCommanderTest.kt
|
gabrielbmoro
| 799,596,261
| false
|
{"Kotlin": 534789, "HTML": 547}
|
package com.gabrielbmoro.jujubasvg.core.commander
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.advanceUntilIdle
import kotlinx.coroutines.test.runTest
import kotlin.test.Test
import kotlin.test.assertEquals
@OptIn(ExperimentalCoroutinesApi::class)
class JujubaCommanderTest {
@Test
fun `given an update background color command when it is invoked then emit the right jsCommand`() =
runTest {
val jsCommand =
"document.getElementById('jujubaSVG').getElementById('12').style.fill='#0000';"
val commander = JujubaCommander()
commander.execute(Command.UpdateBackgroundColor("12", "#0000"))
advanceUntilIdle()
val result = commander.state.value
assertEquals(jsCommand, result)
}
@Test
fun `given an update stroke color command when it is invoked then emit the right jsCommand`() =
runTest {
val jsCommand =
"document.getElementById('jujubaSVG').getElementById('12').style.stroke='#0000';"
val commander = JujubaCommander()
commander.execute(Command.UpdateStrokeColor("12", "#0000"))
advanceUntilIdle()
val result = commander.state.value
assertEquals(jsCommand, result)
}
@Test
fun `given an update stroke width command when it is invoked then emit the right jsCommand`() =
runTest {
val jsCommand =
"document.getElementById('jujubaSVG').getElementById('12').style.strokeWidth='45';"
val commander = JujubaCommander()
commander.execute(Command.UpdateStrokeWidth("12", 45))
advanceUntilIdle()
val result = commander.state.value
assertEquals(jsCommand, result)
}
@Test
fun `given a remove node command when it is invoked then emit the right jsCommand`() =
runTest {
val jsCommand =
"document.getElementById('jujubaSVG').getElementById('12').remove();"
val commander = JujubaCommander()
commander.execute(Command.RemoveNode("12"))
advanceUntilIdle()
val result = commander.state.value
assertEquals(jsCommand, result)
}
}
| 3
|
Kotlin
|
0
| 2
|
6563bfedf758d68020e87d1165c8b91d68bc39ca
| 2,311
|
jujubaSVG
|
MIT License
|
app/src/main/java/com/artemchep/literaryclock/logic/live/AppDependencyLiveData.kt
|
AChep
| 160,681,782
| false
|
{"Kotlin": 130814}
|
package com.artemchep.literaryclock.logic.live
import androidx.lifecycle.LiveData
import com.artemchep.literaryclock.BuildConfig
import com.artemchep.literaryclock.models.DependencyItem
/**
* @author <NAME>
*/
class AppDependencyLiveData : LiveData<List<DependencyItem>>() {
init {
value = BuildConfig.DEPENDENCIES
.map {
DependencyItem(it.name, it.versionName)
}
}
}
| 4
|
Kotlin
|
0
| 8
|
0a067570b49474a049960d892a72749ca3cb903c
| 429
|
literaryclock
|
Apache License 2.0
|
extension/assert/src/main/kotlin/IntermediateEventRepresentationListAssert.kt
|
holixon
| 314,334,294
| false
|
{"Kotlin": 116237, "Java": 24219}
|
package io.holixon.axon.testing.assert
import org.assertj.core.api.AbstractListAssert
import org.axonframework.serialization.Serializer
import org.axonframework.serialization.upcasting.event.IntermediateEventRepresentation
class IntermediateEventRepresentationListAssert(
actual: List<IntermediateEventRepresentation>,
private val serializer: Serializer
) : AbstractListAssert
<IntermediateEventRepresentationListAssert, List<IntermediateEventRepresentation>, IntermediateEventRepresentation, IntermediateEventRepresentationAssert>(
actual, IntermediateEventRepresentationListAssert::class.java
) {
companion object {
fun assertThat(actual: List<IntermediateEventRepresentation>, serializer: Serializer): IntermediateEventRepresentationListAssert =
IntermediateEventRepresentationListAssert(actual, serializer)
}
override fun toAssert(value: IntermediateEventRepresentation, description: String): IntermediateEventRepresentationAssert =
IntermediateEventRepresentationAssert(value, serializer).`as`(description)
override fun newAbstractIterableAssert(iterable: MutableIterable<IntermediateEventRepresentation>): IntermediateEventRepresentationListAssert =
IntermediateEventRepresentationListAssert(iterable.toList(), serializer)
}
| 13
|
Kotlin
|
0
| 5
|
8e622b2a9af26648be882954a6c382d75e1422da
| 1,269
|
axon-testing
|
Apache License 2.0
|
client/client-hapi/src/commonMain/kotlin/de/jlnstrk/transit/api/hapi/model/HapiPolylineDescription.kt
|
jlnstrk
| 229,599,180
| false
|
{"Kotlin": 729374}
|
package de.jlnstrk.transit.api.hapi.model
import de.jlnstrk.transit.api.hafas.HapiXsd
@HapiXsd("1.39")
public typealias HapiPolylineDescription = HapiPolyline
| 0
|
Kotlin
|
0
| 0
|
9f700364f78ebc70b015876c34a37b36377f0d9c
| 160
|
transit
|
Apache License 2.0
|
kondor-core/src/main/kotlin/com/ubertob/kondor/json/JsonAdjunction.kt
|
s4nchez
| 344,814,409
| true
|
{"Kotlin": 59308, "Shell": 526}
|
package com.ubertob.kondor.json
import JsonLexer
import com.ubertob.kondor.outcome.*
data class JsonError(val path: NodePath, val reason: String) : OutcomeError {
override val msg = "error on <${path.getPath()}> $reason"
override fun toString(): String = msg
}
typealias JsonOutcome<T> = Outcome<JsonError, T>
/*
a couple parser/printer form an adjunction (https://en.wikipedia.org/wiki/Adjoint_functors)
The laws are (no id because we cannot reconstruct a wrong json from the error):
render `.` parse `.` render = render
parse `.` render `.` parse = parse
where:
f `.` g: (x) -> g(f(x))
render : JsonOutcome<T> -> JSON
parse : JSON -> JsonOutcome<T>
JSON here can be either the Json string or the JsonNode
*/
typealias JConverter<T> = JsonAdjunction<T, *>
interface JsonAdjunction<T, JN : JsonNode> {
val nodeType: NodeKind<JN>
@Suppress("UNCHECKED_CAST") //but we are confident it's safe
fun safeCast(node: JsonNode): JsonOutcome<JN> =
if (node.nodeKind() == nodeType)
(node as JN).asSuccess()
else
JsonError(
node.path,
"expected a ${nodeType.desc} but found ${node.nodeKind().desc}"
).asFailure()
fun fromJsonNodeBase(node: JsonNode): JsonOutcome<T> = safeCast(node).bind(::fromJsonNode)
fun fromJsonNode(node: JN): JsonOutcome<T>
fun toJsonNode(value: T, path: NodePath): JN
private fun TokensStream.parseFromRoot(): JsonOutcome<JN> =
nodeType.parse(this, NodeRoot)
fun toJson(value: T): String = toJsonNode(value, NodeRoot).render()
fun fromJson(jsonString: String): JsonOutcome<T> =
JsonLexer.tokenize(jsonString).run {
parseFromRoot()
.bind { fromJsonNode(it) }
.bind {
if (hasNext())
parsingFailure("EOF", next(), position(), NodeRoot)
else
it.asSuccess()
}
}
}
| 0
| null |
0
| 0
|
cb84e8603953d1b70bc78c7ca094012a1614d7b1
| 1,998
|
kondor-json
|
Apache License 2.0
|
app/src/main/java/com/github/app/ui/home/UserItem.kt
|
andyhaha
| 870,067,838
| false
|
{"Kotlin": 83479}
|
package com.github.app.ui.home
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.ListItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import coil.compose.AsyncImage
import com.github.app.domain.model.SimpleUser
import com.github.app.navigation.Screen
@Composable
fun UserItem(navController: NavController, simpleUser: SimpleUser) {
ListItem(
modifier = Modifier
.fillMaxWidth()
.clickable {
navController.navigate(Screen.Detail(simpleUser.name))
},
headlineContent = { Text(text = simpleUser.name) },
leadingContent = {
AsyncImage(
model = simpleUser.avatarUrl,
contentDescription = "Net image",
modifier = Modifier
.size(50.dp)
.clip(CircleShape)
)
}
)
HorizontalDivider(thickness = 0.5.dp)
}
| 0
|
Kotlin
|
0
| 0
|
9e6a4dc56c1c840e23dad704c0326787f940f694
| 1,326
|
GitHubApp
|
Apache License 1.1
|
build-logic/conventions/src/main/kotlin/com/squareup/anvil/conventions/utils/project.kt
|
square
| 271,357,426
| false
|
{"Kotlin": 1440554, "Shell": 712}
|
package com.squareup.anvil.conventions.utils
import com.rickbusarow.kgx.isPartOfRootBuild
import com.rickbusarow.kgx.javaExtension
import com.rickbusarow.kgx.parents
import org.gradle.accessors.dm.LibrariesForLibs
import org.gradle.api.Project
import org.gradle.api.internal.project.ProjectInternal
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.tasks.SourceSet
import org.gradle.plugin.devel.GradlePluginDevelopmentExtension
internal fun Project.isInMainAnvilBuild() = rootProject.name == "anvil"
internal fun Project.isInDelegateBuild() = rootProject.name == "delegate"
internal val Project.gradlePublishingExtension: PublishingExtension
get() = extensions.getByType(PublishingExtension::class.java)
internal val Project.gradlePluginDevelopmentExtension: GradlePluginDevelopmentExtension
get() = extensions.getByType(GradlePluginDevelopmentExtension::class.java)
internal val Project.libs: LibrariesForLibs
get() = extensions.getByType(LibrariesForLibs::class.java)
internal fun Project.javaSourceSet(name: String): SourceSet {
return javaExtension.sourceSets.getByName(name)
}
internal fun Project.addTasksToStartParameter(taskNames: Iterable<String>) {
if (isPartOfRootBuild) {
/* Root of composite build: We can just add the task name */
gradle.startParameter.setTaskNames(
gradle.startParameter.taskNames.toSet() + taskNames,
)
} else {
/* This is an included build. Referencing the task path explicitly */
val rootBuild = gradle.parents().last()
val buildId = (project as ProjectInternal).identityPath
val absoluteTaskPaths = taskNames.map { "$buildId:$it" }
rootBuild.startParameter.setTaskNames(
rootBuild.startParameter.taskNames.toSet() + absoluteTaskPaths,
)
}
}
| 38
|
Kotlin
|
72
| 1,210
|
2a0bfe5ffbfaa11a9dc45a27b7b3f3b884e1427c
| 1,770
|
anvil
|
Apache License 2.0
|
remote-config/src/test/kotlin/com/rakuten/tech/mobile/remoteconfig/api/PublicKeyFetcherSpec.kt
|
rakutentech
| 183,537,422
| false
| null |
package com.rakuten.tech.mobile.remoteconfig.api
import androidx.test.core.app.ApplicationProvider
import com.nhaarman.mockitokotlin2.argForWhich
import com.nhaarman.mockitokotlin2.eq
import com.rakuten.tech.mobile.sdkutils.RasSdkHeaders
import junit.framework.TestCase
import okhttp3.*
import org.amshove.kluent.*
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.IOException
open class PublicKeyFetcherSpec {
internal val mockApiClient: ConfigApiClient = mock()
internal fun createFetcher() =
PublicKeyFetcher(mockApiClient)
internal fun enqueueResponse(
body: String,
code: Int
) {
When calling mockApiClient.fetchPath(any(), eq(null)) itReturns Response.Builder()
.request(Request.Builder().url("https://www.example.com").build())
.protocol(Protocol.HTTP_2)
.message("")
.code(code)
.body(ResponseBody.create(MediaType.get("text/plain; charset=utf-8"), body))
.build()
}
}
class PublicKeyFetcherNormalSpec : PublicKeyFetcherSpec() {
private fun enqueueSuccessResponse(
id: String = "test_id",
key: String = "test_key",
createdAt: String = "2019-07-23T07:24:57+00:00"
) {
enqueueResponse(
body = """
{
"id": "$id",
"key": "$key",
"createdAt": "$createdAt"
}
""".trimIndent(),
code = 200
)
}
@Test
fun `should fetch the public key`() {
val fetcher = createFetcher()
enqueueSuccessResponse(key = "test_key")
fetcher.fetch("test_key_id") shouldEqual "test_key"
}
@Test
fun `should fetch the public key for the provided key id`() {
val fetcher = createFetcher()
enqueueSuccessResponse(id = "test_key_id")
fetcher.fetch("test_key_id")
Verify on mockApiClient that mockApiClient.fetchPath(argForWhich {
contains("keys/test_key_id")
}, eq(null))
}
}
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [28])
class PublicKeyFetcherErrorSpec : PublicKeyFetcherSpec() {
private fun enqueueErrorResponse(
body: String = "",
code: Int = 200
) {
enqueueResponse(
body = body,
code = code
)
}
@Test(expected = IOException::class)
fun `should throw when the request is unsuccessful`() {
enqueueErrorResponse(code = 400)
val fetcher = createFetcher()
fetcher.fetch("test_key_id")
}
@Test(expected = Exception::class)
fun `should throw when the 'id' key is missing in response`() {
enqueueErrorResponse(
body = """{
"key": "test_key",
"createdAt": "test_created"
}""".trimIndent()
)
val fetcher = createFetcher()
fetcher.fetch("test_key_id")
}
@Test(expected = Exception::class)
fun `should throw when the 'key' key is missing in response`() {
enqueueErrorResponse(
body = """{
"id": "test_key_id",
"createdAt": "test_created"
}""".trimIndent()
)
val fetcher = createFetcher()
fetcher.fetch("test_key_id")
}
@Test(expected = Exception::class)
fun `should throw when the 'createdAt' key is missing in response`() {
enqueueErrorResponse(
body = """{
"id": "test_key_id",
"key": "test_key"
}""".trimIndent()
)
val fetcher = createFetcher()
fetcher.fetch("test_key_id")
}
@Test(expected = IOException::class)
fun `should throw when valid client but invalid url`() {
val mockRasHeaders: RasSdkHeaders = mock()
When calling mockRasHeaders.asArray() itReturns emptyArray()
enqueueErrorResponse(code = 404)
val fetcher = PublicKeyFetcher(ConfigApiClient(
"https://www.example.com", ApplicationProvider.getApplicationContext(), mockRasHeaders))
fetcher.fetch("test_key_id")
}
@Test
@Suppress("TooGenericExceptionCaught")
fun `should not throw when there are extra keys in the response`() {
enqueueErrorResponse(
body = """{
"id": "test_id",
"key": "test_key",
"createdAt": "test_created",
"randomKey": "random_value"
}""".trimIndent()
)
val fetcher = createFetcher()
try {
fetcher.fetch("test_key_id")
} catch (e: Exception) {
TestCase.fail("Should not throw an exception.")
throw e
}
}
}
| 0
|
Kotlin
|
9
| 5
|
63e10f2e1e5139f962d4a52ab94236856266c7ee
| 4,863
|
android-remote-config
|
MIT License
|
app/src/main/java/com/androidpoet/cleanarchitecture/presentation/root/BottomNavItem.kt
|
AndroidPoet
| 515,106,144
| false
|
{"Kotlin": 104539}
|
package com.androidpoet.cleanarchitecture.presentation.root
import androidx.annotation.StringRes
import com.androidpoet.cleanarchitecture.R
sealed class Screen(val route: String, val image: Int, @StringRes val resourceId: Int) {
object NowPlaying : Screen("Now Playing", R.drawable.ic_baseline_now_playing_24, R.string.now_playing)
object Popular : Screen("Popular", R.drawable.ic_baseline_popular_24, R.string.popular)
object TopRated : Screen("Top Rated", R.drawable.ic_baseline_featured_top_rated, R.string.top_rated)
object Upcoming : Screen("Upcoming", R.drawable.ic_baseline_upcoming_24, R.string.upcoming)
}
| 0
|
Kotlin
|
0
| 1
|
1d7cde8debbd0f24c990febfa0a20d14b586e7d4
| 635
|
Clean-Architecture
|
Apache License 2.0
|
src/main/kotlin/com/joocy/helloworld/HelloWorldConfiguration.kt
|
d3z
| 52,111,566
| false
| null |
package com.joocy.helloworld
import com.fasterxml.jackson.annotation.JsonProperty
import io.dropwizard.Configuration
class HelloWorldConfiguration(@JsonProperty val template: String = "", @JsonProperty val defaultName: String = "") : Configuration() {
}
| 0
|
Kotlin
|
0
| 0
|
65e5cb8dc2f94b2c5a9d260dd7e0eb234f8f6ec6
| 255
|
kotlin_dropwizard_helloworld
|
Apache License 2.0
|
src/main/kotlin/com/aerospike/skyhook/listener/map/SstoreCommandListener.kt
|
aerospike-community
| 349,306,040
| false
|
{"Kotlin": 252788, "CSS": 4448, "JavaScript": 3795, "TypeScript": 1278, "Shell": 868, "Dockerfile": 452, "MDX": 213}
|
package com.aerospike.skyhook.listener.map
import com.aerospike.client.Key
import com.aerospike.client.Record
import com.aerospike.client.Value
import com.aerospike.client.cdt.MapOperation
import com.aerospike.client.cdt.MapPolicy
import com.aerospike.client.listener.RecordArrayListener
import com.aerospike.skyhook.command.RequestCommand
import com.aerospike.skyhook.listener.BaseListener
import com.aerospike.skyhook.listener.ValueType
import com.aerospike.skyhook.util.IntersectMerge
import com.aerospike.skyhook.util.Merge
import com.aerospike.skyhook.util.Typed
import com.aerospike.skyhook.util.UnionMerge
import io.netty.channel.ChannelHandlerContext
abstract class SstoreBaseCommandListener(
ctx: ChannelHandlerContext
) : BaseListener(ctx), RecordArrayListener, Merge {
@Volatile
private lateinit var key: Key
override fun handle(cmd: RequestCommand) {
require(cmd.argCount >= 3) { argValidationErrorMsg(cmd) }
key = createKey(cmd.key)
client.get(
null, this, null,
getKeys(cmd).toTypedArray()
)
}
private fun getKeys(cmd: RequestCommand): List<Key> {
return cmd.args.drop(2)
.map { createKey(it) }
}
override fun onSuccess(keys: Array<out Key>?, records: Array<Record?>?) {
if (records == null) {
writeLong(0L)
} else {
val values = merge(records.filterNotNull()
.map { it.getMap(aeroCtx.bin) }.map { it.keys })
val operation = MapOperation.putItems(
MapPolicy(),
aeroCtx.bin,
values.map {
Typed.getValue(it.toString().toByteArray()) to Value.getAsNull()
}.toMap()
)
client.operate(
defaultWritePolicy, key, *systemOps(ValueType.SET), operation
)
writeLong(values.size)
}
flushCtxTransactionAware()
}
}
class SinterstoreCommandListener(
ctx: ChannelHandlerContext
) : SstoreBaseCommandListener(ctx), IntersectMerge
class SunionstoreCommandListener(
ctx: ChannelHandlerContext
) : SstoreBaseCommandListener(ctx), UnionMerge
| 13
|
Kotlin
|
7
| 26
|
f0b057797c42756bf14998cf7b0e4625ce33e691
| 2,196
|
skyhook
|
Apache License 2.0
|
Mesh_network app/test-app/src/main/java/com/meshnetwork/meshnetworks/testapp/screens/SendFileScreen.kt
|
arif6371
| 862,438,759
| false
|
{"Kotlin": 492389, "TypeScript": 157688, "HTML": 33644, "Java": 18350, "JavaScript": 6573, "Objective-C": 2285, "Ruby": 2277, "Objective-C++": 745}
|
package com.meshnetwork.meshnetworks.testapp.screens
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.ListItem
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.platform.LocalSavedStateRegistryOwner
import androidx.lifecycle.viewmodel.compose.viewModel
import com.meshnetwork.meshnetworks.testapp.ViewModelFactory
import com.meshnetwork.meshnetworks.testapp.appstate.AppUiState
import com.meshnetwork.meshnetworks.testapp.appstate.FabState
import com.meshnetwork.meshnetworks.testapp.viewmodel.SendFileUiState
import com.meshnetwork.meshnetworks.testapp.viewmodel.SendFileViewModel
import org.kodein.di.compose.localDI
@Composable
fun SendFileScreen(
uiState: SendFileUiState,
){
LazyColumn {
items(
items = uiState.pendingTransfers,
key = { it.id }
) {transfer ->
ListItem(
headlineContent = {
Text("${transfer.name} -> ${transfer.toHost.hostAddress}")
},
supportingContent = {
Text("Status: ${transfer.status} Sent ${transfer.transferred} / ${transfer.size}")
}
)
}
}
}
@Composable
fun SendFileScreen(
onNavigateToSelectReceiveNode: (Uri) -> Unit,
onSetAppUiState: (AppUiState) -> Unit,
viewModel: SendFileViewModel = viewModel(
factory = ViewModelFactory(
di = localDI(),
owner = LocalSavedStateRegistryOwner.current,
vmFactory = {
SendFileViewModel(it, onNavigateToSelectReceiveNode)
},
defaultArgs = null,
)
),
) {
val uiState: SendFileUiState by viewModel.uiState.collectAsState(SendFileUiState())
val launcherPicker = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument()
) { uri ->
viewModel.onSelectFileToSend(uri)
}
LaunchedEffect(uiState.appUiState) {
onSetAppUiState(uiState.appUiState.copy(
fabState = FabState(
visible = true,
label = "Send File",
icon = Icons.Default.Send,
onClick = {
launcherPicker.launch(arrayOf("*/*"))
}
)
))
}
SendFileScreen(
uiState = uiState,
)
}
| 0
|
Kotlin
|
0
| 0
|
67810a07661786d72a5f74a2305a16cdd4c96c4a
| 2,844
|
Technova_Mayday-sos-app
|
MIT License
|
src/test/kotlin/com/github/gabrielshanahan/phpkt/statements/constructs/branching/IfElseTest.kt
|
gabrielshanahan
| 226,652,392
| false
| null |
package com.github.gabrielshanahan.phpkt.statements.constructs.branching
import com.github.gabrielshanahan.phpkt.expressions.assignables.`$`
import com.github.gabrielshanahan.phpkt.expressions.assignments.`=`
import com.github.gabrielshanahan.phpkt.invoke
import com.github.gabrielshanahan.phpkt.statements.CompoundStatement
import com.github.gabrielshanahan.phpkt.statements.constructs.php
import io.kotlintest.shouldBe
import io.kotlintest.specs.StringSpec
class IfElseTest : StringSpec({
fun CompoundStatement.createChildren(): CompoundStatement {
`$`("y") `=` "x is true"
`$`("z")`=` "x is true"
return this
}
"An if block renders correctly" {
val code = If(`$`("x"))
.apply { body.createChildren() }
.toPhpStr()
val expected = """
|if (${'$'}x) {
| ${'$'}y = "x is true";
| ${'$'}z = "x is true";
|}""".trimMargin()
code shouldBe expected
}
"`if` DSL method works correctly" {
val code = php {
`if`(`$`("x")) {
`$`("y") `=` 5
}
}.toPhpStr()
val expected = """
|<?php
|
|if (${'$'}x) {
| ${'$'}y = 5;
|}
""".trimMargin()
code shouldBe expected
}
"elseif DSL method can be called after `if` and renders correctly" {
val code = php {
`if`(`$`("x")) {
`$`("y") `=` 5
} elseif(`$`("x")) {
`$`("x") `=` 5
}
}.toPhpStr()
val expected = """
|<?php
|
|if (${'$'}x) {
| ${'$'}y = 5;
|} elseif (${'$'}x) {
| ${'$'}x = 5;
|}
""".trimMargin()
code shouldBe expected
}
"`else` DSL method can be called after `if` and renders correctly" {
val code = php {
`if`(`$`("x")) {
`$`("y") `=` 5
} `else` {
`$`("x") `=` 5
}
}.toPhpStr()
val expected = """
|<?php
|
|if (${'$'}x) {
| ${'$'}y = 5;
|} else {
| ${'$'}x = 5;
|}
""".trimMargin()
code shouldBe expected
}
"if, elseif and else can be called after each other" {
val code = php {
`if`(`$`("x")) {
`$`("x") `=` 5
} elseif(`$`("y")) {
`$`("y") `=` 5
} elseif(`$`("z")) {
`$`("z") `=` 5
} `else` {
`$`("x") `=` `$`("y")
}
}.toPhpStr()
val expected = """
|<?php
|
|if (${'$'}x) {
| ${'$'}x = 5;
|} elseif (${'$'}y) {
| ${'$'}y = 5;
|} elseif (${'$'}z) {
| ${'$'}z = 5;
|} else {
| ${'$'}x = ${'$'}y;
|}
""".trimMargin()
code shouldBe expected
}
})
| 0
|
Kotlin
|
0
| 0
|
132f9ef6a517646f1ea1272af8a3066c4c147785
| 3,123
|
PhpKt
|
MIT License
|
app/src/main/java/com/pocads/MainActivity.kt
|
alexanderdeoliveira
| 632,520,628
| false
| null |
package com.pocads
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.n_ads.util.ProductAdsTypeEnum
import com.pocads.databinding.ActivityMainBinding
class MainActivitySecond: AppCompatActivity() {
private val binding: ActivityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.customRecyclerView.apply {
val mAdapter = ItemAdapter(context, listMock.subList(0, 5))
mAdapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
override fun onChanged() {
setAdsPositionList(mAdapter.items)
}
})
adapter = mAdapter
// layoutManager = GridLayoutManager(context, 2)
}
}
}
private val listMock = listOf(
ItemListModel(id = 0, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 1", rating = 0, price = 139.80),
ItemListModel(id = 1, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 2", rating = 1, price = 139.81),
ItemListModel(id = 2, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 3", rating = 2, price = 139.82),
ItemListModel(id = 3, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 4", rating = 3, price = 139.83),
ItemListModel(id = 4, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 5", rating = 4, price = 139.84),
ItemListModel(id = 5, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 6", rating = 5, price = 139.85),
ItemListModel(id = 6, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 7", rating = 0, price = 139.86),
ItemListModel(id = 7, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 8", rating = 1, price = 139.87),
ItemListModel(id = 8, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 9", rating = 2, price = 139.88),
ItemListModel(id = 9, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 10",rating = 3,price = 139.89),
ItemListModel(id = 10, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 11",rating = 4,price = 139.90),
ItemListModel(id = 11, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 12",rating = 5,price = 139.91),
ItemListModel(id = 12, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 13",rating = 0,price = 139.92),
ItemListModel(id = 13, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 14",rating = 1,price = 139.93),
ItemListModel(id = 14, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 15",rating = 2,price = 139.94),
ItemListModel(id = 15, type = ProductAdsTypeEnum.COMMON, imageUrl = "https://static.netshoes.com.br/produtos/tenis-adidas-breaknet-feminino/12/NQQ-4379-112/NQQ-4379-112_thumb1.jpg?ts=1655223868", title = "Camisa Tottenham Home 19/d sdfd dsf 20º Torcedor - 16",rating = 3,price = 139.95)
)
| 0
|
Kotlin
|
0
| 0
|
e50dac139d2b98e62ec1a0aaaeb9805a18bb60eb
| 5,760
|
POC-Ads
|
Apache License 2.0
|
server/lib/base/src/main/kotlin/dev/reprator/base/action/JwtTokenService.kt
|
TheReprator
| 781,077,991
| false
|
{"Kotlin": 399028, "Swift": 5325, "HTML": 357, "JavaScript": 92}
|
package dev.reprator.base.action
import com.auth0.jwt.interfaces.JWTVerifier
import io.ktor.server.auth.jwt.*
interface JwtTokenService {
companion object {
const val JWT_USER_ID = "userId"
const val SECOND_1 = 1_000L
private const val MINUTE_1_MILLISECONDS = 60 * SECOND_1
const val HOUR_1_MILLISECONDS = 60 * MINUTE_1_MILLISECONDS
}
val jwtConfiguration: JWTConfiguration
val jwtVerifier: JWTVerifier
suspend fun generateAccessToken(userId: String): String
suspend fun generateRefreshToken(userId: String): String
suspend fun customValidator(credential: JWTCredential): JWTPrincipal?
suspend fun isTokenValid(token: String): Pair<Boolean, Int>
}
data class JWTConfiguration(val secret: String, val audience: String, val issuer: String, val realm: String)
| 1
|
Kotlin
|
0
| 0
|
1468ecc36c791f643973d0fadae9f6154d726b84
| 830
|
ExpenseManagment
|
Apache License 2.0
|
src/main/kotlin/io/vlang/lang/VlangFileType.kt
|
vlang
| 754,996,747
| false
|
{"Kotlin": 1646396, "V": 250415, "Java": 68641, "Lex": 20424, "HTML": 6275}
|
package io.vlang.lang
import com.intellij.openapi.fileTypes.LanguageFileType
import com.intellij.openapi.vfs.VirtualFile
import io.vlang.ide.ui.VIcons
object VlangFileType : LanguageFileType(VlangLanguage) {
override fun getName() = "V"
override fun getDescription() = "V file"
override fun getDefaultExtension() = "v"
override fun getIcon() = VIcons.V
override fun getCharset(file: VirtualFile, content: ByteArray): String = "UTF-8"
}
| 5
|
Kotlin
|
5
| 33
|
a0d2cbfa63b995d93aaca3c80676f0c2f9bef117
| 458
|
intellij-v
|
MIT License
|
app/src/main/kotlin/com/lalosoft/myshopping/home/HomeView.kt
|
gonzalonm
| 93,402,704
| false
| null |
package com.lalosoft.myshopping.home
import com.lalosoft.myshopping.BaseView
import com.lalosoft.myshopping.domain.Item
interface HomeView : BaseView {
fun render(list: List<Item>)
fun renderEmpty()
fun renderError()
fun restartApp()
}
| 0
|
Kotlin
|
0
| 0
|
66b558c08af7a77d9c8f9f49bdecdd08d5109d88
| 253
|
sample-my-shopping
|
Apache License 2.0
|
fontawesome/src/de/msrd0/fontawesome/icons/FA_CHEVRON_DOWN.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
object FA_CHEVRON_DOWN: Icon {
override val name get() = "chevron-down"
override val unicode get() = "f078"
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 448 512"><path d="M207.029 381.476L12.686 187.132c-9.373-9.373-9.373-24.569 0-33.941l22.667-22.667c9.357-9.357 24.522-9.375 33.901-.04L224 284.505l154.745-154.021c9.379-9.335 24.544-9.317 33.901.04l22.667 22.667c9.373 9.373 9.373 24.569 0 33.941L240.971 381.476c-9.373 9.372-24.569 9.372-33.942 0z"/></svg>"""
else -> null
}
}
| 0
|
Kotlin
|
0
| 0
|
e757d073562077a753280bf412eebfc4a9121b33
| 1,486
|
fontawesome-kt
|
Apache License 2.0
|
fontawesome/src/de/msrd0/fontawesome/icons/FA_CHEVRON_DOWN.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
object FA_CHEVRON_DOWN: Icon {
override val name get() = "chevron-down"
override val unicode get() = "f078"
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 448 512"><path d="M207.029 381.476L12.686 187.132c-9.373-9.373-9.373-24.569 0-33.941l22.667-22.667c9.357-9.357 24.522-9.375 33.901-.04L224 284.505l154.745-154.021c9.379-9.335 24.544-9.317 33.901.04l22.667 22.667c9.373 9.373 9.373 24.569 0 33.941L240.971 381.476c-9.373 9.372-24.569 9.372-33.942 0z"/></svg>"""
else -> null
}
}
| 0
|
Kotlin
|
0
| 0
|
e757d073562077a753280bf412eebfc4a9121b33
| 1,486
|
fontawesome-kt
|
Apache License 2.0
|
src/test/kotlin/com/stefan_grafberger/streamdq/checks/row/RowValueCompleteTest.kt
|
stefan-grafberger
| 515,256,686
| false
| null |
package com.stefan_grafberger.streamdq.checks.row
import com.stefan_grafberger.streamdq.TestUtils
import com.stefan_grafberger.streamdq.VerificationSuite
import com.stefan_grafberger.streamdq.data.TestDataUtils
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.TestInstance
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class RowValueCompleteTest {
@Test
fun `test RowValueComplete works`() {
val (env, rawStream) = TestDataUtils.createEnvAndGetClickStream()
val rowLevelCheck = RowLevelCheck()
.isComplete("sessionId")
.isComplete("nestedInfo.nestedIntValue")
val verificationResult = VerificationSuite()
.onDataStream(rawStream, env.config)
.addRowLevelCheck(rowLevelCheck)
.build()
val result = TestUtils.collectRowLevelResultStreamAndAssertLen(verificationResult, rowLevelCheck, 10)
TestUtils.assertRowLevelConstraintResults(
result, rowLevelCheck, 0,
arrayOf(true, true, true, true, false)
)
TestUtils.assertRowLevelConstraintResults(
result, rowLevelCheck, 1,
arrayOf(true, true, false, true, true)
)
}
@Test
fun `test RowValueComplete fails for invalid field references`() {
val (env, rawStream) = TestDataUtils.createEnvAndGetClickStream()
val invalidFieldCheck = RowLevelCheck().isComplete("invalid-path")
val expectedExceptionMessage = "Invalid field expression \"invalid-path\"."
TestUtils.assertFailsWithExpectedMessage(rawStream, env, invalidFieldCheck, expectedExceptionMessage)
}
}
| 3
|
Kotlin
|
0
| 4
|
0fafda659a0d1cdbe1791826eb71d34c671b83db
| 1,646
|
StreamDQ
|
Apache License 2.0
|
oldAndroidProjects/More Projects/PraticeProjects/AndReadyCode/basic-android-kotlin-compose-training-bus-schedule-app-starter/app/src/main/java/com/example/busschedule/data/BusScheduleDao.kt
|
shivathapaa
| 800,628,391
| false
|
{"Kotlin": 3413631, "Shell": 2341}
|
package com.example.busschedule.data
import androidx.room.Dao
import androidx.room.Query
import kotlinx.coroutines.flow.Flow
@Dao
interface BusScheduleDao {
// The query now says to select all columns from the items, where the stopName matches the :id argument. Notice the :id uses the colon notation in the query to reference arguments in the function.
@Query(
"""
SELECT * FROM schedule
WHERE stop_name = :stopName
ORDER BY arrival_time ASC
"""
)
fun getByStopName(stopName: String): Flow<List<BusSchedule>>
//It is recommended to use Flow in the persistence layer. With Flow as the return type, you receive notification whenever the data in the database changes. The Room keeps this Flow updated for you, which means you only need to explicitly get the data once.
@Query(
"""
SELECT * FROM schedule
ORDER BY arrival_time ASC
"""
)
fun getAll(): Flow<List<BusSchedule>>
}
| 0
|
Kotlin
|
0
| 0
|
19185d178bb0ff390c9c2c43adbd9ddefc9a2288
| 988
|
Android-Practice-Projects
|
The Unlicense
|
core/common/src/main/java/com/season/winter/common/util/security/RSA2048AlgorithmService.kt
|
f-lab-edu
| 701,993,574
| false
|
{"Kotlin": 272600}
|
package com.season.winter.common.util.security
interface RSA2048AlgorithmService {
fun create(alias: String): Boolean
fun encrypt(plainText: String): String
fun decrypt(base64EncryptedCipherText: String): String
}
| 0
|
Kotlin
|
0
| 0
|
19d12aca76e09848579bc1a2c46b96140ddcc759
| 228
|
CatchBottle
|
Apache License 2.0
|
library/echo/src/jvmBenchmarks/kotlin/io/github/alexandrepiveteau/echo/lww/LWWRegister.kt
|
markdown-party
| 341,117,604
| false
|
{"Kotlin": 603967, "Dockerfile": 723, "JavaScript": 715, "Shell": 646, "HTML": 237, "CSS": 133}
|
package io.github.alexandrepiveteau.echo.lww
import io.github.alexandrepiveteau.echo.core.causality.EventIdentifier
import io.github.alexandrepiveteau.echo.projections.OneWayProjection
/**
* A [OneWayProjection] which represents a [LWWRegister], which will preserve the last value in the
* operation log.
*
* @param T the type of the events.
*/
class LWWRegister<T> : OneWayProjection<LWWRegister.Tagged<T>, T> {
/** A tagged [T] with an [EventIdentifier]. */
data class Tagged<out T>(val value: T, val identifier: EventIdentifier)
override fun forward(
model: Tagged<T>,
identifier: EventIdentifier,
event: T,
) = if (model.identifier >= identifier) model else Tagged(event, identifier)
}
| 0
|
Kotlin
|
3
| 54
|
760a0066fa683d1ca0a99d44370e10db5932dc20
| 725
|
mono
|
MIT License
|
gateway/src/main/kotlin/org/heeheepresso/gateway/recommendation/RecommendationResultSet.kt
|
HeeHeePresso
| 758,780,391
| false
|
{"Kotlin": 73624, "Java": 538}
|
package org.heeheepresso.gateway.recommendation
data class RecommendationResultSet(
val results: List<RecommendationResult>
) {
fun getMenuList(handler: RecommendationHandler): List<RecommendedMenu>? {
return this.results
.firstOrNull { it.handler == handler.name }
?.recommendedMenus
}
}
| 11
|
Kotlin
|
0
| 0
|
22aad7048d85d4a5618ec2026d1fd3e9df85dd1d
| 334
|
Backend
|
Apache License 2.0
|
feature/detail/src/main/java/com/lelestacia/lelenime/feature/detail/util/ListToString.kt
|
Kamil-Malik
| 628,208,142
| false
| null |
package com.lelestacia.lelenime.feature.detail.util
class ListToString {
operator fun invoke(list: List<String>): String {
var newList = ""
for (i in list.indices) {
newList +=
if (i == 0) {
list[i]
} else {
", ${list[i]}"
}
}
return newList
}
}
| 1
|
Kotlin
|
0
| 7
|
4bb4ff8a3e0c1137fe815ac7ce82babcb13cc5d1
| 387
|
lelenime
|
Apache License 2.0
|
lib/src/test/kotlin/com/lemonappdev/konsist/api/ext/list/KoSourceSetProviderListExtTest.kt
|
LemonAppDev
| 621,181,534
| false
|
{"Kotlin": 3830717, "Python": 17471}
|
package com.lemonappdev.konsist.api.ext.list
import com.lemonappdev.konsist.api.provider.KoSourceSetProvider
import io.mockk.every
import io.mockk.mockk
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
class KoSourceSetProviderListExtTest {
@Test
fun `withSourceSet(String) returns declaration with given source set`() {
// given
val sourceSetName = "sourceSetName"
val declaration1: KoSourceSetProvider =
mockk {
every { resideInSourceSet(sourceSetName) } returns true
}
val declaration2: KoSourceSetProvider =
mockk {
every { resideInSourceSet(sourceSetName) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withSourceSet(sourceSetName)
// then
sut shouldBeEqualTo listOf(declaration1)
}
@Test
fun `withSourceSet(String) returns declarations with one of given source sets`() {
// given
val sourceSetName1 = "sourceSetName1"
val sourceSetName2 = "sourceSetName2"
val declaration1: KoSourceSetProvider =
mockk {
every { resideInSourceSet(sourceSetName1) } returns true
every { resideInSourceSet(sourceSetName2) } returns false
}
val declaration2: KoSourceSetProvider =
mockk {
every { resideInSourceSet(sourceSetName1) } returns false
every { resideInSourceSet(sourceSetName2) } returns true
}
val declaration3: KoSourceSetProvider =
mockk {
every { resideInSourceSet(sourceSetName1) } returns false
every { resideInSourceSet(sourceSetName2) } returns false
}
val declarations = listOf(declaration1, declaration2, declaration3)
// when
val sut = declarations.withSourceSet(sourceSetName1, sourceSetName2)
// then
sut shouldBeEqualTo listOf(declaration1, declaration2)
}
@Test
fun `withoutSourceSet(String) returns declaration without given source set`() {
// given
val sourceSetName = "sourceSetName"
val declaration1: KoSourceSetProvider =
mockk {
every { resideInSourceSet(sourceSetName) } returns true
}
val declaration2: KoSourceSetProvider =
mockk {
every { resideInSourceSet(sourceSetName) } returns false
}
val declarations = listOf(declaration1, declaration2)
// when
val sut = declarations.withoutSourceSet(sourceSetName)
// then
sut shouldBeEqualTo listOf(declaration2)
}
@Test
fun `withoutSourceSet(String) returns declaration without any of given source sets`() {
// given
val sourceSetName1 = "sourceSetName1"
val sourceSetName2 = "sourceSetName2"
val declaration1: KoSourceSetProvider =
mockk {
every { resideInSourceSet(sourceSetName1) } returns true
every { resideInSourceSet(sourceSetName2) } returns false
}
val declaration2: KoSourceSetProvider =
mockk {
every { resideInSourceSet(sourceSetName1) } returns false
every { resideInSourceSet(sourceSetName2) } returns true
}
val declaration3: KoSourceSetProvider =
mockk {
every { resideInSourceSet(sourceSetName1) } returns false
every { resideInSourceSet(sourceSetName2) } returns false
}
val declarations = listOf(declaration1, declaration2, declaration3)
// when
val sut = declarations.withoutSourceSet(sourceSetName1, sourceSetName2)
// then
sut shouldBeEqualTo listOf(declaration3)
}
}
| 4
|
Kotlin
|
22
| 840
|
81324e09fe46c9f1095b133713ae0062e742c2e3
| 3,916
|
konsist
|
Apache License 2.0
|
src/main/kotlin/com/sipios/springsearch/SearchOperation.kt
|
sipios
| 205,107,934
| false
|
{"Kotlin": 87940, "ANTLR": 1962}
|
package com.sipios.springsearch
enum class SearchOperation {
EQUALS, NOT_EQUALS, GREATER_THAN, LESS_THAN, STARTS_WITH, ENDS_WITH, CONTAINS, DOESNT_START_WITH, DOESNT_END_WITH, DOESNT_CONTAIN, GREATER_THAN_EQUALS, LESS_THAN_EQUALS;
companion object {
val SIMPLE_OPERATION_SET = arrayOf(":", "!", ">", "<", "~", ">:", "<:")
val ZERO_OR_MORE_REGEX = "*"
val OR_OPERATOR = "OR"
val AND_OPERATOR = "AND"
val LEFT_PARANTHESIS = "("
val RIGHT_PARANTHESIS = ")"
/**
* Parse a string into an operation.
*
* @param input operation as string
* @return The matching operation
*/
fun getSimpleOperation(input: String): SearchOperation? {
return when (input) {
":" -> EQUALS
"!" -> NOT_EQUALS
">" -> GREATER_THAN
"<" -> LESS_THAN
">:" -> GREATER_THAN_EQUALS
"<:" -> LESS_THAN_EQUALS
else -> null
}
}
}
}
| 15
|
Kotlin
|
44
| 188
|
ccde29a13751e9cc39f8220e7c534f30442aa68e
| 1,058
|
spring-search
|
MIT License
|
src/main/kotlin/cn/taskeren/hazelnut/feature/bili/model/BiliLiveRoom.kt
|
Taskeren
| 478,102,629
| false
|
{"Kotlin": 17939}
|
package cn.taskeren.hazelnut.feature.bili.model
import com.google.gson.annotations.SerializedName
data class BiliLiveRoom(
val roomStatus: Int,
val roundStatus: Int,
val liveStatus: Int,
val url: String,
val title: String,
val cover: String,
val online: Int,
val roomId: Int,
@SerializedName("broadcast_type")
val broadcastType: Int,
@SerializedName("online_hidden")
val onlineHidden: Int,
val link: String
) {
/**
* 是否存在房间
*/
fun isValidRoom() = roomStatus == 1
/**
* 是否正在轮播
*/
fun isRoundPlaying() = roundStatus == 1
/**
* 是否正在直播
*/
fun isLiving() = liveStatus == 1
}
| 0
|
Kotlin
|
0
| 1
|
b5e3c697fcecdd6108917625b22a45c67fbfa2d5
| 607
|
Hazelnut
|
MIT License
|
app/src/main/java/com/ethosa/ktc/ui/widgets/TeacherTimetableWidget.kt
|
Ethosa
| 453,099,570
| false
| null |
package com.ethosa.ktc.ui.widgets
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProvider
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import android.widget.RemoteViews
import com.ethosa.ktc.Preferences
import com.ethosa.ktc.R
import com.ethosa.ktc.college.CollegeApi
import com.ethosa.ktc.college.CollegeCallback
import com.ethosa.ktc.college.teacher.TeacherDay
import com.ethosa.ktc.college.teacher.TeacherTimetable
import com.ethosa.ktc.ui.activities.MainActivity
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import okhttp3.Call
import okhttp3.Response
import java.lang.Exception
import java.util.*
/**
* Implementation of App Widget functionality.
*/
class TeacherTimetableWidget : AppWidgetProvider() {
private var preferences: Preferences? = null
override fun onUpdate(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetIds: IntArray
) {
preferences = Preferences(context)
// There may be multiple widgets active, so update all of them
for (appWidgetId in appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId)
}
}
/**
* Update timetable for current widget
*/
@SuppressLint("UnspecifiedImmutableFlag")
private fun updateWidgetPendingIntent(
context: Context?,
appWidgetId: Int
): PendingIntent {
val intent = Intent(context!!, TeacherTimetableWidget::class.java)
val ids = AppWidgetManager.getInstance(context)
.getAppWidgetIds(ComponentName(context, TeacherTimetableWidget::class.java))
intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
return PendingIntent.getBroadcast(
context,
appWidgetId,
intent,
when {
Build.VERSION.SDK_INT >= 31 -> PendingIntent.FLAG_MUTABLE
else -> PendingIntent.FLAG_UPDATE_CURRENT
})
}
/**
* Open app with pending intent
*/
@SuppressLint("UnspecifiedImmutableFlag")
private fun openAppPendingIntent(
context: Context?,
appWidgetId: Int
): PendingIntent {
val intent = Intent(context!!, MainActivity::class.java)
return PendingIntent.getActivity(
context,
appWidgetId,
intent,
when {
Build.VERSION.SDK_INT >= 31 -> PendingIntent.FLAG_MUTABLE
else -> PendingIntent.FLAG_UPDATE_CURRENT
})
}
@SuppressLint("RemoteViewLayout", "SimpleDateFormat")
private fun updateAppWidget(
context: Context,
appWidgetManager: AppWidgetManager,
appWidgetId: Int
) {
// Construct the RemoteViews object
val views = RemoteViews(context.packageName, R.layout.widget_timetable)
views.setOnClickPendingIntent(
R.id.timetable_widget_reload,
updateWidgetPendingIntent(context, appWidgetId)
)
views.setOnClickPendingIntent(
R.id.timetable_widget_background,
openAppPendingIntent(context, appWidgetId)
)
// Load last group ID
val teacherId = Preferences.teacherId
val branchId = Preferences.branch.id
val calendar = Calendar.getInstance()
val weekday = calendar.get(Calendar.DAY_OF_WEEK)
CollegeApi.fetchTeacherTimetable(branchId, teacherId, object : CollegeCallback {
@SuppressLint("SetTextI18n")
override fun onResponse(call: Call, response: Response) {
// Parse JSON
val json = response.body?.string()
val timetable: TeacherTimetable
try {
timetable = Gson().fromJson(json, TeacherTimetable::class.java)
} catch (e: JsonSyntaxException) {
views.setTextViewText(
R.id.timetable_widget_title, "Ошибка расписания"
)
appWidgetManager.updateAppWidget(appWidgetId, views)
return
} catch (e: Exception) {
views.setTextViewText(
R.id.timetable_widget_title, "Неизвестная ошибка"
)
appWidgetManager.updateAppWidget(appWidgetId, views)
return
}
// Get current day timetable
val day: TeacherDay? = when (weekday) {
1 -> null
2 -> timetable.week[0]
else -> timetable.week[weekday-2]
}
if (day == null) {
views.setTextViewText(R.id.timetable_widget_title, "Выходной")
appWidgetManager.updateAppWidget(appWidgetId, views)
return
}
// Setup widget
views.setTextViewText(
R.id.timetable_widget_title, "${timetable.teacher} - ${day.title}"
)
views.removeAllViews(R.id.timetable_widget_lessons)
// Setup views
var lesson: RemoteViews
for (l in day.lessons) {
// Load lesson data
if (l.group == "") continue
lesson = RemoteViews(context.packageName, R.layout.widget_tlesson)
with (lesson) {
setTextViewText(R.id.widget_tlesson_title, l.title)
setTextViewText(R.id.widget_tlesson_classroom, l.classroom)
setTextViewText(R.id.widget_tlesson_group, l.group)
setTextViewText(R.id.widget_tlesson_number, l.number)
}
views.addView(R.id.timetable_widget_lessons, lesson)
}
// Update widget
appWidgetManager.updateAppWidget(appWidgetId, views)
}
})
appWidgetManager.updateAppWidget(appWidgetId, views)
}
}
| 2
|
Kotlin
|
1
| 11
|
751503a27a4ca7761fc3cc37879c0dfccc021e5a
| 6,300
|
KTC
|
MIT License
|
src/main/kotlin/com/williambl/prometheus/common/block/base/BaseTileEntityProviderBlock.kt
|
williambl
| 171,054,820
| false
| null |
package com.williambl.prometheus.common.block.base
import net.minecraft.block.ITileEntityProvider
import net.minecraft.block.SoundType
import net.minecraft.block.material.Material
import net.minecraft.block.state.IBlockState
import net.minecraft.creativetab.CreativeTabs
import net.minecraft.tileentity.TileEntity
import net.minecraft.util.math.BlockPos
import net.minecraft.world.World
open class BaseTileEntityProviderBlock<T : TileEntity>(registryName: String, tab: CreativeTabs, soundType: SoundType, hardness: Float, resistance: Float,
lightLevel: Float, material: Material, val factory: () -> T) : BaseBlock(registryName, tab, soundType, hardness,
resistance, lightLevel, material), ITileEntityProvider {
override fun createNewTileEntity(worldIn: World, meta: Int): TileEntity {
return factory()
}
override fun breakBlock(worldIn: World, pos: BlockPos, state: IBlockState) {
super.breakBlock(worldIn, pos, state)
worldIn.removeTileEntity(pos)
}
}
| 0
|
Kotlin
|
0
| 0
|
32a302a037888658e79709fa57e6a1a5d4842edd
| 1,059
|
prometheus
|
MIT License
|
src/main/kotlin/org/example/domain/port/PersonRepositoryPort.kt
|
jackelinenascimento
| 840,871,765
| false
|
{"Kotlin": 7394, "Dockerfile": 281}
|
package org.example.domain.port
import org.example.domain.model.Person
import java.util.UUID
interface PersonRepositoryPort {
fun save(person: Person): Person
fun findById(id: UUID): Person?
fun findAll(): List<Person>
fun deleteById(id: UUID)
}
| 0
|
Kotlin
|
0
| 0
|
9f571fcabd485b4c2ce1fa60286debace595a707
| 264
|
experimentacoes-kotlin
|
MIT License
|
library-ui/src/main/java/com/pp/library_ui/utils/AppTheme.kt
|
PPQingZhao
| 548,315,946
| false
|
{"Kotlin": 553508, "Java": 1135}
|
package com.pp.library_ui.utils
//noinspection SuspiciousImport,SuspiciousImport
import android.R
import android.annotation.SuppressLint
import android.content.res.Resources
import android.graphics.Color
import androidx.lifecycle.MutableLiveData
class AppTheme : Theme {
val windowBackground = MutableLiveData<Int>()
val colorPrimary = MutableLiveData<Int>()
val colorAccent = MutableLiveData<Int>()
val textColor = MutableLiveData<Int>()
val textColorSecondary = MutableLiveData<Int>()
val textColorHint = MutableLiveData<Int>()
val editTextColor = MutableLiveData<Int>()
val themeTint = MutableLiveData<Int>()
val indicatorNormalColor = MutableLiveData<Int>()
val indicatorSelectedColor = MutableLiveData<Int>()
val dividerColor = MutableLiveData<Int>()
val progressTint = MutableLiveData<Int>()
val secondaryProgressTint = MutableLiveData<Int>()
@SuppressLint("ResourceType", "Recycle")
override fun setTheme(theme: Resources.Theme) {
val attrMap = mapOf(
themeTint to com.pp.library_ui.R.attr.themeTint,
windowBackground to R.attr.windowBackground,
colorPrimary to R.attr.colorPrimary,
colorAccent to R.attr.colorAccent,
textColor to R.attr.textColor,
textColorSecondary to R.attr.textColorSecondary,
textColorHint to R.attr.textColorHint,
editTextColor to R.attr.editTextColor,
indicatorNormalColor to com.pp.library_ui.R.attr.indicatorNormalColor,
indicatorSelectedColor to com.pp.library_ui.R.attr.indicatorSelectedColor,
dividerColor to com.pp.library_ui.R.attr.dividerColor,
progressTint to R.attr.progressTint,
secondaryProgressTint to R.attr.secondaryProgressTint,
)
val attrArr = attrMap.values.toIntArray()
val typedArray = theme.obtainStyledAttributes(attrArr)
attrMap.keys.forEachIndexed { index, mutableLiveData ->
try {
mutableLiveData.value = typedArray.getColor(index, Color.TRANSPARENT)
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
| 0
|
Kotlin
|
0
| 5
|
904d9a980811d502f88479cb450c3a6e8d027f09
| 2,202
|
Eyepetizer
|
Apache License 2.0
|
src/main/kotlin/io/xmake/actions/CleanConfigurationAction.kt
|
xmake-io
| 108,999,121
| false
|
{"Kotlin": 182810, "HTML": 4522}
|
package io.xmake.actions
import com.intellij.execution.ui.ConsoleViewContentType
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import io.xmake.project.xmakeConsoleView
import io.xmake.shared.xmakeConfiguration
import io.xmake.utils.SystemUtils
import io.xmake.utils.exception.XMakeRunConfigurationNotSetException
class CleanConfigurationAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
// the project
val project = e.project ?: return
// clear console first
project.xmakeConsoleView.clear()
try {
// clear configure
val xmakeConfiguration = project.xmakeConfiguration
SystemUtils.runvInConsole(project, xmakeConfiguration.cleanConfigurationCommandLine, true, false, true)
xmakeConfiguration.changed = false
} catch (e: XMakeRunConfigurationNotSetException) {
project.xmakeConsoleView.print(
"Please select a xmake run configuration first!\n",
ConsoleViewContentType.ERROR_OUTPUT
)
NotificationGroupManager.getInstance()
.getNotificationGroup("XMake")
.createNotification("Error with XMake Configuration", e.message ?: "", NotificationType.ERROR)
.notify(project)
}
}
}
| 12
|
Kotlin
|
18
| 76
|
30f7c92deebe71e8cba97187cbf04f8460f2d31a
| 1,493
|
xmake-idea
|
Apache License 2.0
|
src/main/kotlin/com/ecwid/apiclient/v3/dto/producttype/result/ProductTypesGetAllResult.kt
|
Ecwid
| 160,232,759
| false
| null |
package com.ecwid.apiclient.v3.dto.producttype.result
class ProductTypesGetAllResult : ArrayList<FetchedProductType>()
| 6
|
Kotlin
|
8
| 9
|
d1a470002ba7bee6f2edc25d0038aeb085c91352
| 120
|
ecwid-java-api-client
|
Apache License 2.0
|
glimpse/geom/src/commonMain/kotlin/freeform/Surface3BuilderImpl.kt
|
glimpse-graphics
| 319,730,354
| false
| null |
/*
* Copyright 2020-2023 Glimpse Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package graphics.glimpse.geom.freeform
import graphics.glimpse.logging.GlimpseLogger
import graphics.glimpse.types.Vec2
import kotlin.reflect.KClass
internal class Surface3BuilderImpl<T>(
private val type: KClass<T>
) : Surface3.Builder<T> where T : Number, T : Comparable<T> {
private val logger: GlimpseLogger = GlimpseLogger.create(this)
private var freeformType: FreeformType? = null
private var degree: Vec2<Int> = Vec2.nullVector()
private var controlVertices: List<ControlVertex3<T>> = emptyList()
private var knotsU: List<T> = emptyList()
private var knotsV: List<T> = emptyList()
override fun ofType(freeformType: FreeformType): Surface3.Builder<T> {
this.freeformType = freeformType
return this
}
override fun withDegree(degree: Vec2<Int>): Surface3.Builder<T> {
this.degree = degree
return this
}
override fun withControlVertices(controlVertices: List<ControlVertex3<T>>): Surface3.Builder<T> {
this.controlVertices = controlVertices
return this
}
override fun withControlVertices(vararg controlVertices: ControlVertex3<T>): Surface3.Builder<T> {
this.controlVertices = controlVertices.toList()
return this
}
override fun withKnotsU(knotsU: List<T>): Surface3.Builder<T> {
this.knotsU = knotsU
return this
}
override fun withKnotsU(vararg knotsU: T): Surface3.Builder<T> {
this.knotsU = knotsU.toList()
return this
}
override fun withKnotsV(knotsV: List<T>): Surface3.Builder<T> {
this.knotsV = knotsV
return this
}
override fun withKnotsV(vararg knotsV: T): Surface3.Builder<T> {
this.knotsV = knotsV.toList()
return this
}
override fun build(): Surface3<T> {
if (freeformType != FreeformType.B_SPLINE && (knotsU + knotsV).isNotEmpty()) {
logger.warn("Bezier surfaces do not require knots vectors")
}
requireNotNull(degree.u > 0) { "Surface degree must be greater than 0" }
requireNotNull(degree.v > 0) { "Surface degree must be greater than 0" }
return Surface3Impl(
freeformType = requireNotNull(this.freeformType) { "Surface type must be specified" },
degree = this.degree,
controlVertices = this.controlVertices,
knotsU = this.knotsU,
knotsV = this.knotsV,
type = this.type
)
}
}
| 5
|
Kotlin
|
0
| 6
|
e00a9f22db9e10493e7711d5dd8524eb7b06be77
| 3,089
|
glimpse
|
Apache License 2.0
|
androidApp/src/main/java/io/github/lazyengineer/castaway/androidApp/player/PlayerStateUseCase.kt
|
lazy-engineer
| 321,396,462
| false
|
{"Kotlin": 285918, "Swift": 86110, "Ruby": 1720}
|
package io.github.lazyengineer.castaway.androidApp.player
import io.github.lazyengineer.castawayplayer.MediaServiceClient
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
class PlayerStateUseCase(
private val castawayPlayer: MediaServiceClient
) {
operator fun invoke(): Flow<PlayerState> = castawayPlayer.playerState().map { mediaServiceState ->
PlayerState(
connected = mediaServiceState.connected,
prepared = mediaServiceState.playbackState.isPrepared &&
(mediaServiceState.nowPlaying.duration != null && mediaServiceState.nowPlaying.duration != -1L),
mediaData = if (mediaServiceState.nowPlaying.mediaId.isNotEmpty()) {
mediaServiceState.nowPlaying.copy(playbackPosition = mediaServiceState.playbackState.currentPlaybackPosition)
} else {
null
},
playing = mediaServiceState.playbackState.isPlaying,
playbackSpeed = mediaServiceState.playbackSpeed
)
}
}
| 0
|
Kotlin
|
0
| 2
|
556234559b4f94cdcd5b6c2e5046c9a07ce47e4f
| 921
|
castaway
|
MIT License
|
app/src/main/java/com/unilim/iut/truckers/controleur/MessageControleur.kt
|
paul-rezzonico
| 690,680,634
| false
|
{"Kotlin": 72032}
|
package com.unilim.iut.truckers.controleur
import android.content.Context
import android.util.Log
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.kotlin.KotlinModule
import com.google.gson.Gson
import com.unilim.iut.truckers.api.ApiManager
import com.unilim.iut.truckers.commande.AjoutNumeroAdminCommande
import com.unilim.iut.truckers.commande.AjoutMotCleCommande
import com.unilim.iut.truckers.commande.AjoutNumeroListeBlancheCommande
import com.unilim.iut.truckers.commande.ChangerIntervalleSynchronisationCommande
import com.unilim.iut.truckers.commande.SupprimerNumeroAdminCommande
import com.unilim.iut.truckers.commande.SupprimerMotCleCommande
import com.unilim.iut.truckers.commande.SupprimerNumeroListeBlancheCommande
import com.unilim.iut.truckers.modele.Message
import com.unilim.iut.truckers.modele.NumeroTelephone
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
class MessageControleur {
private val controleurJson = JsonControleur()
private val controleurCommande = CommandeControleur()
private val jackson = ObjectMapper().registerModule(KotlinModule())
fun creationNomFichierJSON(prefixe: String): String {
val dateDuJour = SimpleDateFormat("dd-M-yyyy", Locale.FRANCE).format(Date())
return prefixe + "_" + "$dateDuJour.json"
}
/**
* Cette fonction permet de créer un fichier JSON contenant une liste d'objet Message.
*
* @param contexte Ce paramètre est le contexte de l'application.
* @return Cette fonction ne retourne rien.
*/
fun creationJsonBonMessage(contexte: Context?) {
controleurJson.creationFichierJSON(contexte, creationNomFichierJSON("MessageValide"), "messages")
}
/**
* Cette fonction permet d'ajouter un message dans le fichier JSON contenant une liste d'objet Message qui sont ceux recherchés.
*
* @param contexte Ce paramètre est le contexte de l'application.
* @param message Ce paramètre est l'objet Message à ajouter dans le fichier JSON.
* @return Cette fonction ne retourne rien.
*/
fun ajoutMessageDansJsonBonMessage(contexte: Context?, message: Message) {
controleurJson.sauvegarderDonneesDansJSON(contexte, creationNomFichierJSON("MessageValide"), "messages", message)
}
fun avoirMessagesDansBonJsonMessage(contexte: Context?): MutableList<Message> {
val objetJson = controleurJson.chargerDonneesDuJSON(contexte, creationNomFichierJSON("MessageValide"))
val liste = mutableListOf<Message>()
if (objetJson.toString() == "{}") {
return liste
}
val tableauJson = objetJson.getJSONArray("messages")
for (i in 0 until tableauJson.length()) {
val message = tableauJson.getString(i)
liste.add(jackson.readValue(message, Message::class.java))
}
return liste
}
/**
* Cette fonction permet de créer un fichier JSON contenant une liste d'objet Message qui ne sont pas ceux recherchés.
*
* @param contexte Ce paramètre est le contexte de l'application.
* @return Cette fonction ne retourne rien.
*/
fun creationJsonMauvaisMessage(contexte: Context?) {
controleurJson.creationFichierJSON(contexte, creationNomFichierJSON("MessageInvalide"), "messages")
}
/**
* Cette fonction permet d'ajouter un message dans le fichier JSON contenant une liste d'objet Message qui ne sont pas ceux recherchés.
*
* @param contexte Ce paramètre est le contexte de l'application.
* @param message Ce paramètre est l'objet Message à ajouter dans le fichier JSON.
* @return Cette fonction ne retourne rien.
*/
fun ajoutMessageDansMauvaisJsonMessage(contexte: Context?, message: Message) {
controleurJson.sauvegarderDonneesDansJSON(contexte, creationNomFichierJSON("MessageInvalide"), "messages", message)
}
/**
* Cette fonction permet de charger une liste d'objet Message qui sont ceux recherchés.
*
* @param contexte Ce paramètre est le contexte de l'application.
* @return Cette fonction retourne une liste d'objet Message.
*/
fun avoirMessagesDansMauvaisJsonMessage(contexte: Context?): MutableList<Message> {
val objetJson = controleurJson.chargerDonneesDuJSON(contexte, creationNomFichierJSON("MessageInvalide"))
val liste = mutableListOf<Message>()
if (objetJson.toString() == "{}") {
return liste
}
val tableauJson = objetJson.getJSONArray("messages")
for (i in 0 until tableauJson.length()) {
val message = tableauJson.getString(i)
liste.add(jackson.readValue(message, Message::class.java))
}
return liste
}
/**
* Cette fonction permet de mettre en place une commande en fonction du message de l'admin
*
* @param contexte Ce paramètre est le contexte de l'application.
* @return Cette fonction retourne une liste d'objet Message.
*/
fun actionMessage(contexte: Context?, nouveauMessage: Message) {
val motCleAjout = "Ajout"
val motCleSuppression = "Suppression"
val motCleChangement = "Changement"
val lignes = nouveauMessage.message.lines().drop(1)
for (ligne in lignes) {
val action = ligne.split(" ")[0]
val cle = ligne.split(" ")[1]
val value = ligne.split(" ")[2]
when (action) {
motCleAjout -> {
when (cle) {
"mot-clé" -> controleurCommande.executerCommande(AjoutMotCleCommande(contexte, value))
"numéro" -> controleurCommande.executerCommande(AjoutNumeroListeBlancheCommande(contexte, NumeroTelephone(value)))
"administrateur" -> controleurCommande.executerCommande(AjoutNumeroAdminCommande(contexte, NumeroTelephone(value)))
}
}
motCleSuppression -> {
when (cle) {
"mot-clé" -> controleurCommande.executerCommande(SupprimerMotCleCommande(contexte, value))
"numéro" -> controleurCommande.executerCommande(SupprimerNumeroListeBlancheCommande(contexte, NumeroTelephone(value)))
"administrateur" -> controleurCommande.executerCommande(SupprimerNumeroAdminCommande(contexte, NumeroTelephone(value)))
}
}
motCleChangement -> controleurCommande.executerCommande(ChangerIntervalleSynchronisationCommande(contexte, value))
else -> {
Log.d("TruckerService", "Action non reconnue")
}
}
}
}
/**
* Cette fonction permet de supprimer un objet Message dans un fichier JSON en fonction du chemin du fichier, du nom de l'objet JSON et de l'objet Message.
*
* @param messages Ce paramètre est la liste d'objet Message à supprimer dans le fichier JSON.
*/
fun supprimerMessagesApresApi(contexte: Context, androidId: String, messages: List<Message>) {
val messagesApiValides = ApiManager(contexte).recevoirMessages("messages/${androidId}")
val messagesApiInvalides = ApiManager(contexte).recevoirMessages("messages_err/${androidId}")
val jsonMessagesApiValides = Gson().toJson(messagesApiValides)
val jsonMessagesApiInvalides = Gson().toJson(messagesApiInvalides)
for (message in messages) {
if (jsonMessagesApiValides.contains(message.id)) {
controleurJson.supprimerDonneesDansJSON(contexte, creationNomFichierJSON("MessageValide"), "messages", message)
Log.d("TruckerService", "Suppression d'un message dans le JSON Valide: $message")
} else if (jsonMessagesApiInvalides.contains(message.id)) {
controleurJson.supprimerDonneesDansJSON(contexte, creationNomFichierJSON("MessageInvalide"), "messages", message)
Log.d("TruckerService", "Suppression d'un message dans le JSON Invalide: $message")
}
}
}
}
| 0
|
Kotlin
|
1
| 0
|
328800e8b05328616ca13012cd5ddf30f1f045f2
| 8,154
|
truckers
|
The Unlicense
|
feature/main-screen/feature-main-screen-impl/src/main/kotlin/ru/ivk1800/tg/feature/mainscreen/impl/FeatureMainScreenImpl.kt
|
ivk1800
| 429,483,837
| false
|
{"Kotlin": 57209}
|
package ru.ivk1800.tg.feature.mainscreen.impl
import ru.ivk1800.tg.feature.mainscreen.api.FeatureMainScreenApi
import ru.ivk1800.tg.feature.mainscreen.api.MainScreenFactory
class FeatureMainScreenImpl(
private val dependencies: FeatureMainScreenDependencies,
) : FeatureMainScreenApi {
override val mainScreenFactory: MainScreenFactory by lazy { MainScreenFactoryImpl(dependencies) }
}
class FeatureMainScreenDependencies
| 0
|
Kotlin
|
0
| 0
|
9c8bce51d7860541959ddbd5118ca0a70c310151
| 433
|
telegram-compose
|
Apache License 2.0
|
basic/src/main/kotlin/io/github/nishikigii/criterionkt/basic/format/builtin/Move.kt
|
Nishikigii
| 745,864,963
| false
|
{"Kotlin": 28153}
|
package io.github.nishikigii.criterionkt.basic.format.builtin
import io.github.nishikigii.criterionkt.basic.Index
import io.github.nishikigii.criterionkt.basic.Index.First
import io.github.nishikigii.criterionkt.basic.Index.Last
import io.github.nishikigii.criterionkt.basic.Index.Order
import io.github.nishikigii.criterionkt.basic.format.ExportScope
import java.lang.IllegalArgumentException
import java.util.ArrayList
import kotlin.collections.Map.Entry
/**
* move contents inside object to a specific location.
*
* @param moved all child strings match the regex will be moved
* @param order defined that the moved should before or after target location
* @param to target location as regex
* @param multipleTargets defined which should be selected when multiple targets satisfy the Regex
*/
fun ExportScope.move( moved: Regex, order: Order, to: Regex, multipleTargets: Index = First )
{
TODO()
}
/**
* move contents inside object to a specific location.
*
* @param moved all child strings same to it will be moved
* @param order defined that the moved should before or after target location
* @param to target location as child string
* @param multipleTargets defined which should be selected when multiple targets satisfy the Regex
* @see move
*/
fun ExportScope.move( moved: String, order: String, to: Regex, multipleTargets: Index = First )
{
TODO()
}
/**
* move contents inside object to a specific index.
*
* @param moved all child strings match the regex will be moved
* @param to target location
* @see move
*/
fun ExportScope.move( moved: Regex, to: Index )
{
TODO()
}
/**
* move contents inside object to a specific index.
*
* @param moved all child strings same to it will be moved
* @param to target location
* @see move
*/
fun ExportScope.move( moved: String, to: Index )
{
val origin = getEditable()
val matchingChars = origin.filter { it in moved }
val nonMatchingChars = origin.filter { it !in moved }
val result = when( to ) {
Last-> nonMatchingChars.toCharArray() + matchingChars.toCharArray()
First-> matchingChars.toCharArray() + nonMatchingChars
else-> throw IllegalArgumentException("target location are First and Last allowed only")
}
result.copyInto(origin)
}
| 0
|
Kotlin
|
0
| 0
|
70739e722cd1fe7da3c0909b5926c5049249c8f4
| 2,280
|
CriterionKt
|
MIT License
|
src/ru/mobiledimension/study/day5/WhereIAm.kt
|
z-gys
| 187,865,942
| false
| null |
package ru.mobiledimension.study.day5
fun main() {
target()
}
fun whereIAm(): String {
try {
throw Exception()
} catch (e: Exception) {
return e.stackTrace[1].methodName +":"+ e.stackTrace[1].lineNumber
}
}
fun target() {
println(whereIAm())
}
| 0
|
Kotlin
|
0
| 0
|
1b201f2a680d64f46ef19010fe0fc64dd4b9230f
| 282
|
kotlin-basics
|
MIT License
|
plugin/src/test/kotlin/com/jraska/module/graph/GraphvizWriterTest.kt
|
jraska
| 227,907,412
| false
|
{"Kotlin": 65591}
|
package com.jraska.module.graph
import org.junit.Test
class GraphvizWriterTest {
@Test
fun testPrintsProperly() {
val graphvizText = GraphvizWriter.toGraphviz(testGraph())
assert(graphvizText == EXPECTED_OUTPUT)
}
@Test
fun testPrintsProperlyWithAliases() {
val aliases = mapOf(
"app" to "App",
"lib" to "Api",
"feature-about" to "Implementation"
)
val graphvizText = GraphvizWriter.toGraphviz(testGraph(), aliases)
assert(graphvizText == EXPECTED_OUTPUT_WITH_ALISASES)
}
private fun testGraph(): DependencyGraph {
return DependencyGraph.create(
"app" to "feature",
"app" to "feature-about",
"feature-about" to "lib",
"feature-about" to "core",
"app" to "lib",
"feature" to "lib",
"lib" to "core"
)
}
}
private const val EXPECTED_OUTPUT = """digraph G {
"app" -> "feature" [color=red style=bold]
"app" -> "feature-about"
"app" -> "lib"
"feature" -> "lib" [color=red style=bold]
"feature-about" -> "lib"
"feature-about" -> "core"
"lib" -> "core" [color=red style=bold]
}"""
private const val EXPECTED_OUTPUT_WITH_ALISASES = """digraph G {
"app('App')" -> "feature" [color=red style=bold]
"app('App')" -> "feature-about('Implementation')"
"app('App')" -> "lib('Api')"
"feature" -> "lib('Api')" [color=red style=bold]
"feature-about('Implementation')" -> "lib('Api')"
"feature-about('Implementation')" -> "core"
"lib('Api')" -> "core" [color=red style=bold]
}"""
| 3
|
Kotlin
|
22
| 522
|
03a3d40cae4c8625f3f80f0286214f3dd4fd4a78
| 1,478
|
modules-graph-assert
|
Apache License 2.0
|
remix/src/commonMain/kotlin/com/woowla/compose/icon/collections/remix/remix/communication/ChatPollFill.kt
|
walter-juan
| 868,046,028
| false
|
{"Kotlin": 34345428}
|
package com.woowla.compose.icon.collections.remix.remix.communication
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.remix.remix.CommunicationGroup
public val CommunicationGroup.ChatPollFill: ImageVector
get() {
if (_chatPollFill != null) {
return _chatPollFill!!
}
_chatPollFill = Builder(name = "ChatPollFill", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.0f, 3.0f)
curveTo(21.552f, 3.0f, 22.0f, 3.448f, 22.0f, 4.0f)
verticalLineTo(18.0f)
curveTo(22.0f, 18.552f, 21.552f, 19.0f, 21.0f, 19.0f)
horizontalLineTo(6.455f)
lineTo(2.0f, 22.5f)
verticalLineTo(4.0f)
curveTo(2.0f, 3.448f, 2.448f, 3.0f, 3.0f, 3.0f)
horizontalLineTo(21.0f)
close()
moveTo(13.0f, 7.0f)
horizontalLineTo(11.0f)
verticalLineTo(15.0f)
horizontalLineTo(13.0f)
verticalLineTo(7.0f)
close()
moveTo(17.0f, 9.0f)
horizontalLineTo(15.0f)
verticalLineTo(15.0f)
horizontalLineTo(17.0f)
verticalLineTo(9.0f)
close()
moveTo(9.0f, 11.0f)
horizontalLineTo(7.0f)
verticalLineTo(15.0f)
horizontalLineTo(9.0f)
verticalLineTo(11.0f)
close()
}
}
.build()
return _chatPollFill!!
}
private var _chatPollFill: ImageVector? = null
| 0
|
Kotlin
|
0
| 3
|
eca6c73337093fbbfbb88546a88d4546482cfffc
| 2,405
|
compose-icon-collections
|
MIT License
|
sources/feature/landing/src/main/kotlin/com/egoriku/ladyhappy/landing/koin/LandingModule.kt
|
DoTheMonkeyBusiness
| 317,000,577
| true
|
{"Kotlin": 340209, "JavaScript": 2522, "Shell": 289}
|
package com.egoriku.ladyhappy.landing.koin
import com.egoriku.ladyhappy.landing.data.repository.LandingRepository
import com.egoriku.ladyhappy.landing.domain.usecase.LandingUseCase
import com.egoriku.ladyhappy.landing.presentation.LandingPageFragment
import com.egoriku.ladyhappy.landing.presentation.LandingViewModel
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.dsl.module
val landingModule = module {
scope<LandingPageFragment> {
scoped { LandingRepository(firebase = get()) }
scoped { LandingUseCase(landRepository = get()) }
viewModel {
LandingViewModel(
analytics = get(),
landingUseCase = get()
)
}
}
}
| 1
| null |
0
| 0
|
38c6b7ff347763cee016dc04b415951305d5768e
| 736
|
Lady-happy-Android
|
Apache License 2.0
|
src/main/kotlin/enums/Rainbow.kt
|
AnuragThePathak
| 398,529,760
| false
| null |
package enums
enum class Rainbow {
VIOLET, INDIGO, BLUE, GREEN, YELLOW, ORANGE, RED;
companion object {
fun findColorByName(color: String): Boolean {
for (i in values()) {
if (i.name == color) return true
}
return false
}
}
}
fun main() {
val color = readLine()!!.uppercase()
println(Rainbow.findColorByName(color))
}
| 0
|
Kotlin
|
0
| 0
|
1c5db5703904488a9119fef90b92e0c06b585358
| 409
|
Learning-Kotlin
|
MIT License
|
defitrack-protocols/stargate/src/main/java/io/defitrack/protocol/StargateFantomService.kt
|
decentri-fi
| 426,174,152
| false
| null |
package io.defitrack.protocol
import org.springframework.stereotype.Component
@Component
class StargateFantomService : StargateService{
override fun getLpFarm(): String {
return "0x224D8Fd7aB6AD4c6eb4611Ce56EF35Dec2277F03"
}
}
| 16
|
Kotlin
|
6
| 5
|
e4640223e69c30f986b8b4238e026202b08a5548
| 245
|
defi-hub
|
MIT License
|
ImageLoader/src/main/java/cn/quibbler/imageloader/utils/StorageUtils.kt
|
quibbler01
| 524,270,844
| false
|
{"Kotlin": 252007}
|
package cn.quibbler.imageloader.utils
import android.content.Context
import android.content.pm.PackageManager
import android.os.Environment
import java.io.File
import java.io.IOException
private const val EXTERNAL_STORAGE_PERMISSION = "android.permission.WRITE_EXTERNAL_STORAGE"
private const val INDIVIDUAL_DIR_NAME = "uil-images"
/**
* Returns application cache directory. Cache directory will be created on SD card
* <i>("/Android/data/[app_package_name]/cache")</i> if card is mounted and app has appropriate permission. Else -
* Android defines cache directory on device's file system.
*
* @param context Application context
* @return Cache {@link File directory}.<br />
* <b>NOTE:</b> Can be null in some unpredictable cases (if SD card is unmounted and
* {@link android.content.Context#getCacheDir() Context.getCacheDir()} returns null).
*/
fun getCacheDirectory(context: Context): File? = getCacheDirectory(context, true)
/**
* Returns application cache directory. Cache directory will be created on SD card
* <i>("/Android/data/[app_package_name]/cache")</i> (if card is mounted and app has appropriate permission) or
* on device's file system depending incoming parameters.
*
* @param context Application context
* @param preferExternal Whether prefer external location for cache
* @return Cache {@link File directory}.<br />
* <b>NOTE:</b> Can be null in some unpredictable cases (if SD card is unmounted and
* {@link android.content.Context#getCacheDir() Context.getCacheDir()} returns null).
*/
fun getCacheDirectory(context: Context, preferExternal: Boolean): File? {
var appCacheDir: File? = null
var externalStorageState: String? = null
try {
externalStorageState = Environment.getExternalStorageState()
} catch (e: NullPointerException) { // (sh)it happens (Issue #660)
externalStorageState = ""
} catch (e: IncompatibleClassChangeError) { // (sh)it happens too (Issue #989)
externalStorageState = ""
}
if (preferExternal && Environment.MEDIA_MOUNTED.equals(externalStorageState) && hasExternalStoragePermission(context)) {
appCacheDir = getExternalCacheDir(context)
}
if (appCacheDir == null) {
appCacheDir = context.cacheDir
}
if (appCacheDir == null) {
val cacheDirPath = "/data/data/${context.packageName}/cache/"
L.w("Can't define system cache directory! '%s' will be used.", cacheDirPath)
appCacheDir = File(cacheDirPath)
}
return appCacheDir
}
/**
* Returns individual application cache directory (for only image caching from ImageLoader). Cache directory will be
* created on SD card <i>("/Android/data/[app_package_name]/cache/uil-images")</i> if card is mounted and app has
* appropriate permission. Else - Android defines cache directory on device's file system.
*
* @param context Application context
* @return Cache {@link File directory}
*/
fun getIndividualCacheDirectory(context: Context): File = getIndividualCacheDirectory(context, INDIVIDUAL_DIR_NAME)
/**
* Returns individual application cache directory (for only image caching from ImageLoader). Cache directory will be
* created on SD card <i>("/Android/data/[app_package_name]/cache/uil-images")</i> if card is mounted and app has
* appropriate permission. Else - Android defines cache directory on device's file system.
*
* @param context Application context
* @param cacheDir Cache directory path (e.g.: "AppCacheDir", "AppDir/cache/images")
* @return Cache {@link File directory}
*/
fun getIndividualCacheDirectory(context: Context, cacheDir: String): File {
var appCacheDir: File? = getCacheDirectory(context)
var individualCacheDir: File = File(appCacheDir, cacheDir)
if (!individualCacheDir.exists()) {
if (!individualCacheDir.mkdir()) {
appCacheDir?.let {
individualCacheDir = it
}
}
}
return individualCacheDir
}
/**
* Returns specified application cache directory. Cache directory will be created on SD card by defined path if card
* is mounted and app has appropriate permission. Else - Android defines cache directory on device's file system.
*
* @param context Application context
* @param cacheDir Cache directory path (e.g.: "AppCacheDir", "AppDir/cache/images")
* @return Cache {@link File directory}
*/
fun getOwnCacheDirectory(context: Context, cacheDir: String): File? {
var appCacheDir: File? = null
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()) && hasExternalStoragePermission(context)) {
appCacheDir = File(Environment.getExternalStorageDirectory(), cacheDir)
}
if (appCacheDir == null || (!appCacheDir.exists() && !appCacheDir.mkdirs())) {
appCacheDir = context.cacheDir
}
return appCacheDir
}
/**
* Returns specified application cache directory. Cache directory will be created on SD card by defined path if card
* is mounted and app has appropriate permission. Else - Android defines cache directory on device's file system.
*
* @param context Application context
* @param cacheDir Cache directory path (e.g.: "AppCacheDir", "AppDir/cache/images")
* @return Cache {@link File directory}
*/
fun getOwnCacheDirectory(context: Context,cacheDir: String,preferExternal:Boolean): File? {
var appCacheDir: File? = null
if (preferExternal && Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
appCacheDir = File(Environment.getExternalStorageDirectory(), cacheDir)
}
if (appCacheDir == null || (!appCacheDir.exists() && !appCacheDir.mkdirs())) {
appCacheDir = context.cacheDir
}
return appCacheDir
}
fun getExternalCacheDir(context: Context): File? {
val dataDir: File = File(File(Environment.getExternalStorageDirectory(), "Android"), "data")
val appCacheDir: File = File(File(dataDir, context.packageName), "cache")
if (!appCacheDir.exists()) {
if (!appCacheDir.mkdir()) {
L.w("Unable to create external cache directory")
return null
}
try {
File(appCacheDir, ".nomedia").createNewFile()
} catch (e: IOException) {
L.i("Can't create \".nomedia\" file in application external cache directory")
}
}
return appCacheDir
}
fun hasExternalStoragePermission(context: Context): Boolean {
return context.checkCallingOrSelfPermission(EXTERNAL_STORAGE_PERMISSION) == PackageManager.PERMISSION_GRANTED
}
| 0
|
Kotlin
|
0
| 0
|
d2fae5a52fe791f0338bd303f3f7cb128fa7e504
| 6,506
|
ImageLoader
|
Apache License 2.0
|
appactions/interaction/interaction-capabilities-core/src/test/java/androidx/appactions/interaction/capabilities/serializers/types/BuiltInTypeSerializerRegistryTest.kt
|
androidx
| 256,589,781
| false
|
{"Kotlin": 102962181, "Java": 64545272, "C++": 9133578, "AIDL": 614395, "Python": 310931, "Shell": 188067, "TypeScript": 40586, "HTML": 35176, "Groovy": 27482, "ANTLR": 26700, "Svelte": 20307, "CMake": 18011, "C": 16982, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019}
|
/*
* Copyright 2023 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 androidx.appactions.interaction.capabilities.serializers.types
import androidx.appactions.builtintypes.types.AbstractPerson
import androidx.appactions.builtintypes.types.Person
import androidx.appactions.builtintypes.types.Thing
import com.google.common.truth.Truth.assertThat
import org.junit.Test
class BuiltInTypeSerializerRegistryTest {
object AllTestSerializers {
@JvmStatic fun getPersonSerializer() = PersonSerializer()
fun someFunThatShouldBeIgnored() {}
@JvmStatic fun otherFunThatShouldBeIgnored(@Suppress("UNUSED_PARAMETER") int: Int) {}
}
object MoreTestSerializers {
@JvmStatic fun getThingSerializer() = ThingSerializer()
}
class MyPerson internal constructor(person: Person) :
AbstractPerson<MyPerson, MyPerson.Builder>(person) {
protected override val selfTypeName = "MyPerson"
protected override val additionalProperties: Map<String, Any?>
get() = emptyMap()
protected override fun toBuilderWithAdditionalPropertiesOnly() = Builder()
class Builder : AbstractPerson.Builder<Builder, MyPerson>() {
protected override val selfTypeName = "MyPerson.Builder"
override val additionalProperties: Map<String, Any?>
get() = emptyMap()
protected override fun buildFromPerson(person: Person) = MyPerson(person)
}
}
@Test
fun getSerializer() {
val registry =
BuiltInTypeSerializerRegistry(
serializerRegistryClassNames =
listOf(
AllTestSerializers::class.java.canonicalName!!,
MoreTestSerializers::class.java.canonicalName!!),
getClassOrNull = { canonicalName ->
when (canonicalName) {
AllTestSerializers::class.java.canonicalName ->
AllTestSerializers::class.java
MoreTestSerializers::class.java.canonicalName ->
MoreTestSerializers::class.java
else -> null
}
})
assertThat(registry.getSerializer(Person.Builder().build()))
.isInstanceOf(PersonSerializer::class.java)
assertThat(registry.getSerializer(Thing.Builder().build()))
.isInstanceOf(ThingSerializer::class.java)
// No serializer for this but should go up the parent chain and realize this is a Person
assertThat(registry.getSerializer(MyPerson.Builder().build()))
.isInstanceOf(PersonSerializer::class.java)
}
}
| 24
|
Kotlin
|
930
| 5,073
|
559b440b4b57a373b305bfc0fe0f284a9f68a1c1
| 3,265
|
androidx
|
Apache License 2.0
|
src/eu/iamgio/chorus/menus/variables/VariablesPlaceholder.kt
|
Banbeucmas
| 131,820,916
| true
|
{"Kotlin": 167582, "CSS": 55153, "Java": 35307}
|
package eu.iamgio.chorus.menus.variables
import javafx.geometry.Pos
import javafx.scene.control.Label
import javafx.scene.layout.FlowPane
import javafx.scene.layout.StackPane
/**
* @author Gio
*/
class VariablesPlaceholder : FlowPane() {
init {
opacity = .5
val label1 = Label("Press ")
label1.styleClass += "placeholder"
label1.style = "-fx-font-size: 18"
val add = StackPane()
add.style = "-fx-shape: \"M17,13H13V17H11V13H7V11H11V7H13V11H17M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2Z\""
add.styleClass += "placeholder-add-button"
add.prefWidth = 18.0
add.prefHeight = 18.0
add.maxWidth = 18.0
add.maxHeight = 18.0
add.alignment = Pos.CENTER
val label2 = Label(" to add a variable")
label2.styleClass += "placeholder"
label2.style = "-fx-font-size: 18"
alignment = Pos.CENTER
children.addAll(label1, add, label2)
}
}
| 0
|
Kotlin
|
0
| 0
|
a7652096e27593ced804f1e3a9d1a3c85c24a0fd
| 1,003
|
chorus
|
Apache License 2.0
|
protocol/src/main/kotlin/io/kaxis/dtls/message/handshake/EcdhPskServerKeyExchange.kt
|
barudisshu
| 806,368,620
| false
|
{"Kotlin": 1251282, "Java": 451145, "Shell": 28440, "Dockerfile": 956}
|
/*
* COPYRIGHT Cplier 2024
*
* The copyright to the computer program(s) herein is the property of
* Cplier Inc. The programs may be used and/or copied only with written
* permission from Cplier Inc. or in accordance with the terms and
* conditions stipulated in the agreement/contract under which the
* program(s) have been supplied.
*/
package io.kaxis.dtls.message.handshake
import io.kaxis.dtls.PskPublicInformation
import io.kaxis.dtls.cipher.XECDHECryptography
import io.kaxis.exception.HandshakeException
import io.kaxis.util.DatagramReader
import io.kaxis.util.DatagramWriter
import io.kaxis.util.Utility
class EcdhPskServerKeyExchange : ECDHServerKeyExchange {
companion object {
private const val IDENTITY_HINT_LENGTH_BITS = 16
/**
* Creates a new server key exchange instance from its byte representation.
* @param reader reader for the binary encoding of the message.
* @return [EcdhPskServerKeyExchange]
* @throws HandshakeException if the byte array includes unsupported curve
* @throws NullPointerException if either byte array or peer address is `null`
*/
@Throws(HandshakeException::class)
fun fromReader(reader: DatagramReader): EcdhPskServerKeyExchange {
val hintEncoded = reader.readVarBytes(IDENTITY_HINT_LENGTH_BITS)
val ecdhData = readNamedCurve(reader)
return EcdhPskServerKeyExchange(hintEncoded, ecdhData.supportedGroup, ecdhData.encodedPoint)
}
}
/**
* The hint in cleartext.
*/
val hint: PskPublicInformation
/**
* Creates a new key exchange message with psk hint as clear text and ServerDHParams.
* @param pskHint preshared key hint in clear text
* @param ecdhe XECDHECryptography including the supported group and the peer's public key
* @throws NullPointerException if the arguments pskHint or ecdhe are `null`
*/
constructor(pskHint: PskPublicInformation?, ecdhe: XECDHECryptography?) : super(
ecdhe?.supportedGroup,
ecdhe?.encodedPoint,
) {
requireNotNull(pskHint) { "PSK hint must not be null" }
this.hint = pskHint
}
@Throws(HandshakeException::class)
private constructor(
hintEncoded: ByteArray,
supportedGroup: XECDHECryptography.SupportedGroup,
encodedPoint: ByteArray,
) : super(supportedGroup, encodedPoint) {
this.hint = PskPublicInformation.fromByteArray(hintEncoded)
}
override fun fragmentToByteArray(): ByteArray {
val writer = DatagramWriter()
writer.writeVarBytes(hint, IDENTITY_HINT_LENGTH_BITS)
writeNamedCurve(writer)
return writer.toByteArray()
}
override val messageLength: Int
get() = 2 + hint.length() + namedCurveLength
override fun toString(indent: Int): String {
val sb = StringBuilder(super.toString(indent))
val indentation = Utility.indentation(indent + 1)
sb.append(indentation).append("PSK Identity Hint: ")
if (hint.isEmpty()) {
sb.append("not present!")
} else {
sb.append(hint)
}
sb.append(Utility.LINE_SEPARATOR)
return sb.toString()
}
}
| 0
|
Kotlin
|
0
| 0
|
f18e39e826792f145468f33d8751decc79769c07
| 3,040
|
kaxis
|
MIT License
|
kotlin-css/src/commonTest/kotlin/kotlinx/css/TestBoxShadow.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 12635434, "JavaScript": 423801}
|
package kotlinx.css
import kotlinx.css.properties.BoxShadow
import kotlinx.css.properties.BoxShadowInset
import kotlin.test.Test
import kotlin.test.assertEquals
private const val message = "Unexpected generated CSS block"
class TestBoxShadow {
private val testCases = listOf(
PropertyTestCase(
"""
box-shadow: 0 0 0 0 currentColor;
"""
) { boxShadow += BoxShadow() },
PropertyTestCase(
"""
box-shadow: 1px 2px 3px 4px red;
"""
) { boxShadow += BoxShadow(Color.red, 1.px, 2.px, 3.px, 4.px) },
PropertyTestCase(
"""
box-shadow: inset 1px 2px 3px 4px red;
"""
) { boxShadow += BoxShadowInset(Color.red, 1.px, 2.px, 3.px, 4.px) },
PropertyTestCase(
"""
box-shadow: 1px 2px 3px 4px red, 1px 2px 3px 4px blue;
"""
) {
boxShadow += BoxShadow(Color.red, 1.px, 2.px, 3.px, 4.px)
boxShadow += BoxShadow(Color.blue, 1.px, 2.px, 3.px, 4.px)
}
)
@Test
fun testProperties() {
testCases.forEach { (expected, propRuleSet) ->
val cssBuilderProp = CssBuilder()
ruleSet(propRuleSet).invoke(cssBuilderProp)
assertEquals(expected.trimIndent(), cssBuilderProp.toString(), message)
}
}
}
| 38
|
Kotlin
|
162
| 1,347
|
997ed3902482883db4a9657585426f6ca167d556
| 1,406
|
kotlin-wrappers
|
Apache License 2.0
|
app/src/main/java/com/taitascioredev/android/chucknorrisquotes/feature/categories/CategoryIntent.kt
|
phanghos
| 115,355,159
| false
| null |
package com.taitascioredev.android.chucknorrisquotes.feature.categories
import com.google.auto.value.AutoValue
import com.taitascioredev.android.chucknorrisquotes.mvibase.MviIntent
/**
* Created by rrtatasciore on 25/12/17.
*/
interface CategoryIntent : MviIntent {
@AutoValue
abstract class InitialIntent : CategoryIntent {
companion object {
fun create(): InitialIntent {
return AutoValue_CategoryIntent_InitialIntent()
}
}
}
@AutoValue
abstract class LoadIntent : CategoryIntent {
companion object {
fun create(): LoadIntent {
return AutoValue_CategoryIntent_LoadIntent()
}
}
}
}
| 0
|
Kotlin
|
0
| 2
|
c1914d52a37a9bc4d5ae41d168fedd0439690f40
| 724
|
mvi-kotlin-rxjava-livedata-dagger-example
|
MIT License
|
app/src/main/java/com/ademir/moview/ui/home/feed/FeedFragment.kt
|
luizhenriquefbb
| 130,928,148
| true
|
{"Kotlin": 81194, "Java": 39058}
|
package com.ademir.moview.home.fragments
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.ademir.moview.R
import com.ademir.moview.commons.prepare
import com.ademir.moview.home.adapters.FeedAdapter
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.fragment_feed.*
/**
* Created by ademir on 27/05/17.
*/
class FeedFragment : Fragment() {
private var type = -1
private val adapter by lazy { rv_feed.adapter as FeedAdapter }
private var disposable: Disposable? = null
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater!!.inflate(R.layout.fragment_feed, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
rv_feed.prepare(FeedAdapter(), LinearLayoutManager(context))
feed_refresh_layout.setOnRefreshListener { getFeed() }
getFeed()
}
override fun onStop() {
super.onStop()
disposable?.dispose()
}
private fun getFeed() {
// val observable = when (type) {
// DEFAULT -> MoviewApplication.apiService!!.getFeed(SessionController.user!!.token, "true")
// else -> MoviewApplication.apiService!!.getFeed(SessionController.user!!.token, "false")
// }
//
// disposable = observable.observeOn(AndroidSchedulers.mainThread())
// .doOnTerminate { feed_refresh_layout.isRefreshing = false }
// .subscribe({ adapter.setData(it) }, Throwable::printStackTrace)
}
companion object {
const val DEFAULT = 0
const val USER_TIMELINE = 1
fun newInstance(type: Int = FeedFragment.DEFAULT): FeedFragment {
val frag = FeedFragment()
frag.type = type
return frag
}
}
}
| 0
|
Kotlin
|
0
| 0
|
65c1a67556812c3d6a4d8077fd67c4aa34628466
| 2,065
|
Moview
|
MIT License
|
app/src/main/java/com/business/money_minder/presentation/setting_screen/components/LimitSetting.kt
|
myofficework000
| 645,450,368
| false
|
{"Kotlin": 349960}
|
package com.business.money_minder.presentation.setting_screen.components
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.ContentAlpha
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material.MaterialTheme
import androidx.compose.material.ModalBottomSheetState
import androidx.compose.material.Text
import androidx.compose.material.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.business.money_minder.presentation.home_screen.HomeViewModel
import com.business.money_minder.presentation.home_screen.amountFormat
import com.business.money_minder.presentation.setting_screen.SettingViewModel
import com.business.money_minder.util.spacing
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@ExperimentalMaterialApi
@Composable
fun LimitSetting(
modalBottomSheetState: ModalBottomSheetState,
scope: CoroutineScope,
homeViewModel: HomeViewModel = hiltViewModel(),
settingViewModel: SettingViewModel = hiltViewModel(),
onItemClick: (Int) -> Unit
) {
val currencyCode by settingViewModel.currency.collectAsState()
val expenseLimit by settingViewModel.expenseLimit.collectAsState()
TextButton(
onClick = {
onItemClick(1)
scope.launch {
modalBottomSheetState.show()
}
},
modifier = Modifier
.fillMaxSize()
.padding(
horizontal = spacing.medium,
vertical = spacing.small
),
colors = ButtonDefaults.buttonColors(
backgroundColor = Color.DarkGray.copy(alpha = 0.1f),
contentColor = MaterialTheme.colors.onSurface
),
shape = RoundedCornerShape(12.dp),
contentPadding = PaddingValues(
horizontal = spacing.medium,
vertical = 20.dp
)
) {
Text(
text = "Expense Limit",
style = MaterialTheme.typography.button,
modifier = Modifier.weight(2f),
textAlign = TextAlign.Start
)
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) {
Text(
text = "$currencyCode " + expenseLimit.toString().amountFormat(),
style = MaterialTheme.typography.subtitle2,
color = MaterialTheme.colors.onSurface
)
}
}
}
| 1
|
Kotlin
|
2
| 11
|
acfb0f22f145c363d2775b76c86668f75e73dd0f
| 3,057
|
MoneyMinder
|
MIT License
|
app/src/main/java/ar/edu/unlam/mobile/scaffolding/ui/theme/Color.kt
|
unlam-tec-movil
| 787,108,910
| false
|
{"Kotlin": 17455}
|
package ar.edu.unlam.mobile.scaffolding.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
val rojoPokeball = Color(238,21,21)
val negroPokeball = Color(34,34,36)
val gris = Color(0xFF5A5F5F)
| 0
|
Kotlin
|
0
| 0
|
74ed496071d5d6e67182d5622b43f26ce8c8ad8a
| 398
|
A2-2024-H1-Equipo3
|
MIT License
|
src/main/kotlin/br/com/jiratorio/config/ErrorHandler.kt
|
alanjds
| 199,070,045
| true
|
{"Kotlin": 519339, "Dockerfile": 315, "TSQL": 269, "PLSQL": 52}
|
package br.com.jiratorio.config
import br.com.jiratorio.config.internationalization.MessageResolver
import br.com.jiratorio.exception.BadRequestException
import br.com.jiratorio.exception.UniquenessFieldException
import com.fasterxml.jackson.module.kotlin.MissingKotlinParameterException
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.validation.BindException
import org.springframework.validation.BindingResult
import org.springframework.validation.FieldError
import org.springframework.web.bind.MethodArgumentNotValidException
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
@ControllerAdvice
class ErrorHandler(
private val messageResolver: MessageResolver
) {
@ExceptionHandler(MissingKotlinParameterException::class)
fun handleMissingKotlinParameterException(e: MissingKotlinParameterException): ResponseEntity<Map<String, List<String>>> {
return ResponseEntity(
mapOf(e.parameter.name!! to listOf(messageResolver.resolve("javax.validation.constraints.NotNull.message"))),
HttpStatus.BAD_REQUEST
)
}
@ExceptionHandler(MethodArgumentNotValidException::class)
fun handleMethodArgumentNotValidException(e: MethodArgumentNotValidException): ResponseEntity<Map<String, List<String>>> {
val bindingResult = e.bindingResult
return buildBindResultResponseErrors(bindingResult)
}
@ExceptionHandler(BindException::class)
fun handleBindException(e: BindException): ResponseEntity<Map<String, List<String>>> {
val bindingResult = e.bindingResult
return buildBindResultResponseErrors(bindingResult)
}
private fun buildBindResultResponseErrors(bindingResult: BindingResult): ResponseEntity<Map<String, List<String>>> {
val errors = bindingResult.allErrors.groupBy {
it as FieldError
it.field
}.map {
it.key to it.value.mapNotNull { it.defaultMessage }
}.toMap()
return ResponseEntity(errors, HttpStatus.BAD_REQUEST)
}
@ExceptionHandler(UniquenessFieldException::class)
fun handleUniquenessException(e: UniquenessFieldException): ResponseEntity<Map<String, List<String>>> {
return ResponseEntity(
mapOf(e.field to listOf(messageResolver.resolve("validations.uniqueness"))),
HttpStatus.BAD_REQUEST
)
}
@ExceptionHandler(BadRequestException::class)
fun handleBadRequestException(e: BadRequestException): ResponseEntity<Map<String, List<String?>>> {
return ResponseEntity(
mapOf(e.field to listOf(e.message)),
HttpStatus.BAD_REQUEST
)
}
}
| 0
|
Kotlin
|
0
| 0
|
3a49a3b434ce94a4bc5aaca494e3ce5c84ab4bb4
| 2,778
|
jirareport
|
MIT License
|
src/CoroutineContext.kt
|
aibingbing
| 677,432,299
| false
| null |
import kotlinx.coroutines.*
import kotlin.coroutines.Continuation
import kotlin.coroutines.ContinuationInterceptor
import kotlin.coroutines.coroutineContext
fun log(msg: Job?) {
println("[${Thread.currentThread().name}] $msg")
}
suspend inline fun Job.Key.currentJob() = coroutineContext[Job]
suspend fun coroutineJob() {
GlobalScope.launch {
log(Job.currentJob())
}
log(Job.currentJob())
}
//suspend fun main() {
// coroutineJob()
//
// GlobalScope.launch(CoroutineName("Hello")) {
// log(1)
// }
//}
class MyContinuation<T>(private val continuation: Continuation<T>) : Continuation<T> {
override val context = continuation.context
override fun resumeWith(result: Result<T>) {
log("<MyContinuation $result")
continuation.resumeWith(result)
}
}
class MyContinuationInterceptor : ContinuationInterceptor {
override val key = ContinuationInterceptor
override fun <T> interceptContinuation(continuation: Continuation<T>) = MyContinuation(continuation)
}
suspend fun main() {
GlobalScope.launch(MyContinuationInterceptor()) {
log(1)
val job = async {
log(2)
delay(1000)
log(3)
"HelloWorld"
}
log(4)
val result = job.await()
log("5. $result")
}.join()
log(6)
}
| 0
|
Kotlin
|
0
| 0
|
bdef73a74c49ab8e789d0592bd61a1da90ed6a11
| 1,347
|
KotlinCoroutinesDemo
|
Apache License 2.0
|
src/main/kotlin/io/github/nillkki/aoc/Day03.kt
|
Nillkki
| 572,858,950
| false
|
{"Kotlin": 38345}
|
package io.github.nillkki.aoc
import org.openjdk.jmh.annotations.Benchmark
import org.openjdk.jmh.annotations.BenchmarkMode
import org.openjdk.jmh.annotations.Measurement
import org.openjdk.jmh.annotations.Mode
import org.openjdk.jmh.annotations.OutputTimeUnit
import org.openjdk.jmh.annotations.Scope
import org.openjdk.jmh.annotations.Setup
import org.openjdk.jmh.annotations.State
import org.openjdk.jmh.annotations.Warmup
import java.util.concurrent.TimeUnit
private const val UPPER_CASE_DIFF = 38
private const val LOWER_CASE_DIFF = 96
@State(Scope.Benchmark)
@Warmup(time = 500, timeUnit = TimeUnit.MILLISECONDS)
@Measurement(time = 500, timeUnit = TimeUnit.MILLISECONDS)
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
class Day03 {
companion object {
fun getPriorityValue(c: Char): Int {
if (c.isUpperCase()) {
return c.code - UPPER_CASE_DIFF
}
return c.code - LOWER_CASE_DIFF
}
fun part1(input: List<String>): Int {
return input.sumOf { s ->
val halves = s.splitInHalf().toList()
halves.reappearingChars().sumOf {
getPriorityValue(it)
}
}
}
fun part2(input: List<String>): Int {
// Split elves into groups of three
val groups = input.chunked(3)
return groups.sumOf { group ->
group.reappearingChars().sumOf { getPriorityValue(it) }
}
}
}
private var input = emptyList<String>()
@Setup
fun setUp() {
input = readInput("Day03")
}
@Benchmark
public fun part1Bench(): Int {
return part1(input)
}
@Benchmark
public fun part2Bench(): Int {
return part2(input)
}
}
fun main() {
// test if implementation meets criteria from the description, like:
val testInput = readInput("Day03_test")
check(Day03.part1(testInput) == 157)
check(Day03.part2(testInput) == 70)
val input = readInput("Day03")
println(Day03.part1(input))
println(Day03.part2(input))
}
| 0
|
Kotlin
|
0
| 0
|
42b38e2a2592a8a5191c221b3dc648b879920ef8
| 2,143
|
aoc-2022
|
Apache License 2.0
|
app/src/main/java/com/stocksexchange/android/ui/settings/items/SettingAccountItem.kt
|
nscoincommunity
| 277,168,471
| true
|
{"Kotlin": 2814235}
|
package com.stocksexchange.android.ui.settings.items
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.RelativeLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.arthurivanets.adapster.Adapter
import com.arthurivanets.adapster.markers.ItemResources
import com.arthurivanets.adapster.model.BaseItem
import com.arthurivanets.adapster.model.Item
import com.stocksexchange.android.R
import com.stocksexchange.android.model.SettingAccount
import com.stocksexchange.android.ui.base.viewholders.BaseViewHolder
import com.stocksexchange.android.theming.ThemingUtil
import com.stocksexchange.android.theming.model.Theme
import com.stocksexchange.android.ui.settings.SettingResources
class SettingAccountItem(itemModel: SettingAccount) : BaseItem<SettingAccount, SettingAccountItem.ViewHolder, SettingResources>(itemModel) {
companion object {
const val MAIN_LAYOUT_ID = R.layout.setting_account_item_layout
}
override fun init(adapter: Adapter<out Item<RecyclerView.ViewHolder, ItemResources>>?, parent: ViewGroup,
inflater: LayoutInflater, resources: SettingResources?): ViewHolder {
return ViewHolder(inflater.inflate(layout, parent, false)).apply {
applyTheme(resources!!.settings.theme)
}
}
override fun bind(adapter: Adapter<out Item<RecyclerView.ViewHolder, ItemResources>>?,
viewHolder: ViewHolder, resources: SettingResources?) {
super.bind(adapter, viewHolder, resources)
with(viewHolder) {
mTitleTv.text = itemModel.userEmail
mDescriptionTv.text = itemModel.userName
}
}
fun setOnSignOutClickListener(viewHolder: ViewHolder, position: Int,
listener: ((View, SettingAccountItem, Int) -> Unit)?) {
viewHolder.iconIv.setOnClickListener {
listener?.invoke(it, this@SettingAccountItem, position)
}
}
override fun getLayout(): Int = MAIN_LAYOUT_ID
class ViewHolder(itemView: View) : BaseViewHolder<SettingAccount>(itemView) {
val mTitleTv: TextView = itemView.findViewById(R.id.titleTv)
val mDescriptionTv: TextView = itemView.findViewById(R.id.descriptionTv)
val iconIv: ImageView = itemView.findViewById(R.id.iconIv)
val contentContainerRl: RelativeLayout = itemView.findViewById(R.id.contentContainerRl)
override fun applyTheme(theme: Theme) {
with(ThemingUtil.Settings.SettingAccountItem) {
contentContainer(contentContainerRl, theme)
title(mTitleTv, theme)
description(mDescriptionTv, theme)
}
}
}
}
| 0
| null |
0
| 0
|
52766afab4f96506a2d9ed34bf3564b6de7af8c3
| 2,819
|
Android-app
|
MIT License
|
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/ses/SNSActionConfigDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.ses
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import software.amazon.awscdk.services.ses.SNSActionConfig
/**
* SNSAction configuration.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.ses.*;
* SNSActionConfig sNSActionConfig = SNSActionConfig.builder()
* .encoding("encoding")
* .topicArn("topicArn")
* .build();
* ```
*/
@CdkDslMarker
public class SNSActionConfigDsl {
private val cdkBuilder: SNSActionConfig.Builder = SNSActionConfig.builder()
/**
* @param encoding The encoding to use for the email within the Amazon SNS notification.
*/
public fun encoding(encoding: String) {
cdkBuilder.encoding(encoding)
}
/**
* @param topicArn The Amazon Resource Name (ARN) of the Amazon SNS topic to notify.
*/
public fun topicArn(topicArn: String) {
cdkBuilder.topicArn(topicArn)
}
public fun build(): SNSActionConfig = cdkBuilder.build()
}
| 1
|
Kotlin
|
0
| 0
|
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
| 1,266
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
app/src/main/kotlin/com/dot/gallery/feature_node/presentation/search/components/SearchBarElevation.kt
|
IacobIonut01
| 614,314,251
| false
| null |
package com.dot.gallery.feature_node.presentation.search.components
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
sealed class SearchBarElevation(val dp: Dp) {
data object Collapsed : SearchBarElevation(2.dp)
data object Expanded : SearchBarElevation(0.dp)
operator fun invoke() = dp
}
| 65
| null |
57
| 997
|
3510ea658dff358a0ea0716997082d0e06234c83
| 326
|
Gallery
|
Apache License 2.0
|
src/commonMain/kotlin/nl/astraeus/css/properties/Perspective.kt
|
rnentjes
| 413,056,107
| false
|
{"Kotlin": 117943}
|
package nl.astraeus.css.properties
class Perspective(
value: String
) : CssProperty(value) {
companion object {
val none = Perspective("none")
val initial = Perspective("initial")
val inherit = Perspective("inherit")
}
}
| 0
|
Kotlin
|
0
| 0
|
e0a4ff54de9968c180fe180f0d3d58e345993489
| 242
|
kotlin-css-generator
|
MIT License
|
src/commonMain/kotlin/io/github/agrevster/pocketbaseKotlin/models/User.kt
|
agrevster
| 672,076,191
| false
| null |
package io.github.agrevster.pocketbaseKotlin.models
import kotlinx.serialization.Serializable
import kotlinx.serialization.Transient
@Serializable
/**
* A Pocketbase generated 'users' collection user. If you want to work with custom fields use your own object which extends this one.
* @param [verified] weather or not the user is verified
* @param [username] the user's username
* @param [email] the user's email
* @param [emailVisibility] weather or not the user's email is visible to other users when they query the user's collection
*/
public open class User(
public val verified: Boolean? = null,
public open val username: String? = null,
public val email: String? = null,
public val emailVisibility: Boolean? = null,
@Transient private val userId: String? = null
) : Record(userId) {
override fun toString(): String {
return "User(verified=$verified, username=$username, email=$email, emailVisibility=$emailVisibility)"
}
}
| 4
| null |
3
| 5
|
a6b6bd810b4e550ef9b66e19a92b86c41291e34d
| 974
|
pocketbase-kotlin
|
MIT License
|
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/ec2/CfnClientVpnEndpointDsl.kt
|
F43nd1r
| 643,016,506
| false
| null |
package com.faendir.awscdkkt.generated.services.ec2
import com.faendir.awscdkkt.AwsCdkDsl
import javax.`annotation`.Generated
import kotlin.String
import kotlin.Unit
import software.amazon.awscdk.services.ec2.CfnClientVpnEndpoint
import software.amazon.awscdk.services.ec2.CfnClientVpnEndpointProps
import software.constructs.Construct
@Generated
public fun Construct.cfnClientVpnEndpoint(id: String, props: CfnClientVpnEndpointProps):
CfnClientVpnEndpoint = CfnClientVpnEndpoint(this, id, props)
@Generated
public fun Construct.cfnClientVpnEndpoint(
id: String,
props: CfnClientVpnEndpointProps,
initializer: @AwsCdkDsl CfnClientVpnEndpoint.() -> Unit,
): CfnClientVpnEndpoint = CfnClientVpnEndpoint(this, id, props).apply(initializer)
@Generated
public fun Construct.buildCfnClientVpnEndpoint(id: String, initializer: @AwsCdkDsl
CfnClientVpnEndpoint.Builder.() -> Unit): CfnClientVpnEndpoint =
CfnClientVpnEndpoint.Builder.create(this, id).apply(initializer).build()
| 1
|
Kotlin
|
0
| 0
|
b22e397ff37c5fce365a5430790e5d83f0dd5a64
| 991
|
aws-cdk-kt
|
Apache License 2.0
|
app/src/main/java/com/masterplus/notex/viewmodels/BackupDiaViewModel.kt
|
Ramazan713
| 458,716,624
| false
|
{"Kotlin": 467000}
|
package com.masterplus.notex.viewmodels
import android.app.Application
import android.net.Uri
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.masterplus.notex.R
import com.masterplus.notex.managers.BackupManager
import com.masterplus.notex.models.coroutinescopes.IOCoroutineScope
import com.masterplus.notex.models.Result
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import java.util.Observer
import javax.inject.Inject
@HiltViewModel
class BackupDiaViewModel @Inject constructor(app:Application,
private val iOScope: IOCoroutineScope,
private val backupManager: BackupManager
)
: AndroidViewModelBase(app) {
init {
iOScope.addObserver(Observer { observable, any ->
viewModelScope.launch {
mutableIsMessage.emit(getApplication<Application>().getString(R.string.unexpected_error_text))
}
setIsLoading(false)
setIsBackupDownloading(false)
})
}
private val mutableIsLoading= MutableLiveData<Boolean>(false)
val isLoading:LiveData<Boolean> get() = mutableIsLoading
private val mutableIsBackupDownloading= MutableLiveData<Boolean>()
val isBackupDownloading:LiveData<Boolean> get() = mutableIsBackupDownloading
private val mutableIsNavigateToActivity= MutableSharedFlow<Boolean>()
val isNavigateToActivity:SharedFlow<Boolean> get() = mutableIsNavigateToActivity
private val mutableIsMessage= MutableSharedFlow<String?>()
val isMessage:SharedFlow<String?> get() = mutableIsMessage
private fun setIsLoading(isLoading:Boolean){
viewModelScope.launch {
mutableIsLoading.value=isLoading
}
}
private fun setIsBackupDownloading(isLoading: Boolean){
viewModelScope.launch {
mutableIsBackupDownloading.value=isLoading
}
}
fun downloadCloudBackup(fileId:String){
iOScope.launch {
setIsBackupDownloading(true)
setIsLoading(true)
backupManager.loadBackupFromCloud(fileId).let { result ->
if(result.isSuccess){
mutableIsNavigateToActivity.emit(true)
}else
mutableIsMessage.emit(result.error)
}
setIsLoading(false)
setIsBackupDownloading(false)
}
}
fun uploadCloudBackup(){
iOScope.launch {
setIsLoading(true)
showMessageResult(backupManager.formCloudBackup(true))
setIsLoading(false)
}
}
fun loadLocalBackup(uri: Uri){
iOScope.launch {
setIsBackupDownloading(true)
setIsLoading(true)
backupManager.loadLocalBackup(uri).let { result ->
if(result.isSuccess)
mutableIsNavigateToActivity.emit(true)
else
mutableIsMessage.emit(result.error)
}
setIsLoading(false)
setIsBackupDownloading(false)
}
}
fun formLocalBackup(){
iOScope.launch {
backupManager.formLocalBackup().let { result ->
if(result.isSuccess)
mutableIsMessage.emit(getApplication<Application>().getString(R.string.successfully_formed_text))
}
}
}
private suspend fun showMessageResult(result:Result){
mutableIsMessage.emit(if(result.isSuccess)getApplication<Application>().getString(R.string.success_text) else
result.error)
}
}
| 0
|
Kotlin
|
0
| 0
|
69758feb796c6afa728844339ffe8d64bd0a17dc
| 3,780
|
Note-X
|
Apache License 2.0
|
classes.kts
|
tedneward
| 734,969,936
| false
|
{"Kotlin": 18069, "Shell": 58}
|
import kotlin.collections.*
import java.util.*
/*
// {{## BEGIN simple ##}}
class Person(var firstName: String, val lastName: String, var age: Int)
{
init {
println("Person $firstName $lastName constructed")
}
}
val ted = Person("Ted", "Neward", 45)
println("${ted.firstName} is ${ted.age} years old")
// {{## END simple ##}}
*/
// {{## BEGIN secondary ##}}
class Person(var firstName: String, val lastName: String, var age: Int)
{
constructor(soleName: String, age: Int)
: this(soleName, "", age)
{
}
}
val ted = Person("Ted", "Neward", 45)
println("${ted.firstName} is ${ted.age} years old")
val cher = Person("Cher", 39)
println("${cher.firstName} is ${cher.age} years old")
// {{## END secondary ##}}
// {{## BEGIN properties ##}}
public class Address {
public var name: String = ""
public var street: String = ""
public var city: String = ""
public var state: String? = ""
public var zip: String = ""
}
val addr = Address()
addr.name = "<NAME>"
addr.street = "1 Bedrock Way"
// {{## END properties ##}}
// {{## BEGIN getter-setter ##}}
class SecretAsset {
var codeName: String = ""
var realName: String = ""
get() = "<REDACTED>"
set(value) {
field = value
}
}
// {{## END getter-setter ##}}
// {{## BEGIN backing-properties ##}}
class Container {
private var _table: Map<String, Int>? = null
public val table: Map<String, Int>
get() {
if (_table == null)
_table = HashMap()
return _table ?: throw AssertionError("Set to null by another thread")
}
}
// {{## END backing-properties ##}}
// {{## BEGIN methods ##}}
class FootballPlayer {
fun run() { println("Running!") }
fun pass() { println("Passing!") }
}
val genoSmith = FootballPlayer()
genoSmith.run()
genoSmith.pass()
// {{## END methods ##}}
// {{## BEGIN operators ##}}
data class Money(val amount: Int, val currency: String = "USD") {
operator fun plus(other: Money): Money {
if (this.currency != other.currency)
throw Exception("Conversion required!")
else
return Money(this.amount + other.amount, this.currency)
}
}
operator fun Money.unaryMinus() = Money(-amount, currency)
val salary = Money(100000, "USD")
val bonus = Money(50000, "USD")
println(salary + bonus)
// {{## END operators ##}}
// {{## BEGIN infix ##}}
class Matrix(var number : Int) {
infix fun rotate(amt: Int): Matrix {
return this
}
}
var m = Matrix(5)
m = m rotate 5
// {{## END infix ##}}
/*
// {{## BEGIN data ##}}
data class Money(var amount: Int, val type: String)
val salary = Money(100000, "USD")
println("Your salary is ${salary.type}${salary.amount}")
val euroSalary = salary.copy(type = "EUR")
println("In Europe, you would make ${euroSalary}")
// {{## END data ##}}
*/
// {{## BEGIN sealed ##}}
sealed class Expr {
class Const(val number: Double) : Expr()
class Sum(val e1: Expr, val e2: Expr) : Expr()
object NotANumber : Expr()
}
fun eval(expr: Expr): Double = when(expr) {
is Expr.Const -> expr.number
is Expr.Sum -> eval(expr.e1) + eval(expr.e2)
Expr.NotANumber -> Double.NaN
// the `else` clause is not required because we've covered all the cases
}
val expr = Expr.Sum(Expr.Const(2.0), Expr.Const(2.0))
println("${expr.e1} + ${expr.e2} = ${eval(expr)}") // 4.0
// {{## END sealed ##}}
| 0
|
Kotlin
|
0
| 0
|
f407cb981650f31e2b72174b618a8dc9b2cfa292
| 3,294
|
Demo-Kotlin
|
Creative Commons Zero v1.0 Universal
|
src/main/kotlin/TokenBuilder.kt
|
adwardstark
| 339,720,866
| false
| null |
import io.jsonwebtoken.*
import io.jsonwebtoken.io.Decoders
import org.json.JSONException
import org.json.JSONObject
import java.security.Key
import java.util.*
import javax.crypto.spec.SecretKeySpec
/**
* Created by <NAME> on 04/02/2021.
* @author github.com/adwardstark
*/
object TokenBuilder {
// Do not use this in production
private const val TestSecretKey = "<KEY>"
fun createJWT(algorithm: SignatureAlgorithm, key: Key,
header: JSONObject?, body: JSONObject,
isIssuedAt: Boolean = false, expiresIn: Long = 0): String {
Logger.info("Building JWT token")
// Setup JWT headers
val jwtHeaders = mutableMapOf<String, Any>()
header?.let {
Logger.debug("Found ${it.length()} token-headers")
it.keys().forEach { key ->
val value = header.get(key)
jwtHeaders[key] = value
}
} ?: Logger.debug("No token headers found in config, skipping")
// Setup JWT body
val jwtBody = mutableMapOf<String, Any>()
if(!body.isEmpty) {
Logger.debug("Found ${body.length()} claims for token-body")
body.keys().forEach {
val value = body.get(it)
jwtBody[it] = value
}
} else {
throw JSONException("Token body must not be empty")
}
// Construct token
val tokenBuilder = Jwts.builder()
// Add headers
header?.let {
Logger.debug("Adding token headers")
tokenBuilder.setHeader(jwtHeaders)
}
// Add body
Logger.debug("Adding token body")
tokenBuilder.setClaims(jwtBody)
// Add issued-at if set
if(isIssuedAt) {
Logger.debug("Adding issued-at")
tokenBuilder.addIssuedAt()
}
// Add expiry if set
tokenBuilder.addExpiry(expiresIn)
// Sign with key and algorithm
Logger.info("Signing token with ${algorithm.name}")
tokenBuilder.signWith(key, algorithm)
// Generate token
return tokenBuilder.compact()
}
private fun JwtBuilder.addIssuedAt() {
val nowMillis = System.currentTimeMillis()
this.setIssuedAt(Date(nowMillis))
}
private fun JwtBuilder.addExpiry(expiresIn: Long) {
if(expiresIn > 0) {
Logger.debug("Adding expiry of $expiresIn seconds")
val expMillis: Long = System.currentTimeMillis() + expiresIn
this.setExpiration(Date(expMillis))
} else {
Logger.debug("No expiry is set, token will be valid forever")
}
}
@Throws(JwtException::class)
fun parseJWT(jwtToken: String, secretKey: Key): Jws<Claims> {
return Jwts.parserBuilder()
.setSigningKey(secretKey)
.build()
.parseClaimsJws(jwtToken)
}
fun getSigningKey(algorithm: SignatureAlgorithm, keyString: String): Key {
return if(keyString != "not-set") {
Logger.debug("Re-constructing the signing key")
getSigningKeyFrom(algorithm, keyString)
} else {
// Use default
Logger.debug("No secret key specified, using default")
getSigningKeyFrom(algorithm, TestSecretKey)
}
}
private fun getSigningKeyFrom(algorithm: SignatureAlgorithm, keyString: String): Key {
val keyBytes = Decoders.BASE64.decode(keyString)
return SecretKeySpec(keyBytes, algorithm.jcaName)
}
fun getSigningAlgorithm(algorithmName: String): SignatureAlgorithm {
return if(algorithmName != "not-set") {
Logger.debug("Looking for $algorithmName in algorithm index")
getSigningAlgorithmFrom(algorithmName)
?: throw UnsupportedOperationException("Signing algorithm not supported")
} else {
// Use default
Logger.debug("No algorithm specified, using default HS256")
SignatureAlgorithm.HS256
}
}
private fun getSigningAlgorithmFrom(algorithmName: String): SignatureAlgorithm? {
return when(algorithmName) {
// HS
SignatureAlgorithm.HS256.name -> SignatureAlgorithm.HS256
SignatureAlgorithm.HS384.name -> SignatureAlgorithm.HS384
SignatureAlgorithm.HS512.name -> SignatureAlgorithm.HS512
// ES
SignatureAlgorithm.ES256.name -> SignatureAlgorithm.ES256
SignatureAlgorithm.ES384.name -> SignatureAlgorithm.ES384
SignatureAlgorithm.ES512.name -> SignatureAlgorithm.ES512
// PS
SignatureAlgorithm.PS256.name -> SignatureAlgorithm.PS256
SignatureAlgorithm.PS384.name -> SignatureAlgorithm.PS384
SignatureAlgorithm.PS512.name -> SignatureAlgorithm.PS512
// RS
SignatureAlgorithm.RS256.name -> SignatureAlgorithm.RS256
SignatureAlgorithm.RS384.name -> SignatureAlgorithm.RS384
SignatureAlgorithm.RS512.name -> SignatureAlgorithm.RS512
// Not supported
else -> null
}
}
}
| 0
|
Kotlin
|
0
| 1
|
e08a0ae0cc363182689d686da45d4969b62c10ba
| 5,164
|
jwtKT
|
Apache License 2.0
|
app/src/main/java/com/oscarliang/knews/MainActivity.kt
|
iamoscarliang
| 761,140,560
| false
|
{"Kotlin": 151931}
|
package com.oscarliang.knews
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.oscarliang.knews.databinding.ActivityMainBinding
import com.oscarliang.knews.di.Injectable
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasAndroidInjector
import javax.inject.Inject
class MainActivity : AppCompatActivity(), Injectable, HasAndroidInjector {
@Inject
lateinit var dispatchingAndroidInjector: DispatchingAndroidInjector<Any>
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.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
binding.bottomNav?.setupWithNavController(navController)
binding.navView?.setupWithNavController(navController)
navController.addOnDestinationChangedListener { controller, destination, arguments ->
binding.toolbar.isVisible = destination.id != R.id.newsDetailFragment
}
}
override fun androidInjector(): AndroidInjector<Any> = dispatchingAndroidInjector
}
| 0
|
Kotlin
|
0
| 0
|
c03764f4d80338cff8fa98bc59a72ecbd892af6d
| 1,515
|
k-news
|
MIT License
|
src/main/kotlin/dev/galiev/sc/blocks/custom/FoldingChair.kt
|
GalievDev
| 628,931,160
| false
| null |
package dev.galiev.sc.blocks.custom
import dev.galiev.sc.blocks.custom.entity.ChairEntity
import dev.galiev.sc.blocks.custom.entity.ChairEntity.Companion.OCCUPIED
import dev.galiev.sc.helper.EntityTypeRegistry
import net.fabricmc.fabric.api.`object`.builder.v1.block.FabricBlockSettings
import net.minecraft.block.BlockState
import net.minecraft.block.HorizontalFacingBlock
import net.minecraft.block.Material
import net.minecraft.block.Waterloggable
import net.minecraft.entity.Entity
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.util.ActionResult
import net.minecraft.util.Hand
import net.minecraft.util.hit.BlockHitResult
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Box
import net.minecraft.util.math.Vec3d
import net.minecraft.world.World
import net.minecraft.world.event.GameEvent
class FoldingChair(settings: Settings = FabricBlockSettings.of(Material.WOOD).nonOpaque()) : HorizontalFacingBlock(settings), Waterloggable {
@Deprecated("Deprecated in Java", ReplaceWith("ActionResult.CONSUME", "net.minecraft.util.ActionResult"))
override fun onUse(
state: BlockState?,
world: World?,
pos: BlockPos?,
player: PlayerEntity?,
hand: Hand?,
hit: BlockHitResult?
): ActionResult {
if (world?.isClient!!) {
return ActionResult.PASS
}
if (!player?.isSneaking!! && player.getStackInHand(hand).isEmpty) {
val comparePos = Vec3d(hit?.blockPos?.x?.toDouble()!!, hit.blockPos.y.toDouble(), hit.blockPos.z.toDouble())
return spawnChair(world, player, hit.blockPos, 0.3, comparePos)
}
return ActionResult.PASS
}
override fun onBreak(world: World?, pos: BlockPos?, state: BlockState?, player: PlayerEntity?) {
if (pos != null) {
val x = pos.x.toDouble()
val y = pos.y.toDouble()
val z = pos.z.toDouble()
val entities: MutableList<ChairEntity>? = world?.getEntitiesByClass(
ChairEntity::class.java,
Box(x, y, z, x + 1.0, y + 1.0, z + 1.0)
) { entity -> entity.hasPassengers() }
if (entities != null) {
for (entity in entities) {
entity.remove(Entity.RemovalReason.DISCARDED)
}
}
this.spawnBreakParticles(world, player, pos, state)
world?.emitGameEvent(player, GameEvent.BLOCK_DESTROY, pos)
ChairEntity.OCCUPIED.remove(Vec3d(x,y,z))
}
}
private fun spawnChair(world: World?, player: PlayerEntity?, pos: BlockPos?, yOffset: Double, comparePos: Vec3d): ActionResult {
val chair = EntityTypeRegistry.CHAIR_ENTITY.create(world)
if (chair != null) {
val newPos = Vec3d(pos?.x!! + 0.5, pos.y + yOffset, pos.z + 0.5)
OCCUPIED.put(comparePos, player?.blockPos!!)
chair.updatePosition(newPos.x, newPos.y, newPos.z)
world?.spawnEntity(chair)
player.startRiding(chair)
return ActionResult.SUCCESS
}
return ActionResult.PASS
}
}
| 0
|
Kotlin
|
0
| 1
|
212a7e7edef86955fc3ea2d0ac6ff79b06b1bfed
| 3,145
|
Summer-Cottage
|
MIT License
|
data/src/main/java/ru/maksonic/rdpodcast/data/podcast/PodcastRepositoryImpl.kt
|
maksonic
| 455,857,524
| false
| null |
package ru.maksonic.rdpodcast.data.podcast
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow
import ru.maksonic.rdpodcast.core.Result
import ru.maksonic.rdpodcast.core.Abstract
import ru.maksonic.rdpodcast.core.data.BaseRepository
import ru.maksonic.rdpodcast.core.data.Repository
import ru.maksonic.rdpodcast.data.podcast.cache.PodcastCacheDataSource
import ru.maksonic.rdpodcast.data.podcast.cloud.PodcastCloudDataSource
import ru.maksonic.rdpodcast.domain.podcast.PodcastDomain
import ru.maksonic.rdpodcast.domain.podcast.PodcastRepository
import javax.inject.Inject
/**
* @Author: maksonic on 10.02.2022
*/
class PodcastRepositoryImpl @Inject constructor(
private val cloud: PodcastCloudDataSource,
private val cache: PodcastCacheDataSource,
private val mapper: PodcastDataToDomainMapper,
) : BaseRepository<Abstract.EmptyObject, PodcastData, PodcastDomain>(
baseCacheDataSource = null, mapper
), PodcastRepository<PodcastDomain> {
override suspend fun cloudDataList(vararg data: Any?): Result<List<PodcastData>> {
val selectedCategory = data[0].toString()
return cloud.fetchCloudData(selectedCategory)
}
override suspend fun cacheDataList(vararg data: Any?): Result<List<PodcastData>> =
Result.Success(emptyList())
override suspend fun currentPodcast(podcast: PodcastDomain): Flow<Result<PodcastDomain>> =
flow {
val podcastData = mapper.to(podcast)
cache.fetchCurrentPlayingPodcast(podcastData).collect { podcast ->
when (podcast) {
is Result.Success -> {
val podcastDomain = mapper.from(podcast.data)
emit(Result.Success(podcastDomain))
}
is Result.Error -> emit(Result.Error(podcast.exception))
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
12d65900beddd1a0bbf0f95fa79f8c54f11c775b
| 1,929
|
RDPodcast
|
MIT License
|
labstate/src/main/java/com/example/labstate/MainActivity.kt
|
gnoejh
| 738,881,237
| false
|
{"Kotlin": 788673, "HTML": 47717, "JavaScript": 18873, "CSS": 18737, "Java": 268}
|
package com.example.labstate
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.labstate.ui.theme.ComposeMasterTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
ComposeMasterTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
NameCard()
}
}
}
}
}
@Composable
fun NameCard() {
// Mutable states for name, ID number, and photo shape
var name by remember { mutableStateOf("<NAME>") }
var idNumber by remember { mutableStateOf("123456") }
var isCircleShape by remember { mutableStateOf(true) } // True for circle, false for square
// List of careers
val careers = listOf(
"Software Engineer",
"Data Scientist",
"Product Manager",
"Graphic Designer",
"UX Designer",
"Project Manager",
"Web Developer",
"Mobile Developer",
"Systems Analyst",
"IT Consultant",
"Network Administrator",
"Database Administrator",
"Security Analyst",
"Cloud Architect",
"DevOps Engineer",
"Quality Assurance Engineer"
)
Surface(
modifier = Modifier
.fillMaxSize()
.padding(16.dp),
color = MaterialTheme.colorScheme.background
) {
Column(
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxHeight()
) {
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.fillMaxWidth()
) {
val imageShape = if (isCircleShape) CircleShape else RoundedCornerShape(0.dp)
Image(
painter = painterResource(id = R.drawable.hongjeong), // Make sure this drawable exists
contentDescription = "Profile Image",
modifier = Modifier
.size(100.dp)
.clip(imageShape)
.border(1.dp, MaterialTheme.colorScheme.primary, imageShape)
)
Spacer(modifier = Modifier.width(16.dp))
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally
) {
Text(text = name, fontSize = 20.sp)
Text(text = idNumber, fontSize = 20.sp)
}
}
Spacer(modifier = Modifier.height(16.dp))
// Button to toggle the shape
Button(onClick = { isCircleShape = !isCircleShape }) {
Text(if (isCircleShape) "Switch to Square" else "Switch to Circle")
}
Spacer(modifier = Modifier.height(8.dp))
// Buttons to change the state values
Button(onClick = { name = "<NAME>" }) {
Text("Change Name")
}
Spacer(modifier = Modifier.height(8.dp))
Button(onClick = { idNumber = "654321" }) {
Text("Change ID Number")
}
Spacer(modifier = Modifier.height(16.dp))
// Adding a LazyColumn to display the list of careers
Text("Careers:", style = MaterialTheme.typography.titleLarge)
LazyColumn {
items(careers.size) { index ->
Text(text = careers[index], style = MaterialTheme.typography.bodyLarge, modifier = Modifier.padding(8.dp))
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
d4480222d703106f53832f5a71f090aad3c24471
| 5,403
|
AndroidComposeMaster
|
MIT License
|
kotest-core/src/commonMain/kotlin/io/kotest/core/spec/descriptions.kt
|
nagellack5C
| 235,292,077
| true
|
{"Kotlin": 1862796, "HTML": 423, "Java": 153, "Shell": 125}
|
package io.kotest.core.spec
import io.kotest.core.bestName
import io.kotest.core.displayName
import io.kotest.core.test.Description
import io.kotest.fp.getOrElse
import kotlin.reflect.KClass
/**
* Returns a [Description] that can be used for a spec.
*
* If the spec has been annotated with @DisplayName (JVM only), then that will be used, otherwise
* the default is to use the fully qualified class name.
*
* Note: This name must be globally unique. Two specs, even in different packages,
* cannot share the same name, so if @DisplayName is set, users must ensure it does not clash
* with another.
*/
fun KClass<*>.description(): Description {
val name = this.displayName().getOrElse(bestName())
return Description.spec(name)
}
| 0
| null |
0
| 0
|
6c3b7967ec7c9d7604d237a8cf37fb023ab46f09
| 745
|
kotlintest
|
Apache License 2.0
|
graph/graph-application/src/main/kotlin/eu/tib/orkg/prototype/contenttypes/domain/model/Paper.kt
|
TIBHannover
| 197,416,205
| false
|
{"Kotlin": 2627763, "Cypher": 216189, "Python": 4880, "Groovy": 1936, "Shell": 1803, "HTML": 240}
|
package eu.tib.orkg.prototype.contenttypes.domain.model
import eu.tib.orkg.prototype.community.domain.model.ObservatoryId
import eu.tib.orkg.prototype.community.domain.model.OrganizationId
import eu.tib.orkg.prototype.community.domain.model.ContributorId
import eu.tib.orkg.prototype.statements.domain.model.ExtractionMethod
import eu.tib.orkg.prototype.statements.domain.model.ThingId
import eu.tib.orkg.prototype.statements.domain.model.Visibility
import java.time.OffsetDateTime
data class Paper(
val id: ThingId,
val title: String,
val researchFields: List<ObjectIdAndLabel>,
val identifiers: Map<String, String>,
val publicationInfo: PublicationInfo,
val authors: List<Author>,
val contributions: List<ObjectIdAndLabel>,
val observatories: List<ObservatoryId>,
val organizations: List<OrganizationId>,
val extractionMethod: ExtractionMethod,
val createdAt: OffsetDateTime,
val createdBy: ContributorId,
val verified: Boolean,
val visibility: Visibility
)
| 0
|
Kotlin
|
2
| 5
|
31ef68d87499cff09551febb72ae3d38bfbccb98
| 1,018
|
orkg-backend
|
MIT License
|
app/src/main/java/me/ibrahimsn/smoothbottombar/MainActivity.kt
|
tobiasschuerg
| 217,917,496
| true
|
{"Kotlin": 12654}
|
package me.ibrahimsn.smoothbottombar
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import kotlinx.android.synthetic.main.activity_main.*
import me.ibrahimsn.lib.SmoothBottomBar
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
bottomBar.setBottomBarCallback(object: SmoothBottomBar.BottomBarCallback {
override fun onItemSelect(pos: Int) {
}
override fun onItemReselect(pos: Int) {
}
})
}
}
| 0
| null |
0
| 0
|
bd4b353ede098fba8b513a732dc58d9999de176c
| 633
|
SmoothBottomBar
|
MIT License
|
app/src/main/java/com/cngal/app/model/entry/StaffPositionGroupModel.kt
|
CnGal
| 648,083,407
| false
|
{"Kotlin": 421043}
|
package com.cngal.app.model.entry
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class StaffPositionGroupModel(
@Json(name = "modifier")
val modifier: String,
@Json(name = "names")
val content: List<StaffModel>
)
| 0
|
Kotlin
|
1
| 2
|
6703376adae97557825f39d7492a04b3aee55729
| 291
|
cngal-jetpack-app
|
MIT License
|
src/main/kotlin/no/nav/familie/ba/sak/kjerne/behandling/BehandlingHentOgPersisterService.kt
|
navikt
| 224,639,942
| false
| null |
package no.nav.familie.ba.sak.kjerne.behandling
import no.nav.familie.ba.sak.kjerne.behandling.domene.Behandling
import no.nav.familie.ba.sak.kjerne.behandling.domene.BehandlingRepository
import no.nav.familie.ba.sak.kjerne.behandling.domene.BehandlingStatus
import no.nav.familie.ba.sak.statistikk.saksstatistikk.SaksstatistikkEventPublisher
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.stereotype.Service
import java.math.BigInteger
@Service
class BehandlingHentOgPersisterService(
private val behandlingRepository: BehandlingRepository,
private val saksstatistikkEventPublisher: SaksstatistikkEventPublisher
) {
fun lagreEllerOppdater(behandling: Behandling, sendTilDvh: Boolean = true): Behandling {
return behandlingRepository.save(behandling).also {
if (sendTilDvh) {
saksstatistikkEventPublisher.publiserBehandlingsstatistikk(it.id)
}
}
}
fun hentAktivForFagsak(fagsakId: Long): Behandling? {
return behandlingRepository.findByFagsakAndAktiv(fagsakId)
}
fun hentAktivOgÅpenForFagsak(fagsakId: Long): Behandling? {
return behandlingRepository.findByFagsakAndAktivAndOpen(fagsakId)
}
fun hent(behandlingId: Long): Behandling {
return behandlingRepository.finnBehandling(behandlingId)
}
/**
* Henter siste iverksatte behandling på fagsak
*/
fun hentSisteBehandlingSomErIverksatt(fagsakId: Long): Behandling? {
val iverksatteBehandlinger = hentIverksatteBehandlinger(fagsakId)
return Behandlingutils.hentSisteBehandlingSomErIverksatt(iverksatteBehandlinger)
}
/**
* Henter siste iverksatte behandling FØR en gitt behandling.
* Bør kun brukes i forbindelse med oppdrag mot økonomisystemet
* eller ved behandlingsresultat.
*/
fun hentForrigeBehandlingSomErIverksatt(behandling: Behandling): Behandling? {
val iverksatteBehandlinger = hentIverksatteBehandlinger(behandling.fagsak.id)
return Behandlingutils.hentForrigeIverksatteBehandling(iverksatteBehandlinger, behandling)
}
/**
* Henter iverksatte behandlinger FØR en gitt behandling.
* Bør kun brukes i forbindelse med oppdrag mot økonomisystemet
* eller ved behandlingsresultat.
*/
fun hentBehandlingerSomErIverksatt(behandling: Behandling): List<Behandling> {
val iverksatteBehandlinger = hentIverksatteBehandlinger(behandling.fagsak.id)
return Behandlingutils.hentIverksatteBehandlinger(iverksatteBehandlinger, behandling)
}
fun hentSisteBehandlingSomErVedtatt(fagsakId: Long): Behandling? {
return behandlingRepository.finnBehandlinger(fagsakId)
.filter { !it.erHenlagt() && it.status == BehandlingStatus.AVSLUTTET }
.maxByOrNull { it.opprettetTidspunkt }
}
/**
* Henter siste behandling som er vedtatt FØR en gitt behandling
*/
fun hentForrigeBehandlingSomErVedtatt(behandling: Behandling): Behandling? {
val behandlinger = behandlingRepository.finnBehandlinger(behandling.fagsak.id)
return Behandlingutils.hentForrigeBehandlingSomErVedtatt(behandlinger, behandling)
}
fun hentSisteIverksatteBehandlingerFraLøpendeFagsaker(page: Pageable): Page<BigInteger> =
behandlingRepository.finnSisteIverksatteBehandlingFraLøpendeFagsaker(page)
fun <T> partitionByIverksatteBehandlinger(funksjon: (iverksatteBehandlinger: List<Long>) -> List<T>): List<T> {
return behandlingRepository.finnSisteIverksatteBehandlingFraLøpendeFagsaker().chunked(10000)
.flatMap { funksjon(it) }
}
fun hentSisteIverksatteBehandlingerFraLøpendeFagsaker(): List<Long> =
behandlingRepository.finnSisteIverksatteBehandlingFraLøpendeFagsaker()
fun hentBehandlinger(fagsakId: Long): List<Behandling> {
return behandlingRepository.finnBehandlinger(fagsakId)
}
private fun hentIverksatteBehandlinger(fagsakId: Long): List<Behandling> {
return behandlingRepository.finnIverksatteBehandlinger(fagsakId = fagsakId)
}
}
| 13
|
Kotlin
|
0
| 7
|
54d8a8a9f29783a0f76495b11bf563fba3e5d88e
| 4,141
|
familie-ba-sak
|
MIT License
|
src/main/kotlin/com/springKotlinAuthentication/demo/authentication/dto/request/UpdateUserRequest.kt
|
Kenato254
| 854,587,987
| false
|
{"Kotlin": 93453, "Shell": 1143}
|
package com.springKotlinAuthentication.demo.authentication.dto.request
import com.springKotlinAuthentication.demo.authentication.constant.Constant
import com.springKotlinAuthentication.demo.authentication.validators.dob.DateOfBirth
import jakarta.validation.constraints.Email
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.Size
import java.time.LocalDate
data class UpdateUserRequest(
val firstName: String?,
val lastName: String?,
@field:Email(regexp = Constant.EMAIL_REGEX)
val email: String?,
val dateOfBirth: LocalDate?
)
| 0
|
Kotlin
|
0
| 0
|
463f79638fde7e6f9f9db27119b6d5a888ea37eb
| 586
|
spring-kotlin-authentication-demo
|
MIT License
|
android/src/main/java/com/shibumurugan/reactnativestaggered/ReactNativeStaggeredModule.kt
|
shibumrgn
| 458,134,595
| false
|
{"JavaScript": 15403, "Kotlin": 6069, "Swift": 2145, "Ruby": 1435, "TypeScript": 969, "Starlark": 602, "Objective-C": 578}
|
package com.shibumurugan.reactnativestaggered
import com.facebook.react.bridge.ReactApplicationContext
import com.facebook.react.bridge.ReactContextBaseJavaModule
class ReactNativeStaggeredModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
override fun getName() = "ReactNativeStaggeredModule"
override fun getConstants(): MutableMap<String, Any> {
return hashMapOf("count" to 1)
}
}
| 0
|
JavaScript
|
0
| 0
|
daa0e8a9040318b540e2f203d6f123a9974b97ec
| 448
|
react-native-staggered
|
MIT License
|
shared/src/commonMain/kotlin/com/norrisboat/ziuq/domain/utils/Labels.kt
|
norrisboat
| 746,362,661
| false
|
{"Kotlin": 225770, "Swift": 70758}
|
package com.norrisboat.ziuq.domain.utils
import com.norrisboat.ziuq.MR
import dev.icerock.moko.resources.desc.Resource
import dev.icerock.moko.resources.desc.ResourceFormatted
import dev.icerock.moko.resources.desc.StringDesc
class Labels {
val app: StringDesc = StringDesc.Resource(MR.strings.app)
val tagline: StringDesc = StringDesc.Resource(MR.strings.tagline)
val login: StringDesc = StringDesc.Resource(MR.strings.login)
val register: StringDesc = StringDesc.Resource(MR.strings.register)
val username: StringDesc = StringDesc.Resource(MR.strings.username)
val password: StringDesc = StringDesc.Resource(MR.strings.password)
val passwordEmpty: StringDesc = StringDesc.Resource(MR.strings.password_not_empty)
val usernameEmpty: StringDesc = StringDesc.Resource(MR.strings.username_id_not_empty)
val noAccountRegister: StringDesc = StringDesc.Resource(MR.strings.no_account_register)
val backButton: StringDesc = StringDesc.Resource(MR.strings.back_button)
val hello: StringDesc = StringDesc.Resource(MR.strings.hello)
val creatingQuiz: StringDesc = StringDesc.Resource(MR.strings.creating_quiz_message)
val skip: StringDesc = StringDesc.Resource(MR.strings.skip)
val congratulations: StringDesc = StringDesc.Resource(MR.strings.congratulations)
val congratulationsMessage: StringDesc = StringDesc.Resource(MR.strings.congratulations_message)
val done: StringDesc = StringDesc.Resource(MR.strings.done)
val startQuiz: StringDesc = StringDesc.Resource(MR.strings.start_quiz)
val quizCode: StringDesc = StringDesc.Resource(MR.strings.quiz_code)
val enterQuizCode: StringDesc = StringDesc.Resource(MR.strings.enter_quiz_code)
val quizCodeEmpty: StringDesc = StringDesc.Resource(MR.strings.quiz_code_empty)
val share: StringDesc = StringDesc.Resource(MR.strings.share)
val joinCreateQuiz: StringDesc = StringDesc.Resource(MR.strings.join_create_quiz)
val createQuiz: StringDesc = StringDesc.Resource(MR.strings.create_quiz)
val joinQuiz: StringDesc = StringDesc.Resource(MR.strings.join_quiz)
val copyQuizCode: StringDesc = StringDesc.Resource(MR.strings.copy)
val youWin: StringDesc = StringDesc.Resource(MR.strings.you_win)
val youLost: StringDesc = StringDesc.Resource(MR.strings.you_lost)
val draw: StringDesc = StringDesc.Resource(MR.strings.draw)
val logout: StringDesc = StringDesc.Resource(MR.strings.logout)
val more: StringDesc = StringDesc.Resource(MR.strings.more)
val waitingForOpponent: StringDesc = StringDesc.Resource(MR.strings.waiting_for_opponent)
val joiningQuiz: StringDesc = StringDesc.Resource(MR.strings.joining_quiz)
val loading: StringDesc = StringDesc.Resource(MR.strings.loading)
val loadingQuestions: StringDesc = StringDesc.Resource(MR.strings.loading_questions)
val creatingQuizMessage: StringDesc = StringDesc.Resource(MR.strings.creating_quiz)
val quizCodeCopied: StringDesc = StringDesc.Resource(MR.strings.quiz_code_copied)
fun questionNumber(number: Int): StringDesc {
return StringDesc.ResourceFormatted(MR.strings.question_number, number)
}
fun numberQuestion(number: Int): StringDesc {
return StringDesc.ResourceFormatted(MR.strings.number_question, number)
}
fun categoryQuiz(category: String): StringDesc {
return StringDesc.ResourceFormatted(MR.strings.quiz_category, category)
}
}
| 0
|
Kotlin
|
2
| 7
|
94140c28aae2621f87b77a79edd66ea66519b047
| 3,420
|
Ziuq
|
MIT License
|
app/src/main/java/com/ably/tracking/demo/publisher/data/api/OrderResponse.kt
|
ably
| 497,980,892
| false
| null |
package com.ably.tracking.demo.publisher.data.api
import com.google.gson.annotations.SerializedName
data class OrderResponse(
@SerializedName("to") val destination: Destination
)
data class Destination(
val latitude: Double,
val longitude: Double
)
| 0
|
Kotlin
|
1
| 1
|
c7bfe7aacd4e048cebe8d857f5a811b62c5bd328
| 264
|
asset-tracking-android-rider-app-demo
|
Apache License 2.0
|
mobzy-nms-injection/src/main/kotlin/com/mineinabyss/mobzy/injection/types/InteractableEntity.kt
|
MineInAbyss
| 142,800,887
| false
| null |
package com.mineinabyss.mobzy.injection.types
import com.mineinabyss.idofront.nms.aliases.NMSEntity
import com.mineinabyss.idofront.nms.aliases.NMSEntityType
import com.mineinabyss.idofront.nms.aliases.NMSWorld
import com.mineinabyss.idofront.nms.aliases.toBukkit
import com.mineinabyss.idofront.nms.entity.typeName
import com.mineinabyss.mobzy.injection.CustomEntity
import net.minecraft.world.damagesource.DamageSource
import net.minecraft.world.entity.EnumMoveType
import net.minecraft.world.phys.Vec3D
class InteractableEntity(type: NMSEntityType<*>, world: NMSWorld) : PassiveMob(type, world), CustomEntity {
//Stop from being pushed around
override fun move(movementType: EnumMoveType, movement: Vec3D) = Unit
override fun collide(entity: NMSEntity) = Unit
//Prevent NPCs from getting damaged by anything
override fun damageEntity(damagesource: DamageSource, f: Float) = false
init {
//TODO CustomName component perhaps?
toBukkit().customName = entityType.typeName
customNameVisible = false
isInvulnerable = true
addScoreboardTag("interactable")
}
}
| 13
|
Kotlin
|
8
| 29
|
6fdf955a0bc906f297eb91340fcdcabf5031beef
| 1,127
|
Mobzy
|
MIT License
|
app/src/main/java/com/kishknkoopz/onlyus/ui/wheel/InnerWheel.kt
|
NikhilShankar
| 698,557,961
| false
|
{"Kotlin": 33573}
|
package com.kishknkoopz.onlyus.ui.wheel
import androidx.compose.animation.core.Animatable
import androidx.compose.animation.core.AnimationEndReason
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.BoxWithConstraints
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.rotate
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.center
import androidx.compose.ui.unit.dp
import kotlinx.coroutines.launch
import kotlin.math.atan2
@Composable
fun OnlyUsWheelContainer(minSize: Dp = 64.dp,
modifier: Modifier,
onAnimationStartedListener: (() -> Unit)? = null,
onAnimationEndedListener: (() -> Unit)? = null) {
var angle by remember{mutableStateOf(0f)}
var dragStartedAngle by remember { mutableStateOf(0f) }
var oldAngle by remember { mutableStateOf(angle) }
var animationDrivingCoroutineScope = rememberCoroutineScope()
var dragStartedTime = remember { mutableStateOf(0L) }
var dragStartPosition = remember { mutableStateOf(Offset.Zero) }
var dragEndPosition = remember { mutableStateOf(Offset.Zero) }
var shouldAllowDrag = remember { mutableStateOf(true) }
var velocity = remember {
mutableStateOf(0f)
}
BoxWithConstraints(modifier.pointerInput(true) {
if(shouldAllowDrag.value) {
detectDragGestures(onDragStart = { offset ->
dragStartedTime.value = System.currentTimeMillis()
dragStartPosition.value = offset
dragStartedAngle = (atan2(
y = size.center.x - offset.x,
x = size.center.y - offset.y
) * (180f / Math.PI.toFloat()) * -1).toFloat()
}, onDragEnd = {
oldAngle = angle
animationDrivingCoroutineScope.launch {
val dragTime = System.currentTimeMillis() - dragStartedTime.value
val dragAmount = dragStartPosition.value - dragEndPosition.value
velocity.value = dragAmount.getDistance() / dragTime
shouldAllowDrag.value = false
}
}) { change, dragAmount ->
val touchAngle = atan2(
y = size.center.x - change.position.x,
x = size.center.y - change.position.y
) * (180f / Math.PI.toFloat()) * -1
angle = (oldAngle + (touchAngle - dragStartedAngle)) % 360
dragEndPosition.value = change.position
}
}
}) {
InnerWheel(minSize, modifier = modifier, angle = angle,
velocity = velocity.value,
onAnimationEnded = {
shouldAllowDrag.value = true
})
}
}
@Composable
fun InnerWheel(
minSize: Dp = 64.dp,
modifier: Modifier,
angle: Float,
velocity: Float?,
onAnimationEnded: () -> Unit
) {
BoxWithConstraints() {
var animateAngle = remember {
Animatable(angle)
}
val width = if (minWidth < 1.dp)
minSize else minWidth
val height = if (minHeight < 1.dp)
minSize else minHeight
if(velocity != null) {
LaunchedEffect(key1 = velocity) {
if (velocity != 0f) {
try {
animateAngle.snapTo(animateAngle.value)
val result = animateAngle.animateTo(
velocity * 360f,
animationSpec = tween(1000 * velocity.coerceIn(1.0f, 5.0f).toInt())
)
if (result.endReason == AnimationEndReason.Finished) {
onAnimationEnded()
}
} catch (e: Exception) {
onAnimationEnded()
}
}
}
}
Canvas(
modifier = modifier
.size(width, height)
) {
val radius = size.width * 0.75f
val center = Offset(size.width / 2.0f, size.height / 1.2f)
rotate(
animateAngle.value, pivot = center) {
drawCircle(
brush = Brush.horizontalGradient(colors = listOf(Color.Yellow, Color.Green)),
radius = radius,
center = center
)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
033b6792393af1240bc437b633d5b7a6c52e2b59
| 5,220
|
OnlyUs
|
MIT License
|
bluetape4k/coroutines/src/main/kotlin/io/bluetape4k/coroutines/SuspendLazy.kt
|
debop
| 625,161,599
| false
|
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
|
package io.bluetape4k.coroutines
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.CoroutineStart
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.withContext
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
import kotlin.experimental.ExperimentalTypeInference
/**
* lazy operation의 실행 블럭에 suspend 함수를 사용하도록 하는 interface
*
* @param T 지연된 계산을 수행한 결과 값의 수형
*/
fun interface SuspendLazy<out T> {
suspend operator fun invoke(): T
}
@OptIn(ExperimentalTypeInference::class)
@PublishedApi
internal class SuspendLazyBlockImpl<out T>(
private val dispatcher: CoroutineContext = EmptyCoroutineContext,
@BuilderInference initializer: () -> T,
): SuspendLazy<T> {
private val lazyValue: Lazy<T> = lazy(initializer)
override suspend fun invoke(): T = with(lazyValue) {
if (isInitialized()) value else withContext(dispatcher) { value }
}
}
@OptIn(ExperimentalTypeInference::class)
@PublishedApi
internal class SuspendLazySuspendingImpl<out T>(
coroutineScope: CoroutineScope,
coroutineContext: CoroutineContext,
@BuilderInference initializer: suspend CoroutineScope.() -> T,
): SuspendLazy<T> {
private val deferredValue by lazy {
coroutineScope.async(coroutineContext, start = CoroutineStart.LAZY, block = initializer)
}
override suspend fun invoke(): T = deferredValue.await()
}
/**
* [Lazy]와 같이 값 계산을 지연해서 수형합니다.
* 값을 조회할 때, Coroutine Scope 에서 수행해야 한다.
*
* ```
* val lazyValue: SuspendLazy<Int> = suspendBlockingLazy {
* Thread.sleep(100)
* 42
* }
*
* val value = runBlocking { lazyValue() }
* ```
*
* @param T
* @param dispatcher 값을 계산하는 블럭을 수행할 [CoroutineDispatcher]
* @param initializer 지연된 계산을 수행하는 함수
* @return
*/
@OptIn(ExperimentalTypeInference::class)
fun <T> suspendBlockingLazy(
dispatcher: CoroutineContext = EmptyCoroutineContext,
@BuilderInference initializer: () -> T,
): SuspendLazy<T> =
SuspendLazyBlockImpl(dispatcher, initializer)
/**
* [Lazy]와 같이 값 계산을 지연해서 수형하는데, 값 계산을 [Dispatchers.IO] 환경 하에서 Blocking 하게 수행합니다.
* 값을 조회할 때, Coroutine Scope 에서 수행해야 한다.
*
* ```
* val lazyValue: SuspendLazy<Int> = suspendBlockingLazyIO {
* Thread.sleep(100)
* 42
* }
*
* val value = runBlocking { lazyValue() }
* ```
*
* @param T
* @param initializer 지연된 계산을 수행하는 함수
* @return
*/
@OptIn(ExperimentalTypeInference::class)
inline fun <T> suspendBlockingLazyIO(
@BuilderInference crossinline initializer: () -> T,
): SuspendLazy<T> =
SuspendLazyBlockImpl(Dispatchers.IO) { initializer() }
/**
* 지연된 값을 구할 때 suspend 함수를 이용하여 비동기 방식으로 구하고, 값을 조회할 때도 CoroutineScope 하에서 구합니다.
*
* ```
* runBlocking {
* val lazyValue: SuspendLazy<T> = suspendLazy {
* delay(100)
* 42
* }
* val value = lazyValue()
* }
* ```
*
* @param T
* @param context 값을 계산하는 블럭을 수행할 [CoroutineDispatcher]
* @param initializer 지연된 계산을 수행하는 함수
* @return
*/
@OptIn(ExperimentalTypeInference::class)
inline fun <T> CoroutineScope.suspendLazy(
context: CoroutineContext = EmptyCoroutineContext,
@BuilderInference crossinline initializer: suspend CoroutineScope.() -> T,
): SuspendLazy<T> {
return SuspendLazySuspendingImpl(this, context) { initializer() }
}
| 0
|
Kotlin
|
0
| 1
|
ce3da5b6bddadd29271303840d334b71db7766d2
| 3,378
|
bluetape4k
|
MIT License
|
src/main/kotlin/org/gradle/script/lang/kotlin/codegen/Predicates.kt
|
pchintale
| 78,643,265
| true
|
{"Kotlin": 255767, "Shell": 477}
|
/*
* Copyright 2016 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.script.lang.kotlin.codegen
fun ZipInputStreamEntry.isApiClassEntry() =
zipEntry.isFile
&& zipEntry.name.endsWith(".class")
&& zipEntry.name.startsWith("org/gradle/api/")
&& !zipEntry.name.contains("/internal/")
fun conflictsWithExtension(method: MethodDescriptor) =
method.isPublic && !method.isSynthetic && hasLastParameterOfTypeAction(method)
fun hasLastParameterOfTypeAction(method: MethodDescriptor) =
lastParameterOrNullOf(method)?.let {
it is GenericType && isActionClassType(it.definition)
} ?: false
fun lastParameterOrNullOf(method: MethodDescriptor) =
method.signature.parameters.lastOrNull()
fun isActionClassType(definition: JvmType) =
definition is ClassType && definition.internalName == "org/gradle/api/Action"
| 0
|
Kotlin
|
0
| 0
|
7aa0841ede483ff11a8938b09b40971647a5ecca
| 1,424
|
gradle-script-kotlin
|
Apache License 2.0
|
macfiles/src/main/kotlin/garden/ephemeral/macfiles/dsstore/codecs/IconViewOptionsCodec.kt
|
ephemeral-laboratories
| 564,594,150
| false
| null |
package garden.ephemeral.macfiles.dsstore.codecs
import garden.ephemeral.macfiles.common.types.Blob
import garden.ephemeral.macfiles.dsstore.types.IconViewOptions
object IconViewOptionsCodec : Codec<IconViewOptions> {
override fun decode(blob: Blob) = IconViewOptions.fromBlob(blob)
override fun encode(value: IconViewOptions) = value.toBlob()
}
| 0
|
Kotlin
|
0
| 0
|
7ae5f10591429b44408187c0e555a8baaaa085a4
| 355
|
dsstore-kotlin
|
MIT License
|
macfiles/src/main/kotlin/garden/ephemeral/macfiles/dsstore/codecs/IconViewOptionsCodec.kt
|
ephemeral-laboratories
| 564,594,150
| false
| null |
package garden.ephemeral.macfiles.dsstore.codecs
import garden.ephemeral.macfiles.common.types.Blob
import garden.ephemeral.macfiles.dsstore.types.IconViewOptions
object IconViewOptionsCodec : Codec<IconViewOptions> {
override fun decode(blob: Blob) = IconViewOptions.fromBlob(blob)
override fun encode(value: IconViewOptions) = value.toBlob()
}
| 0
|
Kotlin
|
0
| 0
|
7ae5f10591429b44408187c0e555a8baaaa085a4
| 355
|
dsstore-kotlin
|
MIT License
|
app/src/test/kotlin/kotlinadventofcode/2023/2023-03-Test.kt
|
pragmaticpandy
| 356,481,847
| false
|
{"Kotlin": 854605, "Shell": 219}
|
// Originally generated by the template in CodeDAO
package kotlinadventofcode.`2023`
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class `2023-03-Test` {
private infix fun String.when1runsWith(input: String) {
assertEquals(this, `2023-03`().runPart1(input))
}
private infix fun String.when2runsWith(input: String) {
assertEquals(this, `2023-03`().runPart2(input))
}
@Test
fun testExamplePart1() {
assertEquals("4361", `2023-03`().runPart1("""467..114..
...*......
..35..633.
......#...
617*......
.....+.58.
..592.....
......755.
...${'$'}.*....
.664.598.."""))
}
@Test fun testDefaultPart1() {
assertEquals("540131", `2023-03`().runPart1())
}
@Test fun testDefaultPart2() {
assertEquals("86879020", `2023-03`().runPart2())
}
}
| 0
|
Kotlin
|
0
| 3
|
48efe6d4dfd21a33130ce4282487fd33825a9721
| 863
|
kotlinadventofcode
|
MIT License
|
SerawaziApplication/app/src/main/java/com/greenrevive/serawaziapplication/L1SecondQuestion.kt
|
MutindaVictoria
| 718,561,733
| false
|
{"Kotlin": 107697}
|
package com.greenrevive.serawaziapplication
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.widget.Toast
import android.graphics.Color
import android.media.MediaPlayer
import com.greenrevive.serawaziapplication.databinding.ActivityL1SecondQuestionBinding
import com.greenrevive.serawaziapplication.model.ScenarioDataClass
class L1SecondQuestion : AppCompatActivity() {
private lateinit var binding: ActivityL1SecondQuestionBinding
private lateinit var mediaPlayerCorrect: MediaPlayer
private lateinit var mediaPlayerIncorrect: MediaPlayer
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityL1SecondQuestionBinding.inflate(layoutInflater)
setContentView(binding.root)
initializeMediaPlayers()
}
private fun initializeMediaPlayers() {
mediaPlayerCorrect = MediaPlayer.create(this, R.raw.winner_sound_effects_mp3_43014)
mediaPlayerCorrect.setOnCompletionListener {
mediaPlayerCorrect.stop()
mediaPlayerCorrect.reset()
}
mediaPlayerIncorrect = MediaPlayer.create(this, R.raw.freeze_dance_for_kids_dance_music_for_kids_mp3_74824)
mediaPlayerIncorrect.setOnCompletionListener {
mediaPlayerIncorrect.stop()
mediaPlayerIncorrect.reset()
}
}
override fun onResume() {
super.onResume()
binding.btncorrectt.setOnClickListener {
Toast.makeText(this, "Correct!! That's Impressive", Toast.LENGTH_LONG).show()
binding.btncorrectt.setBackgroundColor(Color.GREEN)
binding.btncorrectt.setTextColor(Color.WHITE)
binding.imguser1.setImageResource(R.drawable.rightlyhappy)
binding.btncorrectt.isEnabled = false
mediaPlayerCorrect.start()
Handler().postDelayed({
mediaPlayerCorrect.stop()
mediaPlayerCorrect.stop()
startActivity(Intent(this, L1ThirdQuestion::class.java))
}, 3000)
}
binding.ivchat1.setOnClickListener {
val intent = Intent(this, ChatbotInteraction::class.java)
startActivity(intent)
}
binding.btnanswer4.setOnClickListener {
Toast.makeText(this, "Ooops Incorrect!! Get to know why:", Toast.LENGTH_LONG).show()
binding.btnanswer4.setBackgroundColor(Color.RED)
binding.btnanswer4.setTextColor(Color.WHITE)
binding.imguser1.setImageResource(R.drawable.wronglyshocked)
binding.btnanswer4.isEnabled = false
mediaPlayerIncorrect.start()
Handler().postDelayed({
mediaPlayerIncorrect.stop()
mediaPlayerIncorrect.reset()
startActivity(Intent(this, L1SecondWrongAnswer::class.java))
finish() // Add this line to finish the current activity
}, 3000)
}
displayScenarios()
}
private fun displayScenarios() {
val scenarios = listOf(
ScenarioDataClass(2, "Kwamboka a guardian to Sarah, a child with a disability, is denied admission to a public school due to her disabilities and regarded her as a just needy person.What can she do?What right stands for her?", "Kwamboka can institute court proceedings claiming that Sarah's right or fundamental freedom in the Bill of Rights has been denied,violated.According to constituition everyone has right to institute court proceedings for such cases", "Public schools are not obligated to provide facilities for children with disabilities, and the responsibility lies with the child's family to seek another alternative", "ssssssssssssss", 2),
ScenarioDataClass(1, "Having faced job rejection based on her gender, Susan feels she was a victim of discrimination. what legal avenues are available to uphold her rights in this scenario?", "Susan has the right to file a complaint with the relevant anti-discrimination agency and if she has the evidence to support her claim, It's essential for her to gather any relevant documentation or witnesses to strengthen her case."
, "Job rejections happen all the time, and there is no legal recourse for someone who feels discriminated against hence Susan has no power to claim for the rejection", "hffffffffhfhfh", 1),
ScenarioDataClass(3, "Tom is arrested by the police without being informed of the reasons for his arrest, reaching the police station a statement is forged claiming that Tom had Mirra in his pockets .What are some of the rights that Tom should stand up with in this situation?", "Tom has the right to remain silent and have a lawyer present during police questioning. If he cannot afford one, a lawyer will be provided. He must be informed of the charges and can't be forced to testify against himself.", "Tom should be under the police and let them do as they please. A lawyer should be there but he must pay for it. And Tom should Confess so as to make the trial easier. Tom should unquestioningly comply with the police.", "ssjssjsjsjssj", 3)
)
val scenario = scenarios.firstOrNull()
scenario?.let {
binding.tvscene1.text = it.backgroundInfo
binding.btncorrectt.text = it.correctAnswer
binding.btnanswer4.text = it.incorrectAnswer
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3e68806907fa0489274d5625a35d220ffb79c9a0
| 5,484
|
Serawazi-Mobile
|
MIT License
|
app/src/main/java/com/ti/sunrain/logic/model/dayforecast/DayForecastItem.kt
|
bluebonnet27
| 317,797,469
| false
| null |
package com.ti.sunrain.logic.model.dayforecast
import com.ti.sunrain.logic.model.DailyResponse
/**
* @author: tihon
* @date: 2021/4/3
* @description:
*/
class DayForecastItem(val skycon:DailyResponse.Skycon,
val temp:DailyResponse.Temperature)
| 1
|
Kotlin
|
2
| 6
|
68696f18320a86799e0b2243a92c7fa45df83272
| 271
|
SunRain
|
MIT License
|
v2-model/src/commonMain/kotlin/com/bselzer/gw2/v2/model/quest/QuestId.kt
|
Woody230
| 388,820,096
| false
|
{"Kotlin": 750899}
|
package com.bselzer.gw2.v2.model.quest
import com.bselzer.ktx.value.identifier.IntIdentifier
import kotlinx.serialization.Serializable
import kotlin.jvm.JvmInline
@Serializable
@JvmInline
value class QuestId(override val value: Int = 0) : IntIdentifier {
override fun toString(): String = value.toString()
}
| 2
|
Kotlin
|
0
| 2
|
32f1fd4fc4252dbe886b6fc0f4310cf34ac2ef27
| 313
|
GW2Wrapper
|
Apache License 2.0
|
rubik/rubik_kapt/src/main/java/com/rubik/apt/utility/KotlinPoet.kt
|
baidu
| 504,447,693
| false
|
{"Kotlin": 607049, "Java": 37304}
|
/**
* Copyright (C) Baidu Inc. 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 com.rubik.apt.utility
import com.ktnail.x.Logger
import com.squareup.kotlinpoet.FileSpec
fun String.noSpaces() = this.replace(" ", "·")
fun FileSpec.Builder.process() = apply {
try {
// fix kotlinpoet issue : "import xxx as xxx" auto wrapping
this::class.java.getDeclaredField("memberImports").let { field ->
field.isAccessible = true
(field.get(this) as? Set<*>)?.forEach { import ->
if (null != import) {
val importString = import::class.java.getDeclaredField("importString")
importString.isAccessible = true
importString.set(import, importString.get(import).toString().noSpaces())
}
}
}
} catch (e: Exception) {
Logger.e(e.toString())
}
}
| 1
|
Kotlin
|
7
| 153
|
065ba8f4652b39ff558a5e3f18b9893e2cf9bd25
| 1,442
|
Rubik
|
Apache License 2.0
|
src/main/kotlin/no/nav/tiltakspenger/meldekort/api/repository/MeldekortRepo.kt
|
navikt
| 720,213,646
| false
|
{"Kotlin": 78400, "Shell": 1153, "Dockerfile": 515}
|
package no.nav.tiltakspenger.meldekort.api.repository
import no.nav.tiltakspenger.meldekort.api.domene.Meldekort
import no.nav.tiltakspenger.meldekort.api.domene.MeldekortUtenDager
import no.nav.tiltakspenger.meldekort.api.felles.Periode
import java.util.UUID
interface MeldekortRepo {
fun opprett(grunnlagId: UUID, meldekort: Meldekort.Åpent)
fun hentMeldekortForGrunnlag(grunnlagId: UUID): List<MeldekortUtenDager>
fun hentPerioderForMeldekortForGrunnlag(grunnlagId: UUID): List<Periode>
fun hentMeldekortMedId(meldekortId: UUID): Meldekort?
fun lagreInnsendtMeldekort(meldekort: Meldekort.Innsendt)
}
| 2
|
Kotlin
|
0
| 0
|
bf8d171d9f81e3f7606be9c42331fdf9cf2c73f1
| 630
|
tiltakspenger-meldekort-api
|
MIT License
|
app/src/main/java/com/example/homeswap_android/adapter/ReviewAdapter.kt
|
lisisaraujo
| 834,512,241
| false
|
{"Kotlin": 222972}
|
package com.example.homeswap_android.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import coil.load
import com.example.homeswap_android.data.models.Review
import com.example.homeswap_android.databinding.ReviewListItemBinding
class ReviewAdapter(
) : ListAdapter<Review, ReviewAdapter.ItemViewHolder>(ReviewDiffCallback()) {
inner class ItemViewHolder(val binding: ReviewListItemBinding) :
RecyclerView.ViewHolder(binding.root)
fun sortReviews() {
val sortedList = currentList.sortedBy { it.date }
submitList(sortedList)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ItemViewHolder {
val binding = ReviewListItemBinding.inflate(
LayoutInflater.from(parent.context),
parent,
false
)
return ItemViewHolder(binding)
}
override fun onBindViewHolder(holder: ItemViewHolder, position: Int) {
val item = currentList[position]
holder.binding.nameTV.text = item.reviewerName
holder.binding.reviewTV.text = item.review
holder.binding.dateTV.text = item.date
holder.binding.profileIV.load(item.reviewerProfilePic)
holder.binding.ratingBar.rating = item.rating!!
}
class ReviewDiffCallback : DiffUtil.ItemCallback<Review>() {
override fun areItemsTheSame(oldItem: Review, newItem: Review): Boolean {
return (oldItem.reviewID == newItem.reviewID)
}
override fun areContentsTheSame(oldItem: Review, newItem: Review): Boolean {
return (oldItem.review == newItem.review &&
oldItem.date == newItem.date &&
oldItem.reviewerName == newItem.reviewerName &&
oldItem.rating == newItem.rating &&
oldItem.reviewerProfilePic == newItem.reviewerProfilePic)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
fe031a617a2f456f36ead6d04f85fedf92f8e322
| 2,043
|
HomeSwap---Android
|
MIT License
|
src/main/kotlin/hii/thing/api/sessions/dao/recordsession/SqlSessionDetail.kt
|
hii-in-th
| 190,712,805
| false
| null |
/*
* Copyright (c) 2019 NSTDA
* National Science and Technology Development Agency, Thailand
*
* 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 hii.thing.api.sessions.dao.recordsession
import hii.thing.api.SQL_SESSION_LENGTH
import hii.thing.api.device.dao.SqlDevice
import hii.thing.api.sessions.CreateSessionDetail
import org.jetbrains.exposed.sql.ResultRow
import org.jetbrains.exposed.sql.Table
internal object SqlSessionDetail : Table("session") {
val sessionId = varchar("session_id", SQL_SESSION_LENGTH).primaryKey(0)
val time = datetime("time")
val deviceId = reference("device_id", SqlDevice.deviceId).index()
val citizenId = varchar("citizen_id", 36).nullable()
val citizenIdInput = varchar("citizen_id_input", 10).nullable()
val birthDate = date("birth_date").nullable()
val name = varchar("name", 100).nullable()
val sex = varchar("sex", 10).nullable()
val ipAddress = varchar("ip_address", 40).nullable()
fun getResult(it: ResultRow): CreateSessionDetail {
return CreateSessionDetail(
it[deviceId],
it[citizenId],
try {
CreateSessionDetail.InputType.valueOf(it[citizenIdInput]!!.toUpperCase())
} catch (ignore: Exception) {
null
},
it[birthDate]?.toStringDate(),
it[name],
try {
CreateSessionDetail.Sex.valueOf(it[sex]!!.toUpperCase())
} catch (ignore: Exception) {
null
},
it[ipAddress]
)
}
}
| 0
|
Kotlin
|
0
| 0
|
02fc485731329edfaf3ce7c4b0d5e0e98e9b9d36
| 2,089
|
thing-api
|
Apache License 2.0
|
kotlin-antd/antd-samples/src/main/kotlin/samples/upload/Drag.kt
|
oxiadenine
| 206,398,615
| false
|
{"Kotlin": 1619835, "HTML": 1515}
|
package samples.upload
import antd.icon.inboxOutlined
import antd.message.message
import antd.upload.uploadDragger
import kotlinx.html.classes
import react.RBuilder
import react.dom.p
import styled.css
import styled.styledDiv
fun RBuilder.drag() {
styledDiv {
css { +UploadStyles.drag }
uploadDragger {
attrs {
name = "file"
multiple = true
action = "//jsonplaceholder.typicode.com/posts/"
onChange = { info ->
if (info.file.status != "uploading") {
console.log(info.file, info.fileList)
}
if (info.file.status == "done") {
message.success("${info.file.name} file uploaded successfully")
} else if (info.file.status == "error") {
message.error("${info.file.name} file upload failed.")
}
}
}
p {
attrs.classes = setOf("ant-upload-drag-icon")
inboxOutlined {}
}
p {
attrs.classes = setOf("ant-upload-text")
+"Click or drag file to this area to upload"
}
p {
attrs.classes = setOf("ant-upload-hint")
+"Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files"
}
}
}
}
| 1
|
Kotlin
|
8
| 50
|
e0017a108b36025630c354c7663256347e867251
| 1,489
|
kotlin-js-wrappers
|
Apache License 2.0
|
app/src/main/java/org/grakovne/lissen/domain/PagedItems.kt
|
GrakovNe
| 859,536,477
| false
|
{"Kotlin": 215059}
|
package org.grakovne.lissen.domain
data class PagedItems<T>(
val items: List<T>,
val currentPage: Int
)
| 7
|
Kotlin
|
0
| 20
|
b285aa1f51c6bb242ce45b11a20b4b8212aa6f3f
| 113
|
lissen-android
|
MIT License
|
src/main/kotlin/com/troop77eagle/events/Event.kt
|
quincy
| 763,159,633
| false
|
{"Kotlin": 31312, "Dockerfile": 1687, "HTML": 72}
|
package com.troop77eagle.events
import kotlinx.datetime.Instant
import kotlinx.serialization.Serializable
@Serializable
data class Event(
val id: Long,
val name: String,
val startTime: Instant,
val endTime: Instant,
val summary: String,
val description: String,
val eventLocation: String,
val assemblyLocation: String? = null,
val pickupLocation: String? = null,
)
@Serializable
data class CreateEventRequest(
val name: String,
val startTime: String,
val endTime: String,
val summary: String,
val description: String,
val eventLocation: String,
val assemblyLocation: String? = null,
val pickupLocation: String? = null,
) {
fun toEvent(id: Long): Event =
Event(
id = id,
name = this.name,
startTime = Instant.parse(this.startTime),
endTime = Instant.parse(this.endTime),
summary = this.summary,
description = this.description,
eventLocation = this.eventLocation,
assemblyLocation = this.assemblyLocation,
pickupLocation = this.pickupLocation)
}
| 3
|
Kotlin
|
0
| 0
|
0869134e0cc054bb33dcfd85f502197bd1548d67
| 1,113
|
scout-events-app
|
MIT License
|
TeamCode/src/main/kotlin/org/firstinspires/ftc/teamcode/util/NotForCompetition.kt
|
LightningHawks6032
| 666,608,345
| false
|
{"Kotlin": 258258, "Java": 41887}
|
package org.firstinspires.ftc.teamcode.util
@RequiresOptIn(message = "This is not meant to be used in competition, acknowledgement of this is required.")
@Retention(AnnotationRetention.BINARY)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY)
annotation class NotForCompetition
| 0
|
Kotlin
|
0
| 1
|
d1d75d6f04c318396cee4f8f37dcb5f7fae1b30c
| 316
|
FTCRobotController-2023-24
|
BSD 3-Clause Clear License
|
generator/src/main/kotlin/com/laidpack/sourcerer/generator/generators/ModuleGeneratorManager.kt
|
dpnolte
| 151,090,095
| false
| null |
package com.laidpack.sourcerer.generator.generators
import com.laidpack.sourcerer.generator.resources.widgets.WidgetConnoisseur
import com.laidpack.sourcerer.generator.toCamelCase
import com.squareup.kotlinpoet.ClassName
import java.io.File
class ModuleGeneratorManager(
private val targetDir: File,
val moduleName: String,
private val targetPackageName: String,
private val widgetConnoisseur: WidgetConnoisseur,
private val classGenerators: List<ClassGeneratorManager>
) {
private val adapterWrappers = classGenerators.map { it.adapterRegistrationWrapper }
private val viewGroupToLayoutParamsWrappers by lazy {
val wrappers = mutableListOf<AssociatedViewGroupAndLayoutParamsWrapper>()
for (classGenerator in classGenerators) {
if (classGenerator.viewGroupAndLayoutParamsWrapper != null) {
wrappers.add(classGenerator.viewGroupAndLayoutParamsWrapper)
}
}
wrappers.toList()
}
private val factoryWrappers = classGenerators.map { it.factoryWrapper }
val bootstrapperClassName = ClassName(
targetPackageName,
moduleName.replace("-", "_").toCamelCase() + "Bootstrapper"
)
fun generateBootstrapModuleFile() {
val fileSpec = BootstrapModuleGenerator(
bootstrapperClassName,
adapterWrappers,
viewGroupToLayoutParamsWrappers,
factoryWrappers
).generateFile()
fileSpec.writeTo(targetDir)
}
fun generateTemplateFiles() {
TemplateGenerator().generateTemplates(
moduleName,
widgetConnoisseur,
targetDir,
targetPackageName
)
}
}
| 8
|
Kotlin
|
1
| 0
|
9513bbc54768e9248c450b0aba125b433c447e68
| 1,759
|
sourcerer
|
Apache License 2.0
|
src/main/kotlin/com/vauthenticator/server/account/welcome/WelcomeMailEndPoint.kt
|
VAuthenticator
| 191,632,792
| false
| null |
package com.vauthenticator.server.account.welcome
import com.vauthenticator.server.account.AccountNotFoundException
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RestController
@RestController
class WelcomeMailEndPoint(
private val sayWelcome: SayWelcome
) {
@PutMapping("/api/sign-up/mail/{mail}/welcome")
fun welcome(@PathVariable mail: String) =
sayWelcome.welcome(mail)
.let {
ResponseEntity.noContent().build<Unit>()
}
@ExceptionHandler(AccountNotFoundException::class)
fun noAccountExceptionHAndler() =
ResponseEntity.notFound().build<Unit>()
}
| 21
|
Kotlin
|
1
| 8
|
8847b3b0ed3d9530a85aa1124a8b2fdb634eba2b
| 860
|
vauthenticator
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.