path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/ro/alexmamo/firestorecleanarchitecture/presentation/books/components/DeleteBook.kt
|
alexmamo
| 413,736,186
| false
| null |
package ro.alexmamo.firestorecleanarchitecture.presentation.books.components
import androidx.compose.runtime.Composable
import androidx.hilt.navigation.compose.hiltViewModel
import ro.alexmamo.firestorecleanarchitecture.components.ProgressBar
import ro.alexmamo.firestorecleanarchitecture.core.Utils.Companion.print
import ro.alexmamo.firestorecleanarchitecture.domain.model.Response.*
import ro.alexmamo.firestorecleanarchitecture.presentation.books.BooksViewModel
@Composable
fun DeleteBook(
viewModel: BooksViewModel = hiltViewModel()
) {
when(val deleteBookResponse = viewModel.deleteBookResponse) {
is Loading -> ProgressBar()
is Success -> Unit
is Failure -> print(deleteBookResponse.e)
}
}
| 0
|
Kotlin
|
27
| 98
|
354d33ad5811aae9d3b791386111c47452b4207b
| 734
|
FirestoreCleanArchitectureApp
|
Apache License 2.0
|
lib/src/main/kotlin/io/github/italbytz/adapters/meal/OpenMensaMealCollection.kt
|
Italbytz
| 447,179,548
| false
| null |
package io.github.italbytz.adapters.meal
import io.github.italbytz.ports.meal.Category
import io.github.italbytz.ports.meal.Meal
import io.github.italbytz.ports.meal.MealCollection
class MockMealCollection(
override val category: Category,
override val meals: List<Meal>
) : MealCollection {
}
| 0
|
Kotlin
|
0
| 0
|
c97f428b717bda6bfa89981cb3c1ffea357b397d
| 303
|
mvn-adapters-meal-openmensa
|
Apache License 2.0
|
app/src/main/java/com/android/example/livedatabuilder/SplashScreen.kt
|
nimab16
| 565,113,116
| false
| null |
package com.android.example.livedatabuilder
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import com.android.example.livedata.R
class SplashScreen : AppCompatActivity() {
companion object {
//NOTE: It is recommended to keep the time less than 3000 ms
// but as this is just going to be demo so I'm using 6000 ms
// to show the full animation.
const val ANIMATION_TIME: Long = 6000 //Change time according to your animation.
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_screen)
//Use Handler to delay the start of next Activity
// and show animation in the mean while
Handler(this.mainLooper).postDelayed({
//This block will be executed after ANIMATION_TIME milliseconds.
//After ANIMATION_TIME we will start the MainActivity
startActivity(Intent(this, LiveDataActivity::class.java))
//To remove this activity from back stack so that
// this activity will not show when user closes MainActivity
finish()
}, ANIMATION_TIME)
}
}
| 0
|
Kotlin
|
0
| 0
|
ca39d057e6b02548822a5c1baa938b75b31e9062
| 1,273
|
Kotlin_CoroutineswithArchitecture_LiveData_ViewModel
|
Apache License 2.0
|
mineme-api/src/main/kotlin/me/ddevil/mineme/api/composition/MineComposition.kt
|
BrunoSilvaFreire
| 89,026,535
| false
| null |
package me.ddevil.mineme.api.composition
import me.ddevil.json.JsonObject
import me.ddevil.mineme.api.MineMeConstants
import me.ddevil.shiroi.util.misc.item.Material
import me.ddevil.util.*
import me.ddevil.util.misc.AbstractNameableDescribable
import java.util.*
open class MineComposition : AbstractNameableDescribable, Serializable {
companion object {
private val random = Random()
}
private val internalCompositionMap: MutableList<MineMaterial>
@JvmOverloads
constructor(name: String,
alias: String,
description: List<String>,
compositionMap: List<MineMaterial> = emptyList()) : super(name, alias, description) {
this.internalCompositionMap = ArrayList(compositionMap)
}
constructor(json: JsonObject) : this(json as Map<String, Any>)
constructor(map: Map<String, Any>) : super(map,
DEFAULT_NAME_IDENTIFIER,
DEFAULT_ALIAS_IDENTIFIER,
DEFAULT_DESCRIPTION_IDENTIFIER) {
this.internalCompositionMap = ArrayList()
val serializedMaterials = map.getList <Map<String, Any>>(MineMeConstants.MINE_COMPOSITION_MATERIALS_IDENTIFIER)
serializedMaterials.mapTo(internalCompositionMap, ::MineMaterial)
}
val isEmpty: Boolean
get() = internalCompositionMap.isEmpty()
val compositionMap: List<MineMaterial>
get() = ArrayList(internalCompositionMap)
open val isRegistered get() = false
fun add(material: MineMaterial) {
internalCompositionMap.add(material)
sortList()
}
fun remove(material: MineMaterial) {
internalCompositionMap.remove(material)
sortList()
}
fun randomMaterial(): MineMaterial {
if (isEmpty) {
return MineMaterial.EMPTY
}
return compositionMap[random.nextInt(compositionMap.size)]
}
fun largestMaterial(): MineMaterial {
return largestMaterial(emptySet())
}
fun largestMaterial(filter: Set<Material>): MineMaterial {
val possibleMaterials = compositionMap.filter { !filter.contains(it.material) }
val toIterate = if (possibleMaterials.isNotEmpty()) {
possibleMaterials
} else {
compositionMap
}
return toIterate.max() ?: throw IllegalStateException("There are no materials in the composition!")
}
override fun serialize(): Map<String, Any> = immutableMap {
this[DEFAULT_NAME_IDENTIFIER] = name
this[DEFAULT_ALIAS_IDENTIFIER] = alias
this[DEFAULT_DESCRIPTION_IDENTIFIER] = description
this[MineMeConstants.MINE_COMPOSITION_MATERIALS_IDENTIFIER] = compositionMap.map(MineMaterial::serialize)
}
private fun sortList() {
Collections.sort(compositionMap)
}
fun serializeIndex(): Map<String, Any> = immutableMap {
this[MineMeConstants.ID_IDENTIFIER] = name
this[MineMeConstants.REGISTERED_IDENTIFIER] = isRegistered
}
operator fun contains(material: MineMaterial) = material in compositionMap
}
| 0
|
Kotlin
|
0
| 0
|
6cdfb74a10a5b78d929df9e8bd36b0da626378f4
| 3,067
|
MineMe2
|
Do What The F*ck You Want To Public License
|
embrace-android-sdk/src/test/java/io/embrace/android/embracesdk/MemoryWarningTest.kt
|
embrace-io
| 704,537,857
| false
|
{"Kotlin": 3108474, "C": 189946, "Java": 179438, "C++": 13140, "CMake": 4188}
|
package io.embrace.android.embracesdk
import com.squareup.moshi.JsonDataException
import io.embrace.android.embracesdk.payload.MemoryWarning
import org.junit.Assert.assertEquals
import org.junit.Test
internal class MemoryWarningTest {
private val info = MemoryWarning(16098234098234)
@Test
fun testSerialization() {
assertJsonMatchesGoldenFile("memory_warning_expected.json", info)
}
@Test
fun testDeserialization() {
val obj = deserializeJsonFromResource<MemoryWarning>("memory_warning_expected.json")
assertEquals(16098234098234, obj.timestamp)
}
@Test(expected = JsonDataException::class)
fun testEmptyObject() {
deserializeEmptyJsonString<MemoryWarning>()
}
}
| 9
|
Kotlin
|
7
| 130
|
7ae6904f31de6d7d3e2b5ec5093f8abcd0ccf884
| 742
|
embrace-android-sdk
|
Apache License 2.0
|
app/src/main/java/com/sms/pipe/data/datasourcesImpl/MessagingSlackDataSourceImpl.kt
|
Belak-Ghouas
| 506,643,638
| false
| null |
package com.sms.pipe.data.datasourcesImpl
import android.util.Log
import com.slack.api.Slack
import com.slack.api.methods.MethodsClient
import com.slack.api.methods.SlackApiException
import com.slack.api.methods.request.chat.ChatPostMessageRequest
import com.slack.api.methods.request.conversations.ConversationsListRequest
import com.slack.api.methods.response.chat.ChatPostMessageResponse
import com.slack.api.model.Conversation
import com.slack.api.model.ConversationType
import com.sms.pipe.data.datasources.MessagingSlackDataSource
import com.sms.pipe.data.models.ChannelModel
import com.sms.pipe.domain.models.PacketSlack
import com.sms.pipe.utils.ErrorCodes.MESSAGING_API_CALL_FAILED
import com.sms.pipe.utils.MessagingIsNotInitializedException
import com.sms.pipe.utils.Result
import java.io.IOException
class MessagingSlackDataSourceImpl : MessagingSlackDataSource {
private var slack :MethodsClient? = null
override fun initialize(token: String):Boolean {
slack = Slack.getInstance().methods(token)
return true
}
override suspend fun sendMessage(packetSlack: PacketSlack) {
Slack.getInstance().methods(packetSlack.token).let {
val request = ChatPostMessageRequest.builder()
.channel(packetSlack.to) // Use a channel ID `C1234567` is preferable
.text(packetSlack.content)
.build()
try {
val responses: ChatPostMessageResponse? = it.chatPostMessage(request)
Log.d("PostMessage Response",responses.toString())
}catch (exception:Exception){
Log.e("MessagingDataSource",exception.toString())
}
}?: kotlin.run {
throw MessagingIsNotInitializedException()
}
}
override suspend fun getConversationList():Result<List<ChannelModel>>{
val types: MutableList<ConversationType> = ArrayList()
types.add(ConversationType.PUBLIC_CHANNEL)
types.add(ConversationType.PRIVATE_CHANNEL)
val builder = ConversationsListRequest.builder().types(types)
slack?.let { methodsClient ->
try {
val listResponse = methodsClient.conversationsList(builder.build())
if (!listResponse.isOk) {
Log.e("API call failed: " , listResponse.error.toString())
}
val channels: List<Conversation> = listResponse.channels
Log.d("Conversation", channels.map { it.name }.toString())
return Result.Success(channels.map { ChannelModel(it.name) } )
} catch (e: IOException) {
Log.e("API call failed: " , e.toString())
} catch (e: SlackApiException) {
Log.e("API call failed: " , e.toString())
}
} ?: kotlin.run {
throw MessagingIsNotInitializedException()
}
return Result.Failure(MESSAGING_API_CALL_FAILED,"failed to get conversation list")
}
}
| 1
|
Kotlin
|
0
| 2
|
2151d21769f5c783b1bb84649438ced1e101b3b3
| 2,996
|
Sms-Transfer
|
MIT License
|
kotlin-antd/antd-samples/src/main/kotlin/samples/autocomplete/App.kt
|
xlj44400
| 248,655,590
| true
|
{"Kotlin": 1516065, "HTML": 1503}
|
package samples.autocomplete
import react.*
import react.dom.*
import styled.*
object AutoCompleteStyles : StyleSheet("auto-complete", isStatic = true) {
val container by css {}
val basic by css {}
val custom by css {}
val options by css {}
val nonCaseSensitive by css {}
}
class AutoCompleteApp : RComponent<RProps, RState>() {
override fun RBuilder.render() {
h2 { +"AutoComplete" }
styledDiv {
css { +AutoCompleteStyles.container }
basic()
custom()
options()
nonCaseSensitive()
}
}
}
fun RBuilder.autoCompleteApp() = child(AutoCompleteApp::class) {}
| 0
|
Kotlin
|
0
| 0
|
ce8216c0332abdfefcc0a06cf5fbbbf24e669931
| 669
|
kotlin-js-wrappers
|
Apache License 2.0
|
mybatis-ext-core/src/main/kotlin/com/github/xsi640/mybatis/core/anotations.kt
|
xsi640
| 533,179,826
| false
| null |
package com.github.xsi640.mybatis.core
import org.apache.ibatis.type.JdbcType
import org.apache.ibatis.type.TypeHandler
import kotlin.reflect.KClass
@MustBeDocumented
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class Table(
val schema: String = "",
val name: String = ""
)
@MustBeDocumented
@Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class Column(
val name: String = "",
val nullable: Boolean = true,
)
@MustBeDocumented
@Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class Converter(
val javaType: KClass<*> = Void::class,
val jdbcType: JdbcType = JdbcType.UNDEFINED,
val typeHandler: KClass<out TypeHandler<*>> = EmptyTypeHandler::class
)
@MustBeDocumented
@Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class Id(
val generate: Boolean = false
)
@MustBeDocumented
@Target(AnnotationTarget.CLASS)
@Retention(AnnotationRetention.RUNTIME)
annotation class Index(
val name: String = "",
val properties: Array<String> = [],
val unique: Boolean = false
)
@MustBeDocumented
@Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class Ignore
@MustBeDocumented
@Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class Temporal(
val type: TemporalType = TemporalType.TIMESTAMP
)
@MustBeDocumented
@Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class Embedded
@MustBeDocumented
@Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class CreatedBy
@MustBeDocumented
@Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class CreatedDate
@MustBeDocumented
@Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class LastModifiedBy
@MustBeDocumented
@Target(AnnotationTarget.FIELD, AnnotationTarget.PROPERTY)
@Retention(AnnotationRetention.RUNTIME)
annotation class LastModifiedDate
enum class TemporalType {
DATE,
TIME,
TIMESTAMP
}
annotation class NoArg
| 0
|
Kotlin
|
0
| 0
|
3da072ecebe8d802308b33ee86e926de08fe2855
| 2,399
|
mybatis-ext-spring-boot-starter
|
Apache License 2.0
|
widgets/src/iosMain/kotlin/dev/icerock/moko/widgets/factory/SystemInputViewFactory.kt
|
LeNcE1
| 241,057,818
| true
|
{"Kotlin": 468937, "Swift": 1465, "Ruby": 1012}
|
/*
* Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.moko.widgets.factory
import dev.icerock.moko.graphics.Color
import dev.icerock.moko.graphics.toUIColor
import dev.icerock.moko.widgets.InputWidget
import dev.icerock.moko.widgets.core.ViewBundle
import dev.icerock.moko.widgets.core.ViewFactory
import dev.icerock.moko.widgets.core.ViewFactoryContext
import dev.icerock.moko.widgets.objc.setAssociatedObject
import dev.icerock.moko.widgets.style.applyInputTypeIfNeeded
import dev.icerock.moko.widgets.style.background.Background
import dev.icerock.moko.widgets.style.view.*
import dev.icerock.moko.widgets.utils.applyBackgroundIfNeeded
import dev.icerock.moko.widgets.utils.applyTextStyleIfNeeded
import dev.icerock.moko.widgets.utils.bind
import dev.icerock.moko.widgets.utils.setEventHandler
import dev.icerock.moko.widgets.utils.DefaultTextFormatter
import dev.icerock.moko.widgets.utils.toIosPattern
import dev.icerock.moko.widgets.utils.DefaultFormatterUITextFieldDelegate
import kotlinx.cinterop.readValue
import platform.CoreGraphics.CGRectZero
import platform.Foundation.NSMutableAttributedString
import platform.Foundation.create
import platform.UIKit.NSForegroundColorAttributeName
import platform.UIKit.NSTextAlignmentCenter
import platform.UIKit.NSTextAlignmentLeft
import platform.UIKit.NSTextAlignmentRight
import platform.UIKit.UIControlContentVerticalAlignmentBottom
import platform.UIKit.UIControlContentVerticalAlignmentCenter
import platform.UIKit.UIControlContentVerticalAlignmentTop
import platform.UIKit.UIControlEventEditingChanged
import platform.UIKit.UITextBorderStyle
import platform.UIKit.UITextField
import platform.UIKit.clipsToBounds
import platform.UIKit.translatesAutoresizingMaskIntoConstraints
import platform.UIKit.addSubview
import platform.UIKit.UIView
import platform.UIKit.UITextFieldDelegateProtocol
actual class SystemInputViewFactory actual constructor(
private val background: Background?,
private val margins: MarginValues?,
private val padding: PaddingValues?,
private val textStyle: TextStyle?,
private val labelTextColor: Color?,
private val textHorizontalAlignment: TextHorizontalAlignment?,
private val textVerticalAlignment: TextVerticalAlignment?,
private val iosFieldBorderStyle: IOSFieldBorderStyle?
) : ViewFactory<InputWidget<out WidgetSize>> {
override fun <WS : WidgetSize> build(
widget: InputWidget<out WidgetSize>,
size: WS,
viewFactoryContext: ViewFactoryContext
): ViewBundle<WS> {
val backgroundConfig = background
val textField = UITextField(frame = CGRectZero.readValue()).apply {
translatesAutoresizingMaskIntoConstraints = false
applyBackgroundIfNeeded(backgroundConfig)
applyTextStyleIfNeeded(textStyle)
applyInputTypeIfNeeded(widget.inputType)
clipsToBounds = true
when (textHorizontalAlignment) {
TextHorizontalAlignment.LEFT -> textAlignment = NSTextAlignmentLeft
TextHorizontalAlignment.CENTER -> textAlignment = NSTextAlignmentCenter
TextHorizontalAlignment.RIGHT -> textAlignment = NSTextAlignmentRight
null -> {
}
}
when (textVerticalAlignment) {
TextVerticalAlignment.TOP -> contentVerticalAlignment =
UIControlContentVerticalAlignmentTop
TextVerticalAlignment.MIDDLE -> contentVerticalAlignment =
UIControlContentVerticalAlignmentCenter
TextVerticalAlignment.BOTTOM -> contentVerticalAlignment =
UIControlContentVerticalAlignmentBottom
null -> {
}
}
borderStyle = when (iosFieldBorderStyle) {
IOSFieldBorderStyle.NONE -> UITextBorderStyle.UITextBorderStyleNone
IOSFieldBorderStyle.LINE -> UITextBorderStyle.UITextBorderStyleLine
IOSFieldBorderStyle.BEZEL -> UITextBorderStyle.UITextBorderStyleBezel
IOSFieldBorderStyle.ROUNDED, null -> UITextBorderStyle.UITextBorderStyleRoundedRect
}
if (labelTextColor != null) {
val attrString = NSMutableAttributedString.create(
string = widget.label.value.localized(),
attributes = mapOf<Any?, Any?>(
NSForegroundColorAttributeName to labelTextColor.toUIColor()
)
)
setAttributedPlaceholder(
attributedPlaceholder = attrString
)
}
}
if (widget.inputType?.mask != null) {
val delegate = DefaultFormatterUITextFieldDelegate(
inputFormatter = DefaultTextFormatter(
widget.inputType.mask.toIosPattern(),
patternSymbol = '#'
)
)
textField.delegate = delegate
setAssociatedObject(textField, delegate)
}
textField.setEventHandler(UIControlEventEditingChanged) {
val currentValue = widget.field.data.value
val newValue = textField.text
if (currentValue != newValue) {
widget.field.data.value = newValue.orEmpty()
}
}
widget.enabled?.bind { textField.enabled = it }
widget.label.bind { textField.placeholder = it.localized() }
widget.field.data.bind { textField.text = it }
return ViewBundle(
view = textField,
size = size,
margins = margins
)
}
}
| 0
| null |
0
| 0
|
5ad5080aba2d4e3a2ab6e76e7d0ea8c405b9dc97
| 5,736
|
moko-widgets
|
Apache License 2.0
|
app/src/main/java/com/ilhomsoliev/paging/presentation/ui/main/MainScreen.kt
|
ilhomsoliev
| 672,033,927
| false
| null |
package com.ilhomsoliev.paging.presentation.ui.main
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.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.lazy.itemsIndexed
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
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.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions.withCrossFade
import com.bumptech.glide.request.RequestOptions
import com.ilhomsoliev.paging.presentation.model.CharacterModel
import com.ilhomsoliev.paging.presentation.viewmodel.MainViewModel
import com.skydoves.landscapist.ShimmerParams
import com.skydoves.landscapist.glide.GlideImage
@Composable
fun MainScreen(
vm: MainViewModel,
navController: NavController,
) {
val charactersPagingState by vm.charactersPagingState.collectAsState()
Column(
modifier = Modifier
.fillMaxSize()
.background(MaterialTheme.colorScheme.background)
) {
LazyColumn(modifier = Modifier
.padding(horizontal = 16.dp)
.background(MaterialTheme.colorScheme.background), content = {
itemsIndexed(charactersPagingState.list, key = { _, item ->
item.id
}) { index, item ->
LaunchedEffect(key1 = Unit, block = {
vm.onNewPosition(index)
})
Spacer(modifier = Modifier.height(4.dp))
CharacterItem(
modifier = Modifier
.fillMaxWidth()
.height(160.dp)
.clip(RoundedCornerShape(14.dp))
.background(MaterialTheme.colorScheme.surface)
.clickable {
navController.navigate("details/${item.id}")
}, characterModel = item
)
Spacer(modifier = Modifier.height(4.dp))
}
item {
if (charactersPagingState.isLoading) {
Box(
modifier = Modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator()
}
}
}
})
}
}
@Composable
fun CharacterItem(
modifier: Modifier,
characterModel: CharacterModel
) {
Row(modifier = modifier) {
/*val thumbnailRequest = Glide.with(LocalContext.current)
.asBitmap()
.load("https://picsum.photos/50/50?image=0")*/
GlideImage(
imageModel = characterModel.image,
requestBuilder = Glide
.with(LocalContext.current)
.asBitmap()
.apply(RequestOptions().diskCacheStrategy(DiskCacheStrategy.NONE))
.autoClone()
//.thumbnail(thumbnailRequest)
.transition(withCrossFade()),
modifier = Modifier.width(160.dp),
shimmerParams = ShimmerParams(
baseColor = MaterialTheme.colorScheme.surface,
highlightColor = MaterialTheme.colorScheme.primary
),
failure = {
Text(text = "image request failed.")
})
Column(
modifier = Modifier
.fillMaxWidth()
.fillMaxHeight()
.background(MaterialTheme.colorScheme.surface)
.padding(horizontal = 16.dp, vertical = 12.dp),
verticalArrangement = Arrangement.SpaceBetween
) {
Text(text = characterModel.name)
// Status
Row(verticalAlignment = Alignment.CenterVertically) {
Box(
modifier = Modifier
.size(12.dp)
.clip(CircleShape)
.background(if (characterModel.status == "Alive") Color.Green else if (characterModel.status == "Dead") Color.Red else Color.Gray)
)
Text(
modifier = Modifier.padding(start = 6.dp),
text = characterModel.status + " - " + characterModel.species
)
}
// Location
Column {
Text(text = "Last known location:")
Text(text = characterModel.location)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
806d4484d80dc4a38e0b6a7839d9142c80079e16
| 5,794
|
CustomPagingCompose
|
Apache License 2.0
|
app/app/src/main/java/xyz/mirage/app/business/interactors/account/UpdateAccount.kt
|
sentrionic
| 378,704,735
| false
| null |
package xyz.mirage.app.business.interactors.account
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.flow
import okhttp3.MultipartBody
import okhttp3.RequestBody
import xyz.mirage.app.business.datasources.cache.account.AccountDao
import xyz.mirage.app.business.datasources.network.core.handleUseCaseException
import xyz.mirage.app.business.datasources.network.main.account.AccountService
import xyz.mirage.app.business.domain.core.DataState
import xyz.mirage.app.business.domain.core.MessageType
import xyz.mirage.app.business.domain.core.Response
import xyz.mirage.app.business.domain.core.SuccessHandling.Companion.SUCCESS_ACCOUNT_UPDATED
import xyz.mirage.app.business.domain.core.UIComponentType
import xyz.mirage.app.business.domain.models.Account
class UpdateAccount(
private val service: AccountService,
private val cache: AccountDao,
) {
fun execute(
email: RequestBody,
displayName: RequestBody,
username: RequestBody,
bio: RequestBody?,
image: MultipartBody.Part?,
banner: MultipartBody.Part?,
): Flow<DataState<Account>> = flow {
emit(DataState.loading())
// Update network
val response = service.updateAccount(
email = email,
displayName = displayName,
username = username,
bio = bio,
image = image,
banner = banner
)
// update cache
cache.updateAccount(
id = response.id,
email = response.email,
displayName = response.displayName,
username = response.username,
bio = response.bio,
image = response.image,
banner = response.banner
)
// Tell the UI it was successful
emit(
DataState.data(
data = response.toAccount(),
response = Response(
message = SUCCESS_ACCOUNT_UPDATED,
uiComponentType = UIComponentType.Snackbar(),
messageType = MessageType.Success()
)
)
)
}.catch { e ->
emit(handleUseCaseException(e))
}
}
| 0
|
Kotlin
|
2
| 1
|
8f50fc8244f16b43b8e054e79bcd50e98765a0e1
| 2,232
|
Mirage
|
MIT License
|
utils/leaderboard/src/main/kotlin/dev/schlaubi/mikbot/util_plugins/leaderboard/gdpr/LeaderBoardGDPRExtension.kt
|
DRSchlaubi
| 409,332,765
| false
| null |
package dev.schlaubi.mikbot.util_plugins.leaderboard.gdpr
import dev.schlaubi.mikbot.core.gdpr.api.DataPoint
import dev.schlaubi.mikbot.core.gdpr.api.GDPRExtensionPoint
import org.pf4j.Extension
@Extension
class LeaderBoardGDPRExtension : GDPRExtensionPoint {
override fun provideDataPoints(): List<DataPoint> = listOf(LeaderBoardDataPoint)
}
| 23
|
Kotlin
|
11
| 31
|
ada5a2d41fa4f9aa4f6b387eaee5ba200d7e6e11
| 349
|
mikbot
|
MIT License
|
src/main/kotlin/io/github/ranolp/mfsjea/Mfsjea.kt
|
fossabot
| 130,048,655
| true
|
{"Kotlin": 20955}
|
package io.github.ranolp.mfsjea
import io.github.ranolp.mfsjea.grader.Hangul2350Grader
import io.github.ranolp.mfsjea.grader.NumberGrader
import io.github.ranolp.mfsjea.grader.ParenthesisGrader
import io.github.ranolp.mfsjea.keyboard.*
class Mfsjea(private val inputKeyboards: List<InputKeyboard>, private val outputKeyboards: List<OutputKeyboard>) {
init {
if (inputKeyboards.isEmpty() || outputKeyboards.isEmpty()) {
// todo: throw own exception, we must have one or more in/output keyboards!
}
}
fun jeamfsList(sentence: String): List<ConversionResult> {
val results = mutableListOf<ConversionResult>()
inputKeyboards.forEach { input ->
outputKeyboards.forEach { output ->
val result = output.combinator.combine(
sentence.map { input.getKeycode(it) }.map { output.getCharacter(it) }.joinToString(
""
)
)
results += ConversionResult(
input,
output,
result,
Hangul2350Grader.computeScore(result),
Hangul2350Grader.computeScore(result) +
NumberGrader.computeScore(result) +
ParenthesisGrader.computeScore(result) * 10
)
}
}
return results.sortedByDescending { it.score }
}
fun jeamfsAuto(sentence: String): ConversionResult = jeamfsList(sentence).first()
companion object {
val DEFAULT: Mfsjea = Mfsjea(listOf(QwertyKeyboard, DvorakKeyboard, ColemakKeyboard), listOf(DubeolStandardKeyboard, Sebeol390Keyboard, SebeolFinalKeyboard))
}
}
| 0
|
Kotlin
|
0
| 0
|
d6ee3d28cc5cc613fc317e74985331c9b7c38d85
| 1,746
|
mfsjea.jvm
|
Apache License 2.0
|
ml_inference_offloading/src/main/java/ai/nnstreamer/ml/inference/offloading/data/OffloadingServiceRepositoryImpl.kt
|
nnstreamer
| 780,757,108
| false
|
{"Kotlin": 39705}
|
package ai.nnstreamer.ml.inference.offloading.data
import kotlinx.coroutines.flow.Flow
import org.nnsuite.nnstreamer.Pipeline
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class OffloadingServiceRepositoryImpl @Inject constructor(private val offloadingServiceDao: OffloadingServiceDao) :
OffloadingServiceRepository {
override fun getAllOffloadingService(): Flow<List<OffloadingService>> =
offloadingServiceDao.getAllOffloadingService()
override fun getOffloadingService(serviceId: Int): Flow<OffloadingService> =
offloadingServiceDao.getOffloadingService(serviceId)
override suspend fun insertOffloadingService(offloadingService: OffloadingService) =
offloadingServiceDao.insert(offloadingService)
override suspend fun deleteOffloadingService(serviceId: Int) =
offloadingServiceDao.delete(serviceId)
override suspend fun updateOffloadingService(offloadingService: OffloadingService) =
offloadingServiceDao.update(offloadingService)
override fun changeStateOffloadingService(serviceId: Int, state: Pipeline.State) =
offloadingServiceDao.changeState(serviceId, state)
}
| 3
|
Kotlin
|
3
| 0
|
0b565d02ebe4f697dc1dde659c4a13ddd2b45057
| 1,174
|
nnstreamer-android
|
Apache License 2.0
|
src/main/java/com/mineinabyss/plugin/MineInAbyssPluginImpl.kt
|
MineInAbyss
| 115,279,675
| false
| null |
package com.mineinabyss.plugin
import com.mineinabyss.enchants.FrostAspectListener
import com.mineinabyss.exp.ExpListener
import com.mineinabyss.geary.minecraft.dsl.GearyAddon
import com.mineinabyss.geary.minecraft.dsl.gearyAddon
import com.mineinabyss.idofront.commands.execution.IdofrontCommandExecutor
import com.mineinabyss.idofront.plugin.getServiceOrNull
import com.mineinabyss.idofront.plugin.registerEvents
import com.mineinabyss.idofront.plugin.registerService
import com.mineinabyss.idofront.slimjar.IdofrontSlimjar
import com.mineinabyss.mineinabyss.core.*
import net.milkbowl.vault.economy.Economy
class MineInAbyssPluginImpl : MineInAbyssPlugin() {
override fun onLoad() {
IdofrontSlimjar.loadToLibraryLoader(this)
}
override fun onEnable() {
gearyAddon {
registerService<AbyssContext>(object : AbyssContext {
override val econ = getServiceOrNull<Economy>("Vault")
override val addonScope: GearyAddon = this@gearyAddon
override val commandExecutor = object : IdofrontCommandExecutor() {
override val commands = commands(this@MineInAbyssPluginImpl) { }
}
})
autoscan<AbyssFeature>(runNow = true)
autoscanAll()
}
val config = MIAConfigImpl()
config.load()
registerService<MIAConfig>(config)
registerService<AbyssWorldManager>(AbyssWorldManagerImpl())
registerEvents(
ExpListener(),
FrostAspectListener(),
)
}
}
| 12
|
Kotlin
|
23
| 45
|
3bcae467fd80dba68f5083ddd0d1711f7052fc50
| 1,573
|
MineInAbyss
|
MIT License
|
app/src/main/java/com/kleinreveche/playground/features/cafeteria/ui/AccompanimentMenuScreen.kt
|
KleinReveche
| 537,970,451
| false
|
{"Kotlin": 293106}
|
package com.kleinreveche.playground.features.cafeteria.ui
import androidx.compose.runtime.Composable
import androidx.compose.ui.tooling.preview.Preview
import com.kleinreveche.playground.features.cafeteria.datasource.DataSource
import com.kleinreveche.playground.features.cafeteria.model.MenuItem
import com.kleinreveche.playground.features.cafeteria.model.MenuItem.AccompanimentItem
@Suppress("UNCHECKED_CAST")
@Composable
fun AccompanimentMenuScreen(
options: List<AccompanimentItem>,
onCancelButtonClicked: () -> Unit,
onNextButtonClicked: () -> Unit,
onSelectionChanged: (AccompanimentItem) -> Unit
) {
BaseMenuScreen(
options = options,
onCancelButtonClicked = onCancelButtonClicked,
onNextButtonClicked = onNextButtonClicked,
onSelectionChanged = onSelectionChanged as (MenuItem) -> Unit
)
}
@Preview
@Composable
fun AccompanimentMenuPreview(){
AccompanimentMenuScreen(
options = DataSource.accompanimentMenuItems,
onNextButtonClicked = {},
onCancelButtonClicked = {},
onSelectionChanged = {}
)
}
| 0
|
Kotlin
|
0
| 0
|
062c3257ef1a434ed5b11ec947104908467e9f7f
| 1,102
|
Playground
|
Apache License 2.0
|
resources-generator/src/main/kotlin/dev/icerock/gradle/generator/resources/string/AppleStringResourceGenerator.kt
|
icerockdev
| 204,874,263
| false
|
{"Kotlin": 456033, "Shell": 1362}
|
/*
* Copyright 2024 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.gradle.generator.resources.string
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.CodeBlock
import com.squareup.kotlinpoet.KModifier
import com.squareup.kotlinpoet.TypeSpec.Builder
import dev.icerock.gradle.generator.Constants
import dev.icerock.gradle.generator.PlatformResourceGenerator
import dev.icerock.gradle.generator.addAppleContainerBundleInitializerProperty
import dev.icerock.gradle.generator.addValuesFunction
import dev.icerock.gradle.generator.localization.LanguageType
import dev.icerock.gradle.metadata.resource.StringMetadata
import dev.icerock.gradle.utils.convertXmlStringToLocalization
import java.io.File
internal class AppleStringResourceGenerator(
private val baseLocalizationRegion: String,
private val resourcesGenerationDir: File,
) : PlatformResourceGenerator<StringMetadata> {
override fun imports(): List<ClassName> = emptyList()
override fun generateInitializer(metadata: StringMetadata): CodeBlock {
return CodeBlock.of(
"StringResource(resourceId = %S, bundle = %L)",
metadata.key,
Constants.Apple.platformContainerBundlePropertyName
)
}
override fun generateResourceFiles(data: List<StringMetadata>) {
data.processLanguages().forEach { (lang, strings) ->
generateLanguageFile(
language = LanguageType.fromLanguage(lang),
strings = strings
)
}
}
override fun generateBeforeProperties(
builder: Builder,
metadata: List<StringMetadata>,
modifier: KModifier?,
) {
builder.addAppleContainerBundleInitializerProperty(modifier)
}
override fun generateAfterProperties(
builder: Builder,
metadata: List<StringMetadata>,
modifier: KModifier?,
) {
builder.addValuesFunction(
modifier = modifier,
metadata = metadata,
classType = Constants.stringResourceName
)
}
private fun generateLanguageFile(language: LanguageType, strings: Map<String, String>) {
val resDir = File(resourcesGenerationDir, language.appleResourcesDir)
val localizableFile = File(resDir, "Localizable.strings")
resDir.mkdirs()
val content = strings.mapValues { (_, value) ->
value.convertXmlStringToLocalization()
}.map { (key, value) ->
"\"$key\" = \"$value\";"
}.joinToString("\n")
localizableFile.writeText(content)
if (language == LanguageType.Base) {
val regionDir = File(resourcesGenerationDir, "$baseLocalizationRegion.lproj")
regionDir.mkdirs()
val regionFile = File(regionDir, "Localizable.strings")
regionFile.writeText(content)
}
}
}
| 147
|
Kotlin
|
121
| 1,077
|
2c484808c928a13ab4d0523b82db3b5ab4e90db5
| 2,930
|
moko-resources
|
Apache License 2.0
|
src/main/kotlin/day11/Code.kt
|
fcolasuonno
| 317,324,330
| false
| null |
package day11
import isDebug
import java.io.File
import kotlin.system.measureTimeMillis
fun main() {
val name = if (isDebug()) "test.txt" else "input.txt"
System.err.println(name)
val dir = ::main::class.java.`package`.name
val input = File("src/main/kotlin/$dir/$name").readLines()
val (parsed, size) = parse(input)
System.err.println(measureTimeMillis {
part1(parsed)
})
System.err.println(measureTimeMillis {
part2(parsed, size)
})
}
fun parse(input: List<String>) = input.flatMapIndexed { j, line ->
line.mapIndexedNotNull { i, c ->
(i to j).takeIf { c != '.' }?.to(c == '#')
}
}.toMap() to maxOf(input.first().count(), input.count())
fun part1(input: Map<Pair<Int, Int>, Boolean>) {
val neighboursMap = input.mapValues { (k, _) -> k.neighbours.filter { it in input } }
val res = generateSequence(input) { seats ->
seats.mapValues { (k, occupied) ->
val neighboursCount = neighboursMap.getValue(k).count {
seats.getOrDefault(it, false)
}
when {
!occupied && neighboursCount == 0 -> true
occupied && neighboursCount >= 4 -> false
else -> occupied
}
}
}.zipWithNext().first { (first, second) -> first == second }.second.values.count { it }
println("Part 1 = $res")
}
fun part2(input: Map<Pair<Int, Int>, Boolean>, size: Int) {
val neighboursMap = input.mapValues { (k, _) ->
(1..size).asSequence().run {
listOfNotNull(
map { (k.first - it) to k.second }.firstOrNull { it in input },
map { (k.first - it) to (k.second - it) }.firstOrNull { it in input },
map { (k.first - it) to (k.second + it) }.firstOrNull { it in input },
map { (k.first + it) to k.second }.firstOrNull { it in input },
map { (k.first + it) to (k.second - it) }.firstOrNull { it in input },
map { (k.first + it) to (k.second + it) }.firstOrNull { it in input },
map { (k.first) to (k.second - it) }.firstOrNull { it in input },
map { (k.first) to (k.second + it) }.firstOrNull { it in input })
}
}
val res = generateSequence(input) { seats ->
seats.mapValues { (k, occupied) ->
val neighboursCount = neighboursMap.getValue(k).count {
seats.getOrDefault(it, false)
}
when {
!occupied && neighboursCount == 0 -> true
occupied && neighboursCount >= 5 -> false
else -> occupied
}
}
}.zipWithNext().first { (first, second) -> first == second }.second.values.count { it }
println("Part 2 = $res")
}
val Pair<Int, Int>.neighbours: List<Pair<Int, Int>>
get() = listOf((first - 1) to (second - 1), (first) to (second - 1), (first + 1) to (second - 1),
(first - 1) to second, (first + 1) to second,
(first - 1) to (second + 1), (first) to (second + 1), (first + 1) to (second + 1))
| 0
|
Kotlin
|
0
| 0
|
e7408e9d513315ea3b48dbcd31209d3dc068462d
| 3,125
|
AOC2020
|
MIT License
|
app/src/test/java/com/ikarimeister/loginapp/ui/presenter/LoginPresenterTest.kt
|
IkariMeister
| 280,252,724
| false
| null |
package com.ikarimeister.loginapp.ui.presenter
import arrow.core.left
import arrow.core.right
import com.ikarimeister.loginapp.domain.model.DataNotFound
import com.ikarimeister.loginapp.domain.model.IncorrectCredentials
import com.ikarimeister.loginapp.domain.model.LoginError
import com.ikarimeister.loginapp.domain.model.ValidationErrors
import com.ikarimeister.loginapp.domain.usecases.GetProfile
import com.ikarimeister.loginapp.domain.usecases.Login
import com.ikarimeister.loginapp.ui.view.LoginView
import com.ikarimeister.loginapp.utils.MotherObject.email
import com.ikarimeister.loginapp.utils.MotherObject.emptyEmail
import com.ikarimeister.loginapp.utils.MotherObject.emptyPassword
import com.ikarimeister.loginapp.utils.MotherObject.password
import com.ikarimeister.loginapp.utils.MotherObject.profile
import io.mockk.*
import io.mockk.impl.annotations.MockK
import kotlinx.coroutines.Dispatchers
import org.junit.After
import org.junit.Before
import org.junit.Test
class LoginPresenterTest {
@MockK
lateinit var login: Login
@MockK
lateinit var islogged: GetProfile
@MockK
lateinit var view: LoginView
private lateinit var presenter: LoginPresenter
@Before
fun setUp() {
MockKAnnotations.init(this)
presenter = LoginPresenter(view, login, islogged, Dispatchers.Unconfined, Dispatchers.Unconfined)
presenter.startPresenter()
}
@After
fun tearDown() {
presenter.stopPresenter()
}
@Test
fun `View should show and hide loading and show an error when Login return error`() {
givenAView()
coEvery { login(any()) } returns IncorrectCredentials.left()
presenter.doLogin(email, password)
verifyOrder {
view.showLoading()
view.hideLoading()
view.showError(IncorrectCredentials)
}
}
@Test
fun `View should show and hide loading and navigate to logged screen when Login return OK`() {
givenAView()
coEvery { login(any()) } returns profile.right()
presenter.doLogin(email, password)
verifyOrder {
view.showLoading()
view.hideLoading()
view.navigateToLoggedScreen()
}
}
@Test
fun `View should show and hide loading and navigate to logged screen when starts and a Token is stored`() {
givenAView()
coEvery { islogged() } returns profile.right()
presenter.onStart()
verifyOrder {
view.showLoading()
view.hideLoading()
view.navigateToLoggedScreen()
}
}
@Test
fun `View should show and hide loading and show logging form when starts and a Token is not stored`() {
givenAView()
coEvery { islogged() } returns DataNotFound.left()
presenter.onStart()
verifyOrder {
view.showLoading()
view.hideLoading()
view.showLoginForm()
}
}
@Test
fun `View should show validation errors in login form when user is not valid`() {
givenAView()
presenter.doLogin(emptyEmail, emptyPassword)
verify { view.showError(any<List<ValidationErrors>>()) }
}
private fun givenAView() {
every { view.showLoading() } returns Unit
every { view.hideLoading() } returns Unit
every { view.showError(any<LoginError>()) } returns Unit
every { view.showError(any<List<ValidationErrors>>()) } returns Unit
every { view.navigateToLoggedScreen() } returns Unit
}
}
| 4
|
Kotlin
|
0
| 1
|
1b4bae7240bdc8c871bc444fccf0a6971af933f3
| 3,561
|
LoginApp
|
Apache License 2.0
|
app/src/main/java/com/example/conservationmoney/MyDatabaseHelper.kt
|
zpzpna
| 440,109,572
| false
| null |
package com.example.conservationmoney
import android.content.Context
import android.database.Cursor
import android.database.sqlite.SQLiteDatabase
import android.database.sqlite.SQLiteOpenHelper
import android.widget.Toast
//模仿书上代码创建存储记账列表信息数据库
class MyDatabaseHelper(val context: Context, name: String, version: Int) :
SQLiteOpenHelper(context, name, null, version) {
private val createBook = "create table if not exists List (" +
" id integer primary key autoincrement," +
"typename char," +
"date char," +
"data char)"
override fun onCreate(db: SQLiteDatabase) {
db.execSQL(createBook)
Toast.makeText(context, "table list is ok", Toast.LENGTH_SHORT).show()
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
}
}
| 0
|
Kotlin
|
0
| 3
|
043b4bace924999a24bc6afe1423efc358be3c6b
| 835
|
ConservationMoney
|
Apache License 2.0
|
server/src/server/Parse.kt
|
jonnyzzz
| 25,689,268
| false
| null |
/*
* Copyright 2000-2014 Eugene Petrenko
*
* 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.jonnyzzz.teamcity.plugins.meta.web
import java.io.File
import jetbrains.buildServer.util.FileUtil
import org.jdom.xpath.XPath
import org.jdom.Attribute
import org.jdom.Text
import kotlin.platform.platformStatic
data public class MetaRunnerInfo(val xml: File,
val id: String,
val name: String,
val description: String,
val subRunners: List<String>)
public object MetaParser {
[platformStatic]
public fun parseRunnerSpec(xml : File) : MetaRunnerInfo? {
try {
val root = FileUtil.parseDocument(xml, false)!!
val name = XPath.newInstance("@name")?.selectSingleNode(root) as Attribute
val descr = XPath.newInstance("description/text()")?.selectSingleNode(root) as Text
val runners = XPath.newInstance("settings/build-runners/runner/@type")!!.selectNodes(root)!! map {it as Attribute}
return MetaRunnerInfo(
xml,
FileUtil.getNameWithoutExtension(xml),
name.getValue()!!,
descr.getValue()!!,
runners.map { it -> it.getValue()!! }.toSortedSet().toList())
} catch (e: Throwable) {
return null
}
}
}
| 1
| null |
1
| 4
|
439362155b412449d0b440d70e2678779eaab083
| 1,864
|
TeamCity.Meta
|
Apache License 2.0
|
app/src/androidTest/java/com/example/mytrainingpal/model/WorkoutEntryExerciseMapDaoTest.kt
|
MichaelBuessemeyer
| 572,939,495
| false
|
{"Kotlin": 256987}
|
package com.example.mytrainingpal.model
import android.content.Context
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.room.Room
import androidx.test.core.app.ApplicationProvider
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.example.mytrainingpal.model.daos.ExerciseDao
import com.example.mytrainingpal.model.daos.WorkoutEntryDao
import com.example.mytrainingpal.model.daos.WorkoutEntryExerciseMapDao
import com.example.mytrainingpal.model.entities.Exercise
import com.example.mytrainingpal.model.entities.WorkoutEntry
import com.example.mytrainingpal.model.entities.WorkoutEntryExerciseMap
import com.example.mytrainingpal.utils.getOrAwaitValue
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import java.io.IOException
import java.util.*
@RunWith(AndroidJUnit4::class)
class WorkoutEntryExerciseMapDaoTest {
// Run tasks synchronously by Jose Alcérreca. See TestingUtils.kt.
@Rule
@JvmField
val instantExecutorRule = InstantTaskExecutorRule()
private lateinit var workoutEntryDao: WorkoutEntryDao
private lateinit var exerciseDao: ExerciseDao
private lateinit var workoutEntryExerciseMapDao: WorkoutEntryExerciseMapDao
private lateinit var db: TheMuscleBase
@Before
fun createDb() {
val context = ApplicationProvider.getApplicationContext<Context>()
db = Room.inMemoryDatabaseBuilder(
context, TheMuscleBase::class.java
).build()
workoutEntryDao = db.getWorkoutEntryDao()
exerciseDao = db.getExerciseDao()
workoutEntryExerciseMapDao = db.getWorkoutEntryExerciseMapDao()
}
@After
@Throws(IOException::class)
fun closeDb() {
db.close()
}
@Test
@Throws(Exception::class)
fun testInsert() {
val workoutEntry = WorkoutEntry(
null,
GregorianCalendar(2022, Calendar.DECEMBER, 1).time,
GregorianCalendar(
2022,
Calendar.DECEMBER,
1,
12,
30
).time,
GregorianCalendar(
2022,
Calendar.DECEMBER,
1,
14,
30
).time,
"",
null
)
val workoutEntryId = workoutEntryDao.insert(workoutEntry)
val exercise = Exercise(null, "Biceps Curls", "exercise_1")
val exerciseId = exerciseDao.insert(exercise)
val workoutEntryExerciseMap =
WorkoutEntryExerciseMap(workoutEntryId, exerciseId, 4, "10,10,10,10", 20)
val workoutEntryExerciseMapId = workoutEntryExerciseMapDao.insert(workoutEntryExerciseMap)
val workoutEntryExerciseMapRet =
workoutEntryExerciseMapDao.getWorkoutEntryExerciseMapByWorkoutId(workoutEntryId)
assertThat(workoutEntryExerciseMapRet, equalTo(workoutEntryExerciseMap))
}
@Test
@Throws(Exception::class)
fun testDelete() {
val workoutEntry = WorkoutEntry(
null,
GregorianCalendar(2022, Calendar.DECEMBER, 1).time,
GregorianCalendar(
2022,
Calendar.DECEMBER,
1,
12,
30
).time,
GregorianCalendar(
2022,
Calendar.DECEMBER,
1,
14,
30
).time,
"",
null
)
val workoutEntryId = workoutEntryDao.insert(workoutEntry)
val exercise = Exercise(null, "Biceps Curls", "exercise_1")
val exerciseId = exerciseDao.insert(exercise)
val workoutEntryExerciseMap =
WorkoutEntryExerciseMap(workoutEntryId, exerciseId, 4, "10,10,10,10", 20)
val workoutEntryExerciseMapId = workoutEntryExerciseMapDao.insert(workoutEntryExerciseMap)
val workoutEntryExerciseMapRet =
workoutEntryExerciseMapDao.getWorkoutEntryExerciseMapByWorkoutId(workoutEntryId)
assertThat(workoutEntryExerciseMapRet, equalTo(workoutEntryExerciseMap))
var allMaps = workoutEntryExerciseMapDao.getAllWorkoutEntryExerciseMaps().getOrAwaitValue()
assertEquals(1, allMaps.size)
workoutEntryExerciseMapDao.deleteWorkoutEntryExerciseMap(workoutEntryExerciseMap)
allMaps = workoutEntryExerciseMapDao.getAllWorkoutEntryExerciseMaps().getOrAwaitValue()
assertEquals(0, allMaps.size)
}
@Test
@Throws(Exception::class)
fun testUpdate() {
val workoutEntry = WorkoutEntry(
null,
GregorianCalendar(2022, Calendar.DECEMBER, 1).time,
GregorianCalendar(
2022,
Calendar.DECEMBER,
1,
12,
30
).time,
GregorianCalendar(
2022,
Calendar.DECEMBER,
1,
14,
30
).time,
"",
null
)
val workoutEntryId = workoutEntryDao.insert(workoutEntry)
val exercise = Exercise(null, "Biceps Curls", "exercise_1")
val exerciseId = exerciseDao.insert(exercise)
var workoutEntryExerciseMap =
WorkoutEntryExerciseMap(workoutEntryId, exerciseId, 4, "10,10,10,10", 20)
val workoutEntryExerciseMapId = workoutEntryExerciseMapDao.insert(workoutEntryExerciseMap)
var workoutEntryExerciseMapRet =
workoutEntryExerciseMapDao.getWorkoutEntryExerciseMapByWorkoutId(workoutEntryId)
assertThat(workoutEntryExerciseMapRet, equalTo(workoutEntryExerciseMap))
val updatedReps = "10,10,8,8"
workoutEntryExerciseMap = workoutEntryExerciseMap.copy(reps = updatedReps)
workoutEntryExerciseMapDao.updateWorkoutEntryExerciseMap(workoutEntryExerciseMap)
workoutEntryExerciseMapRet =
workoutEntryExerciseMapDao.getWorkoutEntryExerciseMapByWorkoutId(workoutEntryId)
assertThat(workoutEntryExerciseMapRet, equalTo(workoutEntryExerciseMap))
}
}
| 14
|
Kotlin
|
0
| 2
|
5ef8c98c684bf2bb863dc6781a457c16ab8bb6e1
| 6,289
|
MyTrainingsPal
|
Apache License 2.0
|
src/jsMain/kotlin/ehn/techiop/hcert/kotlin/trust/CoseCreationAdapter.kt
|
asit-fdraschbacher
| 373,781,190
| true
|
{"Kotlin": 195978, "HTML": 3567, "JavaScript": 1308}
|
package ehn.techiop.hcert.kotlin.trust
import ehn.techiop.hcert.kotlin.chain.toByteArray
import ehn.techiop.hcert.kotlin.crypto.Cose
import ehn.techiop.hcert.kotlin.crypto.PrivKey
import kotlin.js.json
actual class CoseCreationAdapter actual constructor(private val content: ByteArray) {
private val header = json()
private var encoded: ByteArray = byteArrayOf()
actual fun addProtectedAttributeByteArray(key: Int, value: Any) {
header.set(key.toString(), value)
}
actual fun sign(key: PrivKey<*>) {
encoded = Cose.sign(header, content, key).toByteArray()
}
actual fun encode(): ByteArray {
return encoded
}
// suspend fun <T> Promise<T>.await(): T = suspendCoroutine { cont ->
// then({ cont.resume(it) }, { cont.resumeWithException(it) })
// }
}
| 0
| null |
0
| 0
|
f347dc143010e5299765551df41bc4228ad728d2
| 836
|
hcert-kotlin
|
Apache License 2.0
|
src/main/kotlin/kotlinmud/mob/skill/impl/weapon/Dagger.kt
|
danielmunro
| 241,230,796
| false
| null |
package kotlinmud.mob.skill.impl.weapon
import kotlinmud.mob.skill.factory.clericAt
import kotlinmud.mob.skill.factory.mageAt
import kotlinmud.mob.skill.factory.thiefAt
import kotlinmud.mob.skill.factory.warriorAt
import kotlinmud.mob.skill.type.CreationGroupType
import kotlinmud.mob.skill.type.Customization
import kotlinmud.mob.skill.type.LearningDifficulty
import kotlinmud.mob.skill.type.Skill
import kotlinmud.mob.skill.type.SkillInvokesOn
import kotlinmud.mob.skill.type.SkillType
import kotlinmud.mob.specialization.type.SpecializationType
import kotlinmud.mob.type.Intent
class Dagger : Skill, Customization {
override val type = SkillType.DAGGER
override val levelObtained = mapOf(
warriorAt(1),
thiefAt(1),
clericAt(15),
mageAt(15)
)
override val difficulty = mapOf(
Pair(SpecializationType.WARRIOR, LearningDifficulty.EASY),
Pair(SpecializationType.THIEF, LearningDifficulty.EASY),
Pair(SpecializationType.CLERIC, LearningDifficulty.NORMAL),
Pair(SpecializationType.MAGE, LearningDifficulty.NORMAL)
)
override val intent = Intent.NEUTRAL
override val invokesOn = SkillInvokesOn.ATTACK_ROUND
override val name = "dagger"
override val points = 4
override val creationGroupType = CreationGroupType.SKILL
override val helpText = "tbd"
}
| 0
|
Kotlin
|
1
| 9
|
b7ee0d21ae813990896b1b8c6703da9bd1f1fc5b
| 1,355
|
kotlinmud
|
MIT License
|
eventscalendar/src/main/java/com/events/calendar/adapters/WeekPageAdapter.kt
|
kapw001
| 173,122,724
| false
| null |
//$Id$
package com.events.calendar.adapters
import android.content.Context
import android.support.v4.view.PagerAdapter
import android.view.View
import android.view.ViewGroup
import com.events.calendar.utils.EventsCalendarUtil
import com.events.calendar.views.EventsCalendar
import com.events.calendar.views.MonthView
import java.util.Calendar
class WeekPageAdapter(viewPager: EventsCalendar, startDay: Calendar, endDay: Calendar) : PagerAdapter() {
private val mMinMonth: Calendar
private val mMaxMonth: Calendar
private val mCount: Int
private val monthDatesGridLayoutsArray: Array<MonthView?>
private val mContext: Context
private val mMonthViewCallback: MonthView.Callback
init {
mContext = viewPager.context
mMonthViewCallback = viewPager
if (EventsCalendarUtil.isPastDay(startDay)) {
mMinMonth = startDay
} else {
mMinMonth = Calendar.getInstance()
}
if (EventsCalendarUtil.isFutureDay(endDay)) {
mMaxMonth = endDay
} else {
mMaxMonth = Calendar.getInstance()
}
mCount = EventsCalendarUtil.getWeekCount(mMinMonth, mMaxMonth)
monthDatesGridLayoutsArray = arrayOfNulls(mCount)
}
override fun getCount(): Int {
return mCount
}
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view === `object`
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val month = EventsCalendarUtil.getMonthForWeekPosition(mMinMonth, position)
val weekNo = EventsCalendarUtil.getWeekNo(mMinMonth, position)
val monthView = MonthView(mContext, month, EventsCalendarUtil.weekStartDay, weekNo)
monthView.setCallback(mMonthViewCallback)
monthDatesGridLayoutsArray[position] = monthView
container.addView(monthView)
return monthView
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(`object` as View)
}
fun getItem(position: Int): MonthView? {
return monthDatesGridLayoutsArray[position]
}
}
| 0
|
Kotlin
|
0
| 0
|
8dec6f4dbf0194b6b18dc2a40a7e7f1a7c1e0677
| 2,168
|
eventscalendar
|
Apache License 2.0
|
microservices/payment/src/main/kotlin/org/demo/CountResource.kt
|
Jason952742
| 717,304,260
| false
|
{"Rust": 765683, "Kotlin": 105553, "Python": 38087, "Shell": 8342, "Dockerfile": 3085, "HTML": 2067, "CSS": 1036, "Go": 338}
|
package org.demo
import jakarta.inject.Inject
import jakarta.ws.rs.GET
import jakarta.ws.rs.Path
import jakarta.ws.rs.Produces
import jakarta.ws.rs.core.MediaType
@Path("/count")
class CountResource {
@Inject
lateinit var counter: CounterBean
@GET
@Produces(MediaType.TEXT_PLAIN)
fun hello(): String {
return "count: " + counter.get()
}
}
| 0
|
Rust
|
0
| 2
|
180459e98c28362e54b7ba9865a4d7aa9ae5955d
| 375
|
multi-language-microservices-boilerplate
|
MIT License
|
mapdb-jcache/src/main/java/org/mapdb/jcache/MJMutableEntry.kt
|
jankotek
| 53,039,005
| false
| null |
package org.mapdb.jcache
import org.jsr107.ri.processor.MutableEntryOperation
import javax.cache.integration.CacheLoaderException
import javax.cache.processor.MutableEntry
class MJMutableEntry<K,V>(
private val key:K,
private val cache:MJCache<K,V>
): MutableEntry<K,V> {
internal var _value:V? = null
private var operation = MutableEntryOperation.NONE
override fun getKey() = key
override fun getValue():V? {
if(operation== MutableEntryOperation.NONE){
//load entry
if(_value==null && cache.map.containsKey(key)){ //containsKey is so valueCreator is not triggered by map.get()
_value = cache.map[key]
operation = MutableEntryOperation.ACCESS
}
}
if(_value==null && cache.isReadThrough)try{
// check for read-through
_value = cache.cacheLoader!!.load(key)
if(_value!=null)
operation = MutableEntryOperation.LOAD
}catch(e:Exception){
throw CacheLoaderException(e)
}
return _value
}
override fun <T : Any?> unwrap(clazz: Class<T>?): T {
if (clazz != null && clazz.isInstance(this)) {
return this as T
} else {
throw IllegalArgumentException("Class $clazz is unknown to this implementation")
}
}
override fun exists(): Boolean {
return (operation == MutableEntryOperation.NONE && cache.map.containsKey(key)) || _value != null;
}
override fun remove() {
_value = null;
operation =
if(operation == MutableEntryOperation.CREATE)
MutableEntryOperation.NONE
else
MutableEntryOperation.REMOVE
}
override fun setValue(value: V) {
operation =
if(cache.map.containsKey(key))
MutableEntryOperation.UPDATE
else
MutableEntryOperation.CREATE
this._value = value
}
fun operation() = operation;
}
| 2
| null |
2
| 2
|
d7c3a4935beee798ef19215ddccb5091bfffd031
| 2,081
|
mapdb-jcache
|
Apache License 2.0
|
app/src/main/java/com/kotlin/mvvm/boilerplate/ui/main/home/TrackDetailActivity.kt
|
kanwalNayyer
| 520,274,229
| false
|
{"Kotlin": 36488}
|
package com.kotlin.mvvm.boilerplate.ui.main.home
import android.os.Bundle
import com.kotlin.mvvm.boilerplate.R
import com.kotlin.mvvm.boilerplate.ui.main.base.BaseActivity
import com.kotlin.mvvm.boilerplate.util.ext.addFragment
class TrackDetailActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
addFragment(R.id.content_frame, intent.extras, ::TrackFragment)
}
}
| 0
|
Kotlin
|
0
| 0
|
a72bfdbf6f427c94c3084d8e5c023e6ce8bcd932
| 503
|
skoovin
|
MIT License
|
app/src/main/java/com/kotlin/mvvm/boilerplate/ui/main/home/TrackDetailActivity.kt
|
kanwalNayyer
| 520,274,229
| false
|
{"Kotlin": 36488}
|
package com.kotlin.mvvm.boilerplate.ui.main.home
import android.os.Bundle
import com.kotlin.mvvm.boilerplate.R
import com.kotlin.mvvm.boilerplate.ui.main.base.BaseActivity
import com.kotlin.mvvm.boilerplate.util.ext.addFragment
class TrackDetailActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
addFragment(R.id.content_frame, intent.extras, ::TrackFragment)
}
}
| 0
|
Kotlin
|
0
| 0
|
a72bfdbf6f427c94c3084d8e5c023e6ce8bcd932
| 503
|
skoovin
|
MIT License
|
app/src/main/java/com/zaurh/bober/screen/chat/modal_sheets/Chat_ModalSheetItem.kt
|
zaurh
| 853,441,625
| false
|
{"Kotlin": 432221}
|
package com.zaurh.bober.screen.chat.modal_sheets
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.KeyboardArrowRight
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
@Composable
fun Chat_ModalSheetItem(
icon: ImageVector,
title: String,
onClick: () -> Unit
) {
Row(
Modifier
.fillMaxWidth()
.height(50.dp)
.clickable {
onClick()
}, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) {
Row {
Icon(imageVector = icon, contentDescription = "", tint = MaterialTheme.colorScheme.primary)
Spacer(modifier = Modifier.size(8.dp))
Text(text = title, color = MaterialTheme.colorScheme.primary)
}
Icon(imageVector = Icons.Default.KeyboardArrowRight, contentDescription = "", tint = MaterialTheme.colorScheme.primary)
}
}
| 0
|
Kotlin
|
0
| 1
|
5010e8ba7b194da9c67592f5aa1e395fb002b64e
| 1,580
|
Bober
|
MIT License
|
src/main/kotlin/xyz/javecs/tools/expr/Function.kt
|
javecs
| 87,185,914
| false
|
{"Java": 29139, "Kotlin": 21716, "ANTLR": 654}
|
package xyz.javecs.tools.expr
// https://regex101.com/r/BeAqi7/1
private val sPattern = Regex("[a-zA-Z][a-zA-Z0-9]*\\s*\\(\\s*([a-zA-Z][a-zA-Z0-9]*\\s*(,\\s*[a-zA-Z][a-zA-Z0-9]*)*)?\\s*\\)")
internal fun validate(signature: String): Pair<String, Array<String>> {
if (!sPattern.matches(signature.trim())) throw Exception()
val separated = signature
.replace(" ", "")
.split("(", ",", ")")
.asSequence()
.filter { !it.isBlank() }
.toList()
return Pair(separated[0], if (separated.size > 1) {
separated.subList(1, separated.size).toTypedArray()
} else {
emptyArray()
})
}
class Function(signature: String, val codes: Array<String>) {
private val calc = Calculator()
val name = validate(signature).first
val params = validate(signature).second
fun setEnvironment(environment: Environment) {
calc.environment = environment
}
fun call(args: Array<Double>): Double {
if (params.size != args.size) return Double.NaN
calc.clear()
params.indices.forEach { calc.eval("${params[it]} = ${args[it]}") }
codes.forEach { calc.eval(it) }
return calc.value.toDouble()
}
}
| 1
|
Java
|
1
| 1
|
d29af52e163053795c85e7792e4c95be1696a2de
| 1,228
|
expr
|
MIT License
|
android/GestionareProduse/app/src/main/java/app/gestionareproduse/chooseWarehouseScreen/viewmodel/ChooseWarehouseViewModel.kt
|
claudiamunteanu
| 547,249,435
| false
| null |
package app.gestionareproduse.chooseWarehouseScreen.viewmodel
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.util.Log
import androidx.compose.runtime.MutableState
import androidx.lifecycle.*
import app.gestionareproduse.chooseWarehouseScreen.domain.Warehouse
import app.gestionareproduse.chooseWarehouseScreen.usecase.WarehousesUseCase
import app.gestionareproduse.utils.MyCallback
import app.gestionareproduse.utils.networkConnectivity
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.launch
import java.lang.Exception
import javax.inject.Inject
@HiltViewModel
class ChooseWarehouseViewModel @Inject constructor(
private val useCase: WarehousesUseCase
) : ViewModel() {
lateinit var listOfWarehouses : LiveData<List<Warehouse>>
val isRetrievedSuccessfully = MutableLiveData<Boolean>()
init{
viewModelScope.launch {
try{
listOfWarehouses = useCase.getLocalWarehouses().asLiveData()
isRetrievedSuccessfully.postValue(true)
} catch (exception : Exception){
isRetrievedSuccessfully.postValue(false)
Log.d("error", "Could not load local data", exception)
}
}
}
fun loadWarehouses(context: Context, showError: (String) -> Unit, progressBarVisibility : MutableState<Boolean>){
viewModelScope.launch {
val connectivity = networkConnectivity(context)
if (!connectivity) {
showError("No internet connection! Showing local data")
} else {
useCase.getAllWarehouses(showError, progressBarVisibility)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
946b42dbd25dcd5625237b1d00654a1bac8efba8
| 1,745
|
product-management
|
MIT License
|
app/src/main/java/com/stratagile/qlink/ui/activity/topup/module/TopupDeductionEthChainModule.kt
|
qlcchain
| 115,608,966
| false
| null |
package com.stratagile.qlink.ui.activity.topup.module
import com.stratagile.qlink.data.api.HttpAPIWrapper
import com.stratagile.qlink.ui.activity.base.ActivityScope
import com.stratagile.qlink.ui.activity.topup.TopupDeductionEthChainActivity
import com.stratagile.qlink.ui.activity.topup.contract.TopupDeductionEthChainContract
import com.stratagile.qlink.ui.activity.topup.presenter.TopupDeductionEthChainPresenter
import dagger.Module;
import dagger.Provides;
/**
* @author hzp
* @Package com.stratagile.qlink.ui.activity.topup
* @Description: The moduele of TopupDeductionEthChainActivity, provide field for TopupDeductionEthChainActivity
* @date 2019/12/27 11:59:29
*/
@Module
class TopupDeductionEthChainModule (private val mView: TopupDeductionEthChainContract.View) {
@Provides
@ActivityScope
fun provideTopupDeductionEthChainPresenter(httpAPIWrapper: HttpAPIWrapper) :TopupDeductionEthChainPresenter {
return TopupDeductionEthChainPresenter(httpAPIWrapper, mView)
}
@Provides
@ActivityScope
fun provideTopupDeductionEthChainActivity() : TopupDeductionEthChainActivity {
return mView as TopupDeductionEthChainActivity
}
}
| 1
|
Java
|
18
| 46
|
1c8066e4ebbb53c7401751ea3887a6315ccbe5eb
| 1,186
|
QWallet-Android
|
MIT License
|
app/src/main/java/com/autosec/pie/data/Errors.kt
|
cryptrr
| 850,497,911
| false
|
{"Kotlin": 355163, "Shell": 1942}
|
package com.autosec.pie.data
sealed class AutoPieError(msg: String) : Exception(msg) {
class UnsafeCommandException(msg: String): AutoPieError(msg)
}
| 2
|
Kotlin
|
0
| 4
|
bbad9def664e896635a22d186c783c2c7a9eb026
| 154
|
AutoPie
|
Apache License 2.0
|
mobile-ui/src/main/java/com/lekaha/simpletube/ui/injection/module/MainActivityModule.kt
|
lekaha
| 122,983,306
| false
| null |
package com.lekaha.simpletube.ui.injection.module
import android.content.Context
import com.lekaha.simpletube.ui.BaseActivity
import com.lekaha.simpletube.ui.Navigator
import com.lekaha.simpletube.ui.browse.BrowseActivity
import com.lekaha.simpletube.ui.browse.VideoFullscreenActivity
import com.lekaha.simpletube.ui.injection.qualifier.ActivityContext
import dagger.Binds
import dagger.Module
import dagger.Provides
@Module
class MainActivityModule {
@Provides
@ActivityContext
fun provideActivityContext(activity: BrowseActivity): Context = activity
@Provides
fun provideNavigator(baseActivity: BrowseActivity) = Navigator(baseActivity)
}
| 0
|
Kotlin
|
1
| 2
|
6ee542991cb6d960e30c37b9b279a4f76c37b238
| 664
|
youtube-like-video-player
|
MIT License
|
core/src/main/java/me/syahdilla/putra/sholeh/story/core/utils/Logger.kt
|
adi-itgg
| 607,399,179
| false
| null |
package me.syahdilla.putra.sholeh.story.core.utils
import android.util.Log
import kotlin.reflect.KClass
class CustomLogger(
private val tag: String
) {
constructor(clazz: KClass<*>) : this(clazz.java.simpleName)
enum class Level(val value: Int) {
VERBOSE(2),
DEBUG(3),
INFO(4),
WARN(5),
ERROR(6),
ASSERT(7)
}
private val testFormat = "%lvl %tag: [%thread] %logs"
private val format = "[%thread] %logs"
private var isTest = false
private val thread
get() = with(Thread.currentThread().name) {
foreground(if (this == "main") Color.BLUE else Color.LIGHT_GRAY)
}
private fun String.asColoredLogs(level: Level) =
when(level) {
Level.VERBOSE -> this
Level.DEBUG -> foreground(Color.LIGHT_MAGENTA)
Level.INFO -> foreground(Color.LIGHT_BLUE)
Level.WARN -> foreground(Color.LIGHT_YELLOW)
Level.ERROR -> foreground(Color.LIGHT_RED)
Level.ASSERT -> foreground(Color.RED)
}
private fun sendLog(level: Level, logs: String) {
if (isTest) return sendLogsTest(level, logs)
tryRun(true) {
sendLogsAndroid(level, logs)
}.onFailure {
isTest = true
sendLogsTest(level, logs)
}
}
private fun sendLogsAndroid(level: Level, logs: String) {
Log.println(level.value, tag, format
.replace("%thread", Thread.currentThread().name)
.replace("%logs", logs)
)
}
private fun sendLogsTest(level: Level, logs: String) {
val lvl = with(" " + level.name[0].toString() + " ") {
when (level) {
Level.VERBOSE -> foreground(Color.WHITE).background(Color.LIGHT_GRAY)
Level.DEBUG -> foreground(Color.WHITE).background(Color.GREEN)
Level.INFO -> foreground(Color.WHITE).background(Color.BLUE)
Level.WARN -> foreground(Color.WHITE).background(Color.YELLOW)
Level.ERROR -> foreground(Color.WHITE).background(Color.RED)
Level.ASSERT -> foreground(Color.MAGENTA).background(Color.RED)
}
}
println(testFormat.replace("%lvl", lvl)
.replace("%thread", thread)
.replace("%logs", logs.asColoredLogs(level))
.replace("%tag", tag))
}
private fun sendLog(level: Level, logs: List<String?>) {
if (logs.size == 1) return sendLog(level, logs[0].toString())
val sb = StringBuilder()
logs.forEach {
if (sb.isNotEmpty()) sb.append(" ")
sb.append(it)
}
sendLog(level, sb.toString())
sb.setLength(0)
}
fun verbose(vararg logs: String?) =
sendLog(Level.VERBOSE, logs.toList())
fun debug(vararg logs: String?) =
sendLog(Level.DEBUG, logs.toList())
inline fun debug(logs: () -> String) =
debug(logs())
fun error(vararg logs: String?) =
sendLog(Level.ERROR, logs.toList())
inline fun error(logs: () -> String) =
error(logs())
}
inline fun<reified T: Any> T.customLogger() = lazy(LazyThreadSafetyMode.NONE) {
CustomLogger(this::class)
}
private const val ESCAPE = '\u001B'
private const val RESET = "$ESCAPE[0m"
private const val BG_JUMP = 10
enum class Color(baseCode: Int) {
RED(31),
GREEN(32),
YELLOW(33),
BLUE(34),
MAGENTA(35),
LIGHT_GRAY(37),
LIGHT_RED(91),
LIGHT_YELLOW(93),
LIGHT_BLUE(94),
LIGHT_MAGENTA(95),
WHITE(97);
val foreground: String = "$ESCAPE[${baseCode}m"
val background: String = "$ESCAPE[${baseCode + BG_JUMP}m"
}
fun String.foreground(color: Color) = color(this, color.foreground)
fun String.background(color: Color) = color(this, color.background)
private fun color(string: String, ansiString: String) = "$ansiString$string$RESET"
| 0
|
Kotlin
|
0
| 0
|
80ab31ed8387d71ea9493ca371f770209b2e7ec0
| 3,908
|
StoryAppDicoding
|
MIT License
|
app/src/main/java/com/wikifind/ui/screens/NotFoundScreen.kt
|
CianciarusoCataldo
| 597,621,775
| false
| null |
package com.wikifind.ui.screens
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.*
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.wikifind.R
import com.wikifind.ui.components.TitleLabel
@Composable
fun NotFoundScreen(page: String, modifier: Modifier = Modifier) {
Column(modifier = modifier.fillMaxSize()) {
Row(
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Image(
modifier = Modifier.size(50.dp),
painter = painterResource(id = R.drawable.failure_icon),
contentDescription = "not found icon"
)
TitleLabel(
title = stringResource(id = R.string.notFound_header),
color = Color.Red,
modifier = Modifier.padding(10.dp, 0.dp)
)
}
Column(modifier = Modifier.padding(10.dp, 0.dp)) {
Row() {
val textSplit = stringResource(R.string.notFound_body).split("PAGE_TO_SEARCH")
Text(
text = textSplit[0],
fontWeight = FontWeight.Medium,
fontSize = 20.sp,
)
Text(
text = page,
color = Color.Blue,
fontWeight = FontWeight.Medium,
fontSize = 20.sp,
)
Text(
text = textSplit[1],
fontWeight = FontWeight.Medium,
fontSize = 20.sp,
)
}
Text(
text = stringResource(R.string.notFound_tryAgain),
fontWeight = FontWeight.Medium,
fontSize = 20.sp,
)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
495a28916305f65df3584dd59325cf15208f5683
| 2,215
|
wiki-find
|
MIT License
|
src/main/java/dev/caledonian/listener/MessageListener.kt
|
VoltrixDev
| 514,977,667
| false
| null |
package dev.caledonian.listener
import dev.caledonian.VoltrixSupportBot
import dev.caledonian.utils.MessageUtils
import dev.caledonian.utils.PremadeEmbeds
import dev.caledonian.utils.Utils
import net.dv8tion.jda.api.JDA
import net.dv8tion.jda.api.events.message.MessageReceivedEvent
import net.dv8tion.jda.api.hooks.ListenerAdapter
import net.dv8tion.jda.api.interactions.components.buttons.Button
class MessageListener(val main: VoltrixSupportBot, val jda: JDA, val embeds: PremadeEmbeds) : ListenerAdapter() {
override fun onMessageReceived(e: MessageReceivedEvent) {
if (e.author.isBot) return
if (e.channel.idLong == main.config.getJSONObject("auto-support").getLong("channel-id")) {
val message = e.message.contentRaw
Utils.sendConsoleLog("Message received in support channel: $message")
if (MessageUtils.containsWordsIfQuestion(message, arrayOf("download", "install")) or MessageUtils.containsPhrases(message, arrayOf("download client", "client link", "download link"))) {
// Download client
e.message.reply(String.format(":wave: Hey %s, if you're looking for the download link, you can find it by clicking the button below! Hopefully this helps!", e.author.asMention)).setActionRow(
Button.link("https://voltrix.caledonian.dev/", "Download")).queue()
return
}
if(MessageUtils.containsWordsIfQuestion(message, arrayOf("wiki", "docs", "install", "installing", "installed", "error"))
or MessageUtils.containsPhrases(message, arrayOf("dont know how", "help install", "how install", "help error", "dont work", "what do install"))) {
e.message.reply(String.format("%s :wave:, your question could already be answered! Check our documentation by clicking the button below!", e.author.asMention)).setActionRow(
Button.link("https://voltrix.caledonian.dev/", "Client wiki")).queue()
return
}
if(MessageUtils.containsWordsIfQuestion(message, arrayOf("support", "ticket"))
or MessageUtils.containsPhrases(message, arrayOf("staff support", "voltrix support", "client support", "report error"))) {
e.message.reply(String.format("%s :wave:, it looks like you're trying to create a ticket. If so, check the <#868239889341247558> channel, and click the button!", e.author.asMention)).queue()
return
}
if(MessageUtils.containsPhrases(message, arrayOf("create mod", "add own mod", "install mod", "implement mod"))) {
e.message.reply(String.format("%s :wave:, Have you checked our wiki yet? It should have everything you need!", e.author.asMention)).setActionRow(
Button.link("https://voltrix.caledonian.dev/smp/api-docs/spigot-events", "Spigot API")).queue()
return
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3e3421acfd71878a6ee4076b1d6660b3f1be1fd2
| 2,953
|
VoltrixSupport
|
MIT License
|
app/src/main/java/alexz/sliderintro/state/ViewHolderScrollState.kt
|
xzhorikx
| 261,413,856
| false
| null |
package alexz.sliderintro.state
/**
* State for view holder scroll transition
*
* @param offsetSum sum of position offset and position
*/
data class ViewHolderScrollState(
val offsetSum: Float
)
| 2
|
Kotlin
|
3
| 6
|
839255a00730b838f19a59ff7d5934b50ade371c
| 204
|
slider-intro
|
Apache License 2.0
|
app/src/main/java/com/iucoding/chatgptclient/composable/MainScreen.kt
|
isaacurbina
| 855,461,550
| false
|
{"Kotlin": 35479}
|
package com.iucoding.chatgptclient.composable
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.PreviewScreenSizes
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.iucoding.chatgptclient.R
import com.iucoding.chatgptclient.actions.UIEvent
import com.iucoding.chatgptclient.ui.theme.ChatGPTClientTheme
import com.iucoding.chatgptclient.viewmodel.MainState
import com.iucoding.chatgptclient.viewmodel.MainViewModel
import kotlinx.coroutines.launch
@Composable
fun MainScreen(
viewModel: MainViewModel,
snackBarHostState: SnackbarHostState,
modifier: Modifier = Modifier
) {
val context = LocalContext.current
val scope = rememberCoroutineScope()
ObserveAsEvents(flow = viewModel.toast) {
scope.launch {
snackBarHostState.showSnackbar(
message = it.asString(context),
actionLabel = context.getString(R.string.snack_ok),
duration = SnackbarDuration.Short
)
}
}
MainScreen(
state = viewModel.uiState.value,
onEvent = viewModel::sendEvent,
modifier = modifier
)
}
@Composable
fun MainScreen(
state: MainState,
onEvent: (event: UIEvent) -> Unit,
modifier: Modifier = Modifier
) {
Column(
modifier = modifier
.fillMaxWidth()
.background(MaterialTheme.colorScheme.background)
.padding(16.dp),
verticalArrangement = Arrangement.Bottom
) {
// Text view to display question
state.question?.let {
Text(
text = it.asString(),
fontSize = 18.sp,
fontWeight = FontWeight.Bold,
modifier = Modifier
.fillMaxWidth()
.padding(4.dp)
)
Spacer(modifier = Modifier.height(16.dp))
}
if (state.isLoading) {
// Display progress indicator
Box(
modifier = Modifier
.weight(1.0f)
.fillMaxWidth()
) {
CircularProgressIndicator(
modifier = Modifier
.width(64.dp)
.align(Alignment.Center),
color = MaterialTheme.colorScheme.secondary,
trackColor = MaterialTheme.colorScheme.surfaceVariant,
)
}
} else {
// Text view to display response
state.response?.let {
// clearing prompt text field once an answer is received
TypewriteText(
text = it.asString(),
fontSize = 16.sp,
modifier = Modifier
.fillMaxWidth()
.padding(4.dp)
.weight(1.0f)
.verticalScroll(rememberScrollState())
)
} ?: Spacer(modifier = Modifier.weight(1f))
}
PromptBar(
enabled = !state.isLoading,
onEvent = onEvent,
modifier = Modifier.fillMaxWidth()
)
}
}
@PreviewScreenSizes
@Composable
private fun MainScreenPreview() {
ChatGPTClientTheme {
MainScreen(
state = MainState(
question = UiText.DynamicString("The prompt for ChatGPT goes here"),
response = UiText.DynamicString("The answer should go here"),
isLoading = false,
),
onEvent = {}
)
}
}
| 0
|
Kotlin
|
0
| 0
|
ef8aa3ce1216b31d0fea3307e2da154466de2d31
| 4,631
|
chatgpt-client
|
Apache License 2.0
|
soil-query-core/src/commonMain/kotlin/soil/query/SubscriptionClient.kt
|
soil-kt
| 789,648,330
| false
|
{"Kotlin": 706543, "Makefile": 1014}
|
// Copyright 2024 Soil Contributors
// SPDX-License-Identifier: Apache-2.0
package soil.query
import soil.query.annotation.ExperimentalSoilQueryApi
import soil.query.core.Marker
/**
* A Subscription client, which allows you to make subscriptions actor and handle [SubscriptionKey].
*/
interface SubscriptionClient {
/**
* The default subscription options.
*/
val defaultSubscriptionOptions: SubscriptionOptions
/**
* Gets the [SubscriptionRef] by the specified [SubscriptionKey].
*/
@ExperimentalSoilQueryApi
fun <T> getSubscription(
key: SubscriptionKey<T>,
marker: Marker = Marker.None
): SubscriptionRef<T>
}
typealias SubscriptionRecoverData<T> = (error: Throwable) -> T
typealias SubscriptionOptionsOverride = (SubscriptionOptions) -> SubscriptionOptions
| 0
|
Kotlin
|
1
| 106
|
a372f6e48fc825e0e2a022e7c4a4e2a672ba5edf
| 828
|
soil
|
Apache License 2.0
|
service/src/main/kotlin/alphabetapeter/util/LocalMap.kt
|
codedrift
| 119,114,313
| false
|
{"Kotlin": 36540, "Java": 22802, "JavaScript": 15869, "HTML": 1610, "Dockerfile": 1072, "CSS": 619, "Shell": 244}
|
package alphabetapeter.util
import alphabetapeter.model.ColorSet
import alphabetapeter.model.PlayStatus
import io.vertx.core.Vertx
import io.vertx.core.json.JsonObject
import io.vertx.core.shareddata.LocalMap
class LocalMap(private val vertx: Vertx) {
enum class Key {
SPOTIFY_ACCESS_TOKEN_KEY,
SPOTIFY_REFRESH_TOKEN,
SPOTIFY_STATUS_KEY,
SPOTIFY_CLIENT_ID,
SPOTIFY_CLIENT_SECRET,
SPOTIFY_ALBUM_URL,
PHILIPS_HUE_COLOR,
PHILIPS_HUE_USERNAME,
PHILIPS_HUE_BRIDGE_IP,
LIGHT_MATCHING,
}
private fun localStringMap(): LocalMap<String, String> {
return vertx.sharedData().getLocalMap<String, String>("string_data")
}
private fun localBooleanMap(): LocalMap<String, Boolean> {
return vertx.sharedData().getLocalMap<String, Boolean>("boolean_data")
}
private fun localJsonObjectMap(): LocalMap<String, JsonObject> {
return vertx.sharedData().getLocalMap<String, JsonObject>("jsonobject_data")
}
private fun localHueColorMap(): LocalMap<String, ColorSet> {
return vertx.sharedData().getLocalMap<String, ColorSet>("color_data")
}
fun putString(key: String, value: String) {
localStringMap()[key] = value
}
fun putBoolean(key: String, value: Boolean) {
localBooleanMap()[key] = value
}
fun putSpotifyAccessToken(accessToken: String) {
localStringMap()[Key.SPOTIFY_ACCESS_TOKEN_KEY.name] = accessToken
}
fun getSpotifyAccessToken(): String? {
return localStringMap()[Key.SPOTIFY_ACCESS_TOKEN_KEY.name]
}
fun putSpotifyRefreshToken(refreshToken: String) {
localStringMap()[Key.SPOTIFY_REFRESH_TOKEN.name] = refreshToken
}
fun getSpotifyRefreshToken(): String? {
return localStringMap()[Key.SPOTIFY_REFRESH_TOKEN.name]
}
fun putHueUserName(username: String) {
localStringMap()[Key.PHILIPS_HUE_USERNAME.name] = username
}
fun getHueUsername(): String? {
return localStringMap()[Key.PHILIPS_HUE_USERNAME.name]
}
fun putHueBridgeIp(ip: String) {
localStringMap()[Key.PHILIPS_HUE_BRIDGE_IP.name] = ip
}
fun getHueBridgeIp(): String? {
return localStringMap()[Key.PHILIPS_HUE_BRIDGE_IP.name]
}
fun getSpotifyClientId(): String? {
return localStringMap()[Key.SPOTIFY_CLIENT_ID.name]
}
fun putSpotifyClientId(clientId: String) {
localStringMap()[Key.SPOTIFY_CLIENT_ID.name] = clientId
}
fun getSpotifyClientSecret(): String? {
return localStringMap()[Key.SPOTIFY_CLIENT_SECRET.name]
}
fun putSpotifyClientSecret(secret: String) {
localStringMap()[Key.SPOTIFY_CLIENT_SECRET.name] = secret
}
fun putLightMatchingEnabled(match: Boolean) {
localBooleanMap()[Key.LIGHT_MATCHING.name] = match
}
fun getLightMatchingEnabled(): Boolean {
return localBooleanMap().getOrDefault(Key.LIGHT_MATCHING.name, true)
}
fun putSpotifyStatus(status: PlayStatus) {
localJsonObjectMap()[Key.SPOTIFY_STATUS_KEY.name] = status.toJsonObject()
}
fun getSpotifyStatus(): PlayStatus {
return PlayStatus.fromJsonObject(localJsonObjectMap().getOrDefault(Key.SPOTIFY_STATUS_KEY.name, JsonObject()))
}
}
| 0
|
Kotlin
|
1
| 2
|
053e977e5bb476a7ae1013ae2fab1dba45cb482f
| 2,984
|
philips-hue-spotify-connector
|
Apache License 2.0
|
steps/http-steps/src/main/kotlin/http/mock/HttpMockSteps.kt
|
testerum
| 241,460,788
| false
|
{"Text": 47, "Gradle Kotlin DSL": 62, "Shell": 17, "Batchfile": 16, "Maven POM": 71, "Java Properties": 2, "Ignore List": 8, "Git Attributes": 1, "EditorConfig": 5, "Markdown": 8, "Kotlin": 1089, "Java": 27, "JSON": 161, "INI": 3, "XML": 30, "JavaScript": 36, "Gherkin": 1, "HTML": 232, "JSON with Comments": 11, "Browserslist": 4, "SVG": 4, "SCSS": 222, "CSS": 12, "YAML": 2, "Dotenv": 1, "Groovy": 1, "Ant Build System": 1}
|
package http.mock
import com.testerum.model.resources.http.mock.server.HttpMockServer
import com.testerum.model.resources.http.mock.stub.HttpMock
import com.testerum_api.testerum_steps_api.annotations.hooks.BeforeEachTest
import com.testerum_api.testerum_steps_api.annotations.steps.Given
import com.testerum_api.testerum_steps_api.annotations.steps.Param
import com.testerum_api.testerum_steps_api.services.TesterumServiceLocator
import com.testerum_api.testerum_steps_api.test_context.logger.TesterumLogger
import http.mock.transformer.HttpMockServerTransformer
import http.mock.transformer.HttpMockTransformer
import http_support.HttpMockService
import http_support.logging.prettyPrint
import http_support.module_di.HttpStepsModuleServiceLocator
class HttpMockSteps {
private val httpMockService: HttpMockService = HttpStepsModuleServiceLocator.bootstrapper.httpStepsModuleFactory.httpMockService
private val logger: TesterumLogger = TesterumServiceLocator.getTesterumLogger()
@BeforeEachTest
fun beforeTest() {
httpMockService.clearAllStubs()
}
@Given(
value = "the HTTP mock server <<httpMockServer>> with the mock request <<httpMock>>",
description = "Sets up an HTTP server that will return the configured response when the configured request matches."
)
fun setupMockServer(
@Param(
transformer = HttpMockServerTransformer::class,
description = "The configuration of the mock server, like the port on which to listen."
)
httpMockServer: HttpMockServer,
@Param(
transformer = HttpMockTransformer::class,
description = "The expected request and the response to return for that request."
)
httpMock: HttpMock
) {
logger.info(
"HTTP Mock Server\n" +
"\n" +
"\tport: ${httpMockServer.port}\n" +
"\n" +
"${httpMock.prettyPrint()}\n"
)
httpMockService.addHttpStub(httpMockServer, httpMock)
}
}
| 33
|
Kotlin
|
3
| 22
|
0a53c71b5f659e41282114127f595aad5ab1e4fb
| 2,129
|
testerum
|
Apache License 2.0
|
app/src/main/java/com/github/satoshun/example/AppActivity.kt
|
satoshun-android-example
| 204,665,272
| false
| null |
package com.github.satoshun.example
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.github.satoshun.example.databinding.AppActBinding
import com.github.satoshun.example.p1.DialogP1Activity
import com.github.satoshun.example.p2.DialogP2Activity
import com.github.satoshun.example.p3.DialogP3Activity
class AppActivity : AppCompatActivity() {
private lateinit var binding: AppActBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.app_act)
binding.pattern1.setOnClickListener {
startActivity(Intent(this@AppActivity, DialogP1Activity::class.java))
}
binding.pattern2.setOnClickListener {
startActivity(Intent(this@AppActivity, DialogP2Activity::class.java))
}
binding.pattern3.setOnClickListener {
startActivity(Intent(this@AppActivity, DialogP3Activity::class.java))
}
}
}
| 0
|
Kotlin
|
0
| 0
|
283b6b3e324c611ee3b66314bfaf7f204e7a6097
| 1,044
|
DialogResult
|
Apache License 2.0
|
formula/src/main/java/com/instacart/formula/ActionExtensions.kt
|
instacart
| 171,923,573
| false
|
{"Kotlin": 565903, "Shell": 1203, "Ruby": 256}
|
package com.instacart.formula
import com.instacart.formula.internal.ActionKey
import com.instacart.formula.internal.OverrideKeyAction
/**
* Wraps this action with a new key to force it to run again.
*/
fun <Event> Action<Event>.runAgain(): Action<Event> {
return overrideKey(key = newActionKey(this, this))
}
/**
* Wraps the action with a unique key to ensure that [previousAction] is cancelled and
* this action runs.
*/
fun <Event> Action<Event>.cancelPrevious(previousAction: Action<Event>?): Action<Event> {
return overrideKey(key = newActionKey(previousAction, this))
}
private fun <Event> Action<Event>.overrideKey(key: Any): Action<Event> {
val unwrappedAction = if (this is OverrideKeyAction) {
this.action
} else {
this
}
return OverrideKeyAction(key, unwrappedAction)
}
private fun newActionKey(previous: Action<*>?, new: Action<*>): ActionKey {
val previousKey = previous?.key() as? ActionKey
val id = if (previousKey != null) {
previousKey.id + 1
} else {
0
}
return ActionKey(id, new.key())
}
| 7
|
Kotlin
|
14
| 151
|
26d544ea41b7a5ab2fa1a3b9ac6b668e69fe4dff
| 1,092
|
formula
|
BSD 3-Clause Clear License
|
data/src/main/java/com/cheesecake/data/remote/fixture/IFixturesApiService.kt
|
Shehab-m
| 648,956,107
| false
| null |
package com.cheesecake.data.remote.fixture
import androidx.paging.DataSource
import com.cheesecake.data.models.BaseResponse
import com.cheesecake.data.models.FixtureResponse
import com.cheesecake.data.models.FixtureStatistics
import com.cheesecake.data.models.HeadToHeadResponse
import com.cheesecake.data.models.SingleEventResponse
import com.cheesecake.data.models.SingleFixtureResponse
import com.cheesecake.data.models.SingleLineupResponse
import com.cheesecake.data.utils.FixtureStatus
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface IFixturesApiService {
//region Rounds
@GET("fixtures/rounds")
suspend fun getFixtureRounds(
@Query("season") seasonId: Int,
@Query("league") leagueId: Int
): Response<BaseResponse<String>>
@GET("fixtures/rounds")
suspend fun getFixtureRoundsCurrentOnly(
@Query("season") seasonId: Int,
@Query("league") leagueId: Int,
@Query("current") current: Boolean,
): Response<BaseResponse<String>>
//endregion
//region Fixtuers
@GET("fixtures")
suspend fun getFixtureById(
@Query("timezone") timeZone: String,
@Query("id") fixtureId: Int
): Response<BaseResponse<SingleFixtureResponse>>
@GET("fixtures")
suspend fun getFixturesBySeasonIdByTeamId(
@Query("timezone") timeZone: String,
@Query("season") season: String,
@Query("team") teamId: Int
): Response<BaseResponse<SingleFixtureResponse>>
@GET("fixtures")
suspend fun getFixturesByDate(
@Query("timezone") timeZone: String,
@Query("date") date: String
): Response<BaseResponse<SingleFixtureResponse>>
@GET("fixtures")
suspend fun getFixturesFromDate(
@Query("timezone") timeZone: String,
@Query("from") date: String
): Response<BaseResponse<SingleFixtureResponse>>
@GET("fixtures")
suspend fun getFixturesToDate(
@Query("timezone") timeZone: String,
@Query("to") date: String
): Response<BaseResponse<SingleFixtureResponse>>
@GET("fixtures")
suspend fun getFixturesFromDateToDate(
@Query("timezone") timeZone: String,
@Query("season") season: String,
@Query("team") teamId: Int,
@Query("from") from: String,
@Query("to") date: String
): Response<BaseResponse<SingleFixtureResponse>>
@GET("fixtures")
suspend fun getFixturesStatus(
@Query("timezone") timeZone: String,
@Query("status") fixtureStatusType: String
): Response<BaseResponse<SingleFixtureResponse>>
//endregion
//region Head 2 Head
@GET("fixtures/headtohead")
suspend fun getHeadToHead(
@Query("h2h") teamsId: String,
@Query("season") seasonId: Int,
@Query("timezone") timeZone: String
): Response<BaseResponse<HeadToHeadResponse>>
@GET("fixtures/headtohead")
suspend fun getHeadToHeadByDate(
@Query("h2h") teamsId: String,
@Query("date") date: String,
@Query("timezone") timeZone: String
): Response<BaseResponse<HeadToHeadResponse>>
@GET("fixtures/headtohead")
suspend fun getHeadToHeadByStatus(
@Query("h2h") teamsId: String,
@Query("status") status: FixtureStatus,
@Query("season") seasonId: Int,
@Query("timezone") timeZone: String
): Response<BaseResponse<HeadToHeadResponse>>
@GET("fixtures/headtohead")
suspend fun getHeadToHeadByFromAndTO(
@Query("h2h") teamsId: String,
@Query("from") from: String,
@Query("to") to: String,
@Query("season") seasonId: Int,
@Query("timezone") timeZone: String
): Response<BaseResponse<HeadToHeadResponse>>
@GET("fixtures/headtohead")
suspend fun getHeadToHeadByLeague(
@Query("h2h") teamsId: String,
@Query("league") leagueId: Int,
@Query("season") seasonId: Int,
@Query("timezone") timeZone: String
): Response<BaseResponse<HeadToHeadResponse>>
@GET("fixtures/headtohead")
suspend fun getHeadToHeadByByDateAndLeague(
@Query("h2h") teamsId: String,
@Query("league") leagueId: Int,
@Query("date") date: String,
@Query("timezone") timeZone: String
): Response<BaseResponse<HeadToHeadResponse>>
@GET("fixtures/headtohead")
suspend fun getHeadToHeadByStatusAndLeague(
@Query("h2h") teamsId: String,
@Query("league") leagueId: Int,
@Query("status") status: FixtureStatus,
@Query("season") seasonId: Int,
@Query("timezone") timeZone: String
): Response<BaseResponse<HeadToHeadResponse>>
@GET("fixtures/headtohead")
suspend fun getHeadToHeadByFromAndTOAndLeague(
@Query("h2h") teamsId: String,
@Query("league") leagueId: Int,
@Query("from") from: String,
@Query("to") to: String,
@Query("season") seasonId: Int,
@Query("timezone") timeZone: String
): Response<BaseResponse<HeadToHeadResponse>>
//endregion
//region Statistics
@GET("fixtures/statistics")
suspend fun getFixtureStatisticsByFixtureId(
@Query("fixture") fixtureId: Int
): Response<BaseResponse<FixtureStatistics>>
@GET("fixtures/statistics")
suspend fun getFixtureStatisticsByFixtureIdByTeamId(
@Query("fixture") fixtureId: Int,
@Query("team") teamId: Int
): Response<BaseResponse<FixtureStatistics>>
//endregion
//region Events
@GET("fixtures/events")
suspend fun getFixtureEventsByFixtureId(
@Query("fixture") fixtureId: Int
): Response<BaseResponse<SingleEventResponse>>
@GET("fixtures/events")
suspend fun getFixtureEventsByFixtureIdByTeamId(
@Query("fixture") fixtureId: Int,
@Query("team") teamId: Int
): Response<BaseResponse<SingleEventResponse>>
@GET("fixtures/events")
suspend fun getFixtureEventsByFixtureIdByTeamIdByPlayerId(
@Query("fixture") fixtureId: Int,
@Query("team") teamId: Int,
@Query("player") playerId: Int,
): Response<BaseResponse<SingleEventResponse>>
@GET("fixtures/events")
suspend fun getFixtureEventsByFixtureIdByTeamIdByPlayerIdByType(
@Query("fixture") fixtureId: Int,
@Query("team") teamId: Int,
@Query("player") playerId: Int,
@Query("type") fixtureEventType: String,
): Response<BaseResponse<SingleEventResponse>>
//endregion
//region Lineups
@GET("fixtures/lineups")
suspend fun getFixtureLineupsByFixtureId(
@Query("fixture") fixtureId: Int
): Response<BaseResponse<SingleLineupResponse>>
@GET("fixtures/lineups")
suspend fun getFixtureLineupsByFixtureIdByTeamId(
@Query("fixture") fixtureId: Int,
@Query("team") teamId: Int
): Response<BaseResponse<SingleLineupResponse>>
@GET("fixtures/lineups")
suspend fun getFixtureLineupsByFixtureIdByPlayerId(
@Query("fixture") fixtureId: Int,
@Query("player") playerId: Int
): Response<BaseResponse<SingleLineupResponse>>
//endregion
//region Players
@GET("fixtures/players")
suspend fun getFixturePlayersByFixtureId(
@Query("fixture") fixtureId: String
): Response<BaseResponse<FixtureResponse>>
@GET("fixtures/players")
suspend fun getFixturePlayersByFixtureIdByTeamId(
@Query("fixture") fixtureId: Int,
@Query("team") teamId: Int
): Response<BaseResponse<FixtureResponse>>
//endregion
}
| 0
|
Kotlin
|
0
| 0
|
c40751a97efddad849ea5330298d58fec7c8b721
| 7,503
|
Kickoff
|
Apache License 2.0
|
app/src/main/java/com/example/filmein/data/MovieRepository.kt
|
realsoc
| 686,377,328
| false
|
{"Kotlin": 69058}
|
package com.example.filmein.data
import com.example.filmein.Movie
import kotlinx.coroutines.flow.Flow
// While the only work on movie is a local CRUD its normal for this class to be dumb
interface MovieRepository {
val movies: Flow<List<Movie>>
suspend fun addMovie(movie: Movie)
suspend fun removeMovie(movie: Movie)
suspend fun changeWatchStatusForMovie(movie: Movie, watched: Boolean)
}
class MovieRepositoryImpl(
private val moviesLocalDataSource: MoviesLocalDataSource
): MovieRepository {
override val movies: Flow<List<Movie>>
get() = moviesLocalDataSource.movies
override suspend fun addMovie(movie: Movie) {
moviesLocalDataSource.addMovie(movie)
}
override suspend fun removeMovie(movie: Movie) {
moviesLocalDataSource.removeMovie(movie)
}
override suspend fun changeWatchStatusForMovie(movie: Movie, watched: Boolean) {
moviesLocalDataSource.changeWatchStatusForMovie(movie, watched)
}
}
| 0
|
Kotlin
|
0
| 0
|
877a83adb1091a50bf0a99b41097729699637450
| 987
|
FilmeIn
|
Apache License 2.0
|
project/common/src/main/kotlin/ink/ptms/adyeshach/core/entity/type/AdyItem.kt
|
TabooLib
| 284,936,010
| false
|
{"Kotlin": 1050024, "Java": 35966}
|
package ink.ptms.adyeshach.core.entity.type
import org.bukkit.inventory.ItemStack
/**
* @author sky
* @date 2020/8/4 23:15
*/
interface AdyItem : AdyEntity {
/**
* 设置物品
*/
fun setItem(itemStack: ItemStack)
/**
* 获取物品
*/
fun getItem(): ItemStack
}
| 13
|
Kotlin
|
86
| 98
|
ac7098b62db19308c9f14182e33181c079b9e561
| 289
|
adyeshach
|
MIT License
|
src/Day14.kt
|
SergeiMikhailovskii
| 573,781,461
| false
|
{"Kotlin": 32574}
|
import kotlin.math.max
import kotlin.math.min
fun main() {
class Point(
val x: Int,
val y: Int
)
val initial = 500
val input = readInput("Day14_test")
val mapped = input.map {
it.split(" -> ").map {
val arr = it.split(",")
Point(arr[0].toInt(), arr[1].toInt())
}
}
var maxY = Int.MIN_VALUE
for (i in mapped.indices) {
for (j in mapped[i].indices) {
maxY = max(maxY, mapped[i][j].y)
}
}
val minX = initial - maxY - 2
val maxX = initial + maxY + 2
val width = maxX - minX + 1
val matrix = Array(maxY + 3) { Array(width) { "." } }
for (j in matrix.last().indices) {
matrix[matrix.size - 1][j] = "#"
}
mapped.forEach {
var start = it[0]
for (i in 1 until it.size) {
val end = it[i]
if (start.x == end.x) {
for (j in min(start.y, end.y)..max(start.y, end.y)) {
matrix[j][start.x - minX] = "#"
}
} else if (start.y == end.y) {
for (j in min(start.x, end.x)..max(start.x, end.x)) {
matrix[start.y][j - minX] = "#"
}
}
start = end
}
}
fun moveLower(point: Point): Boolean {
if (matrix[point.y][point.x] == ".") {
if (!moveLower(Point(y = point.y + 1, x = point.x))) {
matrix[point.y][point.x] = "0"
}
return true
} else if (matrix[point.y][point.x - 1] == ".") {
if (!moveLower(Point(y = point.y + 1, x = point.x - 1))) {
matrix[point.y][point.x - 1] = "0"
}
return true
} else if (matrix[point.y][point.x + 1] == ".") {
if (!moveLower(Point(y = point.y + 1, x = point.x + 1))) {
matrix[point.y][point.x + 1] = "0"
}
return true
}
return false
}
var counter = 0
try {
while (true) {
moveLower(Point(initial - minX, 0))
counter++
}
} catch (e: ArrayIndexOutOfBoundsException) {
println(counter)
}
}
| 0
|
Kotlin
|
0
| 0
|
c7e16d65242d3be6d7e2c7eaf84f90f3f87c3f2d
| 2,214
|
advent-of-code-kotlin
|
Apache License 2.0
|
kmm/shared-ui/src/androidMain/kotlin/com/yao/tmdb/sharedui/ContextUtil.kt
|
yao-xie-kinto
| 598,494,975
| false
| null |
package com.yao.tmdb.sharedui
import android.content.Context
import androidx.annotation.NonNull
class ContextUtil private constructor() {
companion object {
private var appContext: Context? = null
fun init(@NonNull context: Context) {
appContext = context.applicationContext
}
fun getContext(): Context? {
if (appContext != null) {
return appContext
}
throw NullPointerException("Application context is not initialized!")
}
}
}
| 0
|
Kotlin
|
0
| 0
|
8a0a36cf99e807c6dfd870a0f9e2e1db37c03f04
| 544
|
TMDB_KMM
|
MIT License
|
shared/src/main/java/com/stream_suite/link/shared/service/SimpleLifetimeSubscriptionCheckService.kt
|
sstream17
| 231,685,513
| true
|
{"Gradle": 8, "Java Properties": 2, "Shell": 1, "Text": 3, "Ignore List": 6, "Markdown": 1, "JSON": 3, "Proguard": 1, "Java": 160, "Kotlin": 407, "XML": 421, "AIDL": 1, "SVG": 3}
|
package com.stream_suite.link.shared.service
import com.stream_suite.link.shared.util.billing.ProductPurchased
class SimpleLifetimeSubscriptionCheckService : SimpleSubscriptionCheckService() {
override fun handleBestProduct(best: ProductPurchased) {
if (best.productId == "lifetime") {
writeLifetimeSubscriber()
}
}
}
| 1
|
Kotlin
|
0
| 1
|
0589153dd853447b260a3739564371c6b92d481c
| 356
|
pulse-sms-android
|
Apache License 2.0
|
app/src/main/java/com/nosetrap/recyclerview/AddWordFragment.kt
|
mundia416
| 191,127,455
| false
|
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Kotlin": 13, "XML": 22, "Java": 2}
|
package com.nosetrap.recyclerview
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"
/**
* A simple [Fragment] subclass.
*
*/
class AddWordFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add_word, container, false)
}
}
| 0
|
Kotlin
|
0
| 0
|
3be79c830ece307a245ace090ae7199eedc3c092
| 754
|
Recyclerview
|
Apache License 2.0
|
app/src/main/java/com/won/travelreviewpj/travel/wishlist/TravelWishlist.kt
|
wonhyeung
| 757,325,457
| false
|
{"Kotlin": 102652}
|
package com.won.travelreviewpj.travel.wishlist
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
@Entity(tableName = "wishlist_tbl")
data class TravelWishlist(
@ColumnInfo(name = "wishlistTitle")
var wishlistTitle: String = "",
@ColumnInfo(name = "wishlistAddress")
var wishlistAddress: String = "",
@ColumnInfo(name = "wishlistImage")
var wishlistImage: String = "",
@ColumnInfo(name = "wishlistOverrview")
var wishlistOverview: String = "",
@PrimaryKey(autoGenerate = true)
@ColumnInfo(name = "id")
var id: Long = 0L,
)
| 0
|
Kotlin
|
0
| 0
|
08d2659525e3a07a9b42e391e125035ee95fda7b
| 610
|
TravelReviewPJ
|
MIT License
|
app/src/main/java/com/userapp/ui/login/LoginPresenter.kt
|
zumrywahid
| 140,339,325
| false
|
{"Kotlin": 25522}
|
package com.userapp.ui.login
import com.userapp.data.User
import com.userapp.data.UserRepository
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
/**
* Created on 7/7/18.
*/
class LoginPresenter @Inject constructor(
var userRepository: UserRepository,
private val compositeDisposable: CompositeDisposable
) : LoginContract.Presenter {
private var loginView: LoginContract.View? = null
override fun takeView(view: LoginContract.View) {
this.loginView = view
}
override fun dropView() {
this.loginView = null
}
override fun loginUser(email: String, password: String): Boolean {
this.loginView?.setLoadingIndicator()
compositeDisposable.addAll(
Observable.defer {
Observable.just(userRepository.selectUserByEmail(email))
}
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe ({ users ->
if (this.loginView == null) {
return@subscribe
}
if (users != null && users.size > 0) {
val user = users[0]
if (user.password.equals(password)) {
loginView?.showLoginResult(true)
} else {
loginView?.showLoginResult(false)
}
} else {
loginView?.showLoginResult(false)
}
this.loginView?.hideLoadingIndicator()
}, { throwable ->
if (this.loginView == null) {
return@subscribe
}
this.loginView?.hideLoadingIndicator()
})
)
return true
}
}
| 0
|
Kotlin
|
0
| 2
|
0e8df5b4ebe074c764a79916e3794e8f45ef6be6
| 2,245
|
UserManagementApp
|
Apache License 2.0
|
src/main/resources/assets/hollowengine/hevents/blacksmith_event.se.kts
|
HollowHorizon
| 586,593,959
| false
| null |
package assets.hollowstory.hevents
import net.minecraft.client.Minecraft
import net.minecraft.command.arguments.EntityAnchorArgument
import net.minecraft.entity.player.PlayerEntity
import net.minecraft.entity.player.ServerPlayerEntity
import net.minecraft.world.GameType
import net.minecraft.world.server.ServerWorld
import net.minecraftforge.fml.server.ServerLifecycleHooks
import ru.hollowhorizon.hc.client.utils.toRL
import ru.hollowhorizon.hc.client.utils.toSTC
import ru.hollowhorizon.hollowengine.client.screen.OverlayScreen
import ru.hollowhorizon.hollowengine.common.entities.NPCEntity
import ru.hollowhorizon.hollowengine.common.npcs.NPCSettings
import ru.hollowhorizon.hollowengine.cutscenes.replay.Replay
import ru.hollowhorizon.hollowengine.cutscenes.replay.ReplayPlayer
val level: ServerWorld = ServerLifecycleHooks.getCurrentServer().overworld()
val player: PlayerEntity = team.getAllOnline().first().mcPlayer!!
val startPos = player.position()
val overlay = OverlayScreen()
Minecraft.getInstance().gui.setTitles("Тем временем в деревне...".toSTC(), null, 20, 30, 20)
wait(2f)
Minecraft.getInstance().setScreen(overlay)
overlay.makeBlack(1.5f)
wait(1.5f)
player.setGameMode(GameType.SPECTATOR)
(player as ServerPlayerEntity).teleportTo(level, 219.2, 72.0, -790.3, -167.0f, 5.4f)
val obbik = NPCEntity(
NPCSettings(
name = "Оббик",
puppetEntity = "minecraft:villager@{VillagerData:{profession:armorer,level:2,type:savanna}}",
),
level
)
obbik.moveTo(215.5, 71.1, -797.5, 180.0f, 30f)
obbik.lookAt(EntityAnchorArgument.Type.EYES, player.position())
level.addFreshEntity(obbik)
val obbikPlayer = ReplayPlayer(obbik).apply {
isLooped = false
saveEntity = false
applyWorldChanges = true
}
obbikPlayer.play(level, Replay.fromResourceLocation("hollowstory:replays/obbik.hc".toRL()))
wait(1.5f)
val kay = NPCEntity(
NPCSettings(
name = "Кай",
puppetEntity = "minecraft:villager@{VillagerData:{profession:weaponsmith,level:2,type:savanna}}",
),
level
)
kay.moveTo(220.5, 72.1, -791.5, 180.0f, 30f)
kay.lookAt(EntityAnchorArgument.Type.EYES, player.position())
level.addFreshEntity(kay)
overlay.makeTransparent(1f)
val kayPlayer = ReplayPlayer(kay).apply {
isLooped = false
saveEntity = false
applyWorldChanges = true
}
kayPlayer.play(level, Replay.fromResourceLocation("hollowstory:replays/kay.hc".toRL()))
play("hollowstory:ob1")
team.sendMessage("<Оббик> Не отвлекаю? Как там наш заказ?")
wait(3.5f)
play("hollowstory:ka1")
team.sendMessage("<Кай> О! Это ты! Нам осталось не так уж и много. Всё будет в лучшем виде!")
wait(5f)
play("hollowstory:ob2")
team.sendMessage("<Оббик> Я и не сомневаюсь")
wait(3f)
play("hollowstory:ob3")
team.sendMessage("<Оббик> Хочу узнать, что ты думаешь насчёт нашего гостя, у кого не спрошу, у всех своё на уме, а парень то вроде хороший...")
wait(6f)
play("hollowstory:ka2")
team.sendMessage("<Кай> Хмм...")
wait(2f)
play("hollowstory:ka3")
team.sendMessage("<Кай> ты проходи, чего у порога стоять?")
wait(1f)
overlay.makeBlack(2f)
wait(2f)
(player as ServerPlayerEntity).teleportTo(level, 218.4, 72.0, -788.7, -5.0f, 5.4f)
overlay.makeTransparent(2f)
wait(4f)
play("hollowstory:ka4")
team.sendMessage("<Кай> Ничего не думаю, понимаешь? Сколько у нас проезжих гостей было? Коли хороший, пусть остаётся, сколько захочет, а если нет, его быстро зашиворот выгонят. Пока понаблюдаем, а там будет уже видно будет.")
wait(12f)
overlay.makeBlack(2f)
wait(2f)
(player as ServerPlayerEntity).teleportTo(level, startPos.x(), startPos.y(), startPos.z(), 0f, 0f)
player.setGameMode(GameType.SURVIVAL)
overlay.makeTransparent(2f)
wait(2f)
Minecraft.getInstance().setScreen(null)
| 0
|
Kotlin
|
0
| 2
|
6cd5561f599ff7afc638417dfbd1582bc37e31a1
| 3,719
|
HollowEngine
|
MIT License
|
src/main/kotlin/dev/dexsr/gmod/palworld/toolbox/paldex/pals/composeui/PalsScreen.kt
|
flammky
| 758,310,188
| false
|
{"Kotlin": 1491891}
|
package dev.dexsr.gmod.palworld.toolbox.paldex.pals.composeui
| 0
|
Kotlin
|
0
| 4
|
cd07163868b5ee8d3f46d106d467d211b8f3c5d8
| 63
|
PalToolbox
|
Apache License 2.0
|
data/src/main/java/com/example/data/remote/service/CharacterService.kt
|
ardaltunyay
| 449,805,922
| false
|
{"Kotlin": 27963}
|
package com.example.data.remote.service
import com.example.data.remote.model.GetAllCharactersResponse
import com.example.data.remote.model.GetSingleCharacterResponse
import retrofit2.http.GET
import retrofit2.http.Path
interface CharacterService {
@GET("character/{characterId}")
suspend fun getSingleCharacter(@Path("characterId") characterId: String): GetSingleCharacterResponse
@GET("character")
suspend fun getAllCharacters(): GetAllCharactersResponse
}
| 0
|
Kotlin
|
0
| 0
|
7ed2a6305d76f586449245a874509ce44c24e05b
| 478
|
RickAndMortyAndroid
|
Apache License 2.0
|
src/main/kotlinTemp/toolkit/ClassContext.kt
|
lhwdev
| 768,438,766
| false
|
{"Kotlin": 286875, "Java": 19047, "Lua": 11825}
|
package com.lhwdev.asm.toolkit
import com.lhwdev.asm.toolkit.descriptor.ClassDescriptor
import com.lhwdev.asm.toolkit.descriptor.FieldHandle
import com.lhwdev.asm.toolkit.descriptor.MethodDescriptor
@ContextMarker
interface ClassContext {
fun define(access: Int, name: String, superType: Type): ClassDescriptor
fun implements(interfaceType: Type)
fun addField(access: Int, name: String, type: Type, block: context(FieldContext) () -> Unit = {}): FieldHandle?
fun addMethod(descriptor: MethodInfo? = null, block: context(MethodContext) () -> Unit): MethodDescriptor?
fun addMethod(access: Int, name: String, block: context(MethodContext) () -> Unit): MethodDescriptor?
fun addConstructor(access: Int, block: context(MethodContext) () -> Unit): MethodDescriptor?
fun endClass(): ClassDescriptor
}
| 0
|
Kotlin
|
0
| 0
|
ecb8d2c47462627a9d2afc2d23b128ff496aea01
| 824
|
railx
|
MIT License
|
app/src/main/java/com/arjinmc/jetpackplayground/architecture/room/RoomDataBean.kt
|
arjinmc
| 369,449,668
| false
| null |
package com.arjinmc.jetpackplayground.architecture.room
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
/**
* Created by Eminem Lo on 12/2/21
* email: arjinmc@hotmail.com
*
* auto migration support
* @DeleteColumn
* @DeleteTable
* @RenameColumn
* @RenameTable
*/
@Entity(tableName = "room_data")
class RoomDataBean {
@PrimaryKey(autoGenerate = true)
var id: Long? = null
@ColumnInfo(name = "content")
var content: String? = null
//use it when db version=1
@Ignore
var last_update: Long? = null
}
| 0
|
Kotlin
|
0
| 0
|
d31ad59c3198d01b20a8100e2fc4ad4391afce5b
| 609
|
JetpackPlayground
|
Apache License 2.0
|
app/src/main/java/com/arjinmc/jetpackplayground/architecture/room/RoomDataBean.kt
|
arjinmc
| 369,449,668
| false
| null |
package com.arjinmc.jetpackplayground.architecture.room
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
/**
* Created by <NAME> on 12/2/21
* email: <EMAIL>
*
* auto migration support
* @DeleteColumn
* @DeleteTable
* @RenameColumn
* @RenameTable
*/
@Entity(tableName = "room_data")
class RoomDataBean {
@PrimaryKey(autoGenerate = true)
var id: Long? = null
@ColumnInfo(name = "content")
var content: String? = null
//use it when db version=1
@Ignore
var last_update: Long? = null
}
| 0
|
Kotlin
|
0
| 0
|
d31ad59c3198d01b20a8100e2fc4ad4391afce5b
| 594
|
JetpackPlayground
|
Apache License 2.0
|
app/src/main/java/com/semisonfire/cloudgallery/navigation/router/Router.kt
|
Semyon100116907
| 132,183,724
| false
| null |
package com.semisonfire.cloudgallery.navigation.router
import androidx.fragment.app.FragmentManager
import com.semisonfire.cloudgallery.navigation.destination.Destination
interface Router {
fun bind(fragmentManager: FragmentManager)
fun unbind()
fun open(destination: Destination)
fun openBottomSheet(destination: Destination)
fun replaceScreen(destination: Destination)
fun back()
fun clear()
}
| 0
|
Kotlin
|
0
| 1
|
59f8b94fdeaf8db0557deef84f1b25224ab768e4
| 428
|
CloudGallery
|
MIT License
|
ui/src/main/java/es/fnmtrcm/ceres/certificadoDigitalFNMT/ui/cert_list/components/CertificateTypeLabelView.kt
|
CodeNationDev
| 757,931,525
| false
|
{"Kotlin": 1417005, "C": 485745, "C++": 480977, "CMake": 283671, "Java": 166491}
|
package es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.cert_list.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.ExperimentalMaterial3Api
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.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.hilt.navigation.compose.hiltViewModel
import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.R
import es.fnmtrcm.ceres.certificadoDigitalFNMT.common.ui.theme.FnmtTS
import es.fnmtrcm.ceres.certificadoDigitalFNMT.data.local.model.ImportedCertificate
import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.cert_list.model.CertificateLabelViewType
import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.cert_list.viewmodel.IListItemViewModel
import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.cert_list.viewmodel.ListItemViewModel
import es.fnmtrcm.ceres.certificadoDigitalFNMT.ui.onboarding.utils.OnboardingType
@ExperimentalMaterial3Api
@Composable
fun CertificateTypeLabelView(
modifier: Modifier,
viewModel: IListItemViewModel = hiltViewModel<ListItemViewModel>(),
onboardingType: OnboardingType? = null,
installed: ImportedCertificate? = null
) {
val context = LocalContext.current
val labelType: CertificateLabelViewType by remember { mutableStateOf(onboardingType?.let {
viewModel.getCertificateTypeForRequest(it)
} ?: installed?.let {
viewModel.getCertificateTypeForInstalled(it)
} ?: CertificateLabelViewType.OTHERS) }
Box(
modifier = Modifier
.height(dimensionResource(id = R.dimen.cert_item_label_style_height))
.fillMaxWidth()
.padding(end = dimensionResource(id = R.dimen.cert_item_label_style_end_padding))
.clip(
shape = RoundedCornerShape(
bottomEnd = dimensionResource(id = R.dimen.cert_item_status_corner_radius),
bottomStart = dimensionResource(id = R.dimen.cert_item_status_corner_radius)
)
)
.background(
colorResource(id = labelType.color)
)
.then(modifier)
) {
Text(
modifier = Modifier
.padding(start = dimensionResource(id = R.dimen.fnmt_margin_16))
.align(Alignment.CenterStart),
text = stringResource(id = labelType.stringName),
style = FnmtTS.overlineMedium(context),
color = colorResource(id = R.color.fnmt_neutral)
)
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Preview
@Composable
fun PreviewCertificateTypeLabelView() {
CertificateTypeLabelView(
viewModel = object : IListItemViewModel() {
override fun getCertificateTypeForInstalled(request: ImportedCertificate): CertificateLabelViewType {
return CertificateLabelViewType.CITIZEN
}
override fun getCertificateTypeForRequest(onboardingType: OnboardingType): CertificateLabelViewType {
return CertificateLabelViewType.PUBLIC_EMPLOYEE
}
},
onboardingType = OnboardingType.ADMINISTRATIVE,
installed = null,
modifier = Modifier
)
}
| 0
|
Kotlin
|
0
| 0
|
9c5d7b9355c406992ff9126d4bd01d49d4778048
| 3,891
|
FabricK
|
MIT License
|
rx2/src/test/java/com/github/kotlinutils/rx2/RxMutExOperationTypesCallerTest.kt
|
bornest
| 98,300,465
| false
| null |
package com.github.kotlinutils.rx2
import com.github.kotlinutils.random.extensions.randomBoolean
import com.github.kotlinutils.random.extensions.sleepRandomTime
import com.github.kotlinutils.concurrent.java.extensions.curThreadNameInBr
import com.github.unitimber.core.JavaLogger
import com.github.unitimber.core.UniTimber
import com.github.unitimber.core.extensions.uniTimberPlantDebugTree
import com.github.unitimber.core.extensions.v
import io.reactivex.Observable
import io.reactivex.Scheduler
import io.reactivex.Single
import io.reactivex.schedulers.Schedulers
import org.junit.After
import org.junit.Before
import org.junit.Test
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
import java.util.concurrent.atomic.AtomicBoolean
import kotlin.test.assertTrue
class RxMutExOperationTypesCallerTest {
@Before
fun setup() {
uniTimberPlantDebugTree { JavaLogger() }
}
@After
fun tearDown() {
UniTimber.uprootAll()
}
@Test
fun regularDelayCalls() {
val latchCount = 6
val latchTime = 1L
val timeUnit = TimeUnit.MINUTES
val testObj = TestClassRegular("regularDelayOpCaller", latchTime, timeUnit)
runTest(testObj, latchCount, latchTime, timeUnit) {
latch ->
val t1 = Thread {
//1
testObj.aOne(Schedulers.newThread())
.take(3)
.doFinally {
latch.countDown()
}
.test()
Thread.sleep(600)
//4
testObj.bTwo(Schedulers.io())
.doFinally {
latch.countDown()
}
.test()
Thread.sleep(300)
//5
testObj.aTwo(Schedulers.io())
.doFinally {
latch.countDown()
}
.test()
}
val t2 = Thread {
Thread.sleep(200)
//2
testObj.bTwo(Schedulers.io())
.doFinally {
latch.countDown()
}
.test()
Thread.sleep(200)
//3
testObj.aTwo(Schedulers.io())
.doFinally {
latch.countDown()
}
.test()
Thread.sleep(400)
//6
testObj.bOne(Schedulers.newThread())
.take(3)
.doFinally {
latch.countDown()
}
.test()
}
t1.start()
t2.start()
}
}
@Test
fun randomDelayCalls(){
val latchCount = 6
val latchTime = 1L
val timeUnit = TimeUnit.MINUTES
val testObj = TestClassRandom("randomDelayOpCaller", latchTime, timeUnit)
runTest(testObj, latchCount, latchTime, timeUnit) {
latch ->
val t1 = Thread {
//1
testObj.aOne(Schedulers.newThread())
.take(3)
.doFinally {
latch.countDown()
}
.test()
sleepRandomTime(10, 600)
//4
testObj.bTwo(Schedulers.io())
.doFinally {
latch.countDown()
}
.test()
sleepRandomTime(10, 300)
//5
testObj.aTwo(Schedulers.io())
.doFinally {
latch.countDown()
}
.test()
}
val t2 = Thread {
sleepRandomTime(10, 200)
//2
testObj.bTwo(Schedulers.io())
.doFinally {
latch.countDown()
}
.test()
sleepRandomTime(10, 200)
//3
testObj.aTwo(Schedulers.io())
.doFinally {
latch.countDown()
}
.test()
sleepRandomTime(10, 400)
//6
testObj.bOne(Schedulers.newThread())
.take(3)
.doFinally {
latch.countDown()
}
.test()
}
t1.start()
t2.start()
}
}
// @Ignore
@Test
fun zeroDelayCalls() {
val latchCount = 6
val latchTime = 1L
val timeUnit = TimeUnit.MINUTES
val testObj = TestClassRegular("zeroDelayOpCaller", latchTime, timeUnit)
runTest(testObj, latchCount, latchTime, timeUnit) {
latch ->
val t1 = Thread {
testObj.aOne(Schedulers.newThread())
.take(3)
.doFinally {
latch.countDown()
}
.test()
testObj.bTwo(Schedulers.io())
.doFinally {
latch.countDown()
}
.test()
testObj.aTwo(Schedulers.io())
.doFinally {
latch.countDown()
}
.test()
}
val t2 = Thread {
testObj.bTwo(Schedulers.io())
.doFinally {
latch.countDown()
}
.test()
testObj.aTwo(Schedulers.io())
.doFinally {
latch.countDown()
}
.test()
testObj.bOne(Schedulers.newThread())
.take(3)
.doFinally {
latch.countDown()
}
.test()
}
t1.start()
t2.start()
}
}
private inline fun runTest(testObj: AbstractTestClass,
latchCount: Int,
latchTime: Long,
timeUnit: TimeUnit,
testBody: (CountDownLatch) -> Unit
) {
val opInfoQBusExec = testObj.opCaller._opInfoQueueProcessingExecutor
val regUnregBusExec = testObj.opCaller._regUnregReqProcessingExecutor
val latch = CountDownLatch(latchCount)
testBody(latch)
val latchWasOnTime = latch.await(latchTime, timeUnit)
opInfoQBusExec.shutdown()
regUnregBusExec.shutdown()
assertTrue { latchWasOnTime }
}
//region inner Test Classes
abstract class AbstractTestClass(opCallerName: String, keepAliveTime: Long, timeUnit: TimeUnit) {
val opCaller = RxMutExOperationTypesCaller(opCallerName, keepAliveTime, timeUnit)
abstract protected fun waitShort()
abstract protected fun waitLong()
fun aOne(scheduler: Scheduler): Observable<String> {
val opName = "aOne"
val disposed = AtomicBoolean(false)
return opCaller.callObservable(TestOperationType.A, opName,
Observable.create<String> {
emitter ->
v{"$curThreadNameInBr $opName: performing initial setup"}
waitShort() //imitate initial setup
v{"$curThreadNameInBr $opName: sending initial value: 0"}
emitter.onNext("$opName: 0 (initial value)") //send initial value
var i = 0
while ( !disposed.get() )
{
waitLong() //imitate work/delay
// v{"$curThreadNameInBr $opName: sending next value: $i"}
emitter.onNext("$curThreadNameInBr $opName: $i") //send next value
i++
}
}
.doFinally {
disposed.set(true)
}
.subscribeOn(scheduler)
)
}
fun aTwo(scheduler: Scheduler): Single<String> {
val opName = "aTwo"
return opCaller.callSingle(TestOperationType.A, opName,
Single.create<String> {
emitter ->
v{"$curThreadNameInBr $opName: doing work"}
waitLong() //imitate work/delay
if (randomBoolean(0.9)){
v{"$curThreadNameInBr $opName: sending onSuccess"}
emitter.onSuccess("$opName: ")
} else {
v{"$curThreadNameInBr $opName: sending onError"}
emitter.onError(Throwable("$opName: "))
}
}
.subscribeOn(scheduler)
)
}
fun bOne(scheduler: Scheduler): Observable<String> {
val opName = "bOne"
val disposed = AtomicBoolean(false)
return opCaller.callObservable(TestOperationType.A, opName,
Observable.create<String> {
emitter ->
v{"$curThreadNameInBr $opName: performing initial setup"}
waitShort() //imitate initial setup
v{"$curThreadNameInBr $opName: sending initial value: 0"}
emitter.onNext("$opName: 0 (initial value)") //send initial value
var i = 0
while ( !disposed.get() )
{
waitLong() //imitate work/delay
// v{"$curThreadNameInBr $opName: sending next value: $i"}
emitter.onNext("$curThreadNameInBr $opName: $i") //send next value
i++
}
}
.doFinally {
disposed.set(true)
}
.subscribeOn(scheduler)
)
}
fun bTwo(scheduler: Scheduler): Single<String> {
val opName = "bTwo"
return opCaller.callSingle(TestOperationType.B, opName,
Single.create<String> {
emitter ->
v{"$curThreadNameInBr $opName: doing work"}
waitLong() //imitate work/delay
if (randomBoolean(0.9)){
v{"$curThreadNameInBr $opName: sending onSuccess"}
emitter.onSuccess("$opName: ")
} else {
v{"$curThreadNameInBr $opName: sending onError"}
emitter.onError(Throwable("$opName: "))
}
}
.subscribeOn(scheduler)
)
}
}
class TestClassRandom(opCallerName: String, keepAliveTime: Long, timeUnit: TimeUnit) : AbstractTestClass(opCallerName, keepAliveTime, timeUnit){
override fun waitShort() {
sleepRandomTime(10, 300)
}
override fun waitLong() {
sleepRandomTime(10, 1000)
}
}
class TestClassRegular(opCallerName: String, keepAliveTime: Long, timeUnit: TimeUnit) : AbstractTestClass(opCallerName, keepAliveTime, timeUnit){
override fun waitShort() {
Thread.sleep(150)
}
override fun waitLong() {
Thread.sleep(500)
}
}
class TestOperationType(name: String) : RxMutExOperationTypesCaller.OperationType(name)
{
companion object {
val A = TestOperationType("A")
val B = TestOperationType("B")
}
}
//endregion
}
| 0
|
Kotlin
|
0
| 1
|
0030f632df3cb42f6142d1384ff90fcd30da12c9
| 12,872
|
KotlinUtils
|
Apache License 2.0
|
chapter3_4_aianimals/AIAnimals/app/src/main/java/com/example/aianimals/repository/access_log/source/local/AccessLogLocalDataSource.kt
|
shibuiwilliam
| 402,711,899
| false
| null |
package com.example.aianimals.repository.access_log.source.local
import com.example.aianimals.middleware.AppExecutors
import com.example.aianimals.repository.access_log.AccessLog
import com.example.aianimals.repository.access_log.source.AccessLogDataSource
class AccessLogLocalDataSource private constructor(
val appExecutors: AppExecutors
) : AccessLogDataSource {
private val TAG = AccessLogLocalDataSource::class.java.simpleName
override suspend fun createAccessLog(accessLog: AccessLog) {
TODO("Not yet implemented")
}
companion object {
private var INSTANCE: AccessLogLocalDataSource? = null
@JvmStatic
fun getInstance(
appExecutors: AppExecutors,
): AccessLogLocalDataSource {
if (INSTANCE == null) {
synchronized(AccessLogLocalDataSource::javaClass) {
INSTANCE = AccessLogLocalDataSource(appExecutors)
}
}
return INSTANCE!!
}
@JvmStatic
fun destroyInstance() {
INSTANCE = null
}
}
}
| 0
|
Python
|
6
| 18
|
ad8a8b3742bcd3a34764ea9f03966eee064f2a0e
| 1,103
|
building-ml-system
|
MIT License
|
app/src/main/java/com/elementary/tasks/home/scheduleview/viewholder/ScheduleShoppingAndGTaskViewHolder.kt
|
naz013
| 165,067,747
| false
|
{"Kotlin": 2681466, "HTML": 20926}
|
package com.elementary.tasks.home.scheduleview.viewholder
import android.content.res.ColorStateList
import android.view.ViewGroup
import com.elementary.tasks.core.data.ui.UiReminderListActiveShop
import com.elementary.tasks.core.utils.ThemeProvider
import com.elementary.tasks.core.utils.gone
import com.elementary.tasks.core.utils.inflater
import com.elementary.tasks.databinding.ListItemScheduleReminderAndGoogleBinding
import com.elementary.tasks.home.scheduleview.ReminderAndGoogleTaskScheduleModel
class ScheduleShoppingAndGTaskViewHolder(
parent: ViewGroup,
private val isDark: Boolean,
private val common: ScheduleReminderViewHolderCommon,
private val googleCommon: ScheduleGoogleViewHolderCommon,
private val reminderClickListener: (Int) -> Unit,
private val taskClickListener: (Int) -> Unit
) : BaseScheduleHolder<ListItemScheduleReminderAndGoogleBinding>(
ListItemScheduleReminderAndGoogleBinding.inflate(parent.inflater(), parent, false)
) {
init {
binding.reminderPhoneView.gone()
binding.reminderCard.setOnClickListener {
reminderClickListener(bindingAdapterPosition)
}
binding.googleTaskCard.setOnClickListener {
taskClickListener(bindingAdapterPosition)
}
binding.connectionCard.setOnClickListener { }
}
fun setData(data: ReminderAndGoogleTaskScheduleModel) {
binding.reminderTextView.text = data.reminder.summary
binding.reminderTimeView.text = data.reminder.due?.formattedTime
common.loadItems(
reminder = data.reminder as UiReminderListActiveShop,
todoListView = binding.todoListView,
isDark = isDark,
textColor = ThemeProvider.getThemeOnSurfaceColor(itemView.context)
)
data.reminder.group?.also { group ->
binding.reminderIconView.imageTintList = ColorStateList.valueOf(group.color)
}
googleCommon.loadTitle(data.googleTask, binding.googleTaskTitleView)
googleCommon.loadNotes(data.googleTask, binding.googleTaskNoteView)
googleCommon.tintIcon(data.googleTask, binding.googleTaskIconView)
}
}
| 0
|
Kotlin
|
2
| 4
|
f016496eeffdd8ee09d93ecf8a5802305f50eb97
| 2,043
|
reminder-kotlin
|
Apache License 2.0
|
stevedoreviews/src/main/java/com/artear/stevedore/stevedoreviews/presentation/model/EmptyItem.kt
|
Artear
| 176,757,658
| false
| null |
package com.artear.stevedore.stevedoreviews.presentation.model
import com.artear.stevedore.stevedoreitems.presentation.model.ArtearObject
import com.artear.stevedore.stevedoreitems.repository.model.box.BoxStyle
class EmptyItem(val weight: Float = 0.5f) : ArtearObject<BoxStyle>()
| 0
|
Kotlin
|
0
| 0
|
aee7531462a451001592433472a571962f29deb1
| 281
|
app_lib_stevedoreviews_android
|
Apache License 2.0
|
src/main/kotlin/cn/yiiguxing/plugin/translate/ui/wordbook/WordColumnInfo.kt
|
YiiGuxing
| 60,159,997
| false
| null |
package cn.yiiguxing.plugin.translate.ui.wordbook
import cn.yiiguxing.plugin.translate.message
import cn.yiiguxing.plugin.translate.wordbook.WordBookItem
import com.intellij.util.ui.ColumnInfo
import javax.swing.table.TableCellRenderer
internal class WordColumnInfo : ColumnInfo<WordBookItem, String>(message("wordbook.window.table.title.word")) {
private val renderer = WordsTableCellRenderer()
override fun valueOf(item: WordBookItem): String = item.word
override fun getRenderer(item: WordBookItem?): TableCellRenderer = renderer
override fun getComparator(): java.util.Comparator<WordBookItem> = COMPARATOR
companion object {
private val COMPARATOR = Comparator<WordBookItem> { word1, word2 ->
word1.word.compareTo(word2.word, true)
}
}
}
| 38
|
Kotlin
|
711
| 9,758
|
3a5cf29b7765e48ff828c23e3bb960aa72a583d4
| 801
|
TranslationPlugin
|
MIT License
|
app/src/main/java/me/kwsk/odptlibrary/di/activity/ActivityModule.kt
|
teracy
| 115,876,824
| false
| null |
package me.kwsk.odptlibrary.di.activity
import android.support.v7.app.AppCompatActivity
import dagger.Module
import dagger.Provides
import me.kwsk.odptlibrary.di.scope.ActivityScope
@Module
abstract class ActivityModule<out T : AppCompatActivity>(protected val activity: T) {
@Provides
@ActivityScope
fun provideActivity(): T {
return activity
}
// NOTE: Add dependencies here
}
| 0
| null |
0
| 5
|
b3fa9249598148fc9cca0574cb62998e42b538f9
| 410
|
OdptLibrary
|
Apache License 2.0
|
android-jsBridgeCore/src/main/java/me/yamlee/jsbridge/BaseJsCallResponse.kt
|
YamLee
| 122,713,770
| false
| null |
package me.yamlee.jsbridge
/**
* Native return content
* @author yamlee
*/
open class BaseJsCallResponse {
var ret: String? = ResponseCode.SUCCESS
var msg: String? = ""
}
| 0
|
Kotlin
|
2
| 3
|
fca5c0eba5d313a9a06585f46c427a16ee4c8b35
| 183
|
AndroidJsBridge
|
Apache License 2.0
|
demo/src/main/java/com/github/chantsune/swipetoaction/demo/custom/CustomSwipeLayoutViewModel.kt
|
ChanTsune
| 336,486,667
| false
|
{"Kotlin": 53852}
|
package com.github.chantsune.swipetoaction.demo.custom
import androidx.lifecycle.ViewModel
class CustomSwipeLayoutViewModel : ViewModel() {
// TODO: Implement the ViewModel
}
| 6
|
Kotlin
|
1
| 5
|
9a0aa02daf03409a4807a49ae208888b94d6f481
| 180
|
swipe-to-action
|
MIT License
|
lib-network/src/main/java/com/example/lib/network/RetrofitHelper.kt
|
Taiga945
| 654,927,820
| false
| null |
package com.example.lib.network
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
private const val TIMEOUT_IN_SECONDS=60
object RetrofitHelper {
val baseUrl = "https://api.imgur.com/3/"
fun getInstance(): Retrofit {
return Retrofit.Builder().baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(
OkHttpClient.Builder()
.connectTimeout(TIMEOUT_IN_SECONDS.toLong(), TimeUnit.SECONDS)
.readTimeout(TIMEOUT_IN_SECONDS.toLong(), TimeUnit.SECONDS)
.authenticator(TokenAuthenticator())
.build()
)
.build()
}
}
| 0
|
Kotlin
|
0
| 0
|
6a2905f9de5071aa7020de68967095e681e76515
| 790
|
imgur-example-android
|
MIT License
|
logging/src/main/kotlin/kingmc/common/logging/slf4j/Slf4jLoggerManager.kt
|
Kingsthere
| 603,292,992
| false
| null |
package kingmc.common.logging.slf4j
import kingmc.common.logging.Logger
import kingmc.common.logging.LoggerManager
import net.kyori.adventure.text.logger.slf4j.ComponentLogger
import kotlin.reflect.KClass
class Slf4jLoggerManager(
private val defaultLogger: Slf4jLoggerWrapper
) : LoggerManager {
/**
* Provide a logger in current application
*
* @since 0.0.3
*/
override fun createLogger(): Logger =
defaultLogger
/**
* Provide a named logger in current application
*
* @since 0.0.3
*/
override fun createLogger(name: String): Logger =
Slf4jLoggerWrapper(ComponentLogger.logger(name))
/**
* Provide a logger from class in current application
*
* @since 0.0.3
*/
override fun createLogger(clazz: Class<*>): Logger =
Slf4jLoggerWrapper(ComponentLogger.logger(clazz))
/**
* Provide a logger from kotlin class in current application
*
* @since 0.0.3
*/
override fun createLogger(clazz: KClass<*>): Logger =
Slf4jLoggerWrapper(ComponentLogger.logger(clazz.java))
}
| 0
|
Kotlin
|
0
| 1
|
7ce900670cdd8ddbf3b01d20ef3f1810179449b7
| 1,114
|
kingmc-common
|
MIT License
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/Track.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.Track: ImageVector
get() {
if (_track != null) {
return _track!!
}
_track = Builder(name = "Track", 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) {
moveToRelative(16.927f, 10.175f)
curveToRelative(0.572f, 0.559f, 1.322f, 0.838f, 2.073f, 0.838f)
reflectiveCurveToRelative(1.501f, -0.279f, 2.073f, -0.838f)
curveToRelative(0.024f, -0.024f, 1.462f, -1.64f, 1.462f, -1.64f)
curveToRelative(0.945f, -0.944f, 1.465f, -2.2f, 1.465f, -3.536f)
reflectiveCurveToRelative(-0.52f, -2.591f, -1.465f, -3.536f)
curveToRelative(-0.944f, -0.944f, -2.2f, -1.464f, -3.535f, -1.464f)
reflectiveCurveToRelative(-2.591f, 0.52f, -3.536f, 1.464f)
curveToRelative(-1.949f, 1.95f, -1.949f, 5.122f, -0.059f, 7.008f)
curveToRelative(0.0f, 0.0f, 1.497f, 1.678f, 1.521f, 1.703f)
close()
moveTo(5.0f, 21.5f)
curveToRelative(0.0f, 1.381f, -1.119f, 2.5f, -2.5f, 2.5f)
reflectiveCurveToRelative(-2.5f, -1.119f, -2.5f, -2.5f)
reflectiveCurveToRelative(1.119f, -2.5f, 2.5f, -2.5f)
reflectiveCurveToRelative(2.5f, 1.119f, 2.5f, 2.5f)
close()
moveTo(12.5f, 13.0f)
curveToRelative(1.381f, 0.0f, 2.5f, 1.119f, 2.5f, 2.5f)
reflectiveCurveToRelative(-1.119f, 2.5f, -2.5f, 2.5f)
reflectiveCurveToRelative(-2.5f, -1.119f, -2.5f, -2.5f)
reflectiveCurveToRelative(1.119f, -2.5f, 2.5f, -2.5f)
close()
moveTo(6.5f, 17.0f)
curveToRelative(-2.481f, 0.0f, -4.5f, -2.019f, -4.5f, -4.5f)
reflectiveCurveToRelative(2.019f, -4.5f, 4.5f, -4.5f)
horizontalLineToRelative(6.0f)
curveToRelative(0.829f, 0.0f, 1.5f, 0.671f, 1.5f, 1.5f)
reflectiveCurveToRelative(-0.671f, 1.5f, -1.5f, 1.5f)
horizontalLineToRelative(-6.0f)
curveToRelative(-0.827f, 0.0f, -1.5f, 0.673f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.673f, 1.5f, 1.5f, 1.5f)
reflectiveCurveToRelative(1.5f, 0.671f, 1.5f, 1.5f)
reflectiveCurveToRelative(-0.671f, 1.5f, -1.5f, 1.5f)
close()
moveTo(24.0f, 18.5f)
curveToRelative(0.0f, 2.481f, -2.019f, 4.5f, -4.5f, 4.5f)
horizontalLineToRelative(-11.0f)
curveToRelative(-0.829f, 0.0f, -1.5f, -0.671f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.671f, -1.5f, 1.5f, -1.5f)
horizontalLineToRelative(11.0f)
curveToRelative(0.827f, 0.0f, 1.5f, -0.673f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.673f, -1.5f, -1.5f, -1.5f)
horizontalLineToRelative(-1.0f)
curveToRelative(-0.829f, 0.0f, -1.5f, -0.671f, -1.5f, -1.5f)
reflectiveCurveToRelative(0.671f, -1.5f, 1.5f, -1.5f)
horizontalLineToRelative(1.0f)
curveToRelative(2.481f, 0.0f, 4.5f, 2.019f, 4.5f, 4.5f)
close()
moveTo(21.001f, 4.787f)
curveToRelative(0.0f, 1.105f, -0.895f, 2.0f, -2.0f, 2.0f)
reflectiveCurveToRelative(-2.0f, -0.895f, -2.0f, -2.0f)
reflectiveCurveToRelative(0.895f, -2.0f, 2.0f, -2.0f)
reflectiveCurveToRelative(2.0f, 0.895f, 2.0f, 2.0f)
close()
}
}
.build()
return _track!!
}
private var _track: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 4,567
|
icons
|
MIT License
|
MyPayTemplate/app/src/main/java/br/uea/transirie/mypay/mypaytemplate2/repository/room/dao/ServicoDao.kt
|
gldnjmat17
| 438,400,051
| false
|
{"Kotlin": 501915}
|
package br.uea.transirie.mypay.mypaytemplate2.repository.room.dao
import androidx.room.*
import br.uea.transirie.mypay.mypaytemplate2.model.Servico
import br.uea.transirie.mypay.mypaytemplate2.repository.room.dao.BaseDao
import br.uea.transirie.mypay.mypaytemplate2.repository.sqlite.COLUMN_DESCRICAO
import br.uea.transirie.mypay.mypaytemplate2.repository.sqlite.COLUMN_ID
import br.uea.transirie.mypay.mypaytemplate2.repository.sqlite.TABLE_SERVICO
@Dao
interface ServicoDao: BaseDao<Servico> {
/**
* Obtém um Servico utilizando o id
*
* @param id o id do usuário a ser buscado
*/
@Query("SELECT * FROM $TABLE_SERVICO WHERE $COLUMN_ID = :id")
fun servicoById(id: Long): Servico
/**
* Busca um Servico utilizando a descrição (nome) dele
*
* @param query a string de busca com a descrição completa ou parcial
*/
@Query("""SELECT * FROM $TABLE_SERVICO WHERE $COLUMN_DESCRICAO LIKE :query""")
fun searchByDescricao(query: String): List<Servico>
/**
* Obtém todos os serviços cadastrados
*
*/
@Query("""SELECT * FROM $TABLE_SERVICO""")
fun getAllServicos(): List<Servico>
}
| 0
|
Kotlin
|
0
| 0
|
bef2b21101aee9c8f985498532385eee18cb0e05
| 1,166
|
MyPets---Aplicativo
|
MIT License
|
kotlin-electron/src/jsMain/generated/electron/renderer/TouchBarSliderConstructorOptions.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 11411371, "JavaScript": 154302}
|
package electron.renderer
typealias TouchBarSliderConstructorOptions = electron.core.TouchBarSliderConstructorOptions
| 28
|
Kotlin
|
173
| 1,250
|
9e9dda28cf74f68b42a712c27f2e97d63af17628
| 120
|
kotlin-wrappers
|
Apache License 2.0
|
analysis/low-level-api-fir/testData/fileBasedDeclarationProvider/local.kt
|
JetBrains
| 3,432,266
| false
| null |
// FUNCTION: test/#foo
package test
fun foo() {
fun bar() {
fun baz() {
class Foo
object Bar
}
}
}
| 181
| null |
5748
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 148
|
kotlin
|
Apache License 2.0
|
net/src/commonMain/kotlin/uk/co/sentinelweb/cuer/net/remote/RemotePlaylistsService.kt
|
sentinelweb
| 220,796,368
| false
|
{"Kotlin": 2604269, "CSS": 205156, "Java": 98919, "Swift": 85812, "HTML": 19322, "JavaScript": 12105, "Ruby": 2170}
|
package uk.co.sentinelweb.cuer.net.remote
import uk.co.sentinelweb.cuer.app.orchestrator.OrchestratorContract
import uk.co.sentinelweb.cuer.domain.GUID
import uk.co.sentinelweb.cuer.domain.RemoteNodeDomain
import uk.co.sentinelweb.cuer.domain.system.ResponseDomain
import uk.co.sentinelweb.cuer.net.client.ServiceExecutor
import uk.co.sentinelweb.cuer.remote.server.RemoteWebServerContract.Companion.PLAYLISTS_API
import uk.co.sentinelweb.cuer.remote.server.RemoteWebServerContract.Companion.PLAYLIST_API
import uk.co.sentinelweb.cuer.remote.server.ipport
internal class RemotePlaylistsService(
private val executor: ServiceExecutor
) {
internal suspend fun getPlaylists(
node: RemoteNodeDomain
): ResponseDomain = executor.get<ResponseDomain>(
path = node.ipport() + PLAYLISTS_API.PATH
)
internal suspend fun getPlaylist(
id: OrchestratorContract.Identifier<GUID>
): ResponseDomain = executor.get<ResponseDomain>(
path = ((id.locator ?: throw IllegalArgumentException()).ipport() + PLAYLIST_API.PATH)
.replace("{id}", id.id.value) // fixme use whatever ktor way
)
}
| 95
|
Kotlin
|
0
| 2
|
55f09fc30a398c9663789ef58a7b955a7a52153f
| 1,143
|
cuer
|
Apache License 2.0
|
idea/testData/refactoring/changeSignature/ChangeClassParameterAfter.kt
|
staltz
| 44,854,854
| true
|
{"Java": 15450397, "Kotlin": 8578737, "JavaScript": 176060, "HTML": 22810, "Lex": 17327, "Protocol Buffer": 13024, "ANTLR": 9689, "CSS": 9431, "Shell": 3931, "IDL": 3257, "Groovy": 3010, "Batchfile": 2831}
|
open class A(open var <caret>s: String)
class B(override var s: String): A(s)
class C: A(0) {
override var s: String = 1
}
fun test() {
val t1 = A(0).s
A(0).s = 1
val t2 = B(0).s
B(0).s = 2
val t3 = C().s
C().s = 3
val t4 = J().getS()
J().setS(4)
}
| 0
|
Java
|
0
| 1
|
80074c71fa925a1c7173e3fffeea4cdc5872460f
| 290
|
kotlin
|
Apache License 2.0
|
src/main/kotlin/dilivia/s2/S2WedgeRelations.kt
|
Enovea
| 409,487,197
| false
|
{"Kotlin": 3249710}
|
/*
* Copyright © 2021 Enovea (<EMAIL>)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dilivia.s2
import dilivia.s2.S2WedgeRelations.WedgeRelation.WEDGE_EQUALS
import dilivia.s2.S2WedgeRelations.WedgeRelation.WEDGE_IS_DISJOINT
import dilivia.s2.S2WedgeRelations.WedgeRelation.WEDGE_IS_PROPERLY_CONTAINED
import dilivia.s2.S2WedgeRelations.WedgeRelation.WEDGE_PROPERLY_CONTAINS
import dilivia.s2.S2WedgeRelations.WedgeRelation.WEDGE_PROPERLY_OVERLAPS
// Defines functions for determining the relationship between two angles
// ("wedges") that share a common vertex.
object S2WedgeRelations {
// Detailed relation from one wedge A to another wedge B.
enum class WedgeRelation {
WEDGE_EQUALS, // A and B are equal.
WEDGE_PROPERLY_CONTAINS, // A is a strict superset of B.
WEDGE_IS_PROPERLY_CONTAINED, // A is a strict subset of B.
WEDGE_PROPERLY_OVERLAPS, // A-B, B-A, and A intersect B are non-empty.
WEDGE_IS_DISJOINT, // A and B are disjoint.
}
// Given an edge chain (x0, x1, x2), the wedge at x1 is the region to the
// left of the edges. More precisely, it is the set of all rays from x1x0
// (inclusive) to x1x2 (exclusive) in the *clockwise* direction.
//
// The following functions compare two *non-empty* wedges that share the
// same middle vertex: A=(a0, ab1, a2) and B=(b0, ab1, b2).
// Returns the relation from wedge A to B.
// REQUIRES: A and B are non-empty.
fun getWedgeRelation(a0: S2Point, ab1: S2Point, a2: S2Point, b0: S2Point, b2: S2Point): WedgeRelation {
// There are 6 possible edge orderings at a shared vertex (all
// of these orderings are circular, i.e. abcd == bcda):
//
// (1) a2 b2 b0 a0: A contains B
// (2) a2 a0 b0 b2: B contains A
// (3) a2 a0 b2 b0: A and B are disjoint
// (4) a2 b0 a0 b2: A and B intersect in one wedge
// (5) a2 b2 a0 b0: A and B intersect in one wedge
// (6) a2 b0 b2 a0: A and B intersect in two wedges
//
// We do not distinguish between 4, 5, and 6.
// We pay extra attention when some of the edges overlap. When edges
// overlap, several of these orderings can be satisfied, and we take
// the most specific.
if (a0 == b0 && a2 == b2) return WEDGE_EQUALS
if (S2Predicates.orderedCCW(a0, a2, b2, ab1)) {
// The cases with this vertex ordering are 1, 5, and 6,
// although case 2 is also possible if a2 == b2.
if (S2Predicates.orderedCCW(b2, b0, a0, ab1)) return WEDGE_PROPERLY_CONTAINS;
// We are in case 5 or 6, or case 2 if a2 == b2.
return if(a2 == b2) WEDGE_IS_PROPERLY_CONTAINED else WEDGE_PROPERLY_OVERLAPS;
}
// We are in case 2, 3, or 4.
if (S2Predicates.orderedCCW(a0, b0, b2, ab1)) return WEDGE_IS_PROPERLY_CONTAINED;
return if(S2Predicates.orderedCCW(a0, b0, a2, ab1)) WEDGE_IS_DISJOINT else WEDGE_PROPERLY_OVERLAPS
}
// Returns true if wedge A contains wedge B. Equivalent to but faster than
// GetWedgeRelation() == WEDGE_PROPERLY_CONTAINS || WEDGE_EQUALS.
// REQUIRES: A and B are non-empty.
fun wedgeContains(a0: S2Point, ab1: S2Point, a2: S2Point, b0: S2Point, b2: S2Point): Boolean {
// For A to contain B (where each loop interior is defined to be its left
// side), the CCW edge order around ab1 must be a2 b2 b0 a0. We split
// this test into two parts that test three vertices each.
return (S2Predicates.orderedCCW(a2, b2, b0, ab1) && S2Predicates.orderedCCW(b0, a0, a2, ab1))
}
// Returns true if wedge A intersects wedge B. Equivalent to but faster
// than GetWedgeRelation() != WEDGE_IS_DISJOINT.
// REQUIRES: A and B are non-empty.
fun wedgeIntersects(a0: S2Point, ab1: S2Point, a2: S2Point, b0: S2Point, b2: S2Point): Boolean {
// For A not to intersect B (where each loop interior is defined to be
// its left side), the CCW edge order around ab1 must be a0 b2 b0 a2.
// Note that it's important to write these conditions as negatives
// (!OrderedCCW(a,b,c,o) rather than Ordered(c,b,a,o)) to get correct
// results when two vertices are the same.
return !(S2Predicates.orderedCCW(a0, b2, b0, ab1) && S2Predicates.orderedCCW(b0, a2, a0, ab1))
}
}
| 0
|
Kotlin
|
3
| 17
|
eb5139ec5c69556e8dc19c864b052e7e45a48b49
| 4,955
|
s2-geometry-kotlin
|
Apache License 2.0
|
app/src/main/kotlin/suhockii/dev/bookfinder/presentation/categories/CategoriesPresenter.kt
|
fossabot
| 133,040,499
| false
| null |
package suhockii.dev.bookfinder.presentation.categories
import com.arellomobile.mvp.InjectViewState
import com.arellomobile.mvp.MvpPresenter
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import suhockii.dev.bookfinder.data.error.ErrorHandler
import suhockii.dev.bookfinder.domain.CategoriesInteractor
import javax.inject.Inject
@InjectViewState
class CategoriesPresenter @Inject constructor(
private val interactor: CategoriesInteractor,
private val errorHandler: ErrorHandler
) : MvpPresenter<CategoriesView>(), AnkoLogger {
override fun onFirstViewAttach() {
super.onFirstViewAttach()
doAsync(errorHandler.errorReceiver) {
interactor.getCategories()
.let { categories -> uiThread { viewState.showCategories(categories) } }
}
}
}
| 1
|
Kotlin
|
1
| 1
|
76dd17f5d1d541b713466cba1e65b75aca855037
| 861
|
BookFinder-Android
|
Apache License 2.0
|
inject/test/src/main/kotlin/neekle/test/Mocker.kt
|
neyb
| 110,265,948
| false
| null |
package neekle.test
interface Mocker {
fun <T> mock(type: Class<T>): T
}
| 0
|
Kotlin
|
0
| 0
|
ffe1bc7f6fc501486941539a1fea9cac9184c18e
| 77
|
neekle
|
MIT License
|
src/main/kotlin/dev/civmc/oworldgen/populators/desert/DesertDeadShrub.kt
|
Ameliorate
| 196,504,030
| false
| null |
package dev.civmc.oworldgen.populators.desert
import dev.civmc.oworldgen.populators.BiomeDependantBlockPopulator
import org.bukkit.Chunk
import org.bukkit.Material
import org.bukkit.World
import org.bukkit.block.Biome
import java.util.*
class DesertDeadShrub: BiomeDependantBlockPopulator(Biome.DESERT_HILLS) {
override fun populate(world: World, random: Random, chunk: Chunk) {
for (x in 0..15) {
for (z in 0..15) {
if (!shouldRun(world, chunk, x, z))
continue
for (y in 0..255) {
if (chunk.getBlock(x, y - 1, z).type != Material.SAND)
continue
if (chunk.getBlock(x, y, z).type != Material.AIR)
continue
if (random.nextFloat() > 0.003)
continue
chunk.getBlock(x, y, z).type = Material.DEAD_BUSH
}
}
}
}
}
| 1
|
Kotlin
|
0
| 0
|
f73727d26065383b91c13a9d818c9c375f01f41e
| 979
|
OWOrldGen
|
MIT License
|
src/main/kotlin/com/metabrain/bitcoin/blockchain/services/BitcoinAPI.kt
|
metabrain
| 131,651,818
| false
| null |
package com.metabrain.bitcoin.blockchain.services
import com.metabrain.bitcoin.blockchain.services.model.BitcoinTxn
/**
* Interface for providing information about BTC.
*
* Created by daniel.parreira on 01/05/2018.
*/
interface BitcoinAPI {
/**
* Enquires an external entity about the transactions that are currently unspent (transactions received
* that still have not been part of the input to an outgoing transaction) by the bitcoin address.
*
* @param btcAddress the BTC address
* @return the list of unspent transactions this address currently has.
*/
fun getUnspentTxns(btcAddress: String): List<BitcoinTxn>
}
| 0
|
Kotlin
|
0
| 0
|
a6b922a0012ef0f9fa316b91afe1e69b0b364c1d
| 662
|
sample-bitcoin-app-via-blockchain-api
|
The Unlicense
|
src/main/kotlin/com/nikichxp/tgbot/core/dto/BotCommand.kt
|
NikichXP
| 395,716,371
| false
|
{"Kotlin": 151761, "Dockerfile": 242}
|
package com.nikichxp.tgbot.core.dto
data class BotCommand(
val command: String,
val description: String
)
| 2
|
Kotlin
|
0
| 1
|
db8a78e936fac5c43f942c98a9b2e3b88b274128
| 115
|
tgbot
|
Apache License 2.0
|
utils/src/test/kotlin/org/jetbrains/bsp/bazel/utils/dope/DopeFilesTest.kt
|
JetBrains
| 288,953,714
| false
| null |
package org.jetbrains.bsp.bazel.utils.dope
import io.kotest.matchers.shouldBe
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import java.nio.file.AccessDeniedException
import java.nio.file.FileAlreadyExistsException
import java.nio.file.Files
import java.nio.file.NoSuchFileException
class DopeFilesTest {
@Nested
@DisplayName("DopeFiles.readText(filePath) tests")
inner class ReadTextTest {
@Test
fun `should return failure for not existing file`() {
// given
val filePath = DopeTemp.createTempPath("file/doesnt/exist.xd")
// when
val fileContentTry = DopeFiles.readText(filePath)
// then
fileContentTry.isFailure shouldBe true
fileContentTry.cause::class shouldBe NoSuchFileException::class
}
@Test
fun `should parse existing file and return success`() {
// given
val filePath = DopeTemp.createTempFile("path/to/file.xd")
Files.writeString(filePath, "test content")
// when
val fileContentTry = DopeFiles.readText(filePath)
// then
fileContentTry.isSuccess shouldBe true
val fileContent = fileContentTry.get()
fileContent shouldBe "test content"
}
}
@Nested
@DisplayName("DopeFiles.writeText(filePath, text) tests")
inner class WriteTextTest {
@Disabled("It doesn't work on TC, it's deprecated anyway - im about to remove DopeFiles")
@Test
fun `should return failure for path without writing permission`() {
// given
val filePath = DopeTemp.createTempFile("path/to/file.xd", false)
// when
val writeResult = DopeFiles.writeText(filePath, "test content")
// then
writeResult.isFailure shouldBe true
writeResult.cause::class shouldBe AccessDeniedException::class
writeResult.cause.message shouldBe filePath.toString()
}
@Test
fun `should return success and create the file save text for normal path`() {
// given
val filePath = DopeTemp.createTempPath("path/to/file.xd")
// when
val writeResult = DopeFiles.writeText(filePath, "test content")
// then
writeResult.isSuccess shouldBe true
Files.readString(filePath) shouldBe "test content"
}
@Test
fun `should return success and override file content`() {
// given
val filePath = DopeTemp.createTempFile("path/to/file.xd")
Files.writeString(filePath, "old content")
// when
val writeResult = DopeFiles.writeText(filePath, "test content")
// then
writeResult.isSuccess shouldBe true
Files.readString(filePath) shouldBe "test content"
}
}
@Nested
@DisplayName("DopeFiles.createDirectories(dir) tests")
inner class CreateDirectoriesTest {
@Test
fun `should return failure if a file exists in the location`() {
// given
val dirPath = DopeTemp.createTempFile("existing/file.xd")
// when
val createDirectoriesResult = DopeFiles.createDirectories(dirPath)
// then
createDirectoriesResult.isFailure shouldBe true
createDirectoriesResult.cause::class shouldBe FileAlreadyExistsException::class
createDirectoriesResult.cause.message shouldBe dirPath.toString()
}
@Test
fun `should return success and create 1 dir`() {
// given
val dirPath = DopeTemp.createTempPath("dir")
// when
val createDirectoriesResult = DopeFiles.createDirectories(dirPath)
// then
createDirectoriesResult.isSuccess shouldBe true
Files.exists(dirPath) shouldBe true
Files.isDirectory(dirPath) shouldBe true
}
@Test
fun `should return success and create 3 dirs`() {
// given
val dirPath = DopeTemp.createTempPath("path/to/dir")
// when
val createDirectoriesResult = DopeFiles.createDirectories(dirPath)
// then
createDirectoriesResult.isSuccess shouldBe true
Files.exists(dirPath) shouldBe true
Files.isDirectory(dirPath) shouldBe true
Files.exists(dirPath.parent) shouldBe true
Files.isDirectory(dirPath.parent) shouldBe true
Files.exists(dirPath.parent.parent) shouldBe true
Files.isDirectory(dirPath.parent.parent) shouldBe true
}
}
}
| 7
|
Kotlin
|
28
| 107
|
dc2d5782974d1e80185a7fae1fc238342846b04b
| 4,838
|
bazel-bsp
|
Apache License 2.0
|
debug/src/main/kotlin/app/playground/ui/debug/domain/GetHttpLoggingUseCase.kt
|
shawnthye
| 420,680,965
| false
|
{"Kotlin": 416438}
|
package app.playground.ui.debug.domain
import app.playground.ui.debug.data.DebugStorage
import app.playground.ui.debug.data.HttpLogging
import core.playground.IoDispatcher
import core.playground.domain.FlowUseCase
import core.playground.domain.Result
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import javax.inject.Inject
internal class GetHttpLoggingUseCase @Inject constructor(
private val storage: DebugStorage,
@IoDispatcher ioDispatcher: CoroutineDispatcher,
) : FlowUseCase<Unit, HttpLogging>(ioDispatcher) {
override fun execute(params: Unit): Flow<Result<HttpLogging>> = storage.httpLoggingLevel.map {
Result.Success(it)
}
}
| 0
|
Kotlin
|
0
| 0
|
15df4f3acc202e88f2de0e62549e6e5386440c9e
| 733
|
playground
|
MIT License
|
src/main/java/calebxzhou/craftcone/entity/ConeRoom.kt
|
calebxzhou
| 655,742,846
| false
| null |
package calebxzhou.craftcone.entity
import calebxzhou.craftcone.logger
import calebxzhou.craftcone.mc.Mc
import calebxzhou.craftcone.mc.Mcl
import calebxzhou.craftcone.net.ConeNetSender.sendPacket
import calebxzhou.craftcone.net.protocol.*
import calebxzhou.craftcone.net.protocol.game.BlockDataC2CPacket
import calebxzhou.craftcone.net.protocol.room.JoinRoomC2SPacket
import calebxzhou.craftcone.net.protocol.room.LeaveRoomC2SPacket
import calebxzhou.craftcone.ui.coneErrD
import calebxzhou.craftcone.ui.coneMsg
import calebxzhou.craftcone.ui.screen.ConeRoomInfoScreen
import calebxzhou.craftcone.utils.blockStateOfId
import net.minecraft.client.gui.screens.TitleScreen
import net.minecraft.client.multiplayer.ClientLevel
import net.minecraft.core.BlockPos
import net.minecraft.network.FriendlyByteBuf
import net.minecraft.resources.ResourceKey
import net.minecraft.server.level.ServerLevel
import net.minecraft.world.level.Level
import net.minecraft.world.level.block.Blocks
import net.minecraft.world.level.block.state.BlockState
import java.time.Instant
import java.time.LocalDateTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
/**
* Created on 2023-08-11,12:11.
*/
data class ConeRoom(
//房间ID
val id: Int,
//房间名
val name: String,
//房主id
val ownerId: Int,
//mc版本
val mcVersion: String,
//mod加载器?Fabric:Forge
val isFabric: Boolean,
//创造
val isCreative: Boolean,
//方块状态数量
val blockStateAmount: Int,
//地图种子
val seed: Long,
//创建时间
val createTime: Long,
) : Packet, RenderThreadProcessable {
//玩家列表
private val players = hashMapOf<Int, ConePlayer>()
//维度ID以及对应res key
private val dimIdKeys = hashMapOf<Int, ResourceKey<Level>>()
//维度res key以及对应维度ID
private val dimKeysId = hashMapOf<ResourceKey<Level>, Int>()
companion object : BufferReadable<ConeRoom> {
@JvmStatic
var now: ConeRoom? = null
private set
//从服务器收到房间信息
override fun read(buf: FriendlyByteBuf): ConeRoom {
return ConeRoom(
buf.readVarInt(),
buf.readUtf(),
buf.readVarInt(),
buf.readUtf(),
buf.readBoolean(),
buf.readBoolean(),
buf.readVarInt(),
buf.readLong(),
buf.readLong(),
)
}
//载入房间
fun loadAndJoin(room: ConeRoom) {
if (Mc.blockStateAmount != room.blockStateAmount) {
coneErrD("方块状态数量不一致:您${Mc.blockStateAmount}个/房间${room.blockStateAmount}个。检查Mod列表!")
return
}
coneMsg(MsgType.Toast, MsgLevel.Info, "开始载入房间 $room")
logger.info("载入房间中 $room")
sendPacket(JoinRoomC2SPacket(room.id))
now = room
val levelName = "${Mc.playerName}-${room.id}"
if (Mc.hasLevel(levelName)) {
Mc.loadLevel(levelName)
} else {
Mc.createLevel(levelName, room.isCreative, room.seed)
}
}
//卸载房间
fun unload() {
if (now == null) {
logger.warn("现在没有游玩任何房间,不应该要求卸载")
return
}
logger.info("正在卸载房间")
sendPacket(LeaveRoomC2SPacket())
now = null
}
}
override fun process() {
Mc.screen = ConeRoomInfoScreen(Mc.screen ?: TitleScreen(), this)
}
override fun toString(): String {
return "$name(ID=$id)"
}
fun addPlayer(player: ConePlayer) {
players += player.id to player
}
fun removePlayer(id: Int) {
players -= id
}
fun getPlayer(id: Int): ConePlayer? {
return players[id]
}
val createTimeStr: String
get() = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(
LocalDateTime.ofInstant(
Instant.ofEpochMilli(createTime),
ZoneId.systemDefault()
)
)
//新增维度
fun addDimension(level: ServerLevel) {
val id = dimIdKeys.size
dimIdKeys += id to level.dimension()
dimKeysId += level.dimension() to id
}
//根据维度编号取维度
fun getLevelByDimId(dimId: Int): ServerLevel {
val dim: ResourceKey<Level> = dimIdKeys[dimId] ?: run {
//Cone.numDimKeyMap.forEach { (k, v) -> LOG.error("$k $v") }
logger.warn("找不到编号为${dimId}的维度。默认为主世界!")
Level.OVERWORLD
}
val level = Mcl.getLevel(dim) ?: run {
throw IllegalStateException("处理数据包时,未在游玩状态!")
}
return level
}
//根据维度取维度编号(取不到就默认主世界,0)
fun getDimIdByLevel(level: ServerLevel): Int {
return dimKeysId[level.dimension()] ?: 0
}
//当玩家破坏方块
fun onPlayerBreakBlock(clientLevel: Level, blockPos: BlockPos) {
if (clientLevel is ClientLevel)
return
val level = Mcl.getLevel(clientLevel.dimension()) ?: return
sendPacket(
BlockDataC2CPacket(
getDimIdByLevel(level),
blockPos.asLong(),
blockStateOfId(Blocks.AIR.defaultBlockState())
)
)
}
//当玩家右键点击方块
fun onRightClickBlock(clientLevel: Level, pos: BlockPos) {
if (clientLevel is ClientLevel)
return
val level = Mcl.getLevel(clientLevel.dimension()) ?: return
//Mcl.logicThread {
val tag = level.getBlockEntity(pos)?.saveWithoutMetadata()
sendPacket(
BlockDataC2CPacket(
getDimIdByLevel(level),
pos.asLong(),
blockStateOfId(level.getBlockState(pos)),
tag
)
);
// }
}
fun onPlayerPlaceBlock(clientLevel: Level, blockPos: BlockPos) {
if (clientLevel is ClientLevel)
return
val level = Mcl.getLevel(clientLevel.dimension()) ?: return
sendPacket(
BlockDataC2CPacket(
getDimIdByLevel(level),
blockPos.asLong(),
blockStateOfId(level.getBlockState(blockPos)),
level.getBlockEntity(blockPos)?.saveWithoutMetadata()
)
)
}
fun onSetBlock(clientLevel: Level, blockPos: BlockPos, blockState: BlockState) {
if (clientLevel is ClientLevel)
return
if (!Mcl.isLocalServerReady)
return
if (Mcl.player == null)
return
val level = Mcl.getLevel(clientLevel.dimension()) ?: return
val tag = level.getBlockEntity(blockPos)?.saveWithoutMetadata()
sendPacket(
BlockDataC2CPacket(
getDimIdByLevel(level),
blockPos.asLong(),
blockStateOfId(blockState),
tag
)
)
}
}
/*fun initialize(rid: String) {
ConeDialog.show(ConeDialogType.WARN,"正在初始化房间,禁止退出游戏,禁止断开网络连接!")
blockStates.forEachIndexed { i: Int, blockState: BlockState ->
val bState = BlockState.CODEC.encodeStart(NbtOps.INSTANCE, blockState)
val stateStr = bState.get().left().get().asString
ConeNetManager.sendPacket(SetBlockStateC2SPacket(i,stateStr))
}
ConeDialog.show(ConeDialogType.INFO,"初始化完成")
}*/
| 0
|
Kotlin
|
0
| 0
|
24164295c2a96cf81614537d258b8f4b052cba89
| 7,318
|
craftcone-client
|
Creative Commons Zero v1.0 Universal
|
android/src/main/java/co/reby/rnkustomersdk/KustomerSDKPackage.kt
|
fiveagency
| 382,070,538
| true
|
{"Kotlin": 3311, "Swift": 1613, "Ruby": 783, "Objective-C": 580, "JavaScript": 115}
|
package co.reby.rnkustomersdk;
import android.view.View
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import com.facebook.react.uimanager.ReactShadowNode
class KustomerSDKPackage: ReactPackage {
override fun createNativeModules(reactContext: ReactApplicationContext):
MutableList<NativeModule> {
return mutableListOf(KustomerSDKModule(reactContext))
}
override fun createViewManagers(reactContext: ReactApplicationContext): MutableList<ViewManager<View, ReactShadowNode<*>>> {
return mutableListOf();
}
}
| 0
| null |
0
| 0
|
1265d328e46cba5eae3107c306efc9c3551faa14
| 703
|
react-native-kustomer-sdk
|
MIT License
|
src/main/kotlin/br/com/kofood/pagamentos/model/Payment.kt
|
ocartaxo
| 698,048,160
| false
|
{"Kotlin": 13899}
|
package br.com.kofood.pagamentos.model
import br.com.kofood.pagamentos.dto.PaymentUpdate
import jakarta.persistence.*
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotNull
import jakarta.validation.constraints.PositiveOrZero
import jakarta.validation.constraints.Size
import java.math.BigDecimal
@Entity
@Table(name = "pagamentos")
data class Payment(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long ?= null,
@NotNull
@PositiveOrZero
@Column(name = "valor")
var value: BigDecimal,
@NotBlank
@Size(max=169)
@Column(name = "nome")
var name: String,
@NotBlank
@Size(max=19)
@Column(name = "numero")
val number: String,
@NotBlank
@Size(max=7)
@Column(name = "expiracao")
val expiration: String,
@NotBlank
@Size(min = 3, max = 3)
@Column(name = "codigo")
var code: String,
@NotNull
@Enumerated(value = EnumType.STRING)
var status: Status = Status.CREATED,
@NotNull
@Column(name="pedido_id")
val orderId: Long,
@NotNull
@Column(name="forma_pagamento_id")
val paymentMethodId: Long
) {
fun update(newInfo: PaymentUpdate) {
this.value = newInfo.value ?: this.value
this.name = newInfo.name ?: this.name
this.code = newInfo.code ?: this.code
}
}
| 0
|
Kotlin
|
0
| 0
|
2eebf7650a4ec2b5167b5a79c5e1cb8848995478
| 1,528
|
pagamentos
|
MIT License
|
core/src/main/kotlin/com/safframework/statemachine/utils/extension/Transition+Extension.kt
|
fengzhizi715
| 229,218,626
| false
| null |
package com.safframework.statemachine.utils.extension
import com.safframework.statemachine.TransitionAction
import com.safframework.statemachine.domain.Event
import com.safframework.statemachine.transition.TransitionParams
import com.safframework.statemachine.transition.Transition
/**
*
* @FileName:
* com.safframework.statemachine.utils.extension.`Transition+Extension`
* @author: <NAME>
* @date: 2023/7/4 11:58
* @version: V1.0 <描述当前版本功能>
*/
inline fun <reified E : Event> Transition<E>.onAction(crossinline block: TransitionAction) {
addAction(object : TransitionAction {
@Suppress("UNCHECKED_CAST")
override fun invoke(transitionParams: TransitionParams<*>) = block(transitionParams as TransitionParams<E>)
})
}
| 0
|
Kotlin
|
5
| 25
|
0b3b8994e585978af76155b5db1627b5852e0f9c
| 759
|
KStateMachine
|
Apache License 2.0
|
android/core/network/src/main/java/com/jaino/network/model/response/auth/SignInResponse.kt
|
pknu-wap
| 615,959,763
| false
| null |
package com.jaino.network.model.response.auth
import com.jaino.model.auth.User
import com.jaino.model.setting.Profile
import kotlinx.serialization.Serializable
@Serializable
data class SignInResponse (
val memberResponse : MemberResponse,
val token : TokenResponse
){
fun toSignIn(): User = User(
refreshToken = token.refresh,
accessToken = token.access,
userId = memberResponse.id,
nickName = memberResponse.nickname
)
}
@Serializable
data class MemberResponse(
val id : Long,
val nickname : String
){
fun toProfile(): Profile = Profile(
userId = id,
nickname = nickname
)
}
@Serializable
data class TokenResponse(
val access: String,
val refresh: String
)
| 1
|
Kotlin
|
3
| 9
|
f2144cb5f19d0617b146b94fcc3058f330f2df41
| 749
|
2023_1_WAT_BeJuRyu
|
MIT License
|
app/src/main/java/com/philips/bleclient/ui/UsersLog.kt
|
philips-labs
| 384,088,968
| false
| null |
package com.philips.bleclient.ui
import androidx.databinding.BaseObservable
import androidx.databinding.Bindable
import androidx.databinding.library.baseAdapters.BR
object UsersLog: BaseObservable() {
private const val MAX_LOG_CHARACTERS: Int = 4000
@get:Bindable
var log: String = ""
set(value) {
field = value
notifyPropertyChanged(BR.log)
}
fun log(message: String) {
log = (log + "$message\n").last(MAX_LOG_CHARACTERS)
}
fun clear() {
log = ""
}
}
| 0
|
Kotlin
|
0
| 1
|
4c6acc7b6af33b6983253935ef900a0d26ff8c59
| 541
|
BLE-GHS-Client-Example
|
MIT License
|
app/src/main/java/eu/kanade/tachiyomi/ui/browse/manga/source/MangaSourcesFilterScreenModel.kt
|
aniyomiorg
| 358,887,741
| false
|
{"Kotlin": 4957619}
|
package eu.kanade.tachiyomi.ui.browse.manga.source
import androidx.compose.runtime.Immutable
import cafe.adriel.voyager.core.model.StateScreenModel
import cafe.adriel.voyager.core.model.screenModelScope
import eu.kanade.domain.source.interactor.ToggleLanguage
import eu.kanade.domain.source.manga.interactor.GetLanguagesWithMangaSources
import eu.kanade.domain.source.manga.interactor.ToggleMangaSource
import eu.kanade.domain.source.service.SourcePreferences
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import tachiyomi.domain.source.manga.model.Source
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
import java.util.SortedMap
class MangaSourcesFilterScreenModel(
private val preferences: SourcePreferences = Injekt.get(),
private val getLanguagesWithSources: GetLanguagesWithMangaSources = Injekt.get(),
private val toggleSource: ToggleMangaSource = Injekt.get(),
private val toggleLanguage: ToggleLanguage = Injekt.get(),
) : StateScreenModel<MangaSourcesFilterScreenModel.State>(State.Loading) {
init {
screenModelScope.launch {
combine(
getLanguagesWithSources.subscribe(),
preferences.enabledLanguages().changes(),
preferences.disabledMangaSources().changes(),
) { a, b, c -> Triple(a, b, c) }
.catch { throwable ->
mutableState.update {
State.Error(
throwable = throwable,
)
}
}
.collectLatest { (languagesWithSources, enabledLanguages, disabledSources) ->
mutableState.update {
State.Success(
items = languagesWithSources,
enabledLanguages = enabledLanguages,
disabledSources = disabledSources,
)
}
}
}
}
fun toggleSource(source: Source) {
toggleSource.await(source)
}
fun toggleLanguage(language: String) {
toggleLanguage.await(language)
}
sealed interface State {
@Immutable
data object Loading : State
@Immutable
data class Error(
val throwable: Throwable,
) : State
@Immutable
data class Success(
val items: SortedMap<String, List<Source>>,
val enabledLanguages: Set<String>,
val disabledSources: Set<String>,
) : State {
val isEmpty: Boolean
get() = items.isEmpty()
}
}
}
| 180
|
Kotlin
|
315
| 4,992
|
823099f775ef608b7c11f096da1f50762dab82df
| 2,815
|
aniyomi
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Fail.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Outline.Fail: ImageVector
get() {
if (_fail != null) {
return _fail!!
}
_fail = Builder(name = "Fail", 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) {
moveToRelative(4.0f, 8.0f)
horizontalLineToRelative(3.0f)
verticalLineToRelative(1.6f)
horizontalLineToRelative(-1.4f)
verticalLineToRelative(1.801f)
horizontalLineToRelative(1.4f)
verticalLineToRelative(1.6f)
horizontalLineToRelative(-1.4f)
verticalLineToRelative(3.0f)
horizontalLineToRelative(-1.6f)
verticalLineToRelative(-8.0f)
close()
moveTo(18.6f, 8.0f)
horizontalLineToRelative(-1.6f)
verticalLineToRelative(8.0f)
horizontalLineToRelative(3.0f)
verticalLineToRelative(-1.6f)
horizontalLineToRelative(-1.4f)
verticalLineToRelative(-6.4f)
close()
moveTo(14.0f, 16.0f)
horizontalLineToRelative(1.6f)
verticalLineToRelative(-8.0f)
horizontalLineToRelative(-1.6f)
verticalLineToRelative(8.0f)
close()
moveTo(12.161f, 9.627f)
lineToRelative(1.339f, 6.373f)
horizontalLineToRelative(-1.632f)
lineToRelative(-0.295f, -1.4f)
horizontalLineToRelative(-2.379f)
lineToRelative(-0.309f, 1.4f)
horizontalLineToRelative(-1.584f)
lineToRelative(1.365f, -6.418f)
curveToRelative(0.116f, -0.58f, 0.455f, -1.079f, 0.926f, -1.356f)
curveToRelative(0.255f, -0.15f, 0.535f, -0.225f, 0.816f, -0.225f)
curveToRelative(0.242f, 0.0f, 0.486f, 0.056f, 0.718f, 0.168f)
curveToRelative(0.512f, 0.246f, 0.9f, 0.791f, 1.035f, 1.459f)
close()
moveTo(11.237f, 13.0f)
lineToRelative(-0.641f, -3.044f)
curveToRelative(-0.047f, -0.231f, -0.144f, -0.334f, -0.168f, -0.349f)
lineToRelative(-0.017f, -0.006f)
curveToRelative(-0.071f, 0.042f, -0.146f, 0.146f, -0.176f, 0.296f)
lineToRelative(-0.686f, 3.104f)
horizontalLineToRelative(1.688f)
close()
moveTo(24.001f, 6.0f)
verticalLineToRelative(15.0f)
lineTo(0.0f, 21.0f)
lineTo(0.0f, 6.0f)
curveToRelative(0.0f, -1.654f, 1.346f, -3.0f, 3.0f, -3.0f)
horizontalLineToRelative(18.0f)
curveToRelative(1.654f, 0.0f, 3.0f, 1.346f, 3.0f, 3.0f)
close()
moveTo(22.001f, 6.0f)
curveToRelative(0.0f, -0.552f, -0.448f, -1.0f, -1.0f, -1.0f)
lineTo(3.0f, 5.0f)
curveToRelative(-0.551f, 0.0f, -1.0f, 0.448f, -1.0f, 1.0f)
verticalLineToRelative(13.0f)
horizontalLineToRelative(20.0f)
lineTo(22.0f, 6.0f)
close()
}
}
.build()
return _fail!!
}
private var _fail: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 4,204
|
icons
|
MIT License
|
app/src/main/kotlin/be/zvz/billboardoo/dto/RankResponse.kt
|
wakboardoo
| 498,069,799
| false
| null |
package be.zvz.billboardoo.dto
data class RankResponse(
val timestamp: Long = 0,
val ranking: List<RankItem> = emptyList()
)
| 9
|
Kotlin
|
0
| 12
|
50e568b1d2fd13305e7fe114de706a534e399747
| 134
|
libre-billboardoo-backend
|
Apache License 2.0
|
component/base/src/main/java/com/hywq/tomato/base/BaseApplication.kt
|
hy-liuyuzhe
| 388,084,184
| false
| null |
package com.hywq.tomato.base
import android.app.Application
import com.blankj.utilcode.util.Utils
open class BaseApplication : Application() {
override fun onCreate() {
super.onCreate()
Utils.init(this)
}
}
| 0
|
Kotlin
|
0
| 0
|
274448d841fb0fbdf021194203a2bb0e8c947fd6
| 233
|
hy_kotlin_tomato_project
|
MIT License
|
library/renetik-base/src/main/java/renetik/android/primitives/Boolean+.kt
|
rene-dohan
| 69,289,476
| false
| null |
package renetik.android.primitives
val Boolean.Companion.random get() = Int.random(0, 1) == 1
fun <T> Boolean.ifTrue(function: () -> T): T? = if (this) function() else null
fun <T> Boolean.ifFalse(function: () -> T): T? = if (!this) function() else null
val <T : Boolean?> T.isTrue: Boolean get() = this == true
val <T : Boolean?> T.isNotTrue: Boolean get() = this != true
val <T : Boolean?> T.isFalse: Boolean get() = this == false
| 2
|
Kotlin
|
1
| 1
|
29735b81359911206fd16ce50f4d1fc687dae54c
| 434
|
renetik-library-android
|
Apache License 2.0
|
src/main/kotlin/kpy/utils/Operations.kt
|
ghasemdev
| 366,266,690
| false
| null |
package kpy.utils
/*
* Logical Operations
*
* @author jakode
* @since v2.1.0 08/23/2021
*/
/**
* Repeats a string to the number of repetitions
*
* Example:
* ```
* println("10" * 5)
* output: 1010101010
* ```
*/
operator fun String.times(repeat: Int) = repeat(repeat)
/**
* Repeats a character to the number of repetitions
*
* Example:
* ```
* println('0' * 5)
* output: 00000
* ```
*/
operator fun Char.times(repeat: Int) = toString() * repeat
/** not or */
infix fun Boolean.nor(other: Boolean) = !(this or other)
/** not and */
infix fun Boolean.nand(other: Boolean) = !(this and other)
/** not xor */
infix fun Boolean.xnor(other: Boolean) = !(this xor other)
/** not or */
infix fun Int.nor(other: Int): Int {
val orResult = this or other
return if (orResult == 0) 1 else 0
}
/** not and */
infix fun Int.nand(other: Int): Int {
val andResult = this and other
return if (andResult == 0) 1 else 0
}
/** not xor */
infix fun Int.xnor(other: Int): Int {
val xorResult = this xor other
return if (xorResult == 0) 1 else 0
}
/** not */
fun not(value: Int): Int {
return if (value == 0) 1 else 0
}
| 0
|
Kotlin
|
0
| 3
|
ae8f8378ac3280241a52c5122a9508c932b1d45d
| 1,170
|
kpy-core
|
Apache License 2.0
|
widget/src/main/java/com/angcyo/widget/layout/DslCheckFlowLayout.kt
|
angcyo
| 229,037,615
| false
|
{"Kotlin": 6719968, "JavaScript": 5194}
|
package com.angcyo.widget.layout
import android.content.Context
import android.util.AttributeSet
import android.view.View
import com.angcyo.tablayout.DslSelector
/**
* [android.widget.RadioGroup]
*
* Email:<EMAIL>
* @author angcyo
* @date 2022/01/10
* Copyright (c) 2020 ShenZhen Wayto Ltd. All rights reserved.
*/
class DslCheckFlowLayout(context: Context, attrs: AttributeSet? = null) :
DslFlowLayout(context, attrs) {
/**单选/多选支持*/
val selectorHelper = DslSelector()
init {
selectorHelper.install(this) {
dslMultiMode = false
}
}
override fun onViewAdded(child: View?) {
super.onViewAdded(child)
updateLayout()
}
override fun onViewRemoved(child: View?) {
super.onViewRemoved(child)
updateLayout()
}
open fun updateLayout() {
selectorHelper.updateVisibleList()
selectorHelper.updateStyle()
selectorHelper.updateClickListener()
}
/**选中目标*/
open fun selectIndex(index: Int) {
selectorHelper.selector(index)
}
/**监听选中改变*/
open fun onSelectChanged(listener: (fromIndex: Int, selectIndexList: List<Int>, reselect: Boolean, fromUser: Boolean) -> Unit) {
selectorHelper.dslSelectorConfig.onSelectIndexChange = listener
}
}
| 0
|
Kotlin
|
6
| 5
|
18cdbc1d8e6c0ed88adbf3c441ea28e1a61d6e17
| 1,302
|
UICore
|
MIT License
|
common/src/main/java/com/ribsky/common/livedata/ResultMapper.kt
|
nexy791
| 607,748,138
| false
| null |
package com.ribsky.common.livedata
class ResultMapper {
companion object {
fun <T> Result<T>.asResource(): Resource<T> {
return this.fold(
onSuccess = { Resource.success(it) },
onFailure = { Resource.error(it) }
)
}
}
}
| 0
|
Kotlin
|
0
| 7
|
d2e9f7c04635e1793bfe8f421b4bc5ef162556c0
| 301
|
dymka
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.