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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
vico/core/src/main/java/com/patrykandpatryk/vico/core/chart/values/MutableChartValues.kt
|
ThaiCao
| 652,554,705
| false
| null |
/*
* Copyright 2022 Patryk Goworowski and Patryk Michalik
*
* 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.patrykandpatryk.vico.core.chart.values
import com.patrykandpatryk.vico.core.entry.ChartEntry
import com.patrykandpatryk.vico.core.entry.ChartEntryModel
/**
* A subclass of [ChartValues] whose every property is mutable.
*/
public class MutableChartValues : ChartValues {
override var minX: Float = 0f
private set
override var maxX: Float = 0f
private set
override var minY: Float = 0f
private set
override var maxY: Float = 0f
private set
override var chartEntryModel: ChartEntryModel = emptyChartEntryModel()
override val stepX: Float
get() = chartEntryModel.stepX
/**
* Returns `true` if all values have been set and at least one call to [tryUpdate] or [set] has been made.
*/
public var hasValuesSet: Boolean = false
private set
/**
* Attempts to update the stored values to the provided params.
* [minX] and [minY] can be updated to a smaller value.
* [maxX] and [maxY] can be updated to a higher value.
* The [chartEntryModel] is always be updated.
*/
public fun tryUpdate(
minX: Float = this.minX,
maxX: Float = this.maxX,
minY: Float = this.minY,
maxY: Float = this.maxY,
chartEntryModel: ChartEntryModel = this.chartEntryModel,
): MutableChartValues = apply {
this.minX = if (hasValuesSet) minOf(this.minX, minX) else minX
this.maxX = if (hasValuesSet) maxOf(this.maxX, maxX) else maxX
this.minY = if (hasValuesSet) minOf(this.minY, minY) else minY
this.maxY = if (hasValuesSet) maxOf(this.maxY, maxY) else maxY
this.chartEntryModel = chartEntryModel
hasValuesSet = true
}
/**
* Sets [minX], [maxX], [minY], and [maxY] to 0.
*/
public fun reset() {
minX = 0f
maxX = 0f
minY = 0f
maxY = 0f
chartEntryModel = emptyChartEntryModel()
hasValuesSet = false
}
private companion object {
fun emptyChartEntryModel(): ChartEntryModel = object : ChartEntryModel {
override val entries: List<List<ChartEntry>> = emptyList()
override val minX: Float = 0f
override val maxX: Float = 0f
override val minY: Float = 0f
override val maxY: Float = 0f
override val stackedMaxY: Float = 0f
override val stepX: Float = 1f
}
}
}
| 0
|
Kotlin
|
0
| 0
|
58b9b16f786f24b6570ed0252d5785cfe831c906
| 3,059
|
vico-chart
|
Apache License 2.0
|
common/src/main/kotlin/io/nichijou/tujian/common/appwidget/BingAppWidgetConfig.kt
|
david082321
| 244,025,265
| true
|
{"Kotlin": 379481}
|
package io.nichijou.tujian.common.appwidget
import com.chibatching.kotpref.KotprefModel
object BingAppWidgetConfig : KotprefModel() {
var notification: Boolean by booleanPref(true)
var requiresBatteryNotLow: Boolean by booleanPref(false)
var requiresCharging: Boolean by booleanPref(false)
var requiresStorageNotLow: Boolean by booleanPref(false)
var requiresDeviceIdle: Boolean by booleanPref(false)
var enable: Boolean by booleanPref(false)
var blur: Boolean by booleanPref(false)
var pixel: Boolean by booleanPref(false)
var blurValue: Int by intPref(2500)
var pixelValue: Int by intPref(2400)
var textSize: Int by intPref(2600)
var textLines: Int by intPref(300)
var autoTextColor: Boolean by booleanPref(false)
}
| 0
| null |
0
| 0
|
2f46fe5040665975403f25f75507af0bdef6393c
| 746
|
tujian-kt
|
MIT License
|
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/MapCheck.kt
|
walter-juan
| 868,046,028
| false
|
{"Kotlin": 34345428}
|
package com.woowla.compose.icon.collections.tabler.tabler.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
public val OutlineGroup.MapCheck: ImageVector
get() {
if (_mapCheck != null) {
return _mapCheck!!
}
_mapCheck = Builder(name = "MapCheck", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(11.0f, 18.0f)
lineToRelative(-2.0f, -1.0f)
lineToRelative(-6.0f, 3.0f)
verticalLineToRelative(-13.0f)
lineToRelative(6.0f, -3.0f)
lineToRelative(6.0f, 3.0f)
lineToRelative(6.0f, -3.0f)
verticalLineToRelative(9.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(9.0f, 4.0f)
verticalLineToRelative(13.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(15.0f, 7.0f)
verticalLineToRelative(8.0f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(15.0f, 19.0f)
lineToRelative(2.0f, 2.0f)
lineToRelative(4.0f, -4.0f)
}
}
.build()
return _mapCheck!!
}
private var _mapCheck: ImageVector? = null
| 0
|
Kotlin
|
0
| 3
|
eca6c73337093fbbfbb88546a88d4546482cfffc
| 2,901
|
compose-icon-collections
|
MIT License
|
src/main/kotlin/com/nikichxp/tgbot/dto/BotCommand.kt
|
NikichXP
| 395,716,371
| false
|
{"Kotlin": 150225, "Dockerfile": 242}
|
package com.nikichxp.tgbot.dto
data class BotCommand(
val command: String,
val description: String
)
| 2
|
Kotlin
|
0
| 1
|
c93dd6edcb12c5c45651ea49aaf68af6619051d1
| 110
|
tgbot
|
Apache License 2.0
|
app/src/main/java/com/thread0/weather/data/model/Location.kt
|
wuzelong
| 384,625,570
| false
| null |
package com.thread0.weather.data.model
import com.google.gson.annotations.SerializedName
data class Location(
val id: String,
val name: String,
val country: String,
val path: String,
val timezone: String,
@SerializedName("timezone_offset")
val timezoneOffset: String
)
data class LocationResult(
val results: List<Location>
)
| 0
|
Kotlin
|
0
| 1
|
00f93f0c656d3734c4d3bb10c66ec94f6e030d7e
| 361
|
weather
|
Apache License 2.0
|
stdlib/src/commonMain/kotlin/com/sunnychung/lib/multiplatform/kotlite/stdlib/kdatetime/KInstantValue.kt
|
sunny-chung
| 783,528,970
| false
|
{"Kotlin": 1602007}
|
package com.sunnychung.lib.multiplatform.kotlite.stdlib.kdatetime
import com.sunnychung.lib.multiplatform.kdatetime.KInstant
import com.sunnychung.lib.multiplatform.kotlite.model.CustomFunctionParameter
import com.sunnychung.lib.multiplatform.kotlite.model.DelegatedValue
import com.sunnychung.lib.multiplatform.kotlite.model.LongValue
import com.sunnychung.lib.multiplatform.kotlite.model.ProvidedClassDefinition
import com.sunnychung.lib.multiplatform.kotlite.model.SourcePosition
import com.sunnychung.lib.multiplatform.kotlite.model.SymbolTable
fun KInstantValue(value: KInstant, symbolTable: SymbolTable) : DelegatedValue<KInstant>
= DelegatedValue<KInstant>(value, KInstantClass.clazz, symbolTable = symbolTable)
object KInstantClass {
val clazz = ProvidedClassDefinition(
fullQualifiedName = "KInstant",
typeParameters = emptyList(),
isInstanceCreationAllowed = true,
primaryConstructorParameters = listOf(CustomFunctionParameter("timestampMs", "Long")),
constructInstance = { interpreter, callArguments, callPosition ->
KInstantValue(KInstant((callArguments[0] as LongValue).value), interpreter.symbolTable())
},
superInterfaceTypeNames = listOf("KDateTimeFormattable"),
superClassInvocationString = "KPointOfTime()",
position = SourcePosition("KDateTime", 1, 1),
)
}
| 0
|
Kotlin
|
0
| 0
|
7f8e39806b03ed3946457fa3799d7544abc98031
| 1,375
|
kotlite
|
MIT License
|
common/src/main/kotlin/com/dr10/common/models/SelectedConfigHistoryModel.kt
|
Daniel0110000
| 702,220,698
| false
|
{"Kotlin": 250956, "Lex": 15630}
|
package com.dr10.common.models
data class SelectedConfigHistoryModel(
val uniqueId: String,
val optionName: String,
val className: String,
val asmFilePath: String
)
| 1
|
Kotlin
|
3
| 30
|
5114314c76455ddedce4af0762b37ca7730a598f
| 182
|
DeepCodeStudio
|
Apache License 2.0
|
app/src/main/java/io/github/samueljarosinski/ambilight/permission/ActivityScreenCapturePermission.kt
|
samueljarosinski
| 192,970,530
| false
| null |
package io.github.samueljarosinski.ambilight.permission
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.media.projection.MediaProjectionManager
import android.os.Bundle
import androidx.core.content.getSystemService
import timber.log.Timber
class ActivityScreenCapturePermission : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
overridePendingTransition(0, 0)
if (!intent.hasExtra(EXTRA_PERMISSION_REQUEST)) {
Timber.w("Intent is null or has no $EXTRA_PERMISSION_REQUEST, finishing and removing task.")
finishAndRemoveTask()
return
}
Timber.d("Sending screen capture permission request intent.")
startActivityForResult(
getSystemService<MediaProjectionManager>()?.createScreenCaptureIntent(),
REQUEST_CODE_SCREEN_CAPTURE
)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_SCREEN_CAPTURE) {
Timber.d("Received permission result: $resultCode $data")
if (resultCode == RESULT_OK && data != null) {
Timber.d("Screen capture permission was granted!")
ScreenCapturePermissionRequester.permissionResult = PermissionResult(resultCode, data)
} else {
Timber.d("Screen capture permission was denied!")
}
}
finish()
}
override fun onPause() {
super.onPause()
overridePendingTransition(0, 0)
}
companion object {
private const val REQUEST_CODE_SCREEN_CAPTURE = 7272
private const val EXTRA_PERMISSION_REQUEST = "EXTRA_PERMISSION_REQUEST"
internal fun createStartIntent(context: Context): Intent =
Intent(context, ActivityScreenCapturePermission::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra(EXTRA_PERMISSION_REQUEST, true)
}
}
| 0
|
Kotlin
|
0
| 0
|
300ea1579f59b3b3c43e7cdd5b53c12a9eae4ab1
| 2,142
|
Ambilight
|
MIT License
|
privacy-protections-popup/privacy-protections-popup-impl/src/main/java/com/duckduckgo/privacyprotectionspopup/impl/PrivacyProtectionsPopupPixelName.kt
|
hojat72elect
| 822,396,044
| false
|
{"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
|
package com.duckduckgo.privacyprotectionspopup.impl
import com.duckduckgo.app.statistics.pixels.Pixel.PixelName
import com.duckduckgo.app.statistics.pixels.Pixel.PixelType
enum class PrivacyProtectionsPopupPixelName(
override val pixelName: String,
val type: PixelType,
) : PixelName
| 0
|
Kotlin
|
0
| 0
|
b89591136b60933d6a03fac43a38ee183116b7f8
| 294
|
DuckDuckGo
|
Apache License 2.0
|
app/src/main/java/top/roy1994/bilimusic/data/objects/music/MusicEntity.kt
|
MoveCloudROY
| 583,275,245
| false
|
{"Kotlin": 217608}
|
package top.roy1994.bilimusic.data.objects.music
import androidx.compose.ui.graphics.painter.Painter
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
@Entity
data class MusicEntity(
@PrimaryKey(autoGenerate = true) var music_id: Int = 0,
val bvid: String,
val part: Int = 1,
val cover_url: String? = null,
val music_name: String,
val music_artist: String = "None",
val which_artist_id: Int = 1,
val which_sheet_id: Int = 1,
val second: Long = 300,
var times5day: Int = 0,
val add_time: Long = 0,
var last_play_time: Long = 0,
) {
@Ignore var music_cover: Painter? = null
companion object {
fun getEmpty(): MusicEntity {
return MusicEntity(
bvid = "",
music_name = "",
music_artist = "",
)
}
}
override fun hashCode(): Int {
return music_id;
}
override fun equals(other: Any?): Boolean {
return hashCode() == other.hashCode();
}
}
@Entity
data class MusicCntUpdate(
val music_id: Int = 0,
var times5day: Int = 0,
) {}
| 1
|
Kotlin
|
1
| 5
|
dc60ebde773a810c646328f17b21fa3d71ac1f23
| 1,151
|
BiliMusic
|
MIT License
|
upjoin_android_view/src/main/kotlin/de/upjoin/android/view/modules/AbstractSplashModule.kt
|
upjoin
| 280,871,994
| false
| null |
package de.upjoin.android.view.modules
import android.content.Context
import android.content.Intent
import de.upjoin.android.core.application.ModulizedApplication
import de.upjoin.android.core.modules.ModuleLiveCycle
import de.upjoin.android.view.splash.SplashActivity
abstract class AbstractSplashModule: SplashModule, ModuleLiveCycle {
override var visibleTime: Int = 1000
override fun showSplashActivity(context: Context) {
val intent = Intent(context, SplashActivity::class.java)
context.startActivity(intent)
}
override fun onCreate(application: ModulizedApplication) {
splashModule = this
}
}
| 0
|
Kotlin
|
0
| 0
|
0ccdce055876235c695b2955f23ed3165deb7654
| 647
|
upjoin_android
|
Apache License 2.0
|
app/src/main/java/com/example/marsphotos/data/MarsPhotosRepository.kt
|
pol1612
| 868,484,701
| false
|
{"Kotlin": 18733}
|
package com.example.marsphotos.data
interface MarsPhotosRepository {
suspend fun getMarsPhotos(): List<MarsPhoto>
}
class NetworkMarsPhotosRepository(
private val marsApiService: MarsApiService
): MarsPhotosRepository {
override suspend fun getMarsPhotos(): List<MarsPhoto> {
return marsApiService.getPhotos()
}
}
| 0
|
Kotlin
|
0
| 0
|
fbfb30dbee3608bb4a61f224dd0d8811aa0cdf8a
| 340
|
basic-android-kotlin-compose-training-mars-photos
|
Apache License 2.0
|
src/main/kotlin/com/chatandpay/api/service/LogService.kt
|
f-lab-edu
| 634,472,358
| false
| null |
package com.chatandpay.api.service
import com.chatandpay.api.domain.Log
import com.chatandpay.api.repository.LogRepository
import org.springframework.stereotype.Component
@Component
class LogService(private val logRepository: LogRepository) {
fun saveLog(log: Log) {
logRepository.save(log)
}
}
| 3
|
Kotlin
|
1
| 2
|
496222f0f797e78589149ab165a599c6f62821eb
| 314
|
chatAndPay-API
|
MIT License
|
domain/src/main/java/com/ujizin/leafy/domain/usecase/plant/add/AddDraftPlantUseCaseImpl.kt
|
ujizin
| 442,024,281
| false
|
{"Kotlin": 349427}
|
package com.ujizin.leafy.domain.usecase.plant.add
import com.ujizin.leafy.domain.repository.PlantRepository
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flatMapConcat
import kotlinx.coroutines.flow.map
import java.io.File
internal class AddDraftPlantUseCaseImpl(
private val plantRepository: PlantRepository,
) : AddDraftPlantUseCase {
@OptIn(ExperimentalCoroutinesApi::class)
override fun invoke(
title: String?,
file: File?,
description: String?,
): Flow<Unit> = plantRepository.getDraftPlant().map { plant ->
plant.copy(
title = title ?: plant.title,
description = description ?: plant.description,
filePath = file?.path ?: plant.filePath,
)
}.flatMapConcat { plant ->
plantRepository.updateDraftPlant(plant)
}
}
| 3
|
Kotlin
|
1
| 4
|
27e28e5984a0fef94d3aa8d7c813ba1851cfd4f3
| 901
|
Leafy
|
Apache License 2.0
|
apple/green/src/main/kotlin/net/tjalp/peach/apple/green/LaunchServer.kt
|
tjalp
| 421,781,027
| false
| null |
package net.tjalp.peach.apple.green
import net.minestom.server.Bootstrap
import net.minestom.server.extras.selfmodification.MinestomRootClassLoader
fun main(args: Array<String>) {
// Allow mixins without removing arguments (BROKEN)
// String[] argsWithMixins = new String[args.length+2];
// System.arraycopy(args, 0, argsWithMixins, 0, args.length);
// argsWithMixins[argsWithMixins.length-2] = "--mixin";
// argsWithMixins[argsWithMixins.length-1] = "mixins.tjalp.json";
// Prevent lettuce from using Minestom's class loader
val packages = MinestomRootClassLoader.getInstance().protectedPackages
packages.add("io.lettuce")
packages.add("reactor.core")
Bootstrap.bootstrap(MinestomAppleServer::class.qualifiedName + "Kt", args)
}
| 0
|
Kotlin
|
0
| 0
|
0d74c084b3e83dfaaec7a2bf52f056de7a5f6a08
| 786
|
peach
|
MIT License
|
app/src/main/java/com/hackathon/navigation/NavGraph.kt
|
ShivarajMbhagoji
| 840,589,414
| false
|
{"Kotlin": 113087}
|
package com.hackathon.navigation
import android.os.Build
import androidx.annotation.RequiresApi
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.paging.compose.collectAsLazyPagingItems
import com.hackathon.data.dto.GlobalEventsScreen
import com.hackathon.data.dto.GlobalEventsViewModel
import com.hackathon.emergency.EmergencyContactViewModel
import com.hackathon.emergency.EmergenyContactScreen
import com.hackathon.screens.AddDisasterScreen
import com.hackathon.screens.BottomNavScreen
import com.hackathon.screens.DisasterDetails
import com.hackathon.screens.HomeScreen
import com.hackathon.screens.LoginScreen
import com.hackathon.screens.MapScreen
import com.hackathon.screens.ProfileScreen
import com.hackathon.screens.RegisterScreen
import com.hackathon.screens.SplashScreen
sealed class NavRoutes(val route:String){
data object Home:NavRoutes("Home")
data object Login:NavRoutes("Login")
data object Register:NavRoutes("Register")
data object BottomNav:NavRoutes("BottomNav")
data object Search:NavRoutes("Search")
data object Splash:NavRoutes("Splash")
data object Profile:NavRoutes("Profile")
data object AddDisaster:NavRoutes("AddDisaster")
data object Map:NavRoutes("Map")
data object DisasterDetails:NavRoutes("DisasterDetails/{data}")
data object GlobalEvents:NavRoutes("GlobalEvents")
data object EmergencyContacts:NavRoutes("EmergencyContacts")
}
@RequiresApi(Build.VERSION_CODES.TIRAMISU)
@Composable
fun NavGraph(navController: NavHostController, modifier: Modifier = Modifier) {
NavHost(navController = navController, startDestination = NavRoutes.Splash.route) {
composable(NavRoutes.Splash.route) {
SplashScreen(navController)
}
composable(NavRoutes.Home.route) {
HomeScreen(navController)
}
composable(NavRoutes.Search.route) {
val viewModel: EmergencyContactViewModel = hiltViewModel()
val events = viewModel.datas.collectAsLazyPagingItems()
EmergenyContactScreen(events)
}
composable(NavRoutes.Map.route) {
MapScreen()
}
composable(NavRoutes.Profile.route) {
ProfileScreen(navController)
}
composable(NavRoutes.AddDisaster.route){
AddDisasterScreen(navController)
}
composable(NavRoutes.BottomNav.route) {
BottomNavScreen(navController)
}
composable(NavRoutes.Login.route){
LoginScreen(navController)
}
composable(NavRoutes.Register.route) {
RegisterScreen(navController)
}
composable(NavRoutes.DisasterDetails.route) {
val data = it.arguments!!.getString("data")
DisasterDetails(navController,data!!)
}
composable(NavRoutes.GlobalEvents.route) {
val viewModel: GlobalEventsViewModel = hiltViewModel()
val events = viewModel.events.collectAsLazyPagingItems()
GlobalEventsScreen(events) {
}
}
}
}
| 0
|
Kotlin
|
1
| 0
|
12cb94f302007c4c298324407568d43766957383
| 3,310
|
CodeFury_7.0
|
MIT License
|
src/test/kotlin/_50to100/Task54Test.kt
|
embuc
| 735,933,359
| false
|
{"Kotlin": 89867, "Java": 48265}
|
package _50to100
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
import se.embuc._50to100.Task54
// Poker hands
class Task54Test {
@Test
fun solve() {
assertEquals(376, Task54().solve())
assertEquals(376, JTask54().solve())
}
@Test
fun shouldEvaluate() {
// pair of fives
var hand = Task54.Hand("5H 5C 6S 7S KD".split(" ").map { Task54.Card(it) })
// pair of eights
var hand2 = Task54.Hand("2C 3S 8S 8D TD".split(" ").map { Task54.Card(it) })
var winner = hand.compareTo(hand2)
assertEquals(-1, winner)
// Highest card Ace
hand = Task54.Hand("5D 8C 9S JS AC".split(" ").map { Task54.Card(it) })
// Highest card Queen
hand2 = Task54.Hand("2C 5C 7D 8S QH".split(" ").map { Task54.Card(it) })
winner = hand.compareTo(hand2)
assertEquals(1, winner)
}
@Test
fun shouldEvaluateHighestCard() {
// Highest card Ace
var hand = JTask54().Hand("5D 8C 9S JS AC".split(" ").map { JTask54().Card(it) })
// Highest card Queen
var hand2 = JTask54().Hand("2C 5C 7D 8S QH".split(" ").map { JTask54().Card(it) })
var winner = hand.compareTo(hand2)
assertEquals(1, winner)
}
}
| 0
|
Kotlin
|
0
| 1
|
fc5db842ba250ba4e45af549684b1f845bcab770
| 1,149
|
projecteuler
|
MIT License
|
app/src/main/java/com/indisparte/moovaride/di/module/BluetoothModule.kt
|
iamantoniodinuzzo
| 698,121,364
| false
|
{"Kotlin": 170845}
|
package com.indisparte.moovaride.di.module
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import android.os.Build
import androidx.annotation.RequiresApi
import com.indisparte.moovaride.data.bleScanner.BLEReceiverManager
import com.indisparte.moovaride.data.bleScanner.BLEReceiverManagerImpl
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import org.altbeacon.beacon.BeaconManager
import javax.inject.Singleton
/**
* @author <NAME>
*/
@Module
@InstallIn(SingletonComponent::class)
object BluetoothModule {
/**
* Represents the local device Bluetooth adapter. The BluetoothAdapter lets you perform fundamental Bluetooth tasks,
* such as initiate device discovery, query a list of bonded (paired) devices, instantiate a BluetoothDevice using a known MAC address,
*/
@Provides
@Singleton
fun provideBluetoothAdapter(@ApplicationContext context: Context): BluetoothAdapter {
val manager = context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
return manager.adapter
}
@RequiresApi(Build.VERSION_CODES.O)
@Provides
@Singleton
fun bindBLEReceiveManager(
@ApplicationContext context: Context,
beaconManager: BeaconManager,
): BLEReceiverManager {
return BLEReceiverManagerImpl(beaconManager, context)
}
}
| 2
|
Kotlin
|
0
| 0
|
ece192351030418549c8f01c11a684d555a66007
| 1,520
|
MoovaRide
|
Apache License 2.0
|
src/main/kotlin/no/nav/familie/ks/sak/kjerne/tilbakekreving/TilbakekrevingsbehandlingHentService.kt
|
navikt
| 533,308,075
| false
| null |
package no.nav.familie.ks.sak.kjerne.tilbakekreving
import no.nav.familie.ks.sak.common.exception.Feil
import no.nav.familie.ks.sak.integrasjon.tilbakekreving.TilbakekrevingKlient
import no.nav.familie.ks.sak.kjerne.tilbakekreving.domene.TilbakekrevingRepository
import org.springframework.stereotype.Service
// Opprettet denne for å unngå sirkular avhengihet
@Service
class TilbakekrevingsbehandlingHentService(
private val tilbakekrevingKlient: TilbakekrevingKlient,
private val tilbakekrevingRepository: TilbakekrevingRepository
) {
fun hentTilbakekrevingsbehandlinger(fagsakId: Long) = tilbakekrevingKlient.hentTilbakekrevingsbehandlinger(fagsakId)
fun hentTilbakekreving(behandlingId: Long) = tilbakekrevingRepository.findByBehandlingId(behandlingId)
?: throw Feil("Finnes ikke tilbakekreving for behandling $behandlingId")
}
| 3
|
Kotlin
|
0
| 2
|
4d7304873304929bf83e5bde3254b45a94051a5a
| 859
|
familie-ks-sak
|
MIT License
|
app/src/main/kotlin/com/skyline/msgbot/reflow/event/EventBase.kt
|
SkyLineLab
| 451,012,446
| false
| null |
package com.skyline.msgbot.reflow.event
interface EventBase {
val isTrusted: Boolean
val type: String
val timeStamp: Long
val defaultPrevented: Boolean
val scope: String
}
| 4
|
Kotlin
|
1
| 9
|
9e9324e269c729f45f7c86f4939932fd72669355
| 192
|
SkyLine
|
MIT License
|
app/src/main/java/com/timilehinaregbesola/mathalarm/presentation/alarmsettings/components/AlarmBottomSheet.kt
|
t-regbs
| 223,649,248
| false
|
{"Kotlin": 283958}
|
package com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components
import android.app.Activity
import android.media.RingtoneManager
import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.Orientation.Vertical
import androidx.compose.foundation.gestures.scrollable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Arrangement.SpaceBetween
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CornerSize
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.EmojiSymbols
import androidx.compose.material.icons.outlined.Notifications
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults.buttonColors
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.rememberBottomSheetScaffoldState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment.Companion.CenterVertically
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color.Companion.Black
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight.Companion.Bold
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.text.style.TextAlign.Companion.Center
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.app.NotificationManagerCompat
import androidx.core.net.toUri
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.squareup.moshi.Moshi
import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
import com.timilehinaregbesola.mathalarm.R
import com.timilehinaregbesola.mathalarm.framework.database.AlarmEntity
import com.timilehinaregbesola.mathalarm.framework.database.AlarmMapper
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.AddEditAlarmEvent
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.AddEditAlarmEvent.EnteredTitle
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.AddEditAlarmEvent.OnDifficultyChange
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.AddEditAlarmEvent.OnSaveTodoClick
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.AddEditAlarmEvent.OnTestClick
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.AddEditAlarmEvent.OnToneChange
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.AddEditAlarmEvent.OnToneError
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.AddEditAlarmEvent.ToggleDayChooser
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.AddEditAlarmEvent.ToggleRepeat
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.AddEditAlarmEvent.ToggleVibrate
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.AlarmSettingsViewModel
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.TimeState
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.ALARM_DAYS_TOP_PADDING
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.DIFFICULTY_ICON_END_PADDING
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.DIFFICULTY_SECTION_HORIZONTAL_PADDING
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.DIFFICULTY_SECTION_TOP_PADDING
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.DIVIDER_THICKNESS
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.FROM_SHEET_KEY
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.MIDDLE_CONTROL_SECTION_TOP_PADDING
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.NO_ELEVATION
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.SAVE_BUTTON_FONT_SIZE
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.SAVE_BUTTON_TOP_PADDING
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.TEST_BUTTON_FONT_SIZE
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.TIME_CARD_CORNER_SIZE
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.TIME_CARD_HEIGHT
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.TIME_PATTERN
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.TIME_TEXT_FONT_SIZE
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.TIME_TEXT_PADDING
import com.timilehinaregbesola.mathalarm.presentation.alarmsettings.components.AlarmBottomSheet.URL_ENCODER
import com.timilehinaregbesola.mathalarm.presentation.ui.MathAlarmTheme
import com.timilehinaregbesola.mathalarm.presentation.ui.darkPrimaryLight
import com.timilehinaregbesola.mathalarm.presentation.ui.spacing
import com.timilehinaregbesola.mathalarm.presentation.ui.unSelectedDay
import com.timilehinaregbesola.mathalarm.utils.Navigation.NAV_ALARM_MATH
import com.timilehinaregbesola.mathalarm.utils.Navigation.NAV_ALARM_MATH_ARGUMENT
import com.timilehinaregbesola.mathalarm.utils.PickRingtone
import com.timilehinaregbesola.mathalarm.utils.checkPermissions
import com.timilehinaregbesola.mathalarm.utils.confirmationDialog
import com.timilehinaregbesola.mathalarm.utils.handleNotificationPermission
import com.timilehinaregbesola.mathalarm.utils.openNotificationSettings
import com.timilehinaregbesola.mathalarm.utils.permissionRequiredDialog
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.net.URLEncoder
import java.time.format.DateTimeFormatter
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AlarmBottomSheet(
viewModel: AlarmSettingsViewModel = hiltViewModel(),
navController: NavHostController,
darkTheme: Boolean,
alarm: AlarmEntity,
) {
viewModel.setAlarm(AlarmMapper().mapToDomainModel(alarm))
val scaffoldState = rememberBottomSheetScaffoldState()
var showDialog by remember { mutableStateOf(false) }
val context = LocalContext.current
val toneText = remember { mutableStateOf<String?>(null) }
val result = remember { mutableStateOf<Uri?>(null) }
val pickToneLauncher =
rememberLauncherForActivityResult(PickRingtone(viewModel.tone.value)) {
result.value = it
}
result.value?.let {
val alert = it.toString()
checkPermissions(context as Activity, listOf(alert))
viewModel.onEvent(OnToneChange(alert))
toneText.value =
RingtoneManager.getRingtone(context, alert.toUri()).getTitle(context)
}
LaunchedEffect(true) {
viewModel.eventFlow.collectLatest { event ->
when (event) {
is AlarmSettingsViewModel.UiEvent.ShowSnackbar -> {
scaffoldState.snackbarHostState.showSnackbar(
message = event.message,
)
}
is AlarmSettingsViewModel.UiEvent.SaveAlarm -> {
navController.navigateUp()
}
is AlarmSettingsViewModel.UiEvent.TestAlarm -> {
navController
.previousBackStackEntry?.savedStateHandle?.set(FROM_SHEET_KEY, true)
// Nav to Math Screen
launch(IO) {
val moshi = Moshi.Builder().addLast(KotlinJsonAdapterFactory()).build()
val jsonAdapter = moshi.adapter(AlarmEntity::class.java).lenient()
val json = jsonAdapter.toJson(AlarmMapper().mapFromDomainModel(event.alarm))
val alarmJson = URLEncoder.encode(json, URL_ENCODER)
withContext(Main) {
navController.navigate(
NAV_ALARM_MATH.replace(
"{$NAV_ALARM_MATH_ARGUMENT}",
alarmJson,
),
)
}
}
}
}
}
}
AlarmBottomSheetContent(
topSection = {
TopSection(
selectedDays = viewModel.dayChooser.value,
darkTheme = darkTheme,
currentTime = viewModel.alarmTime.value.formattedTime,
onTimeCardClick = { showDialog = true },
onSelectedDaysChanged = {
viewModel.onEvent(ToggleDayChooser(it))
}
)
},
bottomSection = {
BottomSettingsSection(
repeatWeekly = viewModel.repeatWeekly.value,
vibrate = viewModel.vibrate.value,
difficulty = viewModel.difficulty.value,
onRepeatToggle = {
viewModel.onEvent(ToggleRepeat(it))
},
onVibrateToggle = {
viewModel.onEvent(ToggleVibrate(it))
},
onToneClick = {
try {
pickToneLauncher.launch(null)
} catch (e: Exception) {
Timber.e(e)
viewModel.onEvent(
OnToneError(
context.getString(R.string.details_no_ringtone_picker),
),
)
}
},
onDifficultyChange = {
viewModel.onEvent(OnDifficultyChange(it))
},
labelTextField = {
LabelTextField(
text = viewModel.alarmTitle.value,
onValueChange = { newValue ->
viewModel.onEvent(EnteredTitle(newValue))
},
label = { Text("Alarm title") },
placeholder = { Text("Good day") },
)
},
currentTone = when {
toneText.value != null -> {
toneText.value!!
}
viewModel.tone.value == "" -> {
context.getString(R.string.default_alarm_tone)
}
else -> {
RingtoneManager.getRingtone(context, viewModel.tone.value.toUri())
.getTitle(context)
}
}
)
},
buttonSection = {
SheetActionButtons(
onTestClick = {
viewModel.onEvent(OnTestClick)
},
onSaveClick = {
handleNotificationPermission(context = context) {
if (it) {
if (NotificationManagerCompat.from(context)
.areNotificationsEnabled()
) {
viewModel.onEvent(OnSaveTodoClick)
} else {
confirmationDialog(
context = context,
message = "Notifications of this application are disabled. Please go to your device settings and enable them.",
positive = "ok"
) {
viewModel.onEvent(OnSaveTodoClick)
}
}
} else {
permissionRequiredDialog(
context = context,
message = "You must allow the app to display notifications, else it cannot show alarms",
onPositive = { context.openNotificationSettings() }
)
}
}
}
)
},
timePickerDialog = {
with(viewModel.alarmTime.value) {
if (showDialog) {
TimePickerDialog(
timeState = rememberTimePickerState(
initialHour = hour,
initialMinute = minute
),
darkTheme = darkTheme,
onCancel = {
showDialog = false
},
onConfirm = { newTime ->
val dtf = DateTimeFormatter.ofPattern(TIME_PATTERN)
viewModel.onEvent(
AddEditAlarmEvent.ChangeTime(
TimeState(
hour = newTime.hour,
minute = newTime.minute,
formattedTime = newTime.format(dtf).toString(),
),
),
)
showDialog = false
}
)
}
}
}
)
}
@Composable
private fun AlarmBottomSheetContent(
topSection: @Composable () -> Unit,
bottomSection: @Composable () -> Unit,
buttonSection: @Composable () -> Unit,
timePickerDialog: @Composable () -> Unit
) {
with(MaterialTheme) {
Surface {
Box {
Column(
Modifier
.fillMaxWidth()
.padding(spacing.extraMedium)
.scrollable(rememberScrollState(), Vertical),
) {
topSection()
HorizontalDivider(
modifier = Modifier.padding(
top = spacing.medium,
start = spacing.medium,
end = spacing.medium,
),
thickness = DIVIDER_THICKNESS,
color = unSelectedDay
)
bottomSection()
buttonSection()
}
timePickerDialog()
}
}
}
}
@Composable
fun TopSection(
selectedDays: String,
currentTime: String,
darkTheme: Boolean,
onTimeCardClick: () -> Unit,
onSelectedDaysChanged: (String) -> Unit
) {
Card(
modifier = Modifier
.fillMaxWidth()
.height(TIME_CARD_HEIGHT)
.padding(horizontal = MaterialTheme.spacing.medium),
colors = CardDefaults.cardColors(
containerColor = if (darkTheme) darkPrimaryLight else unSelectedDay
),
elevation = CardDefaults.cardElevation(defaultElevation = NO_ELEVATION),
shape = MaterialTheme.shapes.medium.copy(CornerSize(TIME_CARD_CORNER_SIZE)),
) {
Row(
modifier = Modifier
.fillMaxSize()
.clickable(
onClick = { onTimeCardClick() }
),
verticalAlignment = CenterVertically,
horizontalArrangement = Arrangement.Center,
) {
Text(
modifier = Modifier
.fillMaxWidth()
.padding(TIME_TEXT_PADDING),
text = currentTime,
fontSize = TIME_TEXT_FONT_SIZE,
fontWeight = Bold,
textAlign = Center,
)
}
}
Spacer(modifier = Modifier.height(ALARM_DAYS_TOP_PADDING))
AlarmDays(currentDays = selectedDays) {
onSelectedDaysChanged(it)
}
}
@Composable
private fun BottomSettingsSection(
repeatWeekly: Boolean,
vibrate: Boolean,
difficulty: Int,
onRepeatToggle: (Boolean) -> Unit,
onVibrateToggle: (Boolean) -> Unit,
onToneClick: () -> Unit,
onDifficultyChange: (Int) -> Unit,
labelTextField: @Composable () -> Unit,
currentTone: String
) {
Row(
modifier = Modifier
.padding(
top = MIDDLE_CONTROL_SECTION_TOP_PADDING,
start = MaterialTheme.spacing.medium,
end = MaterialTheme.spacing.medium,
)
.fillMaxWidth(),
horizontalArrangement = SpaceBetween,
) {
TextWithCheckbox(
text = "Repeat Weekly",
initialState = repeatWeekly,
) {
onRepeatToggle(it)
}
TextWithCheckbox(text = "Vibrate", initialState = vibrate) {
onVibrateToggle(it)
}
}
labelTextField()
TextWithIcon(
modifier = Modifier.padding(horizontal = MaterialTheme.spacing.medium),
text = currentTone,
image = Icons.Outlined.Notifications,
onClick = {
onToneClick()
},
)
Row(
modifier = Modifier
.padding(
top = DIFFICULTY_SECTION_TOP_PADDING,
start = DIFFICULTY_SECTION_HORIZONTAL_PADDING,
end = DIFFICULTY_SECTION_HORIZONTAL_PADDING,
)
.fillMaxWidth(),
) {
Icon(
modifier = Modifier.padding(end = DIFFICULTY_ICON_END_PADDING),
imageVector = Icons.Outlined.EmojiSymbols,
contentDescription = null,
)
DifficultyChooser(difficulty) {
onDifficultyChange(it)
}
}
}
@Composable
private fun SheetActionButtons(
onTestClick: () -> Unit,
onSaveClick: () -> Unit
) {
Button(
modifier = Modifier
.padding(top = MaterialTheme.spacing.large)
.fillMaxWidth(),
onClick = {
onTestClick()
},
colors = buttonColors(
containerColor = unSelectedDay,
contentColor = Black,
),
) {
Text(
fontSize = TEST_BUTTON_FONT_SIZE,
text = "TEST ALARM",
)
}
Button(
modifier = Modifier
.padding(top = SAVE_BUTTON_TOP_PADDING)
.fillMaxWidth(),
onClick = {
onSaveClick()
},
colors = buttonColors(containerColor = MaterialTheme.colorScheme.secondary),
) {
Text(
fontSize = SAVE_BUTTON_FONT_SIZE,
text = "SAVE",
)
}
}
@Preview
@Composable
private fun BottomSheetPreview() {
MathAlarmTheme(darkTheme = true) {
Surface {
AlarmBottomSheetContent(
topSection = {
TopSection(
selectedDays = "TFFFFFF",
currentTime = "12:00",
darkTheme = true,
onTimeCardClick = {}
) {}
},
bottomSection = {
BottomSettingsSection(
repeatWeekly = true,
vibrate = true,
difficulty = 1,
onRepeatToggle = {},
onVibrateToggle = {},
onToneClick = {},
onDifficultyChange = {},
labelTextField = {
LabelTextField(
text = TextFieldValue(),
) {}
},
currentTone = "1000",
)
},
buttonSection = {
SheetActionButtons(
onTestClick = {},
onSaveClick = {}
)
}) {}
}
}
}
private object AlarmBottomSheet {
const val FROM_SHEET_KEY = "fromSheet"
const val URL_ENCODER = "utf-8"
const val TIME_PATTERN = "hh:mm a"
val TIME_CARD_HEIGHT = 150.dp
val NO_ELEVATION = 0.dp
val TIME_CARD_CORNER_SIZE = 24.dp
val TIME_TEXT_PADDING = 30.dp
val TIME_TEXT_FONT_SIZE = 50.sp
val ALARM_DAYS_TOP_PADDING = 12.dp
val DIVIDER_THICKNESS = 10.dp
val MIDDLE_CONTROL_SECTION_TOP_PADDING = 28.dp
val DIFFICULTY_SECTION_TOP_PADDING = 30.dp
val DIFFICULTY_SECTION_HORIZONTAL_PADDING = 26.dp
val DIFFICULTY_ICON_END_PADDING = 14.dp
val TEST_BUTTON_FONT_SIZE = 14.sp
val SAVE_BUTTON_FONT_SIZE = 14.sp
val SAVE_BUTTON_TOP_PADDING = 12.dp
}
| 2
|
Kotlin
|
2
| 15
|
1cc000f3c8345209b0494efed3274f2a3f8a4373
| 22,270
|
MathAlarm
|
MIT License
|
app/src/main/java/com/example/dropy/network/models/ongoingjobs/DeliveryMethod.kt
|
dropyProd
| 705,360,878
| false
|
{"Kotlin": 3916897, "Java": 20617}
|
package com.example.dropy.network.models.ongoingjobs
data class DeliveryMethod(
val method_name: String?
)
| 0
|
Kotlin
|
0
| 0
|
6d994c9c61207bac28c49717b6c250656fe4ae6b
| 111
|
DropyLateNights
|
Apache License 2.0
|
src/main/kotlin/com/icosillion/pine/validator/Rule.kt
|
icosillion
| 89,846,161
| false
| null |
package com.icosillion.pine.validator
import com.google.gson.JsonElement
class Rule {
protected var optional = false
protected var nullable = false
private val rules = hashMapOf<String, (Any) -> Boolean>()
//Rules
fun string(): Rule {
rules.put("string") { value ->
if(value is JsonElement) {
if(value.isJsonPrimitive) {
return@put value.asJsonPrimitive.isString
}
}
return@put value is String
}
return this
}
fun integer(): Rule {
rules.put("integer") { value ->
if(value is JsonElement) {
if(value.isJsonPrimitive) {
if(value.asJsonPrimitive.isNumber) {
return@put value.asJsonPrimitive.asNumber.toDouble().mod(1) == 0.0
}
}
}
return@put value is Int
}
return this
}
fun optional(): Rule {
optional = true
return this
}
fun nullable(): Rule {
nullable = true
return this
}
fun min(min: Number): Rule {
rules.put("min") { value ->
val numberValue = valueAsNumber(value)
val stringValue = valueAsString(value)
if(numberValue != null) {
if(numberValue.toDouble() < min.toDouble()) {
return@put false
}
return@put true
}
if(stringValue != null) {
if(stringValue.length < min.toInt()) {
return@put false
}
return@put true
}
return@put false
}
return this
}
fun max(max: Number): Rule {
rules.put("max") { value ->
val numberValue = valueAsNumber(value)
val stringValue = valueAsString(value)
if(numberValue != null) {
if(numberValue.toDouble() > max.toDouble()) {
return@put false
}
return@put true
}
if(stringValue != null) {
if(stringValue.length > max.toInt()) {
return@put false
}
return@put true
}
return@put false
}
return this
}
fun boolean(): Rule {
rules.put("boolean") { value ->
val boolValue = valueAsBoolean(value)
return@put boolValue != null
}
return this
}
fun number(): Rule {
rules.put("number") { value ->
val numberValue = valueAsNumber(value)
return@put numberValue != null
}
return this
}
fun length(length: Int): Rule {
rules.put("length") { value ->
val stringValue = valueAsString(value)
if(stringValue == null) {
return@put false
}
return@put stringValue.length == length
}
return this
}
fun anyOf(items: Array<String>, ignoreCase: Boolean = true): Rule {
rules.put("anyOf") { value ->
val stringValue = valueAsString(value)
if(stringValue == null) {
return@put false
}
items.forEach { item ->
if(stringValue.equals(stringValue, ignoreCase)) {
return@put true
}
}
return@put false
}
return this
}
fun validateWithReporting(obj: JsonElement?): ValidationResult {
if(obj == null) {
if(optional) {
return ValidationResult(true)
} else {
return ValidationResult(false, arrayListOf(ValidationError(
field = null,
reason = "Json Element not passed"
)))
}
}
if(obj.isJsonNull) {
if(nullable) {
return ValidationResult(true)
} else {
return ValidationResult(false, arrayListOf(ValidationError(
field = null,
reason = "Element is not nullable"
)))
}
}
var isValid = true
val errors = arrayListOf<ValidationError>()
rules.forEach { type, action ->
if(action.invoke(obj).not()) {
isValid = false
errors.add(ValidationError(
field = null,
reason = "Rule $type failed"
))
return@forEach
}
}
return ValidationResult(isValid, errors)
}
fun validate(obj: JsonElement?): Boolean {
return validateWithReporting(obj).isValid
}
//Helper Methods
private fun valueAsInteger(value: Any): Int? {
if(value is Int) {
return value
}
if(value is JsonElement
&& value.isJsonPrimitive
&& value.asJsonPrimitive.isNumber
&& value.asJsonPrimitive.asNumber is Int
) {
return value.asJsonPrimitive.asInt
}
return null
}
private fun valueAsNumber(value: Any): Number? {
if(value is Number) {
return value
}
if(value is JsonElement
&& value.isJsonPrimitive
&& value.asJsonPrimitive.isNumber
) {
return value.asJsonPrimitive.asNumber
}
return null
}
private fun valueAsString(value: Any): String? {
if(value is String) {
return value
}
if(value is JsonElement
&& value.isJsonPrimitive
&& value.asJsonPrimitive.isString
) {
return value.asJsonPrimitive.asString
}
return null
}
private fun valueAsBoolean(value: Any): Boolean? {
if(value is Boolean) {
return value
}
if(value is JsonElement
&& value.isJsonPrimitive
&& value.asJsonPrimitive.isBoolean
) {
return value.asJsonPrimitive.asBoolean
}
return null
}
}
| 0
|
Kotlin
|
0
| 4
|
14d79db813fe2c89a2c002abf3c84e1c4a42f6a6
| 6,351
|
pine
|
MIT License
|
zeapp/desktop/src/main/kotlin/de/berlindroid/zekompanion/desktop/ZeBadgeKompanion.kt
|
gdg-berlin-android
| 636,343,114
| false
|
{"Kotlin": 251126, "Python": 41102, "JavaScript": 4816, "HTML": 2584, "Shell": 74}
|
@file:JvmName("ZeBadgeKompanion")
package de.berlindroid.zekompanion.desktop
import androidx.compose.material.MaterialTheme
import androidx.compose.ui.awt.ComposePanel
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import de.berlindroid.zekompanion.BadgePayload
import de.berlindroid.zekompanion.base64
import de.berlindroid.zekompanion.buildBadgeManager
import de.berlindroid.zekompanion.desktop.ui.DrawNameBadge
import de.berlindroid.zekompanion.desktop.ui.ImageEditorBadge
import de.berlindroid.zekompanion.desktop.ui.ZeDesktopApp
import de.berlindroid.zekompanion.desktop.ui.fromJSONtoConfig
import de.berlindroid.zekompanion.ditherFloydSteinberg
import de.berlindroid.zekompanion.resize
import de.berlindroid.zekompanion.toBinary
import de.berlindroid.zekompanion.BADGE_WIDTH
import de.berlindroid.zekompanion.BADGE_HEIGHT
import de.berlindroid.zekompanion.zipit
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import java.awt.BorderLayout
import java.awt.Dimension
import java.awt.GraphicsEnvironment
import java.awt.Rectangle
import java.awt.Robot
import java.awt.image.BufferedImage
import java.io.File
import java.nio.IntBuffer
import javax.swing.JFrame
fun main() = application {
val painter = painterResource("icon.png")
MaterialTheme {
Window(
title = "ZeBadge - Kompanion",
icon = painter,
onCloseRequest = ::exitApplication,
) {
ZeDesktopApp(
sendToBadge = { state ->
when (state) {
is State.EditNameBadge ->
sendImageToBadge(
image = state.toBufferedImage(),
callback = ::sendResult,
)
is State.EditImage ->
sendImageToBadge(
image = state.toBufferedImage(),
callback = ::sendResult,
)
is State.Undecided -> Unit
}
},
)
}
}
}
private fun sendResult(result: Result<Int>) {
if (result.isFailure) {
result.exceptionOrNull()?.printStackTrace()
} else {
println("Successfully sent: ${result.getOrNull() ?: "unknown"} bytes.")
}
}
private fun State.EditImage.toBufferedImage(): BufferedImage {
val img = BufferedImage(BADGE_WIDTH, BADGE_HEIGHT, BufferedImage.TYPE_INT_RGB)
val g = img.createGraphics()
val badge = ComposePanel()
badge.size = Dimension(BADGE_WIDTH * 2, BADGE_HEIGHT * 2)
badge.setContent {
ImageEditorBadge(
image,
File(configFileName).readText().fromJSONtoConfig(),
)
}
return with(JFrame("badge")) {
layout = BorderLayout()
defaultCloseOperation = JFrame.DISPOSE_ON_CLOSE
size = Dimension(BADGE_WIDTH, BADGE_HEIGHT)
isAlwaysOnTop = true // make sure it is ontop, before we screenshot
isUndecorated = true // no borders, no things we need to consider
isVisible = true // also: visible for screenshot is important
setLocationRelativeTo(null) // center on screen
add(badge)
paintAll(g)
g.dispose()
val center = GraphicsEnvironment.getLocalGraphicsEnvironment().centerPoint
Robot().createScreenCapture(
Rectangle(
center.x - BADGE_WIDTH / 2,
center.y - BADGE_HEIGHT / 2,
BADGE_WIDTH,
BADGE_HEIGHT,
),
).also {
dispose()
}
}
}
private fun State.EditNameBadge.toBufferedImage(): BufferedImage {
val img = BufferedImage(BADGE_WIDTH, BADGE_HEIGHT, BufferedImage.TYPE_INT_RGB)
val g = img.createGraphics()
val badge = ComposePanel()
badge.size = Dimension(BADGE_WIDTH * 2, BADGE_HEIGHT * 2)
badge.setContent {
DrawNameBadge(
state = this,
factor = 2.0f,
/** Hand waving of high def displays **/
)
}
return with(JFrame("badge")) {
layout = BorderLayout()
defaultCloseOperation = JFrame.DISPOSE_ON_CLOSE
size = Dimension(BADGE_WIDTH, BADGE_HEIGHT)
isAlwaysOnTop = true // make sure it is ontop, before we screenshot
isUndecorated = true // no borders, no things we need to consider
isVisible = true // also: visible for screenshot is important
setLocationRelativeTo(null) // center on screen
add(badge)
paintAll(g)
g.dispose()
val center = GraphicsEnvironment.getLocalGraphicsEnvironment().centerPoint
Robot().createScreenCapture(
Rectangle(
center.x - BADGE_WIDTH / 2,
center.y - BADGE_HEIGHT / 2,
BADGE_WIDTH,
BADGE_HEIGHT,
),
).also {
dispose()
}
}
}
private fun sendImageToBadge(image: BufferedImage, callback: (Result<Int>) -> Unit) {
try {
GlobalScope.launch {
with(buildBadgeManager("")) {
if (isConnected()) {
val payload = BadgePayload(
debug = false,
type = "preview",
meta = "",
image.toPayload(),
)
callback(sendPayload(payload))
} else {
callback(
Result.failure(IllegalStateException("Not connected")),
)
}
}
}
} catch (e: Exception) {
callback(
Result.failure(UnknownError("")),
)
}
}
private fun BufferedImage.toPayload(): String {
val array = IntArray(width * height * 3)
getRGB(0, 0, width, height, array, 0, width)
return IntBuffer
.wrap(array)
.resize(width, height, BADGE_WIDTH, BADGE_HEIGHT)
.ditherFloydSteinberg(BADGE_WIDTH, BADGE_HEIGHT)
.toBinary()
.zipit()
.base64()
}
| 17
|
Kotlin
|
105
| 48
|
e06da6dd31962a340427556c40357cfd2fef1b2c
| 6,242
|
ZeBadge
|
Apache License 2.0
|
src/main/kotlin/cn/lnkdoc/sdk/uia/instance/github/GithubSdkInstance.kt
|
langkye
| 615,896,447
| false
|
{"Kotlin": 398542, "Java": 196}
|
package cn.lnkdoc.sdk.uia.instance.github
import cn.lnkdoc.sdk.uia.common.request.IUiaRequest
import cn.lnkdoc.sdk.uia.common.response.UiaResponse
import cn.lnkdoc.sdk.uia.instance.AbstractInstance
import cn.lnkdoc.sdk.uia.instance.ISdkInstance
import cn.lnkdoc.sdk.uia.instance.github.request.AccessTokenRequest
import cn.lnkdoc.sdk.uia.instance.github.client.GithubUiaClient
import cn.lnkdoc.sdk.uia.instance.github.property.GithubProperty
/**
* @author langkye
* @since 1.0.0.RELEASE
*/
@Suppress("Unchecked_cast")
class GithubSdkInstance(property: GithubProperty) : AbstractInstance(), ISdkInstance {
/**
* constructor
*/
init {
client = GithubUiaClient.getInstance(property)
}
/**
* get accessToken
*
* @param r code
* @return accessToken
*/
override fun <T, R> getAccessToken(r: R): UiaResponse<T> {
return client.execute<Any>((r as AccessTokenRequest)) as UiaResponse<T>
}
/**
* get UserInfo
*
* @param accessToken accessToken
* @return UserInfo
*/
override fun <T, R> getUserInfo(accessToken: R): UiaResponse<T> {
return client.execute<Any>((accessToken as IUiaRequest)) as UiaResponse<T>
}
}
| 0
|
Kotlin
|
0
| 1
|
a0d45b63a1fb6f66df77934c5c0ed65deca215a5
| 1,228
|
awesome-uia-sdk
|
Apache License 2.0
|
src/test/resources/examples/inLinedObject/models/SecondInlineObjectGeneration.kt
|
cjbooms
| 229,844,927
| false
|
{"Kotlin": 874094, "Handlebars": 4874}
|
package examples.inLinedObject.models
import com.fasterxml.jackson.`annotation`.JsonProperty
import javax.validation.Valid
import kotlin.String
public data class SecondInlineObjectGeneration(
@param:JsonProperty("call_home")
@get:JsonProperty("call_home")
@get:Valid
public val callHome: SecondInlineObjectCallHome? = null,
@param:JsonProperty("database_view")
@get:JsonProperty("database_view")
@get:Valid
public val databaseView: SecondInlineObjectDatabaseView? = null,
@param:JsonProperty("direct")
@get:JsonProperty("direct")
public val direct: String? = null,
)
| 33
|
Kotlin
|
41
| 154
|
b95cb5bd8bb81e59eca71e467118cd61a1848b3f
| 591
|
fabrikt
|
Apache License 2.0
|
PennMobile/src/main/java/com/pennapps/labs/pennmobile/adapters/FitnessHeaderAdapter.kt
|
pennlabs
| 16,791,473
| false
|
{"Kotlin": 618643, "Java": 96504, "HTML": 1719}
|
package com.pennapps.labs.pennmobile.adapters
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.pennapps.labs.pennmobile.R
class FitnessHeaderAdapter(
private val text: String,
) : RecyclerView.Adapter<FitnessHeaderAdapter.ViewHolder>() {
class ViewHolder(
view: View,
) : RecyclerView.ViewHolder(view) {
val headerView: TextView
init {
headerView = view.findViewById(R.id.fitness_section_title_text)
}
}
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int,
): ViewHolder {
val view =
LayoutInflater
.from(parent.context)
.inflate(R.layout.fitness_section_title, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int = 1
override fun onBindViewHolder(
holder: ViewHolder,
position: Int,
) {
holder.headerView.text = text
}
}
| 0
|
Kotlin
|
5
| 34
|
661a90384e308119f285ebe6c75109d6b2686497
| 1,085
|
penn-mobile-android
|
MIT License
|
AS/NetworkImageView/app/src/main/java/com/josericardojr/networkimageview/datamodel/PixabayResult.kt
|
josericardojr
| 683,865,030
| false
|
{"Kotlin": 70283}
|
package com.josericardojr.networkimageview.datamodel
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class PixabayResult (
@SerialName("total" ) var total : Int? = null,
@SerialName("totalHits" ) var totalHits : Int? = null,
@SerialName("hits" ) var hits : ArrayList<Hits> = arrayListOf()
)
| 0
|
Kotlin
|
0
| 0
|
86f039657bfa4ad2449a7a7001a8073003e8b17b
| 393
|
AndroidKotlin
|
Apache License 2.0
|
typescript/ts-nodes/src/org/jetbrains/dukat/ast/model/nodes/MethodNodeMeta.kt
|
posix-dev
| 270,574,458
| true
|
{"Kotlin": 2679797, "WebIDL": 323303, "TypeScript": 126912, "JavaScript": 15989, "ANTLR": 11333}
|
package org.jetbrains.dukat.ast.model.nodes
data class MethodNodeMeta(
val generated: Boolean
)
| 0
| null |
0
| 0
|
2a843bb20614e02c011b33ddb8bbe84c4755c107
| 101
|
dukat
|
Apache License 2.0
|
kotlin-electron/src/jsMain/generated/electron/renderer/WebviewTagPrintOptions.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 11411371, "JavaScript": 154302}
|
package electron.renderer
typealias WebviewTagPrintOptions = electron.core.WebviewTagPrintOptions
| 28
|
Kotlin
|
173
| 1,250
|
9e9dda28cf74f68b42a712c27f2e97d63af17628
| 100
|
kotlin-wrappers
|
Apache License 2.0
|
library/src/main/java/com/shopapp/shopify/api/adapter/ProductAdapter.kt
|
rubygarage
| 121,784,219
| false
| null |
package com.shopapp.shopify.api.adapter
import com.shopapp.gateway.entity.Image
import com.shopapp.gateway.entity.Product
import com.shopapp.gateway.entity.ProductVariant
import com.shopapp.shopify.api.ext.isSingleOptions
import com.shopapp.shopify.constant.Constant.DEFAULT_STRING
import com.shopify.buy3.Storefront
import java.math.BigDecimal
object ProductAdapter {
private val DEFAULT_PRICE = BigDecimal.ZERO
fun adapt(shopAdaptee: Storefront.Shop,
productAdaptee: Storefront.Product,
paginationValue: String? = null,
isConvertVariants: Boolean = true): Product {
return if (isConvertVariants) {
adapt(
shopAdaptee,
productAdaptee,
paginationValue,
productAdaptee.variants.edges.filterNotNull().map { ProductVariantAdapter.adapt(it.node) }
)
} else {
adapt(
shopAdaptee,
productAdaptee,
paginationValue,
listOf()
)
}
}
private fun adapt(shopAdaptee: Storefront.Shop,
productAdaptee: Storefront.Product,
paginationValue: String? = null,
variants: List<ProductVariant>): Product {
val productImages = convertImage(productAdaptee)
if (productAdaptee.isSingleOptions()) {
productAdaptee.variants.edges.forEach { it.node.title = DEFAULT_STRING }
}
val pricePair = convertPrice(productAdaptee)
return Product(
id = productAdaptee.id.toString(),
title = productAdaptee.title,
productDescription = productAdaptee.description,
additionalDescription = productAdaptee.descriptionHtml,
vendor = productAdaptee.vendor,
currency = shopAdaptee.paymentSettings.currencyCode.toString(),
type = productAdaptee.productType,
tags = productAdaptee.tags,
createdAt = productAdaptee.createdAt.toDate(),
updatedAt = productAdaptee.updatedAt.toDate(),
price = pricePair.first,
hasAlternativePrice = pricePair.first != pricePair.second,
images = productImages,
options = ProductOptionListAdapter.adapt(productAdaptee.options),
variants = variants,
paginationValue = paginationValue
)
}
private fun convertPrice(productAdaptee: Storefront.Product): Pair<BigDecimal, BigDecimal> {
val variantsList = productAdaptee.variants.edges
return if (variantsList.size > 0) {
val mappedList = variantsList.filterNotNull().map { it.node.price }
Pair(mappedList.min() ?: DEFAULT_PRICE, mappedList.max() ?: DEFAULT_PRICE)
} else {
Pair(DEFAULT_PRICE, DEFAULT_PRICE)
}
}
private fun convertImage(productAdaptee: Storefront.Product): List<Image> =
productAdaptee.images.edges.filterNotNull().mapNotNull { ImageAdapter.adapt(it.node) }
}
| 4
|
Kotlin
|
31
| 51
|
33d10ee580d12ad94042566677a4607ab21d236b
| 3,077
|
shopapp-shopify-android
|
Apache License 2.0
|
app/src/main/java/com/tonia/githubandroidtrending/repodetails/RepoDetailsFragment.kt
|
lomza
| 162,416,049
| false
| null |
package com.tonia.githubandroidtrending.repodetails
import android.content.Intent
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.View
import androidx.annotation.NonNull
import androidx.appcompat.app.AppCompatActivity
import com.tonia.githubandroidtrending.BaseFragment
import com.tonia.githubandroidtrending.R
import com.tonia.githubandroidtrending.model.Repo
import com.tonia.githubandroidtrending.util.visible
import com.tonia.githubandroidtrending.util.gone
import com.tonia.githubandroidtrending.util.toastLong
import com.tonia.githubandroidtrending.util.loadImageFromUrl
import com.tonia.githubandroidtrending.util.valueOrUnknown
import com.tonia.githubandroidtrending.util.getRepoDate
import es.dmoral.markdownview.MarkdownView
import kotlinx.android.synthetic.main.fragment_repo_details.view.*
import kotlinx.android.synthetic.main.fragment_repo_list.*
/**
* Fragment, that shows the details of a chosen GitHub repo.
* Contains the presenter and refreshes the UI on presenter's callbacks.
*/
class RepoDetailsFragment : BaseFragment(), RepoDetailsContract.View {
private var parentView: View? = null
private val presenter = RepoDetailsPresenter()
companion object {
const val TAG = "repo_details_fragment"
private const val EXTRA_REPO = "extra_repo"
fun newInstance(@NonNull repo: Repo) =
RepoDetailsFragment().apply {
arguments = Bundle().apply {
putParcelable(EXTRA_REPO, repo)
}
}
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
super.onCreateOptionsMenu(menu, inflater)
menu.clear()
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
(context as AppCompatActivity).setSupportActionBar(toolbar)
setHasOptionsMenu(true)
}
override fun getContentResource() = R.layout.fragment_repo_details
override fun init(view: View, state: Bundle?) {
parentView = view
}
override fun showProgressBar() {
parentView?.progressBarDetails?.visible()
}
override fun hideProgressBar() {
parentView?.progressBarDetails?.gone()
}
override fun showErrorMessage(messageResId: Int) {
context?.toastLong(getString(messageResId))
}
override fun setTitle(title: String) {
toolbar.title = title
}
override fun showRepo(repo: Repo) {
parentView?.apply {
with(repo) {
loadImageFromUrl(
fragment = this@RepoDetailsFragment,
url = owner.avatar_url,
imageView = imageViewCollapsing
)
textViewStars.text = stargazers_count.toString()
textViewForks.text = forks_count.toString()
textViewWatchers.text = watchers_count.toString()
textViewOpenIssues.text = open_issues_count.toString()
textViewLanguage.text = language.valueOrUnknown()
textViewLicense.text = license?.name.valueOrUnknown()
textViewLastUpdated.text = getRepoDate(updated_at)
textViewFullName.text = full_name
textViewDesc.text = description
imageButtonGitHubRepo.setOnClickListener {
presenter.openGitHubProject(html_url)
}
fabShare.setOnClickListener {
presenter.shareRepo(
url = html_url,
message = getString(R.string.repo_share_text, html_url),
chooserTitle = getString(R.string.send_to))
}
presenter.loadRepoReadme(owner.login, name)
}
}
}
override fun showRepoReadme(url: String) {
parentView?.markdownViewReadmeContent?.loadFromUrl(url)
parentView?.markdownViewReadmeContent?.setOnMarkdownRenderingListener(object :
MarkdownView.OnMarkdownRenderingListener {
override fun onMarkdownRenderError() {
hideProgressBar()
showErrorMessage(R.string.general_error_message)
}
override fun onMarkdownFinishedRendering() {
hideProgressBar()
}
})
}
override fun showRepoShareChooser(intent: Intent) {
context?.startActivity(intent)
}
override fun showProjectInBrowser(intent: Intent) {
context?.startActivity(intent)
}
override fun onStart() {
super.onStart()
presenter.attach(this)
arguments?.let {
presenter.loadRepo(it.getParcelable(EXTRA_REPO))
}
}
override fun onStop() {
super.onStop()
presenter.detach()
}
}
| 0
|
Kotlin
|
0
| 0
|
5db284805ed42822a7201f339984ada198000c3a
| 4,893
|
github-android-trending
|
MIT License
|
app/src/main/java/top/jowanxu/wanandroidclient/view/CommonUseFragmentView.kt
|
fyhtosky
| 138,373,682
| false
|
{"Kotlin": 157771}
|
package top.jowanxu.wanandroidclient.view
import top.jowanxu.wanandroidclient.bean.FriendListResponse
import top.jowanxu.wanandroidclient.bean.HotKeyResponse
/**
* CommonUse Fragment View interface
*/
interface CommonUseFragmentView {
/**
* get Friend list Success
*/
fun getFriendListSuccess(bookmarkResult: FriendListResponse?, commonResult: FriendListResponse, hotResult: HotKeyResponse)
/**
* get Friend list Failed
*/
fun getFriendListFailed(errorMessage: String?)
/**
* get Friend list data size equal zero
*/
fun getFriendListZero()
}
| 0
|
Kotlin
|
0
| 0
|
2e4b9fd04da815093b9f68372b7cf552c5d6247e
| 599
|
WanAndroidClient
|
Apache License 2.0
|
kotlin/graphs/shortestpaths/DijkstraHeap.kt
|
polydisc
| 281,633,906
| true
|
{"Java": 540473, "Kotlin": 515759, "C++": 265630, "CMake": 571}
|
package graphs.shortestpaths
import java.util.stream.Stream
// https://en.wikipedia.org/wiki/Dijkstra's_algorithm
object DijkstraHeap {
// calculate shortest paths in O(E*log(V)) time and O(E) memory
fun shortestPaths(edges: Array<List<Edge>>, s: Int, prio: IntArray, pred: IntArray) {
Arrays.fill(pred, -1)
Arrays.fill(prio, Integer.MAX_VALUE)
prio[s] = 0
val q: PriorityQueue<Long> = PriorityQueue()
q.add(s.toLong())
while (!q.isEmpty()) {
val cur: Long = q.remove()
val curu = cur.toInt()
if (cur ushr 32 != prio[curu]) continue
for (e in edges[curu]) {
val v = e.t
val nprio = prio[curu] + e.cost
if (prio[v] > nprio) {
prio[v] = nprio
pred[v] = curu
q.add((nprio.toLong() shl 32) + v)
}
}
}
}
// Usage example
fun main(args: Array<String?>?) {
val cost = arrayOf(intArrayOf(0, 3, 2), intArrayOf(0, 0, -2), intArrayOf(0, 0, 0))
val n = cost.size
val graph: Array<List<Edge>> = Stream.generate { ArrayList() }.limit(n).toArray { _Dummy_.__Array__() }
for (i in 0 until n) {
for (j in 0 until n) {
if (cost[i][j] != 0) {
graph[i].add(Edge(j, cost[i][j]))
}
}
}
val dist = IntArray(n)
val pred = IntArray(n)
shortestPaths(graph, 0, dist, pred)
System.out.println(0 == dist[0])
System.out.println(3 == dist[1])
System.out.println(1 == dist[2])
System.out.println(-1 == pred[0])
System.out.println(0 == pred[1])
System.out.println(1 == pred[2])
}
class Edge(var t: Int, var cost: Int)
}
| 1
|
Java
|
0
| 0
|
4566f3145be72827d72cb93abca8bfd93f1c58df
| 1,847
|
codelibrary
|
The Unlicense
|
app/src/main/kotlin/io/github/shadow578/yodel/ui/splash/SplashScreenActivity.kt
|
shadow578
| 387,132,583
| false
| null |
package io.github.shadow578.yodel.ui.splash
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import io.github.shadow578.yodel.ui.main.MainActivity
import io.github.shadow578.yodel.util.launchMain
import kotlinx.coroutines.delay
/**
* basic splash- screen activity.
* displays a splash- screen, then redirects the user to the correct activity
*/
class SplashScreenActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
launchMain {
delay(50)
startActivity(Intent(this@SplashScreenActivity, MainActivity::class.java))
finish()
}
}
}
| 0
|
Kotlin
|
0
| 9
|
132f0178422fc3e900348437456d05ee15481bae
| 723
|
Yodel
|
Apache License 2.0
|
app/src/main/java/com/dede/android_eggs/main/entity/Egg.kt
|
user0-07161
| 691,672,633
| false
|
{"Java Properties": 4, "YAML": 7, "Gradle Kotlin DSL": 6, "Markdown": 9, "Shell": 1, "Batchfile": 1, "Text": 31, "Ruby": 2, "Gemfile.lock": 1, "Ignore List": 22, "SVG": 5, "XML": 818, "Kotlin": 117, "TOML": 1, "Python": 4, "JSON": 2, "Dotenv": 1, "Proguard": 17, "Java": 1609, "Gradle": 15, "JAR Manifest": 1, "Maven POM": 2, "IDL": 1}
|
package com.dede.android_eggs.main.entity
import android.app.Activity
import android.content.Context
import android.graphics.drawable.Drawable
import android.os.Bundle
import android.text.SpannableStringBuilder
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
import com.dede.android_eggs.R
import com.dede.android_eggs.ui.adapter.VType
import com.dede.android_eggs.ui.drawables.AlterableAdaptiveIconDrawable
import com.dede.android_eggs.views.settings.prefs.IconShapePref
import com.dede.basic.requireDrawable
data class Egg(
@DrawableRes val iconRes: Int,
@StringRes val androidRes: Int,
@StringRes val eggNameRes: Int,
val versionCommentFormatter: VersionCommentFormatter,
val targetClass: Class<out Activity>? = null,
val supportAdaptiveIcon: Boolean = false,
val key: String? = null,
val extras: Bundle? = null,
private val itemType: Int = VIEW_TYPE_EGG,
) : VType {
class VersionCommentFormatter(
private val versionCode1: Int,
private val versionCode2: Int,
private val versionName1: CharSequence,
private val versionName2: CharSequence
) {
constructor(versionCode: Int, versionName: CharSequence) :
this(versionCode, versionCode, versionName, versionName)
fun format(context: Context): CharSequence {
val sb = StringBuilder("API ")
.append(versionCode1)
if (versionCode1 == versionCode2) {
sb.append("\nAndroid ")
.append(versionName1)
} else {
val enDash = context.getString(R.string.char_en_dash)
sb.append(enDash)
.append(versionCode2.toString())
.append("\nAndroid ")
.append(versionName1)
.append(enDash)
.append(versionName2)
}
return sb
}
}
companion object {
const val VIEW_TYPE_EGG = 0
const val VIEW_TYPE_WAVY = -1
const val VIEW_TYPE_PREVIEW = 1
const val VIEW_TYPE_EGG_GROUP = 2
fun Egg.getIcon(context: Context): Drawable {
if (supportAdaptiveIcon) {
val pathStr = IconShapePref.getMaskPath(context)
return AlterableAdaptiveIconDrawable(context, iconRes, pathStr)
}
return context.requireDrawable(iconRes)
}
}
override val viewType: Int = itemType
}
class EggGroup(
val child: List<Egg>,
var selectedIndex: Int = 0,
) : VType {
constructor(selectedIndex: Int, vararg child: Egg) : this(
child.toList(),
selectedIndex
)
val selectedEgg: Egg get() = child[selectedIndex]
override val viewType: Int
get() = Egg.VIEW_TYPE_EGG_GROUP
}
class Wavy(val wavyRes: Int, val repeat: Boolean = false) : VType {
override val viewType: Int = Egg.VIEW_TYPE_WAVY
}
| 1
| null |
1
| 1
|
eb428446eef024622f00b3a22f728d5f56368861
| 2,953
|
AndroidEasterEggs
|
Apache License 2.0
|
home-service/src/main/kotlin/ru/handh/homeservice/controller/HomeController.kt
|
mBayzigitov
| 759,726,460
| false
|
{"Kotlin": 147151, "Java": 847}
|
package ru.handh.homeservice.controller
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
import ru.handh.homeservice.dto.HomeSimple
import ru.handh.homeservice.dto.request.HomeRequest
import ru.handh.homeservice.service.HomeService
@RestController
@RequestMapping("/api/homes")
class HomeController(
private val service: HomeService
) {
@PostMapping
fun createHome(@Validated @RequestBody request: HomeRequest) =
service.save(request)
@PutMapping("/{id}")
fun editHome(@PathVariable id: Int,
@Validated @RequestBody request: HomeRequest) =
service.edit(id, request)
@GetMapping("/{id}")
fun getHome(@PathVariable id: Int) =
service.getHomeById(id)
@DeleteMapping("/{id}")
fun deleteHome(@PathVariable id: Int) =
service.remove(id)
@GetMapping("/all/{userId}")
fun getListOfHomes(@PathVariable("userId") userId: Int): List<HomeSimple> =
service.getListOfHomes(userId)
@GetMapping("/{id}/userId")
fun getUserIdByHomeId(@PathVariable id: Int) =
service.getUserIdByHomeId(id)
}
| 0
|
Kotlin
|
0
| 0
|
bf1fc71d6b4c1feb48fbc770d782cea2ebd6df6d
| 1,588
|
smart-devices-microservice
|
MIT License
|
wearable-support/src/main/java/healthstack/wearable/support/viewmodel/EcgMainViewModel.kt
|
S-HealthStack
| 520,365,275
| false
|
{"Kotlin": 900773}
|
package healthstack.wearable.support.viewmodel
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import healthstack.wearable.support.data.pref.TrackMeasureTimePref
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import javax.inject.Inject
@HiltViewModel
class EcgMainViewModel @Inject constructor(
application: Application,
trackMeasureTimePref: TrackMeasureTimePref,
) : AndroidViewModel(application) {
private val _lastMeasurementTime = MutableLiveData<String>()
val lastMeasurementTime: LiveData<String>
get() = _lastMeasurementTime
init {
viewModelScope.launch(Dispatchers.IO) {
kotlin.runCatching {
viewModelScope.launch {
trackMeasureTimePref.getLastMeasureFlow().collect {
_lastMeasurementTime.postValue(it.getTimeString())
}
}
}.onFailure {
it.printStackTrace()
}
}
}
}
fun Long.getTimeString(): String {
val format_date = SimpleDateFormat("dd/MM/yyyy")
val format_time = SimpleDateFormat("hh:mm a")
val currentDate = Date()
val currentDateString = format_date.format(currentDate)
return if (this == 0L) {
""
} else {
val lastMeasure = Date(this)
val lastMeasureDate = format_date.format(lastMeasure)
if (currentDateString == lastMeasureDate) {
format_time.format(lastMeasure)
} else {
lastMeasureDate
}
}
}
| 5
|
Kotlin
|
19
| 25
|
a8fc44c65b482e53e4ef3fb8f539ec731ef59230
| 1,788
|
app-sdk
|
Apache License 2.0
|
app/src/main/java/com/wpf/app/quick/demo/http/TestService.kt
|
walgr
| 487,438,913
| false
|
{"Kotlin": 427396, "Java": 106045, "Shell": 404}
|
package com.wpf.app.quick.demo.http
import com.wpf.app.quicknetwork.base.*
import com.wpf.app.quicknetwork.call.RealCall
import com.wpf.app.quicknetwork.helper.RetrofitCreateHelper
inline fun <Data, Fail> request(context: RequestCoroutineScope? = null, run: TestApi.() -> RealCall<Data, Fail>): BaseRequest<Data, Fail> {
return RetrofitCreateHelper.getService<TestApi>().run(run).enqueue(WpfRequest(context))
}
| 0
|
Kotlin
|
1
| 6
|
ee509f62288fc6a926c2e1b1f944857ed32ef548
| 416
|
Quick
|
MIT License
|
src/day25/Code.kt
|
fcolasuonno
| 221,697,249
| false
| null |
package day25
import java.io.File
fun main() {
val name = if (false) "test.txt" else "input.txt"
val dir = ::main::class.java.`package`.name
val input = File("src/$dir/$name").readLines()
val parsed = parse(input)
println("Part 1 = ${part1(parsed.toMutableList())}")
}
val output = mutableListOf<Long>()
val opcodes = mapOf<String, (String, String) -> ((MutableMap<String, Long>, MutableList<Triple<String, String, String>>) -> Unit)>(
"inc" to { a: String, _ ->
{ regs: MutableMap<String, Long>, _: MutableList<Triple<String, String, String>> ->
regs[a] = regs.getValue(a) + 1
regs["ip"] = regs.getValue("ip") + 1
}
},
"dec" to { a: String, _ ->
{ regs: MutableMap<String, Long>, _: MutableList<Triple<String, String, String>> ->
regs[a] = regs.getValue(a) - 1
regs["ip"] = regs.getValue("ip") + 1
}
},
"tgl" to { a: String, _ ->
{ regs: MutableMap<String, Long>, input: MutableList<Triple<String, String, String>> ->
val position = regs.getValue("ip").toInt() + regs.getValue(a).toInt()
val instruction = input.getOrNull(position)
if (instruction != null) {
input[position] = instruction.copy(first = when (instruction.first) {
"inc" -> "dec"
"dec" -> "inc"
"tgl" -> "inc"
"jnz" -> "cpy"
"cpy" -> "jnz"
else -> ""
})
}
regs["ip"] = regs.getValue("ip") + 1
}
},
"cpy" to { a: String, b: String ->
{ regs: MutableMap<String, Long>, _: MutableList<Triple<String, String, String>> ->
regs[b] = (a.toLongOrNull() ?: regs.getValue(a))
regs["ip"] = regs.getValue("ip") + 1
}
},
"jnz" to { a: String, b: String ->
{ regs: MutableMap<String, Long>, _: MutableList<Triple<String, String, String>> ->
if ((a.toLongOrNull() ?: regs.getValue(a)) != 0L) {
regs["ip"] = regs.getValue("ip") + (b.toLongOrNull() ?: regs.getValue(b))
} else {
regs["ip"] = regs.getValue("ip") + 1
}
}
},
"out" to { a: String, _ ->
{ regs: MutableMap<String, Long>, _: MutableList<Triple<String, String, String>> ->
output.add(a.toLongOrNull() ?: regs.getValue(a))
regs["ip"] = regs.getValue("ip") + 1
}
}
)
private val lineStructure = """(\w+) (-?\w+) ?(-?\w+)?""".toRegex()
fun parse(input: List<String>) = input.map {
lineStructure.matchEntire(it)?.destructured?.let {
val (op, op1, op2) = it.toList()
Triple(op, op1, op2)
}
}.requireNoNulls()
fun part1(input: MutableList<Triple<String, String, String>>): Any? = generateSequence(1) { it + 1 }.first {
output.clear()
mutableMapOf<String, Long>("a" to it.toLong()).withDefault { 0L }.let { regs ->
generateSequence {
input.getOrNull(regs.getValue("ip").toInt())
}.map { (op, op1, op2) ->
opcodes.getValue(op)(op1, op2)(regs, input)
}.takeWhile { output.size < 10 }.last()
output.zipWithNext().all { it.first != it.second }
}
}
| 0
|
Kotlin
|
0
| 0
|
73110eb4b40f474e91e53a1569b9a24455984900
| 3,485
|
AOC2016
|
MIT License
|
mobile/shared/src/main/java/dev/trotrohailer/shared/util/location/live/LiveLocationUpdate.kt
|
quabynah-bilson
| 204,245,589
| false
| null |
package dev.trotrohailer.shared.util.location.live
import android.location.Location
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.*
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.api.GoogleApiClient
import com.google.android.gms.location.LocationListener
import com.google.android.gms.location.LocationRequest
import com.google.android.gms.location.LocationServices
import dev.trotrohailer.shared.util.debugger
class LiveLocationUpdate(private val host: AppCompatActivity) : LifecycleOwner, LocationListener,
GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
override fun onConnected(p0: Bundle?) {
debugger("API client connected")
}
override fun onConnectionSuspended(p0: Int) {
debugger("API client suspended")
}
override fun onConnectionFailed(p0: ConnectionResult) {
debugger("Failed to connect to API client")
}
private val _liveLocation = MutableLiveData<Location>()
val lastLocation: LiveData<Location> = _liveLocation
private var apiClient: GoogleApiClient? = null
override fun onLocationChanged(location: Location?) {
if (location != null) {
_liveLocation.value = location
}
}
init {
val locationRequest = LocationRequest()
with(locationRequest) {
fastestInterval = 1000
interval = 1000
priority = LocationRequest.PRIORITY_HIGH_ACCURACY
}
buildApiClient()
LocationServices.getFusedLocationProviderClient(host).lastLocation.addOnCompleteListener(
host
) {
if (it.isSuccessful) {
_liveLocation.value = it.result
}
}
}
@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
@Synchronized
//@RequiresPermission(allOf = [Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION])
private fun buildApiClient() {
apiClient = GoogleApiClient.Builder(host.applicationContext)
.addApi(LocationServices.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build()
apiClient?.connect()
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
private fun disconnect() = apiClient?.disconnect()
override fun getLifecycle(): Lifecycle = host.lifecycle
}
| 5
|
Kotlin
|
1
| 0
|
fb347931d9ecefe1566f8662028bcf0187de468f
| 2,468
|
project-trotro-hailer
|
Apache License 2.0
|
sources/naf_presentation_layer/library/src/androidTest/java/com/github/nikolaymenzhulin/naf_presentation_layer/android_test/presentation/view/fragment/test_data/fragment/view_binding/base/TestViewBindingFragment.kt
|
NikolayMenzhulin
| 360,942,326
| false
| null |
/*
Copyright © 2021 Nikolay Menzhulin.
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.github.nikolaymenzhulin.naf_presentation_layer.android_test.presentation.view.fragment.test_data.fragment.view_binding.base
import android.os.Bundle
import android.view.View
import androidx.annotation.LayoutRes
import androidx.fragment.app.viewModels
import com.github.nikolaymenzhulin.naf_presentation_layer.android_test.presentation.view.fragment.ViewBindingFragmentTest.Companion.CURRENT_NUMBER_INIT_VALUE
import com.github.nikolaymenzhulin.naf_presentation_layer.databinding.FragmentViewBindingTestBinding
import com.github.nikolaymenzhulin.naf_presentation_layer.presentation.view.view_binding.ViewBindingFragment
abstract class TestViewBindingFragment(
@LayoutRes contentLayoutId: Int = 0
) : ViewBindingFragment<TestViewBindingFragmentViewModel, FragmentViewBindingTestBinding>(
contentLayoutId,
FragmentViewBindingTestBinding::class.java
) {
override val vm: TestViewBindingFragmentViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
vb.currentNumberTv.root.text = CURRENT_NUMBER_INIT_VALUE
vb.viewBindingHashTv.text = vb.hashCode().toString()
}
}
| 0
|
Kotlin
|
0
| 0
|
5e478b4c0f527913f3f0cc3aa952e120c9275ae3
| 1,792
|
NAF
|
Apache License 2.0
|
shardis-web/src/main/kotlin/com/shardis/config/JpaConfig.kt
|
dkul108
| 92,852,566
| true
|
{"Kotlin": 47845, "TypeScript": 38849, "HTML": 2879, "JavaScript": 2024, "Batchfile": 748, "Shell": 659, "CSS": 80}
|
package com.shardis.config
import com.shardis.support.security.SecurityUtils
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.data.domain.AuditorAware
import org.springframework.data.jpa.repository.config.EnableJpaAuditing
@Configuration
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
open class JpaConfig {
@Bean(name = arrayOf("auditorProvider"))
open fun auditorProvider(): AuditorAware<Long?> {
return AuditorAware { SecurityUtils.getLoggedUser()?.userId }
}
}
| 0
|
Kotlin
|
0
| 0
|
95585b7c47579a2c66a3e5fbeb0b232ebf02e536
| 586
|
shardis
|
Apache License 2.0
|
src/commonMain/kotlin/Container.kt
|
tomuvak
| 504,971,567
| false
|
{"Kotlin": 52872, "Shell": 643}
|
package com.tomuvak.optional
import com.tomuvak.optional.Optional.None
import com.tomuvak.optional.Optional.Value
fun <T, R> Optional<T>.map(transform: (T) -> R): Optional<R> = switch(None) { Value(transform(it)) }
fun <T, R> Optional<T>.flatMap(transform: (T) -> Optional<R>): Optional<R> = switch(None, transform)
fun <T> Optional<Optional<T>>.flatten(): Optional<T> = switch(None) { it }
fun <T> Optional<T>.filter(predicate: (T) -> Boolean): Optional<T> = switch(None) { if (predicate(it)) this else None }
fun <T> Optional<T>.filterNot(predicate: (T) -> Boolean): Optional<T> =
switch(None) { if (predicate(it)) None else this }
inline fun <reified T> Optional<Any?>.filterIsInstance(): Optional<T> =
switch(None) { if (it is T) Value(it) else None }
fun <T> Optional<T>.asSequence(): Sequence<T> = switch(::emptySequence) { sequenceOf(it) }
fun <T> Optional<T>.asIterable(): Iterable<T> = asSequence().asIterable()
fun <T> Optional<T>.toList(): List<T> = switch(::emptyList) { listOf(it) }
inline fun <reified T> Optional<T>.toTypedArray(): Array<T> = toList().toTypedArray()
| 0
|
Kotlin
|
0
| 0
|
367dae6e8bcc393309f381968de0fbfcff6db63f
| 1,094
|
optional
|
MIT License
|
app/src/main/java/datanapps/recycleviewexample/utils/LayoutUtils.kt
|
datanapps
| 398,742,055
| false
| null |
package datanapps.example.utils
import android.graphics.Bitmap
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.core.content.ContextCompat
import androidx.palette.graphics.Palette
import datanapps.recycleviewexample.R
import android.graphics.drawable.BitmapDrawable
import android.graphics.drawable.Drawable
/*
* Created by Dev_Network_PC on 18/8/2021
*/
fun ConstraintLayout.setColorFromBitmap(drawable: Drawable) {
if(drawable is BitmapDrawable) {
val bitmap = drawable.bitmap
Palette.Builder(bitmap).generate {
it?.let { palette ->
val dominantColor =
palette.getDominantColor(ContextCompat.getColor(context, R.color.white))
setBackgroundColor(dominantColor)
}
}
}
}
| 0
|
Kotlin
|
0
| 2
|
621ccafc680604560d9023469ed17f5762608ea0
| 809
|
RecycleViewExample
|
Apache License 2.0
|
wear/src/main/java/audio/omgsoundboard/presentation/ui/main/MainScreen.kt
|
OMGSoundboard
| 72,438,238
| false
|
{"Kotlin": 214441, "HTML": 30981, "Dockerfile": 709}
|
package audio.omgsoundboard.presentation.ui.main
import android.widget.Toast
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.wear.compose.foundation.lazy.ScalingLazyColumn
import androidx.wear.compose.foundation.lazy.items
import androidx.wear.compose.foundation.lazy.rememberScalingLazyListState
import androidx.wear.compose.material.Text
import audio.omgsoundboard.core.R
import audio.omgsoundboard.core.utils.Constants
import audio.omgsoundboard.presentation.composables.Chip
import audio.omgsoundboard.presentation.navigation.DrawerParams
import audio.omgsoundboard.presentation.navigation.Screens
@Composable
fun MainScreen(
onNavigate: (route: String) -> Unit,
viewModel: MainScreenViewModel = hiltViewModel(),
) {
val context = LocalContext.current
val state = viewModel.uiState
val scalingLazyListState = rememberScalingLazyListState()
ScalingLazyColumn(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.Top,
state = scalingLazyListState
) {
item {
Text(text = stringResource(id = R.string.categories_header))
}
items(state.categories) {
Chip(title = it.name) {
onNavigate(Screens.SoundsScreen.route + "/${it.id}")
}
}
item {
Chip(title = stringResource(R.string.favorites_title)) {
onNavigate(Screens.FavoritesScreen.route)
}
}
item {
Text(text = stringResource(id = R.string.options_header))
}
items(DrawerParams.drawerOptions) {
Chip(icon = it.drawableId, title = stringResource(it.title)) {
when (it.action) {
Constants.OPTIONS_ABOUT -> {
onNavigate(Screens.AboutScreen.route)
}
Constants.OPTIONS_SYNC -> {
viewModel.sync()
Toast.makeText(
context,
context.resources.getString(R.string.data_synced_confirm),
Toast.LENGTH_SHORT
).show()
}
}
}
}
}
}
| 3
|
Kotlin
|
4
| 21
|
0faef380ed935dcbe5e7fb87f5a3f601388f51d8
| 2,548
|
android-app
|
Apache License 2.0
|
app/src/main/java/my/nanihadesuka/lazycolumnscrollbar/MainActivity.kt
|
nanihadesuka
| 400,096,135
| false
|
{"Kotlin": 101407}
|
package my.nanihadesuka.lazycolumnscrollbar
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.rememberLazyGridState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import my.nanihadesuka.compose.ColumnScrollbar
import my.nanihadesuka.compose.LazyColumnScrollbar
import my.nanihadesuka.compose.LazyGridVerticalScrollbar
import my.nanihadesuka.compose.ScrollbarSelectionMode
import my.nanihadesuka.lazycolumnscrollbar.ui.theme.LazyColumnScrollbarTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent { MainView() }
}
}
@Preview(showBackground = true)
@Composable
fun MainView() {
LazyColumnScrollbarTheme {
Surface(color = MaterialTheme.colors.background) {
// LazyColumnView()
// ColumnView()
lazyGridView()
}
}
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun LazyColumnView() {
val listData = (0..1000).toList()
val listState = rememberLazyListState()
Box(
modifier = Modifier
.padding(16.dp)
.border(width = 1.dp, MaterialTheme.colors.primary)
.padding(1.dp)
) {
LazyColumnScrollbar(
listState,
selectionMode = ScrollbarSelectionMode.Thumb,
alwaysShowScrollBar = true,
indicatorContent = { index, isThumbSelected ->
Surface {
Text(
text = "i: $index",
Modifier
.clip(
RoundedCornerShape(
topStart = 20.dp,
bottomStart = 20.dp,
bottomEnd = 16.dp
)
)
.background(Color.Green)
.padding(8.dp)
.clip(CircleShape)
.background(if (isThumbSelected) MaterialTheme.colors.surface else MaterialTheme.colors.background)
.padding(12.dp)
)
}
}
) {
LazyColumn(
state = listState,
reverseLayout = false
) {
(0..3).forEach { number ->
stickyHeader {
Surface {
Text(
text = "HEADER $number",
modifier = Modifier
.fillMaxWidth()
.padding(8.dp),
textAlign = TextAlign.Center,
)
}
}
}
items(listData) {
Text(
text = "Item $it",
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
)
}
}
}
}
}
@Composable
fun lazyGridView(){
val photos by rememberSaveable {
mutableStateOf(List(100) { it })
}
val lazyGridState = rememberLazyGridState()
Box(
modifier = Modifier
.padding(16.dp)
.border(width = 1.dp, MaterialTheme.colors.primary)
.padding(1.dp)
){
LazyGridVerticalScrollbar(
state = lazyGridState,
selectionMode = ScrollbarSelectionMode.Thumb,
alwaysShowScrollBar = true,
indicatorContent = { index, isThumbSelected ->
Surface {
Text(
text = "i: $index",
modifier = Modifier
.clip(
RoundedCornerShape(
topStart = 20.dp,
bottomStart = 20.dp,
bottomEnd = 16.dp
)
)
.background(Color.Green)
.padding(8.dp)
.clip(CircleShape)
.background(if (isThumbSelected) Color.Blue else Color.Yellow)
.padding(12.dp),
color = Color.Red
)
}
}
){
LazyVerticalGrid(
state = lazyGridState,
columns = GridCells.Adaptive(minSize = 128.dp),
verticalArrangement = Arrangement.spacedBy(3.dp),
horizontalArrangement = Arrangement.spacedBy(3.dp),
) {
items(photos.size, key = { it }) {
Surface(
elevation = 3.dp,
modifier = Modifier.aspectRatio(1f),
color = Color.Yellow
) {
Text(
text = "Item $it",
modifier = Modifier
.padding(24.dp),
color = Color.Black
)
}
}
}
}
}
}
@Composable
fun ColumnView() {
val listData = (0..100).toList()
val listState = rememberScrollState()
val indicatorContent = @Composable { normalizedOffset: Float, isThumbSelected: Boolean ->
Surface {
Text(
text = "i: ${"%.2f".format(normalizedOffset)}",
Modifier
.clip(
RoundedCornerShape(
topStart = 20.dp,
bottomStart = 20.dp,
bottomEnd = 16.dp
)
)
.background(Color.Green)
.padding(8.dp)
.clip(CircleShape)
.background(if (isThumbSelected) MaterialTheme.colors.surface else MaterialTheme.colors.background)
.padding(12.dp)
)
}
}
Box(
modifier = Modifier
.padding(16.dp)
.border(width = 1.dp, MaterialTheme.colors.primary)
.padding(1.dp)
) {
ColumnScrollbar(
state = listState,
indicatorContent = indicatorContent,
selectionMode = ScrollbarSelectionMode.Disabled,
alwaysShowScrollBar = true,
) {
Column(
modifier = Modifier.verticalScroll(listState)
) {
for (it in listData) {
Text(
text = "Item $it",
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
)
}
}
}
}
}
| 4
|
Kotlin
|
12
| 97
|
98962054315d25bd4df9a877ce15ef3154eff0c2
| 8,752
|
LazyColumnScrollbar
|
MIT License
|
app/src/main/java/ru/ekbtrees/treemap/ui/TreeTapListener.kt
|
dienyaaa
| 355,126,052
| true
|
{"Kotlin": 8056}
|
package ru.ekbtrees.treemap.ui
import android.widget.Toast
import com.yandex.mapkit.geometry.Point
import com.yandex.mapkit.map.MapObject
import com.yandex.mapkit.map.MapObjectTapListener
class TreeTapListener : MapObjectTapListener{
override fun onMapObjectTap(p0: MapObject, p1: Point): Boolean {
val data = p0.userData
if (data is TreeData) {
var instance = data.tree
Toast.makeText(data.context, "ID дерева:${instance.id} | ${instance.latitude} ${instance.longitude} \n" +
"Диаметр кроны: ${instance.diameterOfCrown} Вид: ${instance.type}", Toast.LENGTH_SHORT).show()
return true
}
return false
}
}
| 0
|
Kotlin
|
0
| 0
|
c6097eea7daf2e51906453c39fdca25029c98b97
| 701
|
ekbtrees-android
|
MIT License
|
app/src/main/java/com/hci/tom/android/network/SendExerciseDataWorker.kt
|
TOM-Platform
| 837,201,728
| false
|
{"Kotlin": 154904}
|
package com.hci.tom.android.network
import ExerciseWearOsDataOuterClass
import android.content.Context
import android.util.Log
import androidx.work.Worker
import androidx.work.WorkerParameters
import com.google.protobuf.ByteString
import com.google.protobuf.MessageLite
import com.hci.tom.android.db.ExerciseData
import com.hci.tom.android.db.ExerciseDataDatabase
import com.hci.tom.android.network.Credentials.SERVER_URL
import com.hci.tom.android.proto.DataTypes
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.WebSocket
class SendExerciseDataWorker(
context: Context, params: WorkerParameters
) : Worker(context, params), ReconnectableWorker {
private val client = OkHttpClient()
private val request = Request.Builder()
.url(SERVER_URL)
.addHeader("websocket_client_type", "wearOS")
.build()
private val webSocketListener = TOMWebSocketListener(this)
private lateinit var webSocket: WebSocket
// the time interval between each update to the server
private val updateInterval = 2000L
private val exerciseDataDao =
ExerciseDataDatabase.getInstance(applicationContext).exerciseDataDao()
private var exerciseEnded = false
private var retryCount = 0
private val maxRetries = 10
// to track if waypoints have been sent to server before
private var sentWaypoints = false
private var newestDestLat: Double? = null
private var newestDestLng: Double? = null
override fun doWork(): Result = runBlocking {
try {
// attempt to get websocket
webSocket = client.newWebSocket(request, webSocketListener)
// only send data to server when exercise is not stopped
while (!isStopped) {
// check if websocket is open
if (webSocketListener.isConnected) {
// reset retry count if previously failed to connect to server
retryCount = 0
// to set a fixed time interval between each update to the server
delay(updateInterval)
// get the most recent exercise data based on the latest start time of the exercise
val latestExerciseData = exerciseDataDao.getLatestExerciseData()
sendExerciseData(latestExerciseData)
val currLat = latestExerciseData?.currLat
val currLng = latestExerciseData?.currLng
val destLat = latestExerciseData?.destLat
val destLng = latestExerciseData?.destLng
if (currLat != null && currLng != null) {
// if destination changes or waypoints have not been sent to server before
if (newestDestLat != destLat || newestDestLng != destLng || !sentWaypoints) {
newestDestLat = destLat
newestDestLng = destLng
sendWaypointsData(currLat, currLng, destLat, destLng)
}
}
}
}
Result.success()
} catch (e: Exception) {
Result.failure()
}
}
override fun attemptReconnect() {
// this is to prevent a previous exercise from attempting to reconnect to the server
// in the case where it was stopped by the user while failing to achieve a connection
if (exerciseEnded) {
Log.d(
"SendExerciseDataWorker",
"Previous exercise had ended. Stop reconnecting to server."
)
return
}
retryCount++
// try reconnecting to server if max retries is not reached
if (retryCount <= maxRetries) {
Log.d("SendExerciseDataWorker", "Failed to connect to server. Retrying in 10s...")
webSocket = client.newWebSocket(request, webSocketListener)
} else {
Log.d(
"SendExerciseDataWorker",
"Failed to connect to server after $maxRetries attempts."
)
}
}
override fun onStopped() {
exerciseEnded = true
webSocket.close(1000, "WorkManager stopped")
super.onStopped()
}
private fun sendExerciseData(latestExerciseData: ExerciseData?) {
val exerciseWearOsDataProto = ExerciseWearOsDataOuterClass.ExerciseWearOsData.newBuilder()
.setCalories(latestExerciseData?.calories ?: 0.0)
.setCurrentStatus(latestExerciseData?.currentStatus ?: "UNKNOWN")
.setDistance(latestExerciseData?.distance ?: 0.0)
.setDuration(latestExerciseData?.duration ?: 0)
.setHeartRate(latestExerciseData?.heartRate ?: 0.0)
.setHeartRateAvg(latestExerciseData?.heartRateAvg ?: 0.0)
.setCurrLat(latestExerciseData?.currLat ?: 0.0)
.setCurrLng(latestExerciseData?.currLng ?: 0.0)
.setBearing(latestExerciseData?.bearing ?: 0)
.setSpeed(latestExerciseData?.speed ?: 0.0)
.setSpeedAvg(latestExerciseData?.speedAvg ?: 0.0)
.setStartTime(latestExerciseData?.startTime ?: 0L)
.setSteps(latestExerciseData?.steps ?: 0)
.setUpdateTime(latestExerciseData?.updateTime ?: 0L)
.build()
val bytes =
wrapMessageWithMetadata(DataTypes.EXERCISE_WEAR_OS_DATA, exerciseWearOsDataProto)
webSocketListener.sendBytes(webSocket, bytes)
// Log the current time when the data is sent
val currentTimeMillis = System.currentTimeMillis()
Log.d("SendExerciseDataWorker", "Sent exercise data to server. $currentTimeMillis")
}
private fun sendWaypointsData(
currLat: Double,
currLng: Double,
destLat: Double?,
destLng: Double?
) {
val waypointsListDataProto = WaypointsListDataOuterClass.WaypointsListData.newBuilder()
.addWaypointsList(
WaypointData.Waypoint.newBuilder()
.setLat(currLat)
.setLng(currLng)
.build()
)
if (destLat != null && destLng != null) {
waypointsListDataProto.addWaypointsList(
WaypointData.Waypoint.newBuilder()
.setLat(destLat)
.setLng(destLng)
.build()
)
}
val bytes = wrapMessageWithMetadata(DataTypes.WAYPOINTS_LIST_DATA, waypointsListDataProto.build())
webSocketListener.sendBytes(webSocket, bytes)
sentWaypoints = true
Log.d("SendExerciseDataWorker", "Sent waypoints list data to server.")
}
private fun wrapMessageWithMetadata(messageType: Int, message: MessageLite): ByteArray {
val wrapperBuilder = SocketDataOuterClass.SocketData.newBuilder()
.setDataType(messageType)
.setData(ByteString.copyFrom(message.toByteArray()))
val wrapper = wrapperBuilder.build()
return wrapper.toByteArray()
}
}
| 0
|
Kotlin
|
0
| 1
|
baa0ffa4d3fb4e16490f2860f54b18247dbc5a8c
| 7,154
|
TOM-Client-WearOS
|
MIT License
|
responses/src/commonMain/kotlin/ru/krindra/vkkt/responses/messages/MessagesMarkAsImportantDeprecatedResponse.kt
|
krindra
| 780,080,411
| false
|
{"Kotlin": 1336107}
|
package ru.krindra.vkkt.responses.messages
import ru.krindra.vkkt.objects.messages.*
typealias MessagesMarkAsImportantDeprecatedResponse = List<Int>
| 0
|
Kotlin
|
0
| 1
|
58407ea02fc9d971f86702f3b822b33df65dd3be
| 151
|
VKKT
|
MIT License
|
gara-photo-app-server/src/main/kotlin/org/contourgara/garaphotospringboot/infrastructure/PhotoRepositoryImpl.kt
|
contour-gara
| 783,416,988
| false
|
{"Kotlin": 67535, "Dockerfile": 808, "Shell": 611}
|
package org.contourgara.garaphotospringboot.infrastructure
import org.contourgara.garaphotospringboot.domain.Media
import org.contourgara.garaphotospringboot.domain.infrastructure.PhotoRepository
import org.springframework.core.io.support.PathMatchingResourcePatternResolver
import org.springframework.stereotype.Component
@Component
class PhotoRepositoryImpl: PhotoRepository {
override fun findForYesterday(sourcePath: String): Media {
return Media(PathMatchingResourcePatternResolver().getResources("${sourcePath}/*").map { it.file }.toList())
}
}
| 0
|
Kotlin
|
0
| 1
|
6f43844b0d3cbc1d0d52920dfc37fb6445db7d99
| 561
|
gara-photo-spring-boot
|
Creative Commons Zero v1.0 Universal
|
spring-web/src/main/kotlin/us/venky/library/springweb/services/MemberService.kt
|
ramana-git
| 580,225,190
| false
| null |
package us.venky.library.springweb.services
import org.springframework.stereotype.Service
import us.venky.library.springweb.entities.Member
import us.venky.library.springweb.repository.MemberRepository
import java.util.*
@Service
class MemberService(private val repo: MemberRepository) {
fun get(): List<Member> {
return repo.findAll()
}
fun get(lastName:String): List<Member> {
return repo.findByLastName(lastName)
}
fun get(id: UUID): Member? {
return repo.findById(id).orElse(null)
}
fun create(member: Member): Member {
member.id=null
return repo.save(member)
}
fun update(id: UUID, member: Member): Member?{
val mem=get(id)
mem?.let {member.id=id;return repo.save(member)}
return null;
}
fun update(id: UUID, joinDate: Date): Member?{
val member=get(id)
member?.let {member.joinDate=joinDate;return repo.save(member)}
return null;
}
fun update(id: UUID, verified: Boolean): Member?{
val member=get(id)
member?.let {member.verified=verified;return repo.save(member)}
return null;
}
fun delete(id:UUID): Member? {
val member=get(id)
member?.let { repo.deleteById(id) }
return member
}
}
| 0
|
Kotlin
|
0
| 0
|
782005f51cf583445281ea20e37160951d52843b
| 1,291
|
library
|
MIT License
|
app/src/main/java/com/wzz/firstlinecode/chapter09/kotlin/infix.kt
|
weigg520
| 489,902,751
| false
| null |
package com.wzz.firstlinecode.chapter09.kotlin
import androidx.core.content.contentValuesOf
/**
* @ClassName infix
* @Description TODO
* @Author Lenovo
* @Date 2022/7/4 14:58
* @Version 1.0
*/
infix fun String.beginsWith(prefix : String) = startsWith(prefix)
infix fun <T> Collection<T>.has(element:T) = contains(element)
infix fun<A,B> A.with(that : B):Pair<A,B> = Pair(this,that)
fun main() {
val startW = "Hello world" beginsWith "hello"
val cts = listOf("苹果","香蕉","梨子") has "香蕉"
val mapOf = mapOf("小明" with "帅哥" , "阿魏" with "尚可")
}
| 0
|
Kotlin
|
0
| 0
|
7a10fe1d876f8a7f7ec55ad414c1823e24400b2b
| 556
|
FirsLineCode
|
Apache License 2.0
|
tl/src/main/kotlin/com/github/badoualy/telegram/tl/api/updates/TLAbsChannelDifference.kt
|
Miha-x64
| 436,587,061
| true
|
{"Kotlin": 3919807, "Java": 75352}
|
package com.github.badoualy.telegram.tl.api.updates
import com.github.badoualy.telegram.tl.core.TLObject
/**
* Abstraction level for the following constructors:
* * [updates.channelDifference#2064674e][TLChannelDifference]
* * [updates.channelDifferenceEmpty#3e11affb][TLChannelDifferenceEmpty]
* * [updates.channelDifferenceTooLong#a4bcc6fe][TLChannelDifferenceTooLong]
*
* @author <NAME> <EMAIL>
* @see <a href="http://github.com/badoualy/kotlogram">http://github.com/badoualy/kotlogram</a>
*/
abstract class TLAbsChannelDifference : TLObject() {
abstract var _final: Boolean
abstract var timeout: Int?
}
| 1
|
Kotlin
|
2
| 3
|
1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b
| 626
|
kotlogram-resurrected
|
MIT License
|
app/src/main/java/io/cricket/app/data/database/database_tables/Tables.kt
|
amirishaque
| 375,128,729
| false
| null |
package io.cricket.app.data.database.database_tables
import android.os.Parcelable
import androidx.room.Entity
import androidx.room.PrimaryKey
import io.cricket.app.data.database.*
import io.cricket.app.utils.Constants.CAN_UNDO_STATUS
import io.cricket.app.utils.Constants.NOT_OUT
import kotlinx.android.parcel.Parcelize
class Tables {
@Parcelize
@Entity(tableName = PLAYERS)
data class Players(
@PrimaryKey
val playerID: Int,
val name: String,
val uniqueId: String,
val playerAs: Int,
val playerFor: String?
) : Parcelable
@Parcelize
@Entity(tableName = MATCH_INNINGS)
data class MatchInnings(
@PrimaryKey(autoGenerate = true)
var inningId: Long? = 0,
var matchId: Long = 0,
var inningNumber: Int? = 1, /// 1 or 2
var matchType: String, /// bowling or batting
var targetScore: Int? = 0, /// target will be inserted in case of inning number is 2
var inningStatus: Int? = 0 /// 0 inning in progress 1 inning completed
) : Parcelable
@Parcelize
@Entity(tableName = MATCHES)
data class Matches(
@PrimaryKey(autoGenerate = true)
var matchId: Long? = 0,
var teamId: Int? = 0,
var tournamentName: String?,
var opponentTeamName: String?,
var opponentTeamPhoneNumber: String?,
var groundName: String?,
var matchOvers: Int?,
var currentOver: Int? = 0,
var currentOverId: Long? = 0,
var currentOverBalls: Int? = 0,
var matchScores: Int? = 0,
var matchExtraScores: Int? = 0,
var currentRunRate: Double? = 0.0,
var matchStatus: Int? = 0, /// 0 match in progress 1 match completed,2 no players selected
var resultStatus: Int? = 1, /// 1 pending 2 won 3 lose
var matchUploadStatus: Int? = 0
) : Parcelable
@Parcelize
@Entity(tableName = BATTING_STATS)
data class BattingStats(
@PrimaryKey(autoGenerate = true)
var statId: Long? = 0,
var playerID: Int?,
var playerName: String? = "",
var scores: Int? = 0,
var balls: Int? = 0,
var fourCounts: Int? = 0,
var sixCounts: Int? = 0,
var outStatus: String = NOT_OUT, /// NOT OUT RUN OUT,CATCH OUT,BOWLED,STUMP OUT,HEAD WICKET
var inningId: Long? = 0,
var onStrike: Int? = 0
) : Parcelable
@Parcelize
@Entity(tableName = BOWLING_STATS)
data class BowlingStats(
@PrimaryKey(autoGenerate = true)
var statId: Long? = 0,
var playerID: Long? = 0,
var inningId: Long? = 0,
var playerName: String? = "",
var overBalls: Int? = 0,
var scores: Int? = 0,
var wicketsCount: Int? = 0,
var onStrike: Int? = 1,
var economy: Double? = 0.0
) : Parcelable
@Parcelize
@Entity(tableName = MATCH_OVERS)
data class MatchOvers(
@PrimaryKey(autoGenerate = true)
var overId: Long = 0,
var inningId: Long?,
var currentOverBalls: Int? = 0,
var playerId: Long? = 0, /// ref from Players table
var playerName: String? = "", /// ref from Players table
var thisOver: String? = "" /// 0,1,2,3,4,5,6,W,NB,WD,B,LB,RUN OUT,CATCH OUT,BOWLED,STUMP OUT,HEAD WICKET,LBW
) : Parcelable
@Parcelize
@Entity(tableName = MATCH_SCORES)
data class ScoreBoard(
@PrimaryKey
var ballId: Long = 0,
var overId: Long? = 0,
var ballScore: Int?,
var isLegalDelivery: Int?, ///0 or 1
var ballResultName: String?
) : Parcelable
@Parcelize
@Entity(tableName = UNDO_LOGS)
data class UndoLogs(
@PrimaryKey
var logId: Long = 0,
var transactionId: Long? = 0,
var matchId: Long? = 0,
var inningId: Long?,
var data: String?,
var status: Int? = CAN_UNDO_STATUS, /// 1 can undo 2 unable to undo
var transactionType: Int? = 1, /// 1 update 2 insert 3 delete
var tableName: String = "",
var recordID: Long = 0
) : Parcelable
}
| 0
|
Kotlin
|
0
| 0
|
42808ddd775b5ac6f7bff0d8cf518091588df844
| 4,120
|
Cricklub_livecode
|
MIT License
|
app/src/main/java/net/rolodophone/covidsim/Player.kt
|
Rolodophone
| 260,254,346
| false
| null |
package net.rolodophone.covidsim
import android.graphics.Bitmap
import android.graphics.RectF
import android.os.SystemClock
import net.rolodophone.core.*
import kotlin.math.abs
import kotlin.math.atan
import kotlin.math.pow
import kotlin.math.sqrt
class Player(override val window: GameWindow) : Object {
override val dim: RectF
init {
val w = w(10)
val h = w * (30f/32f)
val left = window.tiles.getPosAtTile(78f, 110f).x
val top = window.tiles.getPosAtTile(78f, 110f).y
dim = RectF(left, top, left + w, top + h)
}
val allImgs = listOf(
window.ctx.bitmaps.load(R.drawable.player0),
window.ctx.bitmaps.load(R.drawable.player1),
window.ctx.bitmaps.load(R.drawable.player2),
window.ctx.bitmaps.load(R.drawable.player3),
window.ctx.bitmaps.load(R.drawable.player4),
window.ctx.bitmaps.load(R.drawable.player5)
)
var currentImgs = listOf<Bitmap>()
var imgNum = 0
var timeImgLastChanged = SystemClock.elapsedRealtime()
private val walkWood = window.soundPool.load(window.ctx, R.raw.walk_wood , 1)
private val walkTiles = window.soundPool.load(window.ctx, R.raw.walk_tiles , 1)
private val walkPavement = window.soundPool.load(window.ctx, R.raw.walk_pavement , 1)
private val walkGrass = window.soundPool.load(window.ctx, R.raw.walk_grass , 1)
private val openDoor = window.soundPool.load(window.ctx, R.raw.open_door , 1)
private val closeDoor = window.soundPool.load(window.ctx, R.raw.close_door , 1)
private val openFrontDoor = window.soundPool.load(window.ctx, R.raw.open_front_door , 1)
private val closeFrontDoor = window.soundPool.load(window.ctx, R.raw.close_front_door, 1)
private val openShopDoor = window.soundPool.load(window.ctx, R.raw.open_shop_door , 1)
private val closeShopDoor = window.soundPool.load(window.ctx, R.raw.close_shop_door , 1)
private val openGate = window.soundPool.load(window.ctx, R.raw.open_gate , 1)
private val closeGate = window.soundPool.load(window.ctx, R.raw.close_gate , 1)
var currentSound = 0
var currentTileSound = walkWood
var moving = false
var rotation = 0f
var holdingDoor = false
var currentDoorSound = 0
private val warningDistance = 5 * window.tiles.tileWidth
private val deathDistance = 2 * window.tiles.tileWidth
override fun update() {
//change sprite list based on speed
currentImgs = when {
//running
window.joystick.speed() > window.joystick.dim.width() * (3/4f) -> allImgs
//walking
window.joystick.speed() > 0f -> listOf(allImgs[0], allImgs[1], allImgs[3], allImgs[4])
//stationary
else -> listOf(allImgs[0], allImgs[3])
}
//animate
val currentTime = SystemClock.elapsedRealtime()
if (currentTime - timeImgLastChanged > 200) {
imgNum += 1
timeImgLastChanged = currentTime
}
//ensure imgNum is within the currentImgs length
imgNum %= currentImgs.size
//--move--
var xOffset = window.joystick.velocityX() / fps
if (window.tiles.getTileAt(dim.centerX() + xOffset, dim.centerY()) !in window.tiles.walkableTiles) xOffset = 0f
var yOffset = window.joystick.velocityY() / fps
if (window.tiles.getTileAt(dim.centerX(), dim.centerY() + yOffset) !in window.tiles.walkableTiles) yOffset = 0f
if (window.joystick.velocityX() != 0f || window.joystick.velocityY() != 0f) {
if (moving) {
val newCurrentTileSound = when (window.tiles.getTileAt(dim.centerX(), dim.centerY())) {
in window.tiles.woodTiles -> walkWood
in window.tiles.grassTiles -> walkGrass
in window.tiles.pavementTiles -> walkPavement
in window.tiles.tileTiles -> walkTiles
else -> currentTileSound
}
if (newCurrentTileSound != currentTileSound) {
window.soundPool.pause(currentSound)
currentSound = window.soundPool.play(newCurrentTileSound, 1f, 1f, 1, -1, 1f)
currentTileSound = newCurrentTileSound
}
}
else {
if (currentSound == 0) { //not initialised yet
currentSound = window.soundPool.play(walkWood, 1f, 1f, 1, -1, 1f)
}
else { //resume same walking sound
window.soundPool.resume(currentSound)
moving = true
}
}
}
else { //stop walking sound
if (moving) {
window.soundPool.pause(currentSound)
moving = false
}
}
val newCenterX = dim.centerX() + xOffset
val newCenterY = dim.centerY() + yOffset
//close doors
if (holdingDoor && window.tiles.getTileAt(newCenterX, newCenterY) !in window.tiles.doorMap.values) {
if (window.tiles.tryCloseDoor(dim.centerX(), dim.centerY())) {
window.soundPool.stop(currentDoorSound)
window.soundPool.play(
when (window.tiles.getTileAt(dim.centerX(), dim.centerY())) {
in window.tiles.closeDoorTiles -> closeDoor
in window.tiles.closeFrontDoorTiles -> closeFrontDoor
in window.tiles.closeShopDoorTiles -> closeShopDoor
in window.tiles.closeGateTiles -> closeGate
else -> throw IllegalStateException("Can't close tile ID ${window.tiles.getTileAt(newCenterX, newCenterY)} like a door")
},
1f, 1f, 1, 0, 1f
)
holdingDoor = false
}
}
//open doors
if (window.tiles.tryOpenDoor(newCenterX, newCenterY)) {
currentDoorSound = window.soundPool.play(
when (window.tiles.getTileAt(newCenterX, newCenterY)) {
in window.tiles.openDoorTiles -> openDoor
in window.tiles.openFrontDoorTiles -> openFrontDoor
in window.tiles.openShopDoorTiles -> openShopDoor
in window.tiles.openGateTiles -> openGate
else -> throw IllegalStateException("Can't open tile ID ${window.tiles.getTileAt(newCenterX, newCenterY)} like a door")
},
1f, 1f, 1, 0, 1f
)
holdingDoor = true
}
dim.offset(xOffset, yOffset)
//rotate based on movement
if (window.joystick.velocityX() != 0f) rotation = (atan(window.joystick.velocityY() / window.joystick.velocityX()).toDouble().toDegrees() + 90) % 180
// I add 90 degrees because it seems to need it. Something with how atan works I guess
if (window.joystick.velocityX() < 0f) rotation += 180 // because atan only returns 0-180
//check if player is within a set distance of any player and if so how far
var minDistSq = Float.POSITIVE_INFINITY
for (person in window.people.people) {
//quick square check to see if it's worth a precise check
if ((abs(person.dim.left - this.dim.right) < warningDistance || abs(this.dim.left - person.dim.right) < warningDistance) &&
(abs(person.dim.top - this.dim.bottom) < warningDistance || abs(this.dim.top - person.dim.bottom) < warningDistance)) {
val newMinDistSq = abs((this.dim.centerX() - person.dim.centerX()).pow(2) + (this.dim.centerY() - person.dim.centerY()).pow(2)) // distance^2
if (newMinDistSq < minDistSq) minDistSq = newMinDistSq
}
}
val minDist = sqrt(minDistSq)
when {
minDist > warningDistance -> window.deathWarning.opacity = 0 // not in danger
minDist <= deathDistance -> die() // dead
else -> window.deathWarning.opacity = (((warningDistance - deathDistance) - (minDist - deathDistance)) / (warningDistance - deathDistance) * 255).toInt() // in danger but not dead
}
//check if player has reached toilet paper
if (sqrt((this.dim.centerX() - window.arrow.target.x).pow(2) + (this.dim.centerY() - window.arrow.target.y).pow(2)) < window.tiles.tileWidth) victory()
}
override fun draw() {
super.draw()
canvas.save()
canvas.rotate(rotation, dim.centerX(), dim.centerY())
canvas.drawBitmap(currentImgs[imgNum], null, dim, bitmapPaint)
canvas.restore()
}
private fun die() {
window.dead = true
window.soundPool.release()
}
private fun victory() {
window.victorious = true
window.soundPool.release()
}
}
| 0
|
Kotlin
|
0
| 0
|
1b280f30369f2c09fcaabae564a4ed7919bdceba
| 9,024
|
bog-roll-run
|
Creative Commons Attribution 4.0 International
|
app/src/main/java/net/rolodophone/covidsim/Player.kt
|
Rolodophone
| 260,254,346
| false
| null |
package net.rolodophone.covidsim
import android.graphics.Bitmap
import android.graphics.RectF
import android.os.SystemClock
import net.rolodophone.core.*
import kotlin.math.abs
import kotlin.math.atan
import kotlin.math.pow
import kotlin.math.sqrt
class Player(override val window: GameWindow) : Object {
override val dim: RectF
init {
val w = w(10)
val h = w * (30f/32f)
val left = window.tiles.getPosAtTile(78f, 110f).x
val top = window.tiles.getPosAtTile(78f, 110f).y
dim = RectF(left, top, left + w, top + h)
}
val allImgs = listOf(
window.ctx.bitmaps.load(R.drawable.player0),
window.ctx.bitmaps.load(R.drawable.player1),
window.ctx.bitmaps.load(R.drawable.player2),
window.ctx.bitmaps.load(R.drawable.player3),
window.ctx.bitmaps.load(R.drawable.player4),
window.ctx.bitmaps.load(R.drawable.player5)
)
var currentImgs = listOf<Bitmap>()
var imgNum = 0
var timeImgLastChanged = SystemClock.elapsedRealtime()
private val walkWood = window.soundPool.load(window.ctx, R.raw.walk_wood , 1)
private val walkTiles = window.soundPool.load(window.ctx, R.raw.walk_tiles , 1)
private val walkPavement = window.soundPool.load(window.ctx, R.raw.walk_pavement , 1)
private val walkGrass = window.soundPool.load(window.ctx, R.raw.walk_grass , 1)
private val openDoor = window.soundPool.load(window.ctx, R.raw.open_door , 1)
private val closeDoor = window.soundPool.load(window.ctx, R.raw.close_door , 1)
private val openFrontDoor = window.soundPool.load(window.ctx, R.raw.open_front_door , 1)
private val closeFrontDoor = window.soundPool.load(window.ctx, R.raw.close_front_door, 1)
private val openShopDoor = window.soundPool.load(window.ctx, R.raw.open_shop_door , 1)
private val closeShopDoor = window.soundPool.load(window.ctx, R.raw.close_shop_door , 1)
private val openGate = window.soundPool.load(window.ctx, R.raw.open_gate , 1)
private val closeGate = window.soundPool.load(window.ctx, R.raw.close_gate , 1)
var currentSound = 0
var currentTileSound = walkWood
var moving = false
var rotation = 0f
var holdingDoor = false
var currentDoorSound = 0
private val warningDistance = 5 * window.tiles.tileWidth
private val deathDistance = 2 * window.tiles.tileWidth
override fun update() {
//change sprite list based on speed
currentImgs = when {
//running
window.joystick.speed() > window.joystick.dim.width() * (3/4f) -> allImgs
//walking
window.joystick.speed() > 0f -> listOf(allImgs[0], allImgs[1], allImgs[3], allImgs[4])
//stationary
else -> listOf(allImgs[0], allImgs[3])
}
//animate
val currentTime = SystemClock.elapsedRealtime()
if (currentTime - timeImgLastChanged > 200) {
imgNum += 1
timeImgLastChanged = currentTime
}
//ensure imgNum is within the currentImgs length
imgNum %= currentImgs.size
//--move--
var xOffset = window.joystick.velocityX() / fps
if (window.tiles.getTileAt(dim.centerX() + xOffset, dim.centerY()) !in window.tiles.walkableTiles) xOffset = 0f
var yOffset = window.joystick.velocityY() / fps
if (window.tiles.getTileAt(dim.centerX(), dim.centerY() + yOffset) !in window.tiles.walkableTiles) yOffset = 0f
if (window.joystick.velocityX() != 0f || window.joystick.velocityY() != 0f) {
if (moving) {
val newCurrentTileSound = when (window.tiles.getTileAt(dim.centerX(), dim.centerY())) {
in window.tiles.woodTiles -> walkWood
in window.tiles.grassTiles -> walkGrass
in window.tiles.pavementTiles -> walkPavement
in window.tiles.tileTiles -> walkTiles
else -> currentTileSound
}
if (newCurrentTileSound != currentTileSound) {
window.soundPool.pause(currentSound)
currentSound = window.soundPool.play(newCurrentTileSound, 1f, 1f, 1, -1, 1f)
currentTileSound = newCurrentTileSound
}
}
else {
if (currentSound == 0) { //not initialised yet
currentSound = window.soundPool.play(walkWood, 1f, 1f, 1, -1, 1f)
}
else { //resume same walking sound
window.soundPool.resume(currentSound)
moving = true
}
}
}
else { //stop walking sound
if (moving) {
window.soundPool.pause(currentSound)
moving = false
}
}
val newCenterX = dim.centerX() + xOffset
val newCenterY = dim.centerY() + yOffset
//close doors
if (holdingDoor && window.tiles.getTileAt(newCenterX, newCenterY) !in window.tiles.doorMap.values) {
if (window.tiles.tryCloseDoor(dim.centerX(), dim.centerY())) {
window.soundPool.stop(currentDoorSound)
window.soundPool.play(
when (window.tiles.getTileAt(dim.centerX(), dim.centerY())) {
in window.tiles.closeDoorTiles -> closeDoor
in window.tiles.closeFrontDoorTiles -> closeFrontDoor
in window.tiles.closeShopDoorTiles -> closeShopDoor
in window.tiles.closeGateTiles -> closeGate
else -> throw IllegalStateException("Can't close tile ID ${window.tiles.getTileAt(newCenterX, newCenterY)} like a door")
},
1f, 1f, 1, 0, 1f
)
holdingDoor = false
}
}
//open doors
if (window.tiles.tryOpenDoor(newCenterX, newCenterY)) {
currentDoorSound = window.soundPool.play(
when (window.tiles.getTileAt(newCenterX, newCenterY)) {
in window.tiles.openDoorTiles -> openDoor
in window.tiles.openFrontDoorTiles -> openFrontDoor
in window.tiles.openShopDoorTiles -> openShopDoor
in window.tiles.openGateTiles -> openGate
else -> throw IllegalStateException("Can't open tile ID ${window.tiles.getTileAt(newCenterX, newCenterY)} like a door")
},
1f, 1f, 1, 0, 1f
)
holdingDoor = true
}
dim.offset(xOffset, yOffset)
//rotate based on movement
if (window.joystick.velocityX() != 0f) rotation = (atan(window.joystick.velocityY() / window.joystick.velocityX()).toDouble().toDegrees() + 90) % 180
// I add 90 degrees because it seems to need it. Something with how atan works I guess
if (window.joystick.velocityX() < 0f) rotation += 180 // because atan only returns 0-180
//check if player is within a set distance of any player and if so how far
var minDistSq = Float.POSITIVE_INFINITY
for (person in window.people.people) {
//quick square check to see if it's worth a precise check
if ((abs(person.dim.left - this.dim.right) < warningDistance || abs(this.dim.left - person.dim.right) < warningDistance) &&
(abs(person.dim.top - this.dim.bottom) < warningDistance || abs(this.dim.top - person.dim.bottom) < warningDistance)) {
val newMinDistSq = abs((this.dim.centerX() - person.dim.centerX()).pow(2) + (this.dim.centerY() - person.dim.centerY()).pow(2)) // distance^2
if (newMinDistSq < minDistSq) minDistSq = newMinDistSq
}
}
val minDist = sqrt(minDistSq)
when {
minDist > warningDistance -> window.deathWarning.opacity = 0 // not in danger
minDist <= deathDistance -> die() // dead
else -> window.deathWarning.opacity = (((warningDistance - deathDistance) - (minDist - deathDistance)) / (warningDistance - deathDistance) * 255).toInt() // in danger but not dead
}
//check if player has reached toilet paper
if (sqrt((this.dim.centerX() - window.arrow.target.x).pow(2) + (this.dim.centerY() - window.arrow.target.y).pow(2)) < window.tiles.tileWidth) victory()
}
override fun draw() {
super.draw()
canvas.save()
canvas.rotate(rotation, dim.centerX(), dim.centerY())
canvas.drawBitmap(currentImgs[imgNum], null, dim, bitmapPaint)
canvas.restore()
}
private fun die() {
window.dead = true
window.soundPool.release()
}
private fun victory() {
window.victorious = true
window.soundPool.release()
}
}
| 0
|
Kotlin
|
0
| 0
|
1b280f30369f2c09fcaabae564a4ed7919bdceba
| 9,024
|
bog-roll-run
|
Creative Commons Attribution 4.0 International
|
src/main/kotlin/nl/nielsvanhove/githistoricalstats/measurements/ClocExecutor.kt
|
nielsz
| 390,751,207
| false
| null |
package nl.nielsvanhove.githistoricalstats.measurements
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonObject
import kotlinx.serialization.json.jsonPrimitive
import nl.nielsvanhove.githistoricalstats.core.CommandExecutor
import nl.nielsvanhove.githistoricalstats.measurements.MeasurementConfig.ClocMeasurementConfig
import nl.nielsvanhove.githistoricalstats.project.ProjectConfig
class ClocExecutor(
private val projectConfig: ProjectConfig,
private val commandExecutor: CommandExecutor,
private val measurement: ClocMeasurementConfig
) {
operator fun invoke(): Int {
val fileTypeIncludes = if (measurement.filetypes.isNotEmpty()) {
"--include-ext=" + measurement.filetypes.joinToString(",")
} else {
""
}
val c = "cloc $fileTypeIncludes --json ${measurement.folder}"
val command = listOf("bash", "-c") + listOf(c)
val output = commandExecutor.execute(command).trim()
if (output.isNotEmpty()) {
val x = Json.parseToJsonElement(output) as JsonObject
return (x["SUM"]!! as JsonObject)["code"]!!.jsonPrimitive.content.toInt()
}
return 0
}
}
| 0
|
Kotlin
|
0
| 5
|
bd3254f18bcdcd119a17a197153a1db3a5c7fb6e
| 1,212
|
git-historical-stats
|
MIT License
|
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/filled/CircleNumber3.kt
|
walter-juan
| 868,046,028
| false
|
{"Kotlin": 34345428}
|
package com.woowla.compose.icon.collections.tabler.tabler.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.FilledGroup
public val FilledGroup.CircleNumber3: ImageVector
get() {
if (_circleNumber3 != null) {
return _circleNumber3!!
}
_circleNumber3 = Builder(name = "CircleNumber3", defaultWidth = 24.0.dp, defaultHeight =
24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(12.0f, 2.0f)
curveToRelative(5.523f, 0.0f, 10.0f, 4.477f, 10.0f, 10.0f)
reflectiveCurveToRelative(-4.477f, 10.0f, -10.0f, 10.0f)
reflectiveCurveToRelative(-10.0f, -4.477f, -10.0f, -10.0f)
reflectiveCurveToRelative(4.477f, -10.0f, 10.0f, -10.0f)
close()
moveTo(13.0f, 7.0f)
horizontalLineToRelative(-2.0f)
lineToRelative(-0.15f, 0.005f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, -1.85f, 1.995f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, 1.974f, 0.23f)
lineToRelative(0.02f, -0.113f)
lineToRelative(0.006f, -0.117f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(-2.0f)
lineToRelative(-0.133f, 0.007f)
curveToRelative(-1.111f, 0.12f, -1.154f, 1.73f, -0.128f, 1.965f)
lineToRelative(0.128f, 0.021f)
lineToRelative(0.133f, 0.007f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(-2.0f)
lineToRelative(-0.007f, -0.117f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, -1.993f, 0.117f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 1.85f, 1.995f)
lineToRelative(0.15f, 0.005f)
horizontalLineToRelative(2.0f)
lineToRelative(0.15f, -0.005f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, 1.844f, -1.838f)
lineToRelative(0.006f, -0.157f)
verticalLineToRelative(-2.0f)
lineToRelative(-0.005f, -0.15f)
arcToRelative(1.988f, 1.988f, 0.0f, false, false, -0.17f, -0.667f)
lineToRelative(-0.075f, -0.152f)
lineToRelative(-0.019f, -0.032f)
lineToRelative(0.02f, -0.03f)
arcToRelative(2.01f, 2.01f, 0.0f, false, false, 0.242f, -0.795f)
lineToRelative(0.007f, -0.174f)
verticalLineToRelative(-2.0f)
lineToRelative(-0.005f, -0.15f)
arcToRelative(2.0f, 2.0f, 0.0f, false, false, -1.838f, -1.844f)
lineToRelative(-0.157f, -0.006f)
close()
}
}
.build()
return _circleNumber3!!
}
private var _circleNumber3: ImageVector? = null
| 0
|
Kotlin
|
0
| 3
|
eca6c73337093fbbfbb88546a88d4546482cfffc
| 3,707
|
compose-icon-collections
|
MIT License
|
compiler-ksp/src/main/java/com/bennyhuo/tieguanyin/compiler/ksp/utils/Extensions.kt
|
bennyhuo
| 119,345,142
| false
|
{"Kotlin": 186984, "Java": 138272, "Shell": 724, "PowerShell": 417}
|
package com.bennyhuo.tieguanyin.compiler.ksp.utils
import com.bennyhuo.tieguanyin.annotations.PendingTransition
fun PendingTransition.isDefault(): Boolean {
return enterAnim == PendingTransition.DEFAULT && exitAnim == PendingTransition.DEFAULT
}
| 0
|
Kotlin
|
27
| 183
|
74cfc86f2cdf4bbb5ab6dd82bc3c568d78386d29
| 252
|
TieGuanYin
|
Apache License 2.0
|
utbot-framework/src/main/kotlin/org/utbot/framework/context/custom/RerunningConcreteExecutionContext.kt
|
UnitTestBot
| 480,810,501
| false
|
{"Kotlin": 6538839, "Java": 2209528, "Python": 174619, "Go": 99696, "C#": 80947, "JavaScript": 42483, "Shell": 15961, "HTML": 8704, "Batchfile": 8586, "Dockerfile": 2059}
|
package org.utbot.framework.context.custom
import kotlinx.coroutines.runBlocking
import mu.KotlinLogging
import org.utbot.engine.executeConcretely
import org.utbot.framework.UtSettings
import org.utbot.framework.context.ConcreteExecutionContext
import org.utbot.framework.plugin.api.ExecutableId
import org.utbot.framework.plugin.api.UtExecution
import org.utbot.instrumentation.ConcreteExecutor
import org.utbot.instrumentation.instrumentation.execution.UtConcreteExecutionResult
import org.utbot.instrumentation.instrumentation.execution.UtExecutionInstrumentation
class RerunningConcreteExecutionContext(
private val delegateContext: ConcreteExecutionContext,
private val maxRerunsPerMethod: Int,
private val rerunTimeoutInMillis: Long = 10L * UtSettings.concreteExecutionDefaultTimeoutInInstrumentedProcessMillis,
) : ConcreteExecutionContext by delegateContext {
companion object {
private val logger = KotlinLogging.logger {}
}
override fun transformExecutionsAfterMinimization(
executions: List<UtExecution>,
methodUnderTest: ExecutableId,
rerunExecutor: ConcreteExecutor<UtConcreteExecutionResult, UtExecutionInstrumentation>,
): List<UtExecution> {
@Suppress("NAME_SHADOWING")
val executions = delegateContext.transformExecutionsAfterMinimization(
executions,
methodUnderTest,
rerunExecutor
)
// it's better to rerun executions with non-empty coverage,
// because executions with empty coverage are often duplicated
.sortedBy { it.coverage?.coveredInstructions.isNullOrEmpty() }
return executions
.take(maxRerunsPerMethod)
.map { execution ->
runBlocking {
val result = try {
rerunExecutor.executeConcretely(
methodUnderTest = methodUnderTest,
stateBefore = execution.stateBefore,
instrumentation = emptyList(),
timeoutInMillis = rerunTimeoutInMillis,
isRerun = true,
)
} catch (e: Throwable) {
// we can't update execution result if we don't have a result
logger.warn(e) { "Rerun failed, keeping original result for execution [$execution]" }
return@runBlocking execution
}
execution.copy(
stateBefore = result.stateBefore,
stateAfter = result.stateAfter,
result = result.result,
coverage = result.coverage,
)
}
} + executions.drop(maxRerunsPerMethod)
}
}
| 415
|
Kotlin
|
38
| 131
|
2b37f0736eabf4444a9e86be2a9a424dbc2bb111
| 2,859
|
UTBotJava
|
Apache License 2.0
|
domain/tmdb-shows/src/main/java/io/filmtime/domain/tmdb/shows/impl/GetEpisodesBySeasonUseCaseImpl.kt
|
moallemi
| 633,160,161
| false
|
{"Kotlin": 522936, "Shell": 3102}
|
package io.filmtime.domain.tmdb.shows.impl
import io.filmtime.data.model.EpisodeThumbnail
import io.filmtime.data.model.GeneralError
import io.filmtime.data.model.Result
import io.filmtime.data.tmdb.shows.TmdbShowsRepository
import io.filmtime.domain.tmdb.shows.GetEpisodesBySeasonUseCase
import javax.inject.Inject
internal class GetEpisodesBySeasonUseCaseImpl @Inject constructor(
private val showsRepository: TmdbShowsRepository,
) : GetEpisodesBySeasonUseCase {
override suspend fun invoke(showId: Int, seasonNumber: Int): Result<List<EpisodeThumbnail>, GeneralError> =
showsRepository.episodesBySeason(showId, seasonNumber)
}
| 21
|
Kotlin
|
14
| 87
|
ad3eeed30bed20216a9fa12e34f06e43b70a74cc
| 642
|
Film-Time
|
MIT License
|
src/main/kotlin/eZmaxApi/apis/ObjectEzsigntemplatesignerApi.kt
|
eZmaxinc
| 271,950,932
| false
| null |
/**
*
* Please note:
* This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* Do not edit this file manually.
*
*/
@file:Suppress(
"ArrayInDataClass",
"EnumEntryName",
"RemoveRedundantQualifierName",
"UnusedImport"
)
package eZmaxApi.apis
import java.io.IOException
import okhttp3.OkHttpClient
import okhttp3.HttpUrl
import eZmaxApi.models.CommonMinusResponseMinusError
import eZmaxApi.models.EzsigntemplatesignerMinusCreateObjectMinusV1MinusRequest
import eZmaxApi.models.EzsigntemplatesignerMinusCreateObjectMinusV1MinusResponse
import eZmaxApi.models.EzsigntemplatesignerMinusDeleteObjectMinusV1MinusResponse
import eZmaxApi.models.EzsigntemplatesignerMinusEditObjectMinusV1MinusRequest
import eZmaxApi.models.EzsigntemplatesignerMinusEditObjectMinusV1MinusResponse
import eZmaxApi.models.EzsigntemplatesignerMinusGetObjectMinusV2MinusResponse
import com.squareup.moshi.Json
import eZmaxApi.infrastructure.ApiClient
import eZmaxApi.infrastructure.ApiResponse
import eZmaxApi.infrastructure.ClientException
import eZmaxApi.infrastructure.ClientError
import eZmaxApi.infrastructure.ServerException
import eZmaxApi.infrastructure.ServerError
import eZmaxApi.infrastructure.MultiValueMap
import eZmaxApi.infrastructure.PartConfig
import eZmaxApi.infrastructure.RequestConfig
import eZmaxApi.infrastructure.RequestMethod
import eZmaxApi.infrastructure.ResponseType
import eZmaxApi.infrastructure.Success
import eZmaxApi.infrastructure.toMultiValue
class ObjectEzsigntemplatesignerApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ApiClient.defaultClient) : ApiClient(basePath, client) {
companion object {
@JvmStatic
val defaultBasePath: String by lazy {
System.getProperties().getProperty(ApiClient.baseUrlKey, "https://prod.api.appcluster01.ca-central-1.ezmax.com/rest")
}
}
/**
* Create a new Ezsigntemplatesigner
* The endpoint allows to create one or many elements at once.
* @param ezsigntemplatesignerMinusCreateObjectMinusV1MinusRequest
* @return EzsigntemplatesignerMinusCreateObjectMinusV1MinusResponse
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun ezsigntemplatesignerCreateObjectV1(ezsigntemplatesignerMinusCreateObjectMinusV1MinusRequest: EzsigntemplatesignerMinusCreateObjectMinusV1MinusRequest) : EzsigntemplatesignerMinusCreateObjectMinusV1MinusResponse {
val localVarResponse = ezsigntemplatesignerCreateObjectV1WithHttpInfo(ezsigntemplatesignerMinusCreateObjectMinusV1MinusRequest = ezsigntemplatesignerMinusCreateObjectMinusV1MinusRequest)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as EzsigntemplatesignerMinusCreateObjectMinusV1MinusResponse
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Create a new Ezsigntemplatesigner
* The endpoint allows to create one or many elements at once.
* @param ezsigntemplatesignerMinusCreateObjectMinusV1MinusRequest
* @return ApiResponse<EzsigntemplatesignerMinusCreateObjectMinusV1MinusResponse?>
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class)
fun ezsigntemplatesignerCreateObjectV1WithHttpInfo(ezsigntemplatesignerMinusCreateObjectMinusV1MinusRequest: EzsigntemplatesignerMinusCreateObjectMinusV1MinusRequest) : ApiResponse<EzsigntemplatesignerMinusCreateObjectMinusV1MinusResponse?> {
val localVariableConfig = ezsigntemplatesignerCreateObjectV1RequestConfig(ezsigntemplatesignerMinusCreateObjectMinusV1MinusRequest = ezsigntemplatesignerMinusCreateObjectMinusV1MinusRequest)
return request<EzsigntemplatesignerMinusCreateObjectMinusV1MinusRequest, EzsigntemplatesignerMinusCreateObjectMinusV1MinusResponse>(
localVariableConfig
)
}
/**
* To obtain the request config of the operation ezsigntemplatesignerCreateObjectV1
*
* @param ezsigntemplatesignerMinusCreateObjectMinusV1MinusRequest
* @return RequestConfig
*/
fun ezsigntemplatesignerCreateObjectV1RequestConfig(ezsigntemplatesignerMinusCreateObjectMinusV1MinusRequest: EzsigntemplatesignerMinusCreateObjectMinusV1MinusRequest) : RequestConfig<EzsigntemplatesignerMinusCreateObjectMinusV1MinusRequest> {
val localVariableBody = ezsigntemplatesignerMinusCreateObjectMinusV1MinusRequest
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
localVariableHeaders["Content-Type"] = "application/json"
localVariableHeaders["Accept"] = "application/json"
return RequestConfig(
method = RequestMethod.POST,
path = "/1/object/ezsigntemplatesigner",
query = localVariableQuery,
headers = localVariableHeaders,
requiresAuthentication = true,
body = localVariableBody
)
}
/**
* Delete an existing Ezsigntemplatesigner
*
* @param pkiEzsigntemplatesignerID
* @return EzsigntemplatesignerMinusDeleteObjectMinusV1MinusResponse
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun ezsigntemplatesignerDeleteObjectV1(pkiEzsigntemplatesignerID: kotlin.Int) : EzsigntemplatesignerMinusDeleteObjectMinusV1MinusResponse {
val localVarResponse = ezsigntemplatesignerDeleteObjectV1WithHttpInfo(pkiEzsigntemplatesignerID = pkiEzsigntemplatesignerID)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as EzsigntemplatesignerMinusDeleteObjectMinusV1MinusResponse
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Delete an existing Ezsigntemplatesigner
*
* @param pkiEzsigntemplatesignerID
* @return ApiResponse<EzsigntemplatesignerMinusDeleteObjectMinusV1MinusResponse?>
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class)
fun ezsigntemplatesignerDeleteObjectV1WithHttpInfo(pkiEzsigntemplatesignerID: kotlin.Int) : ApiResponse<EzsigntemplatesignerMinusDeleteObjectMinusV1MinusResponse?> {
val localVariableConfig = ezsigntemplatesignerDeleteObjectV1RequestConfig(pkiEzsigntemplatesignerID = pkiEzsigntemplatesignerID)
return request<Unit, EzsigntemplatesignerMinusDeleteObjectMinusV1MinusResponse>(
localVariableConfig
)
}
/**
* To obtain the request config of the operation ezsigntemplatesignerDeleteObjectV1
*
* @param pkiEzsigntemplatesignerID
* @return RequestConfig
*/
fun ezsigntemplatesignerDeleteObjectV1RequestConfig(pkiEzsigntemplatesignerID: kotlin.Int) : RequestConfig<Unit> {
val localVariableBody = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
localVariableHeaders["Accept"] = "application/json"
return RequestConfig(
method = RequestMethod.DELETE,
path = "/1/object/ezsigntemplatesigner/{pkiEzsigntemplatesignerID}".replace("{"+"pkiEzsigntemplatesignerID"+"}", encodeURIComponent(pkiEzsigntemplatesignerID.toString())),
query = localVariableQuery,
headers = localVariableHeaders,
requiresAuthentication = true,
body = localVariableBody
)
}
/**
* Edit an existing Ezsigntemplatesigner
*
* @param pkiEzsigntemplatesignerID
* @param ezsigntemplatesignerMinusEditObjectMinusV1MinusRequest
* @return EzsigntemplatesignerMinusEditObjectMinusV1MinusResponse
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun ezsigntemplatesignerEditObjectV1(pkiEzsigntemplatesignerID: kotlin.Int, ezsigntemplatesignerMinusEditObjectMinusV1MinusRequest: EzsigntemplatesignerMinusEditObjectMinusV1MinusRequest) : EzsigntemplatesignerMinusEditObjectMinusV1MinusResponse {
val localVarResponse = ezsigntemplatesignerEditObjectV1WithHttpInfo(pkiEzsigntemplatesignerID = pkiEzsigntemplatesignerID, ezsigntemplatesignerMinusEditObjectMinusV1MinusRequest = ezsigntemplatesignerMinusEditObjectMinusV1MinusRequest)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as EzsigntemplatesignerMinusEditObjectMinusV1MinusResponse
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Edit an existing Ezsigntemplatesigner
*
* @param pkiEzsigntemplatesignerID
* @param ezsigntemplatesignerMinusEditObjectMinusV1MinusRequest
* @return ApiResponse<EzsigntemplatesignerMinusEditObjectMinusV1MinusResponse?>
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class)
fun ezsigntemplatesignerEditObjectV1WithHttpInfo(pkiEzsigntemplatesignerID: kotlin.Int, ezsigntemplatesignerMinusEditObjectMinusV1MinusRequest: EzsigntemplatesignerMinusEditObjectMinusV1MinusRequest) : ApiResponse<EzsigntemplatesignerMinusEditObjectMinusV1MinusResponse?> {
val localVariableConfig = ezsigntemplatesignerEditObjectV1RequestConfig(pkiEzsigntemplatesignerID = pkiEzsigntemplatesignerID, ezsigntemplatesignerMinusEditObjectMinusV1MinusRequest = ezsigntemplatesignerMinusEditObjectMinusV1MinusRequest)
return request<EzsigntemplatesignerMinusEditObjectMinusV1MinusRequest, EzsigntemplatesignerMinusEditObjectMinusV1MinusResponse>(
localVariableConfig
)
}
/**
* To obtain the request config of the operation ezsigntemplatesignerEditObjectV1
*
* @param pkiEzsigntemplatesignerID
* @param ezsigntemplatesignerMinusEditObjectMinusV1MinusRequest
* @return RequestConfig
*/
fun ezsigntemplatesignerEditObjectV1RequestConfig(pkiEzsigntemplatesignerID: kotlin.Int, ezsigntemplatesignerMinusEditObjectMinusV1MinusRequest: EzsigntemplatesignerMinusEditObjectMinusV1MinusRequest) : RequestConfig<EzsigntemplatesignerMinusEditObjectMinusV1MinusRequest> {
val localVariableBody = ezsigntemplatesignerMinusEditObjectMinusV1MinusRequest
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
localVariableHeaders["Content-Type"] = "application/json"
localVariableHeaders["Accept"] = "application/json"
return RequestConfig(
method = RequestMethod.PUT,
path = "/1/object/ezsigntemplatesigner/{pkiEzsigntemplatesignerID}".replace("{"+"pkiEzsigntemplatesignerID"+"}", encodeURIComponent(pkiEzsigntemplatesignerID.toString())),
query = localVariableQuery,
headers = localVariableHeaders,
requiresAuthentication = true,
body = localVariableBody
)
}
/**
* Retrieve an existing Ezsigntemplatesigner
*
* @param pkiEzsigntemplatesignerID
* @return EzsigntemplatesignerMinusGetObjectMinusV2MinusResponse
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
* @throws UnsupportedOperationException If the API returns an informational or redirection response
* @throws ClientException If the API returns a client error response
* @throws ServerException If the API returns a server error response
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class)
fun ezsigntemplatesignerGetObjectV2(pkiEzsigntemplatesignerID: kotlin.Int) : EzsigntemplatesignerMinusGetObjectMinusV2MinusResponse {
val localVarResponse = ezsigntemplatesignerGetObjectV2WithHttpInfo(pkiEzsigntemplatesignerID = pkiEzsigntemplatesignerID)
return when (localVarResponse.responseType) {
ResponseType.Success -> (localVarResponse as Success<*>).data as EzsigntemplatesignerMinusGetObjectMinusV2MinusResponse
ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.")
ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.")
ResponseType.ClientError -> {
val localVarError = localVarResponse as ClientError<*>
throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
ResponseType.ServerError -> {
val localVarError = localVarResponse as ServerError<*>
throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse)
}
}
}
/**
* Retrieve an existing Ezsigntemplatesigner
*
* @param pkiEzsigntemplatesignerID
* @return ApiResponse<EzsigntemplatesignerMinusGetObjectMinusV2MinusResponse?>
* @throws IllegalStateException If the request is not correctly configured
* @throws IOException Rethrows the OkHttp execute method exception
*/
@Suppress("UNCHECKED_CAST")
@Throws(IllegalStateException::class, IOException::class)
fun ezsigntemplatesignerGetObjectV2WithHttpInfo(pkiEzsigntemplatesignerID: kotlin.Int) : ApiResponse<EzsigntemplatesignerMinusGetObjectMinusV2MinusResponse?> {
val localVariableConfig = ezsigntemplatesignerGetObjectV2RequestConfig(pkiEzsigntemplatesignerID = pkiEzsigntemplatesignerID)
return request<Unit, EzsigntemplatesignerMinusGetObjectMinusV2MinusResponse>(
localVariableConfig
)
}
/**
* To obtain the request config of the operation ezsigntemplatesignerGetObjectV2
*
* @param pkiEzsigntemplatesignerID
* @return RequestConfig
*/
fun ezsigntemplatesignerGetObjectV2RequestConfig(pkiEzsigntemplatesignerID: kotlin.Int) : RequestConfig<Unit> {
val localVariableBody = null
val localVariableQuery: MultiValueMap = mutableMapOf()
val localVariableHeaders: MutableMap<String, String> = mutableMapOf()
localVariableHeaders["Accept"] = "application/json"
return RequestConfig(
method = RequestMethod.GET,
path = "/2/object/ezsigntemplatesigner/{pkiEzsigntemplatesignerID}".replace("{"+"pkiEzsigntemplatesignerID"+"}", encodeURIComponent(pkiEzsigntemplatesignerID.toString())),
query = localVariableQuery,
headers = localVariableHeaders,
requiresAuthentication = true,
body = localVariableBody
)
}
private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String =
HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0]
}
| 0
|
Kotlin
|
0
| 0
|
775bfa1e6452d8ba1c6c4d7e1781b0977f5301b0
| 19,500
|
eZmax-SDK-kotlin
|
MIT License
|
app/src/main/java/com/thenishchalraj/jetpackcomposelivestream/model/CommentsData.kt
|
thenishchalraj
| 595,458,531
| false
| null |
package com.thenishchalraj.jetpackcomposelivestream.model
data class CommentsData(
val avatar: Int,
val name: String,
val comment: String
)
| 0
|
Kotlin
|
0
| 1
|
2d17cc386084f5dbcc34830b6bae22ee41ab9517
| 153
|
Jetpack-Compose-LIVE-Stream
|
Apache License 2.0
|
web/src/main/kotlin/top/bettercode/summer/web/error/CustomErrorController.kt
|
top-bettercode
| 387,652,015
| false
|
{"Kotlin": 3010960, "Java": 24119, "JavaScript": 22541, "CSS": 22336, "HTML": 15833}
|
package top.bettercode.summer.web.error
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication
import org.springframework.boot.autoconfigure.web.ErrorProperties
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController
import org.springframework.boot.web.servlet.error.ErrorAttributes
import org.springframework.boot.web.servlet.error.ErrorController
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.context.request.RequestContextHolder
import org.springframework.web.context.request.ServletRequestAttributes
import org.springframework.web.cors.CorsConfigurationSource
import org.springframework.web.cors.CorsProcessor
import org.springframework.web.cors.CorsUtils
import org.springframework.web.cors.DefaultCorsProcessor
import org.springframework.web.servlet.ModelAndView
import java.io.IOException
import java.util.*
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
/**
* 自定义错误处理
*
* @author <NAME>
*/
@ConditionalOnWebApplication
@ConditionalOnMissingBean(ErrorController::class)
@RequestMapping("\${server.error.path:\${error.path:/error}}")
class CustomErrorController(
errorAttributes: ErrorAttributes?,
errorProperties: ErrorProperties?,
@param:Autowired(required = false) @param:Qualifier("corsConfigurationSource") private val configSource: CorsConfigurationSource?) : BasicErrorController(errorAttributes, errorProperties) {
private val log = LoggerFactory.getLogger(CustomErrorController::class.java)
private val processor: CorsProcessor = DefaultCorsProcessor()
@Autowired(required = false)
private val response: HttpServletResponse? = null
@RequestMapping(produces = ["text/html"])
override fun errorHtml(request: HttpServletRequest,
response: HttpServletResponse): ModelAndView {
val model = Collections.unmodifiableMap(getErrorAttributes(
request, getErrorAttributeOptions(request, MediaType.TEXT_HTML)))
val status = getStatus(request)
response.status = status.value()
val modelAndView = resolveErrorView(request, response, status, model)
setCors(request, response)
return modelAndView ?: ModelAndView("error", model)
}
private fun setCors(request: HttpServletRequest, response: HttpServletResponse) {
if (configSource != null && CorsUtils.isCorsRequest(request)) {
val corsConfiguration = configSource.getCorsConfiguration(request)
if (corsConfiguration != null) {
try {
processor.processRequest(corsConfiguration, request, response)
} catch (e: IOException) {
log.error("跨域设置出错", e)
}
}
}
}
@RequestMapping
@ResponseBody
override fun error(request: HttpServletRequest): ResponseEntity<Map<String, Any>> {
val body = getErrorAttributes(request,
getErrorAttributeOptions(request, MediaType.ALL))
val status = getStatus(request)
val requestAttributes = RequestContextHolder
.getRequestAttributes() as ServletRequestAttributes?
if (requestAttributes != null) {
setCors(request, requestAttributes.response!!)
}
response!!.status = status.value()
response.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
return ResponseEntity.status(status).headers(noCache()).body(body)
}
/**
* @return 不支持客户端缓存,不支持客户端保存数据的响应头
*/
protected fun noCache(): HttpHeaders {
val headers = HttpHeaders()
headers.cacheControl = "no-cache, no-store, max-age=0, must-revalidate"
headers.pragma = "no-cache"
headers.expires = -1
return headers
}
}
| 0
|
Kotlin
|
0
| 1
|
98b2b930bcf4addab63ec219c7cca4d4f39d9861
| 4,314
|
summer
|
Apache License 2.0
|
src/main/kotlin/app/web/drjacky/anticaptcha/api/RecaptchaV3EnterpriseProxyless.kt
|
Drjacky
| 531,616,505
| false
|
{"Kotlin": 92433}
|
package app.web.drjacky.anticaptcha.api
import app.web.drjacky.anticaptcha.apiresponse.TaskResultResponse
import app.web.drjacky.anticaptcha.helper.DebugHelper
import org.json.JSONException
import org.json.JSONObject
class RecaptchaV3EnterpriseProxyless : RecaptchaV3Proxyless() {
override fun getPostData(): JSONObject? {
val postData: JSONObject? = super.getPostData()
try {
postData?.put("isEnteprise", true)
} catch (e: JSONException) {
DebugHelper.out("JSON compilation error: " + e.message, DebugHelper.Type.ERROR)
return null
}
return postData
}
override fun getTaskSolution(): TaskResultResponse.SolutionData? = taskInfo?.solution
}
| 0
|
Kotlin
|
2
| 3
|
41bf9cc2ee324230f0f83adbef98086fc0f4c324
| 732
|
anticaptcha-kotlin
|
MIT License
|
app/src/main/java/com/example/pokemongo/model/ItemLib.kt
|
FarmBera
| 715,438,873
| false
|
{"Kotlin": 35431}
|
package com.example.pokemongo.model
data class ItemLib(val imageUrl: String, val bool: Boolean) {
}
| 0
|
Kotlin
|
0
| 0
|
b7b1b29adfc5d1a70184b2c1e00618bfca797d91
| 101
|
PokemonGo
|
MIT License
|
json/src/main/java/de/markusressel/kodehighlighter/language/json/rule/NumericRule.kt
|
markusressel
| 167,466,321
| false
|
{"Kotlin": 113203, "Python": 19475, "OCaml": 10026, "Shell": 2354, "Makefile": 156}
|
package de.markusressel.kodehighlighter.language.json.rule
import de.markusressel.kodehighlighter.core.rule.LanguageRule
import de.markusressel.kodehighlighter.core.rule.RuleHelper
import de.markusressel.kodehighlighter.core.rule.RuleMatch
class NumericRule : LanguageRule {
override fun findMatches(text: CharSequence): List<RuleMatch> {
return RuleHelper.findRegexMatches(text, PATTERN)
}
companion object {
val PATTERN = "\\b(-?(0x)?\\d*\\.?[\\da-f]+|NaN|-?Infinity)\\b".toRegex()
}
}
| 12
|
Kotlin
|
3
| 19
|
8811982b1f35ff3b43d4885b01b2781e1e30815b
| 524
|
KodeHighlighter
|
MIT License
|
app/src/main/java/com/gcc/gccapplication/ui/activity/LoginActivity.kt
|
hanyarui
| 836,702,073
| false
|
{"Kotlin": 193146}
|
package com.gcc.gccapplication.ui.activity
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import com.gcc.gccapplication.data.local.UserPreferences
import com.gcc.gccapplication.databinding.ActivityLoginBinding
import com.gcc.gccapplication.viewModel.LoginViewModel
import com.google.firebase.messaging.FirebaseMessaging
import com.gcc.gccapplication.service.MyFirebaseMessagingService
class LoginActivity : AppCompatActivity() {
private lateinit var binding: ActivityLoginBinding
private val loginViewModel: LoginViewModel by viewModels()
private lateinit var userPreferences: UserPreferences
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
supportActionBar?.hide()
binding.btnLogin.setOnClickListener {
val email = binding.etEmail.text.toString().trim()
val password = binding.etPass.text.toString().trim()
loginViewModel.login(
context = this,
email = email,
password = password,
onSuccess = {
userPreferences = UserPreferences(this)
Toast.makeText(this, "Login successful!", Toast.LENGTH_SHORT).show()
val intent = Intent(this, PageActivity::class.java)
startActivity(intent)
handleLogin()
finish()
},
onFailure = { errorMessage ->
Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT).show()
Toast.makeText(this, "password salah", Toast.LENGTH_SHORT).show()
}
)
}
binding.tvAkun.setOnClickListener {
val intent = Intent(this, RegisterActivity::class.java)
startActivity(intent)
finish()
}
binding.tvPassword.setOnClickListener{
val intent = Intent(this, ForgotPasswordActivity::class.java)
startActivity(intent)
finish()
}
}
private fun handleLogin() {
FirebaseMessaging.getInstance().token.addOnCompleteListener { task ->
if (!task.isSuccessful) {
Log.w("FCM", "Fetching FCM token failed", task.exception)
return@addOnCompleteListener
}
// Dapatkan token FCM
val token = task.result
Log.d("FCM", "Token FCM didapatkan: $token")
val email = userPreferences.getEmail()
// Pastikan email tidak null
if (email != null) {
loginViewModel.saveNotificationToken(
this,
email,
token,
onSuccess = {
Log.d("FCM", "Token FCM berhasil dikirim ke server backend.")
},
onFailure = {
Log.w("FCM", "Gagal mengirim token FCM ke server backend")
}
)
} else {
Log.w("FCM", "Email tidak ditemukan, token tidak disimpan.")
}
}
}
private fun sendTokenToServer(token: String) {
// Implementasi untuk mengirim token baru ke server Anda
}
}
| 0
|
Kotlin
|
0
| 0
|
0afd0e392d550506ba318fadac7d0d21637c56b3
| 3,572
|
GCC-Application
|
MIT License
|
server/src/test/kotlin/io/rippledown/model/rule/IsNumericSuggestionTest.kt
|
TimLavers
| 513,037,911
| false
|
{"Kotlin": 1309914, "Gherkin": 117611}
|
package io.rippledown.model.rule
import io.kotest.matchers.shouldBe
import io.rippledown.model.condition.isNumeric
import io.rippledown.model.condition.rr
import io.rippledown.model.condition.tr
import kotlin.test.Test
class IsNumericSuggestionTest: ConditionFactoryTestBase() {
@Test
fun suggestion() {
IsNumericSuggestion().invoke(tsh, null) shouldBe null
IsNumericSuggestion().invoke(tsh, tr("whatever")) shouldBe null
with(IsNumericSuggestion().invoke(tsh, tr("1.2", rr("1.5", null)))!!) {
initialSuggestion() shouldBe isNumeric(tsh)
isEditable() shouldBe false
editableCondition() shouldBe null
}
}
}
| 0
|
Kotlin
|
0
| 0
|
4d3a0820aa4d27b84e9e07159e877fe9ada47bdb
| 688
|
OpenRDR
|
MIT License
|
Chapter03/src/main/kotlin/com/rivuchk/packtpub/reactivekotlin/chapter03/SubscribeExmpl.kt
|
tymicki
| 175,694,440
| true
|
{"Kotlin": 121444}
|
package com.rivuchk.packtpub.reactivekotlin.chapter03
import io.reactivex.Observable
import io.reactivex.Observer
import io.reactivex.disposables.Disposable
fun main() {
val observable: Observable<Int> = Observable.range(1, 5)//1
observable.subscribe({
//2
//onNext method
println("Next $it")
}, {
//onError Method
println("Error ${it.message}")
}, {
//onComplete Method
println("Done")
})
val observer: Observer<Int> = object : Observer<Int> {
//3
override fun onComplete() {
println("All Completed")
}
override fun onNext(item: Int) {
println("Next $item")
}
override fun onError(e: Throwable) {
println("Error Occurred ${e.message}")
}
override fun onSubscribe(d: Disposable) {
println("New Subscription ")
}
}
observable.subscribe(observer)
}
| 0
|
Kotlin
|
0
| 0
|
143e1bd1473c6da3fb3fe1b9373124052f87874d
| 962
|
Reactive-Programming-in-Kotlin
|
MIT License
|
app/src/main/java/com/example/ingressolive/Adapter/AdapterProduto.kt
|
joaopedrovr91
| 480,575,322
| false
|
{"Kotlin": 4217}
|
package com.example.ingressolive.Adapter
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.example.ingressolive.R
import com.example.ingressolive.model.Produto
class AdapterProduto(private val context: Context, private val produtos: MutableList<Produto>): RecyclerView.Adapter<AdapterProduto.ProdutoViewHolder>() {
inner class ProdutoViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val imagem = itemView.findViewById<ImageView>(R.id.imagem)
val nome = itemView.findViewById<TextView>(R.id.titulo)
val local = itemView.findViewById<TextView>(R.id.local)
val data = itemView.findViewById<TextView>(R.id.data)
val icone = itemView.findViewById<ImageView>(R.id.icone)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProdutoViewHolder {
val itemLista = LayoutInflater.from(context).inflate(R.layout.ingresso_item, parent,false)
val holder = ProdutoViewHolder(itemLista)
return holder
}
override fun onBindViewHolder(holder: ProdutoViewHolder, position: Int) {
holder.imagem.setImageResource(produtos[position].imagem)
holder.nome.text = produtos[position].nome
holder.local.text = produtos[position].local
holder.data.text = produtos[position].data
holder.icone.setImageResource(produtos[position].icone)
}
override fun getItemCount(): Int = produtos.size
}
| 0
|
Kotlin
|
0
| 0
|
a3bc66462b40a2f50afbd9d666ac5770ee806f75
| 1,624
|
Layout_ingressolive
|
RSA Message-Digest License
|
transport/src/androidTest/kotlin/com/genesys/cloud/messenger/transport/core/MessageExtensionTest.kt
|
MyPureCloud
| 425,920,457
| false
|
{"Kotlin": 651315, "Swift": 113325, "Shell": 5872, "Ruby": 4062}
|
package com.genesys.cloud.messenger.transport.core
import assertk.assertThat
import assertk.assertions.containsExactly
import assertk.assertions.isEmpty
import assertk.assertions.isEqualTo
import assertk.assertions.isFalse
import assertk.assertions.isNull
import assertk.assertions.isTrue
import com.genesys.cloud.messenger.transport.core.Message.Direction
import com.genesys.cloud.messenger.transport.core.Message.Participant
import com.genesys.cloud.messenger.transport.core.Message.State
import com.genesys.cloud.messenger.transport.core.Message.Type
import com.genesys.cloud.messenger.transport.core.events.Event
import com.genesys.cloud.messenger.transport.network.TestWebMessagingApiResponses
import com.genesys.cloud.messenger.transport.network.TestWebMessagingApiResponses.isoTestTimestamp
import com.genesys.cloud.messenger.transport.shyrka.WebMessagingJson
import com.genesys.cloud.messenger.transport.shyrka.receive.MessageEntityList
import com.genesys.cloud.messenger.transport.shyrka.receive.PreIdentifiedWebMessagingMessage
import com.genesys.cloud.messenger.transport.shyrka.receive.PresenceEvent
import com.genesys.cloud.messenger.transport.shyrka.receive.StructuredMessage
import com.genesys.cloud.messenger.transport.shyrka.receive.StructuredMessageEvent
import com.genesys.cloud.messenger.transport.shyrka.receive.isInbound
import com.genesys.cloud.messenger.transport.shyrka.receive.isOutbound
import com.genesys.cloud.messenger.transport.shyrka.send.HealthCheckID
import com.genesys.cloud.messenger.transport.util.extensions.fromIsoToEpochMilliseconds
import com.genesys.cloud.messenger.transport.util.extensions.getUploadedAttachments
import com.genesys.cloud.messenger.transport.util.extensions.isHealthCheckResponseId
import com.genesys.cloud.messenger.transport.util.extensions.isOutbound
import com.genesys.cloud.messenger.transport.util.extensions.mapOriginatingEntity
import com.genesys.cloud.messenger.transport.util.extensions.toMessage
import com.genesys.cloud.messenger.transport.util.extensions.toMessageList
import com.genesys.cloud.messenger.transport.utility.MessageValues
import com.genesys.cloud.messenger.transport.utility.QuickReplyTestValues
import com.genesys.cloud.messenger.transport.utility.StructuredMessageValues
import com.genesys.cloud.messenger.transport.utility.TestValues
import kotlinx.serialization.decodeFromString
import kotlinx.serialization.encodeToString
import net.bytebuddy.utility.RandomString
import org.junit.Test
internal class MessageExtensionTest {
@Test
fun `when MessageEntityList toMessageList()`() {
val expectedMessage1 = Message(
id = "5befde6373a23f32f20b59b4e1cba0e6",
direction = Direction.Outbound,
state = State.Sent,
messageType = Type.Text,
text = "\uD83E\uDD2A",
timeStamp = 1398892191411L,
from = Participant(originatingEntity = Participant.OriginatingEntity.Bot),
)
val expectedMessage2 = Message(
id = "1234567890",
direction = Direction.Inbound,
state = State.Sent,
messageType = Type.Event,
text = "customer msg 7",
timeStamp = null,
events = listOf(Event.ConversationAutostart),
from = Participant(originatingEntity = Participant.OriginatingEntity.Human),
)
val expectedMessage3 = Message(
id = "1234567890",
direction = Direction.Outbound,
state = State.Sent,
messageType = Type.QuickReply,
text = "quick reply text",
timeStamp = null,
quickReplies = listOf(
QuickReplyTestValues.buttonResponse_a,
QuickReplyTestValues.buttonResponse_b,
),
from = Participant(originatingEntity = Participant.OriginatingEntity.Bot),
)
val result = TestWebMessagingApiResponses.testMessageEntityList.entities.toMessageList()
assertThat(result).containsExactly(expectedMessage1, expectedMessage2, expectedMessage3)
}
@Test
fun `when inbound StructuredMessage toMessage()`() {
val givenStructuredMessage = StructuredMessage(
id = "id",
channel = StructuredMessage.Channel(
time = isoTestTimestamp,
from = StructuredMessage.Participant(
nickname = "Bob",
image = "http://image.png",
)
),
type = StructuredMessage.Type.Text,
text = "test text",
content = listOf(
StructuredMessage.Content.AttachmentContent(
contentType = "Attachment",
attachment = StructuredMessage.Content.AttachmentContent.Attachment(
id = "test attachment id",
url = "http://test.com",
filename = "test.png",
mediaType = "image/png",
)
)
),
direction = "Inbound",
metadata = mapOf("customMessageId" to "test custom id"),
events = listOf(
PresenceEvent(
eventType = StructuredMessageEvent.Type.Presence,
presence = PresenceEvent.Presence(PresenceEvent.Presence.Type.Join)
)
)
)
val expectedMessage =
Message(
id = "test custom id",
direction = Direction.Inbound,
state = State.Sent,
messageType = Type.Text,
text = "test text",
timeStamp = 1398892191411L,
attachments = mapOf(
"test attachment id" to Attachment(
id = "test attachment id",
fileName = "test.png",
state = Attachment.State.Sent("http://test.com")
)
),
events = listOf<Event>(Event.ConversationAutostart),
from = Participant(
name = "Bob",
imageUrl = "http://image.png",
originatingEntity = Participant.OriginatingEntity.Human
),
)
givenStructuredMessage.toMessage().run {
assertThat(this).isEqualTo(expectedMessage)
assertThat(id).isEqualTo(expectedMessage.id)
assertThat(direction).isEqualTo(expectedMessage.direction)
assertThat(state).isEqualTo(expectedMessage.state)
assertThat(type).isEqualTo(expectedMessage.type)
assertThat(timeStamp).isEqualTo(expectedMessage.timeStamp)
assertThat(events).containsExactly(*expectedMessage.events.toTypedArray())
from.run {
assertThat(name).isEqualTo(expectedMessage.from.name)
assertThat(imageUrl).isEqualTo(expectedMessage.from.imageUrl)
assertThat(originatingEntity).isEqualTo(expectedMessage.from.originatingEntity)
}
}
}
@Test
fun `when getUploadedAttachments() with 1 uploaded and 1 deleted attachment`() {
val givenMessage =
Message(
id = "test custom id",
direction = Direction.Inbound,
state = State.Sent,
attachments = mapOf(
"first test attachment id" to Attachment(
id = "first test attachment id",
fileName = "test.png",
Attachment.State.Uploaded("http://test.com")
),
"second test attachment id" to Attachment(
id = "second test attachment id",
fileName = "test2.png",
Attachment.State.Detached,
)
)
)
val expectedContent = Message.Content(
contentType = Message.Content.Type.Attachment,
attachment = Attachment(
id = "first test attachment id",
fileName = "test.png",
state = Attachment.State.Uploaded("http://test.com")
)
)
assertThat(givenMessage.getUploadedAttachments()).containsExactly(expectedContent)
}
@Test
fun `when getUploadedAttachments() without attachments`() {
val givenMessage =
Message(
id = "test custom id",
direction = Direction.Inbound,
state = State.Sent,
attachments = emptyMap()
)
assertThat(givenMessage.getUploadedAttachments()).isEmpty()
}
@Test
fun `when outbound StructuredMessage toMessage() from Participant with unknown info`() {
val givenStructuredMessage = StructuredMessage(
id = "id",
type = StructuredMessage.Type.Text,
direction = "Outbound",
)
val expectedMessage =
Message(
id = "id",
direction = Direction.Outbound,
state = State.Sent,
messageType = Type.Text,
from = Participant(
originatingEntity = Participant.OriginatingEntity.Unknown
),
)
assertThat(givenStructuredMessage.toMessage()).isEqualTo(expectedMessage)
}
@Test
fun `when fromIsoToEpochMilliseconds() on valid ISO string`() {
val expectedTimestamp = 1398892191411L
val result = isoTestTimestamp.fromIsoToEpochMilliseconds()
assertThat(result).isEqualTo(expectedTimestamp)
}
@Test
fun `when fromIsoToEpochMilliseconds() on invalid string`() {
val result = "invalid timestamp format".fromIsoToEpochMilliseconds()
assertThat(result).isNull()
}
@Test
fun `when fromIsoToEpochMilliseconds() on null string`() {
val result = null.fromIsoToEpochMilliseconds()
assertThat(result).isNull()
}
@Test
fun `when outbound StructuredMessage is checked for isOutbound()`() {
val givenStructuredMessage = StructuredMessage(
id = "some_id",
type = StructuredMessage.Type.Text,
direction = "Outbound"
)
assertThat(givenStructuredMessage.isOutbound()).isTrue()
}
@Test
fun `when inbound StructuredMessage is checked for isOutbound()`() {
val givenStructuredMessage = StructuredMessage(
id = "some_id",
type = StructuredMessage.Type.Text,
direction = "Inbound"
)
assertThat(givenStructuredMessage.isOutbound()).isFalse()
}
@Test
fun `when inbound StructuredMessage is checked for isInbound()`() {
val givenStructuredMessage = StructuredMessage(
id = "some_id",
type = StructuredMessage.Type.Text,
direction = "Inbound"
)
assertThat(givenStructuredMessage.isInbound()).isTrue()
}
@Test
fun `when outbound StructuredMessage is checked for isInbound()`() {
val givenStructuredMessage = StructuredMessage(
id = "some_id",
type = StructuredMessage.Type.Text,
direction = "Outbound"
)
assertThat(givenStructuredMessage.isInbound()).isFalse()
}
@Test
fun `when mapOriginatingEntity() with originatingEntity=Human and isInbound=false`() {
val givenIsInbound = false
val originatingEntity = "Human"
val expectedOriginatingEntity = Participant.OriginatingEntity.Human
val result = originatingEntity.mapOriginatingEntity { givenIsInbound }
assertThat(result).isEqualTo(expectedOriginatingEntity)
}
@Test
fun `when mapOriginatingEntity() with originatingEntity=Bot and isInbound=false`() {
val givenIsInbound = false
val originatingEntity = "Bot"
val expectedOriginatingEntity = Participant.OriginatingEntity.Bot
val result = originatingEntity.mapOriginatingEntity { givenIsInbound }
assertThat(result).isEqualTo(expectedOriginatingEntity)
}
@Test
fun `when mapOriginatingEntity() with originatingEntity=Unknown and isInbound=false`() {
val givenIsInbound = false
val originatingEntity = "any value"
val expectedOriginatingEntity = Participant.OriginatingEntity.Unknown
val result = originatingEntity.mapOriginatingEntity { givenIsInbound }
assertThat(result).isEqualTo(expectedOriginatingEntity)
}
@Test
fun `when mapOriginatingEntity() with originatingEntity=null and isInbound=false`() {
val givenIsInbound = false
val originatingEntity = null
val expectedOriginatingEntity = Participant.OriginatingEntity.Unknown
val result = originatingEntity.mapOriginatingEntity { givenIsInbound }
assertThat(result).isEqualTo(expectedOriginatingEntity)
}
@Test
fun `when mapOriginatingEntity() with originatingEntity=Bot and isInbound=true`() {
val givenIsInbound = true
val originatingEntity = "Bot"
val expectedOriginatingEntity = Participant.OriginatingEntity.Human
val result = originatingEntity.mapOriginatingEntity { givenIsInbound }
assertThat(result).isEqualTo(expectedOriginatingEntity)
}
@Test
fun `when isHealthCheckResponseId match HealthCheckId`() {
assertThat(HealthCheckID.isHealthCheckResponseId()).isTrue()
}
@Test
fun `when isHealthCheckResponseId not equals HealthCheckId`() {
var randomString: String
do {
randomString = RandomString().nextString()
} while (randomString == HealthCheckID)
assertThat(randomString.isHealthCheckResponseId()).isFalse()
}
@Test
fun `when outbound Message is checked for isOutbound()`() {
val givenMessage = Message(direction = Direction.Outbound)
assertThat(givenMessage.isOutbound()).isTrue()
}
@Test
fun `when inbound Message is checked for isOutbound()`() {
val givenMessage = Message(direction = Direction.Inbound)
assertThat(givenMessage.isOutbound()).isFalse()
}
@Test
fun `when StructureMessage toMessage() has Content with QuickReplyContent`() {
val givenStructuredMessage = StructuredMessageValues.createStructuredMessageForTesting(
type = StructuredMessage.Type.Structured,
content = listOf(QuickReplyTestValues.createQuickReplyContentForTesting())
)
val expectedButtonResponse = ButtonResponse(
text = QuickReplyTestValues.Text_A,
payload = QuickReplyTestValues.Payload_A,
type = QuickReplyTestValues.QuickReply
)
val expectedMessage = Message(
id = MessageValues.Id,
state = State.Sent,
type = Message.Type.QuickReply.name,
messageType = Message.Type.QuickReply,
quickReplies = listOf(expectedButtonResponse)
)
val result = givenStructuredMessage.toMessage()
assertThat(result).isEqualTo(expectedMessage)
}
@Test
fun `when StructureMessage toMessage() has Content with ButtonResponseContent`() {
val givenStructuredMessage = StructuredMessageValues.createStructuredMessageForTesting(
type = StructuredMessage.Type.Structured,
content = listOf(QuickReplyTestValues.createButtonResponseContentForTesting())
)
val expectedButtonResponse = ButtonResponse(
text = QuickReplyTestValues.Text_A,
payload = QuickReplyTestValues.Payload_A,
type = QuickReplyTestValues.QuickReply
)
val expectedMessage = Message(
id = MessageValues.Id,
state = State.Sent,
type = Message.Type.QuickReply.name,
messageType = Message.Type.QuickReply,
quickReplies = listOf(expectedButtonResponse)
)
val result = givenStructuredMessage.toMessage()
assertThat(result).isEqualTo(expectedMessage)
}
@Test
fun `when StructureMessage toMessage() has Content with QuickReplyContent and ButtonResponseContent`() {
val givenStructuredMessage = StructuredMessageValues.createStructuredMessageForTesting(
type = StructuredMessage.Type.Structured,
content = listOf(
QuickReplyTestValues.createQuickReplyContentForTesting(),
QuickReplyTestValues.createButtonResponseContentForTesting(),
)
)
val expectedButtonResponse = ButtonResponse(
text = QuickReplyTestValues.Text_A,
payload = QuickReplyTestValues.Payload_A,
type = QuickReplyTestValues.QuickReply
)
val expectedMessage = Message(
id = MessageValues.Id,
state = State.Sent,
type = Message.Type.QuickReply.name,
messageType = Message.Type.QuickReply,
quickReplies = listOf(expectedButtonResponse)
)
val result = givenStructuredMessage.toMessage()
assertThat(result).isEqualTo(expectedMessage)
}
@Test
fun `when StructureMessage toMessage() has Content without QuickReplyContent or ButtonResponseContent`() {
val givenStructuredMessage = StructuredMessageValues.createStructuredMessageForTesting(
type = StructuredMessage.Type.Structured
)
val expectedMessage = Message(
id = MessageValues.Id,
state = State.Sent,
type = Message.Type.Unknown.name,
messageType = Message.Type.Unknown,
)
val result = givenStructuredMessage.toMessage()
assertThat(result).isEqualTo(expectedMessage)
}
@Test
fun `when MessageEntityList toMessageList() has message with type Unknown`() {
val givenStructuredMessageList = listOf(
StructuredMessageValues.createStructuredMessageForTesting(
type = StructuredMessage.Type.Structured
)
)
val result = givenStructuredMessageList.toMessageList()
assertThat(result).isEmpty()
}
@Test
fun `when MessageEntityList serialized`() {
val givenStructuredMessage = StructuredMessage(
id = "some_id",
type = StructuredMessage.Type.Text,
direction = "Inbound"
)
val givenMessageEntityList = MessageEntityList(
entities = listOf(givenStructuredMessage),
pageSize = MessageValues.PageSize,
pageNumber = MessageValues.PageNumber,
total = MessageValues.Total,
pageCount = MessageValues.PageCount,
)
val expectedMessageEntityListAsJson =
"""{"entities":[{"id":"some_id","type":"Text","direction":"Inbound"}],"pageSize":25,"pageNumber":1,"total":25,"pageCount":1}"""
val result = WebMessagingJson.json.encodeToString(givenMessageEntityList)
assertThat(result).isEqualTo(expectedMessageEntityListAsJson)
}
@Test
fun `when MessageEntityList deserialized`() {
val givenMessageEntityListAsJson =
"""{"entities":[{"id":"some_id","type":"Text","direction":"Inbound"}],"pageSize":25,"pageNumber":1,"total":25,"pageCount":1}"""
val expectedStructuredMessage = StructuredMessage(
id = "some_id",
type = StructuredMessage.Type.Text,
direction = "Inbound"
)
val expectedMessageEntityList = MessageEntityList(
entities = listOf(expectedStructuredMessage),
pageSize = MessageValues.PageSize,
pageNumber = MessageValues.PageNumber,
total = MessageValues.Total,
pageCount = MessageValues.PageCount,
)
val result =
WebMessagingJson.json.decodeFromString<MessageEntityList>(givenMessageEntityListAsJson)
result.run {
assertThat(this).isEqualTo(expectedMessageEntityList)
assertThat(entities).containsExactly(*expectedMessageEntityList.entities.toTypedArray())
assertThat(pageSize).isEqualTo(expectedMessageEntityList.pageSize)
assertThat(pageNumber).isEqualTo(expectedMessageEntityList.pageNumber)
assertThat(total).isEqualTo(expectedMessageEntityList.total)
assertThat(pageCount).isEqualTo(expectedMessageEntityList.pageCount)
}
}
@Test
fun `validate default constructor of MessageEntityList`() {
val givenMessageEntityList = MessageEntityList(
pageSize = MessageValues.PageSize,
pageNumber = MessageValues.PageNumber,
total = MessageValues.Total,
pageCount = MessageValues.PageCount,
)
assertThat(givenMessageEntityList.entities).isEmpty()
}
@Test
fun `when PreIdentifiedWebMessagingMessage serialized`() {
val givenMPreIdentifiedWebMessagingMessage = PreIdentifiedWebMessagingMessage(
type = MessageValues.PreIdentifiedMessageType,
code = MessageValues.PreIdentifiedMessageCode,
className = MessageValues.PreIdentifiedMessageClass,
)
val expectedPreIdentifiedWebMessagingMessageAsJson = """{"type":"type","code":200,"class":"clazz"}"""
val result = WebMessagingJson.json.encodeToString(givenMPreIdentifiedWebMessagingMessage)
assertThat(result).isEqualTo(expectedPreIdentifiedWebMessagingMessageAsJson)
}
@Test
fun `when PreIdentifiedWebMessagingMessage deserialized`() {
val givenPreIdentifiedWebMessagingMessageAsJson =
"""{"type":"type","code":200,"class":"clazz"}"""
val result = WebMessagingJson.json.decodeFromString<PreIdentifiedWebMessagingMessage>(
givenPreIdentifiedWebMessagingMessageAsJson
)
result.run {
assertThat(type).isEqualTo(MessageValues.PreIdentifiedMessageType)
assertThat(code).isEqualTo(MessageValues.PreIdentifiedMessageCode)
assertThat(className).isEqualTo(MessageValues.PreIdentifiedMessageClass)
}
}
@Test
fun `when Channel serialized`() {
val givenChannel = StructuredMessage.Channel(
time = TestValues.Timestamp,
messageId = MessageValues.Id,
type = MessageValues.Type,
to = StructuredMessage.Participant(
firstName = MessageValues.ParticipantName,
lastName = MessageValues.ParticipantLastName,
nickname = MessageValues.ParticipantNickname,
image = MessageValues.ParticipantImageUrl,
),
from = StructuredMessage.Participant(),
)
val expectedChannelAsJson =
"""{"time":"2022-08-22T19:24:26.704Z","messageId":"test_message_id","type":"Text","to":{"firstName":"participant_name","lastName":"participant_last_name","nickname":"participant_nickname","image":"http://participant.image"},"from":{}}"""
val result = WebMessagingJson.json.encodeToString(givenChannel)
assertThat(result).isEqualTo(expectedChannelAsJson)
}
@Test
fun `when Channel deserialized`() {
val givenChannelDefaultConstructor = StructuredMessage.Channel()
val givenChannelAsJson =
"""{"time":"2022-08-22T19:24:26.704Z","messageId":"test_message_id","type":"Text","to":{"firstName":"participant_name","lastName":"participant_last_name","nickname":"participant_nickname","image":"http://participant.image"},"from":{}}"""
val expectedChannel = StructuredMessage.Channel(
time = TestValues.Timestamp,
messageId = MessageValues.Id,
type = MessageValues.Type,
to = StructuredMessage.Participant(
firstName = MessageValues.ParticipantName,
lastName = MessageValues.ParticipantLastName,
nickname = MessageValues.ParticipantNickname,
image = MessageValues.ParticipantImageUrl,
),
from = StructuredMessage.Participant(),
)
val result = WebMessagingJson.json.decodeFromString<StructuredMessage.Channel>(givenChannelAsJson)
result.run {
assertThat(time).isEqualTo(expectedChannel.time)
assertThat(messageId).isEqualTo(expectedChannel.messageId)
assertThat(type).isEqualTo(expectedChannel.type)
assertThat(to).isEqualTo(expectedChannel.to)
to?.run {
assertThat(firstName).isEqualTo(expectedChannel.to?.firstName)
assertThat(lastName).isEqualTo(expectedChannel.to?.lastName)
assertThat(nickname).isEqualTo(expectedChannel.to?.nickname)
assertThat(image).isEqualTo(expectedChannel.to?.image)
}
assertThat(from).isEqualTo(expectedChannel.from)
from?.run {
assertThat(firstName).isNull()
assertThat(lastName).isNull()
assertThat(nickname).isNull()
assertThat(image).isNull()
}
givenChannelDefaultConstructor.run {
assertThat(time).isNull()
assertThat(messageId).isNull()
assertThat(type).isNull()
assertThat(to).isNull()
assertThat(from).isNull()
}
}
}
}
| 2
|
Kotlin
|
6
| 9
|
62ae0018724192357dbfa337153f425c7c792511
| 25,543
|
genesys-messenger-transport-mobile-sdk
|
MIT License
|
app/src/main/kotlin/com/gunkel/android/drift/DriftApp.kt
|
FabioGunkel
| 587,782,229
| false
|
{"Kotlin": 12005}
|
package com.gunkel.android.drift
import android.app.Application
class DriftApp : Application() {
init {
}
}
| 3
|
Kotlin
|
0
| 0
|
a1f9ad44b3fac0b1ea0d1363f8531a024c94b02a
| 119
|
drift
|
Apache License 2.0
|
app/src/main/java/com/example/urbancart/home/list/UiProductEpoxyModel.kt
|
preetishsrivastav
| 732,448,084
| false
|
{"Kotlin": 73235}
|
package com.example.urbancart.home.list
import androidx.core.view.isGone
import androidx.core.view.isInvisible
import androidx.core.view.isVisible
import coil.load
import com.example.urbancart.R
import com.example.urbancart.databinding.EpoxyModelProductItemBinding
import com.example.urbancart.epoxy.ViewBindingKotlinModel
import com.example.urbancart.model.ui.UiProduct
import java.text.NumberFormat
import kotlin.math.roundToInt
data class UiProductEpoxyModel(
val uiProduct: UiProduct?,
val onFavoriteIconClicked: (Int) -> Unit,
val onUiProductClicked: (Int) -> Unit,
val onAddToCartClicked: (Int) -> Unit
) : ViewBindingKotlinModel<EpoxyModelProductItemBinding>(R.layout.epoxy_model_product_item) {
private val currencyFormatter = NumberFormat.getCurrencyInstance()
override fun EpoxyModelProductItemBinding.bind() {
shimmerLayout.isVisible = uiProduct == null
cardView.isInvisible = uiProduct == null
uiProduct?.let { uiProduct ->
shimmerLayout.stopShimmer()
// Setup our text
productTitleTextView.text = uiProduct.product.title
productDescriptionTextView.text = uiProduct.product.description
productCategoryTextView.text = uiProduct.product.category
productPriceTextView.text = currencyFormatter.format(uiProduct.product.price)
// Expanded state
productDescriptionTextView.isVisible = uiProduct.isExpanded
root.setOnClickListener { onUiProductClicked(uiProduct.product.id) }
// Favorite icon
val imageRes = if (uiProduct.isFavorite) {
R.drawable.ic_round_favorite_24
} else {
R.drawable.ic_round_favorite_border_24
}
favoriteImageView.setIconResource(imageRes)
favoriteImageView.setOnClickListener {
onFavoriteIconClicked(uiProduct.product.id)
}
// In cart status
inCartView.isVisible = uiProduct.isInCart
addToCartButton.setOnClickListener {
onAddToCartClicked(uiProduct.product.id)
}
// Load our image
productImageViewLoadingProgressBar.isVisible = true
productImageView.load(data = uiProduct.product.image) {
listener { request, result ->
productImageViewLoadingProgressBar.isGone = true
}
}
ratingIndicator.progress = (uiProduct.product.rating.value * 10).roundToInt()
ratingTextView.text = "${uiProduct.product.rating.value}"
} ?: shimmerLayout.startShimmer()
}
}
| 0
|
Kotlin
|
0
| 1
|
82d1917c13c15bf633169e682993e9ddfab960db
| 2,674
|
UrbanCart
|
MIT License
|
BaseStudy/app/src/main/java/com/gredicer/basestudy/ui/LaunchActivity.kt
|
Gredicer
| 447,598,319
| false
| null |
package com.gredicer.basestudy.ui
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.gredicer.basestudy.MainActivity
import com.gredicer.basestudy.base.BaseBindingActivity
import com.gredicer.basestudy.databinding.ActivityLaunchBinding
class LaunchActivity : BaseBindingActivity<ActivityLaunchBinding>() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Thread {
Thread.sleep(2000);
//耗时任务,比如加载网络数据
runOnUiThread { // 这里可以睡几秒钟,如果要放广告的话
startActivity(Intent(this, MainActivity::class.java))
finish()
}
}.start()
}
}
| 0
|
Kotlin
|
0
| 0
|
62a25689607d2342b76b41250864bb20caee251f
| 732
|
AndroidStudy
|
Apache License 2.0
|
app/src/main/java/info/degirona/creativelab/node/experiment/ExperimentNode.kt
|
manuel-martos
| 576,757,261
| false
| null |
package info.degirona.creativelab.node.experiment
import com.bumble.appyx.core.modality.BuildContext
import com.bumble.appyx.core.node.Node
import com.bumble.appyx.interop.rx2.connectable.Connectable
import com.bumble.appyx.interop.rx2.connectable.NodeConnector
internal class ExperimentNode(
buildContext: BuildContext,
experimentView: ExperimentView,
) : Node(
buildContext = buildContext,
view = experimentView
), Experiment, Connectable<Experiment.Input, Experiment.Output> by NodeConnector()
| 0
|
Kotlin
|
5
| 98
|
80ab274cbd87b864da95fa22cb623628d77fa848
| 514
|
creative-lab
|
MIT License
|
androidauto/src/main/java/com/mapbox/navigation/ui/androidauto/navigation/speedlimit/CarSpeedLimitRenderer.kt
|
mapbox
| 87,455,763
| false
|
{"Kotlin": 8885438, "Makefile": 8762, "Python": 7925, "Java": 4624}
|
package com.mapbox.navigation.ui.androidauto.navigation.speedlimit
import android.graphics.Rect
import androidx.annotation.VisibleForTesting
import com.mapbox.maps.EdgeInsets
import com.mapbox.maps.MapboxExperimental
import com.mapbox.maps.extension.androidauto.MapboxCarMapObserver
import com.mapbox.maps.extension.androidauto.MapboxCarMapSurface
import com.mapbox.navigation.base.formatter.DistanceFormatterOptions
import com.mapbox.navigation.base.formatter.UnitType
import com.mapbox.navigation.base.speed.model.SpeedLimitSign
import com.mapbox.navigation.base.speed.model.SpeedUnit
import com.mapbox.navigation.core.MapboxNavigation
import com.mapbox.navigation.core.lifecycle.MapboxNavigationApp
import com.mapbox.navigation.core.trip.session.LocationMatcherResult
import com.mapbox.navigation.core.trip.session.LocationObserver
import com.mapbox.navigation.ui.androidauto.MapboxCarContext
import com.mapbox.navigation.ui.androidauto.MapboxCarOptions
import com.mapbox.navigation.ui.androidauto.internal.extensions.mapboxNavigationForward
import com.mapbox.navigation.ui.androidauto.internal.logAndroidAuto
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlin.math.roundToInt
/**
* Create a speed limit sign. This class is demonstrating how to create a renderer.
* To Create a new speed limit sign experience, try creating a new class.
*/
@OptIn(MapboxExperimental::class)
class CarSpeedLimitRenderer
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal constructor(
private val services: CarSpeedLimitServices,
private val options: MapboxCarOptions,
) : MapboxCarMapObserver {
/**
* Public constructor and the internal constructor is for unit testing.
*/
constructor(mapboxCarContext: MapboxCarContext) : this(
CarSpeedLimitServices(),
mapboxCarContext.options,
)
@VisibleForTesting(otherwise = VisibleForTesting.PRIVATE)
internal var speedLimitWidget: SpeedLimitWidget? = null
private var distanceFormatterOptions: DistanceFormatterOptions? = null
private val navigationObserver = mapboxNavigationForward(this::onAttached, this::onDetached)
private val locationObserver = object : LocationObserver {
override fun onNewLocationMatcherResult(locationMatcherResult: LocationMatcherResult) {
updateSpeed(locationMatcherResult)
}
override fun onNewRawLocation(rawLocation: com.mapbox.common.location.Location) {
// no op
}
}
private lateinit var scope: CoroutineScope
private fun onAttached(mapboxNavigation: MapboxNavigation) {
distanceFormatterOptions = mapboxNavigation
.navigationOptions.distanceFormatterOptions
mapboxNavigation.registerLocationObserver(locationObserver)
}
private fun onDetached(mapboxNavigation: MapboxNavigation) {
mapboxNavigation.unregisterLocationObserver(locationObserver)
distanceFormatterOptions = null
}
private fun updateSpeed(locationMatcherResult: LocationMatcherResult) {
val speedLimitOptions = options.speedLimitOptions.value
val signFormat = speedLimitOptions.forcedSignFormat
?: locationMatcherResult.speedLimitInfo.sign
val threshold = speedLimitOptions.warningThreshold
when (distanceFormatterOptions!!.unitType) {
UnitType.IMPERIAL -> {
val speedLimit = when (locationMatcherResult.speedLimitInfo.unit) {
SpeedUnit.MILES_PER_HOUR ->
locationMatcherResult.speedLimitInfo.speed?.toDouble()
SpeedUnit.KILOMETERS_PER_HOUR ->
locationMatcherResult.speedLimitInfo.speed?.toDouble()?.kmphToMph()
SpeedUnit.METERS_PER_SECOND ->
locationMatcherResult.speedLimitInfo.speed?.toDouble()?.mtpsToMph()
}
speedLimitWidget?.update(
speedLimit = speedLimit?.roundToInt(),
speed = locationMatcherResult.enhancedLocation.speed
?.mtpsToMph()
?.roundToInt()
?: 0,
signFormat = signFormat,
threshold = threshold,
)
}
UnitType.METRIC -> {
val speedLimit = when (locationMatcherResult.speedLimitInfo.unit) {
SpeedUnit.MILES_PER_HOUR ->
locationMatcherResult.speedLimitInfo.speed?.toDouble()?.mphToKmph()
SpeedUnit.KILOMETERS_PER_HOUR ->
locationMatcherResult.speedLimitInfo.speed?.toDouble()
SpeedUnit.METERS_PER_SECOND ->
locationMatcherResult.speedLimitInfo.speed?.toDouble()?.mtpsToKmph()
}?.roundToInt()
speedLimitWidget?.update(
speedLimit = speedLimit,
speed = locationMatcherResult.enhancedLocation.speed
?.mtpsToKmph()
?.roundToInt()
?: 0,
signFormat = signFormat,
threshold = threshold,
)
}
}
}
override fun onAttached(mapboxCarMapSurface: MapboxCarMapSurface) {
logAndroidAuto("CarSpeedLimitRenderer carMapSurface loaded")
val signFormat = options.speedLimitOptions.value.forcedSignFormat
?: SpeedLimitSign.MUTCD
val speedLimitWidget = services.speedLimitWidget(signFormat).also { speedLimitWidget = it }
mapboxCarMapSurface.mapSurface.addWidget(speedLimitWidget)
MapboxNavigationApp.registerObserver(navigationObserver)
scope = MainScope()
options.speedLimitOptions
.onEach { speedLimitWidget.update(it.forcedSignFormat, it.warningThreshold) }
.launchIn(scope)
}
override fun onDetached(mapboxCarMapSurface: MapboxCarMapSurface) {
logAndroidAuto("CarSpeedLimitRenderer carMapSurface detached")
MapboxNavigationApp.unregisterObserver(navigationObserver)
speedLimitWidget?.let { mapboxCarMapSurface.mapSurface.removeWidget(it) }
speedLimitWidget = null
scope.cancel()
}
override fun onVisibleAreaChanged(visibleArea: Rect, edgeInsets: EdgeInsets) {
val currentPosition = speedLimitWidget?.getPosition() ?: return
speedLimitWidget?.setPosition(
currentPosition.toBuilder()
.apply {
offsetX = -SpeedLimitWidget.MARGIN_X - edgeInsets.right.toFloat()
offsetY = -SpeedLimitWidget.MARGIN_Y - edgeInsets.bottom.toFloat()
}.build(),
)
}
private companion object {
/**
* Convert meters per second to kilometers per hour.
*/
private fun Double.mtpsToKmph(): Double = this * 3.6
/**
* Convert meters per second to miles per hour.
*/
private fun Double.mtpsToMph(): Double = this * 2.23694
/**
* Convert kilometers per hour to miles per hour.
*/
private fun Double.kmphToMph(): Double = this / 1.60934
/**
* Convert miles per hour to kilometers per hour.
*/
private fun Double.mphToKmph(): Double = this * 1.60934
}
}
| 508
|
Kotlin
|
318
| 621
|
88163ae3d7e34948369d6945d5b78a72bdd68d7c
| 7,528
|
mapbox-navigation-android
|
Apache License 2.0
|
app/src/main/java/com/github/ferum_bot/bookreuse/ui/activity/CreatingNewStuffActivity.kt
|
Ferum-bot
| 337,029,384
| false
| null |
package com.github.ferum_bot.bookreuse.ui.activity
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.github.ferum_bot.bookreuse.R
/**
* Created by <NAME>.
* Date: 25.02.2021
* Time: 23:28
* Project: BookReuse
*/
class CreatingNewStuffActivity: AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_creating_new_stuff)
}
}
| 0
|
Kotlin
|
0
| 0
|
cd3344d5f4d971595f99eb519ed3859df0325f6a
| 476
|
BookReuse
|
Apache License 2.0
|
health-services/PassiveDataCompose/app/src/main/java/com/example/passivedatacompose/presentation/HeartRateCard.kt
|
android
| 368,660,859
| false
|
{"Kotlin": 597723}
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.passivedatacompose.presentation
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
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.stringResource
import androidx.compose.ui.tooling.preview.Devices
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Card
import androidx.wear.compose.material.Icon
import androidx.wear.compose.material.MaterialTheme
import androidx.wear.compose.material.Text
import com.example.passivedatacompose.R
import com.example.passivedatacompose.theme.PassiveDataTheme
import kotlin.math.roundToInt
/**
* Displays a heart rate value with icon and label.
*/
@Composable
fun HeartRateCard(
heartRate: Double,
modifier: Modifier = Modifier
) {
Card(
onClick = {},
enabled = false,
modifier = modifier
) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = modifier
) {
Icon(
imageVector = Icons.Default.Favorite,
contentDescription = stringResource(R.string.heart_description),
tint = Color.Red,
modifier = Modifier.padding(end = 8.dp)
)
Column {
val hrText = if (heartRate.isNaN()) "--" else heartRate.roundToInt().toString()
Text(hrText)
Text(
text = stringResource(id = R.string.last_measured),
style = MaterialTheme.typography.caption3
)
}
}
}
}
@Preview(
device = Devices.WEAR_OS_SMALL_ROUND,
showSystemUi = true
)
@Composable
fun HeartRateCardPreview() {
PassiveDataTheme {
HeartRateCard(122.2)
}
}
| 25
|
Kotlin
|
147
| 262
|
74624d210086d1198953b089688794704254304e
| 2,719
|
health-samples
|
Apache License 2.0
|
Section 3/SelectCategoriesActivity.kt
|
PacktPublishing
| 187,827,530
| false
| null |
package com.markodevcic.newsreader.categories
import android.app.Activity
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import com.markodevcic.newsreader.R
import com.markodevcic.newsreader.injection.Injector
import kotlinx.android.synthetic.main.layout_categories.*
import javax.inject.Inject
class SelectCategoriesActivity: BaseCategoriesActivity(), SelectCategoriesView {
override val categoriesViewGroup: ViewGroup
get() = categoriesHost
@Inject
override lateinit var presenter: SelectCategoriesPresenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_select_categories)
Injector.appComponent.inject(this)
setSupportActionBar(toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
chooseCategoriesText.text = getString(R.string.available_categories)
presenter.bind(this)
fillCategories()
downloadBtn.visibility = View.GONE
presenter.onStartCategorySelect()
}
override fun onBackPressed() {
setResult(Activity.RESULT_OK)
super.onBackPressed()
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == android.R.id.home) {
onBackPressed()
return true
}
return super.onOptionsItemSelected(item)
}
}
| 0
|
Kotlin
|
2
| 7
|
c7e5ab27b6747915fdeb03c925ba0582a3caa693
| 1,319
|
Kotlin-in-Practice
|
MIT License
|
src/main/kotlin/com.highthunder.kotlr/types/Colors.kt
|
Emamatcyber90
| 189,778,198
| true
|
{"Kotlin": 500099}
|
package com.highthunder.kotlr.types
import com.squareup.moshi.JsonClass
/**
* Colors - TODO: Documentation
*
* TODO: Figure out how to use an adapter to back this with an array.
* @author highthunder
* @since 10/27/18
* @version 1.0.0
*/
@JsonClass(generateAdapter = true)
data class Colors(
var c0: String? = null,
var c1: String? = null,
var c2: String? = null,
var c3: String? = null,
var c4: String? = null,
var c5: String? = null,
var c6: String? = null,
var c7: String? = null,
var c8: String? = null,
var c9: String? = null
)
| 0
|
Kotlin
|
0
| 0
|
5d7a671ac9fe68f061a52d19bf0ff7ef8e3dc7c8
| 622
|
kotlr
|
MIT License
|
app/src/main/java/com/architectcoders/aacboard/ui/activities/MainNavHostActivity.kt
|
fesave
| 616,599,477
| false
| null |
package com.architectcoders.aacboard.ui.activities
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.setupWithNavController
import com.architectcoders.aacboard.R
import com.architectcoders.aacboard.databinding.ActivityMainNavHostBinding
class MainNavHostActivity : AppCompatActivity() {
private val binding by lazy {
ActivityMainNavHostBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
initView()
}
private fun initView() {
setSupportActionBar(binding.toolbar)
val navController = (
supportFragmentManager.findFragmentById(R.id.nav_host_fragment)
as NavHostFragment
).navController
val config = AppBarConfiguration(navController.graph)
binding.toolbar.setupWithNavController(navController, config)
}
}
| 7
|
Kotlin
|
0
| 0
|
e76c7eb9e9ae08e85ab6daa5126707eda6b747be
| 1,090
|
AAC-Board
|
Apache License 2.0
|
lib/src/main/kotlin/com/vinaysshenoy/oklognet/db/NetLogDao.kt
|
vinaysshenoy
| 117,660,281
| false
| null |
package com.vinaysshenoy.oklognet.db
import android.arch.persistence.room.Dao
import android.arch.persistence.room.Insert
import android.arch.persistence.room.OnConflictStrategy
import android.arch.persistence.room.Query
/**
* Created by vinaysshenoy on 16/01/18.
*/
@Dao
internal interface NetLogDao {
@Insert(onConflict = OnConflictStrategy.ABORT)
fun put(netLog: NetLogEntity): Long
@Query("SELECT * FROM `NetLogs`")
fun getAll(): List<NetLogEntity>
}
| 0
|
Kotlin
|
0
| 0
|
4d4f57a060adf89fc071ac5df546ebee89e79f37
| 476
|
OkLogNet
|
Apache License 2.0
|
core/utils/src/main/java/com/griffin/core/utils/mmkv/BaseMV.kt
|
Chen-Xi-g
| 769,860,561
| false
|
{"Kotlin": 241849}
|
package com.griffin.core.utils.mmkv
/**
* 持久化数据
*/
object BaseMV {
object System: Delegates(){
override fun zoneId(): String {
return "system"
}
/**
* 是否第一次启动
*/
var isFirst by boolean(true)
}
object User: Delegates(){
override fun zoneId(): String {
return "user"
}
/**
* Token
*/
var token by string()
}
}
| 0
|
Kotlin
|
0
| 1
|
ab3507211daafe8c117bac67d6eedf03473821d4
| 456
|
VerveLedger
|
MIT License
|
app/src/main/java/dev/dai/bloom/data/PlantTheme.kt
|
Dai1678
| 347,076,603
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.dai.bloom.data
import androidx.annotation.DrawableRes
import dev.dai.bloom.R
data class PlantTheme(
@DrawableRes val imageResId: Int,
val name: String
)
val plantThemeList = listOf(
PlantTheme(R.drawable.desert_chic, "Desert chic"),
PlantTheme(R.drawable.tiny_terrariums, "Tiny terrariums"),
PlantTheme(R.drawable.jungle_vibes, "Jungle vibes"),
PlantTheme(R.drawable.easy_care, "Easy care"),
PlantTheme(R.drawable.statements, "Statements")
)
| 0
|
Kotlin
|
0
| 0
|
da7bad378623fd2c0aca689488d4c6df7f87ff0a
| 1,101
|
Bloom
|
Apache License 2.0
|
src/main/kotlin/com/myapp/repository/RelatedUserRepositoryImpl.kt
|
springboot-angular2-tutorial
| 46,042,914
| false
| null |
package com.myapp.repository
import com.myapp.domain.RelatedUser
import com.myapp.domain.UserStats
import com.myapp.dto.request.PageParams
import com.myapp.generated.tables.Relationship.RELATIONSHIP
import com.myapp.generated.tables.User.USER
import com.myapp.generated.tables.UserStats.USER_STATS
import org.jooq.DSLContext
import org.jooq.Record
import org.springframework.stereotype.Repository
import com.myapp.generated.tables.User as UserTable
@Repository
class RelatedUserRepositoryImpl(
private val dsl: DSLContext
) : RelatedUserRepository, Pager {
override fun findFollowers(userId: Long, pageParams: PageParams): List<RelatedUser> {
return dsl.select()
.from(USER)
.join(RELATIONSHIP)
.on(USER.ID.eq(RELATIONSHIP.FOLLOWER_ID))
.join(USER_STATS)
.on(USER.ID.eq(USER_STATS.USER_ID))
.where(RELATIONSHIP.FOLLOWED_ID.eq(userId))
.and(pageParams.toCondition(RELATIONSHIP.ID))
.orderBy(RELATIONSHIP.ID.desc())
.limit(pageParams.count)
.fetch(mapper())
}
override fun findFollowings(userId: Long, pageParams: PageParams): List<RelatedUser> {
return dsl.select()
.from(USER)
.join(RELATIONSHIP)
.on(USER.ID.eq(RELATIONSHIP.FOLLOWED_ID))
.join(USER_STATS)
.on(USER.ID.eq(USER_STATS.USER_ID))
.where(RELATIONSHIP.FOLLOWER_ID.eq(userId))
.and(pageParams.toCondition(RELATIONSHIP.ID))
.orderBy(RELATIONSHIP.ID.desc())
.limit(pageParams.count)
.fetch(mapper())
}
private fun mapper() = { r: Record ->
val userRecord = r.into(USER)
val relationshipRecord = r.into(RELATIONSHIP)
val userStatsRecord = r.into(USER_STATS)
RelatedUser(
_id = userRecord.id,
username = userRecord.username,
name = userRecord.name,
relationshipId = relationshipRecord.id,
userStats = UserStats(userStatsRecord)
)
}
}
| 2
|
Kotlin
|
46
| 115
|
c6daf1df3dcb06813bbeb9096e5a5672c58481a7
| 2,079
|
boot-app
|
MIT License
|
app/src/main/java/com/app/lingcompanion/ui/home/HomeFragment.kt
|
nuochka
| 772,680,081
| false
|
{"Kotlin": 82244}
|
package com.app.lingcompanion.ui.home
import android.content.Context
import android.content.SharedPreferences
import android.graphics.Color
import android.os.AsyncTask
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.fragment.app.Fragment
import com.app.lingcompanion.R
import com.app.lingcompanion.databinding.FragmentHomeBinding
import org.json.JSONArray
import org.json.JSONException
import okhttp3.OkHttpClient
import okhttp3.Request
import java.text.SimpleDateFormat
import java.util.*
import java.util.concurrent.TimeUnit
class HomeFragment : Fragment() {
private var _binding: FragmentHomeBinding? = null
private val binding get() = _binding!!
private lateinit var sharedPreferences: SharedPreferences
private lateinit var wordTextView: TextView
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentHomeBinding.inflate(inflater, container, false)
val root: View = binding.root
wordTextView = binding.wordTextView
sharedPreferences = requireActivity().getSharedPreferences("WordFetch", Context.MODE_PRIVATE)
fetchRandomWordIfNeeded()
val squares = arrayOf(
binding.square1, // Monday
binding.square2, // Tuesday
binding.square3, // Wednesday
binding.square4, // Thursday
binding.square5, // Friday
binding.square6, // Saturday
binding.square7 // Sunday
)
val currentDate = Calendar.getInstance().apply {
time = Date()
}
val dayOfWeek = currentDate.get(Calendar.DAY_OF_WEEK)
val coloredSquareIndex = (dayOfWeek + 5) % 7 // Monday is the first day in the week.
val sdf = SimpleDateFormat("yyyyMMdd", Locale.getDefault())
val formattedDate = sdf.format(currentDate.time)
val squaresSharedPreferences = requireActivity().getSharedPreferences("Squares", Context.MODE_PRIVATE)
val userStreakTextView: TextView = root.findViewById(R.id.user_streak)
// Getting the current streak count
var streakCount = squaresSharedPreferences.getInt("StreakCount", 0)
//Clear data from Shared Preferences
// squaresSharedPreferences.edit().clear().apply()
for ((index, square) in squares.withIndex()) {
val isSquareColored = squaresSharedPreferences.getBoolean("streak-$index", false)
if (isSquareColored) {
square.setBackgroundColor(Color.rgb(57, 54, 145))
} else {
square.setBackgroundColor(Color.rgb(188, 185, 240))
}
}
val button: Button = root.findViewById(R.id.btn_streak)
button.setOnClickListener {
if (squaresSharedPreferences.getBoolean("streak-$coloredSquareIndex", false)) {
Toast.makeText(requireContext(), "You have already marked your progress", Toast.LENGTH_SHORT).show()
} else {
squares[coloredSquareIndex].setBackgroundColor(Color.rgb(57, 54, 145))
if (!squaresSharedPreferences.getBoolean("streak-$coloredSquareIndex", false)) {
streakCount++
}
with(squaresSharedPreferences.edit()) {
putBoolean("streak-$coloredSquareIndex", true)
putInt("StreakCount", streakCount)
apply()
}
userStreakTextView.text = "Your streak: $streakCount days"
Toast.makeText(requireContext(), "Your today's streak was saved", Toast.LENGTH_SHORT).show()
}
}
userStreakTextView.text = "Your streak: $streakCount days"
return root
}
//Getting a random word from a list
private fun fetchRandomWordIfNeeded() {
val lastFetchTime = sharedPreferences.getLong("lastFetchTime", 0)
val currentTime = System.currentTimeMillis()
// Check if 24 hours has passed since the last fetch (temporary change)
if (currentTime - lastFetchTime > TimeUnit.HOURS.toMillis(24)) {
val englishWordsArray = resources.getStringArray(R.array.english_words)
val randomWord = getRandomWord(englishWordsArray)
val apiUrl = "https://api.dictionaryapi.dev/api/v2/entries/en/$randomWord"
DictionaryApiTask().execute(apiUrl)
} else {
// Load saved data
val savedDefinition = sharedPreferences.getString("definition", "Definition not found")
val savedExample = sharedPreferences.getString("example", "Example not found")
wordTextView.text = "$savedDefinition\n$savedExample"
}
}
private fun getRandomWord(wordsArray: Array<String>): String {
val random = Random()
return wordsArray[random.nextInt(wordsArray.size)]
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
//The word of the day
inner class DictionaryApiTask : AsyncTask<String, Void, Pair<String, String>>() {
override fun doInBackground(vararg params: String?): Pair<String, String>? {
val apiUrl = params[0]
apiUrl?.let {
val client = OkHttpClient()
val request = Request.Builder()
.url(apiUrl)
.build()
val response = client.newCall(request).execute()
val responseData = response.body?.string()
responseData?.let {
val jsonArray = JSONArray(it)
if (jsonArray.length() > 0) {
val firstItem = jsonArray.getJSONObject(0)
val word = firstItem.optString("word", "Word not found")
val phonetic = firstItem.optString("phonetic", "Phonetic not found")
val meaningsArray = firstItem.optJSONArray("meanings")
val definitionsArray = meaningsArray?.optJSONObject(0)?.optJSONArray("definitions")
val definition = definitionsArray?.optJSONObject(0)?.optString("definition", "Definition not found")
val example = findExample(jsonArray)
return Pair("$word\n$phonetic\n\n- $definition", example)
}
}
}
return null
}
override fun onPostExecute(result: Pair<String, String>?) {
super.onPostExecute(result)
result?.let { (displayText, example) ->
wordTextView.text = "$displayText\n$example"
// Save the results to SharedPreferences
saveResultsToStorage(displayText, example)
} ?: run {
wordTextView.text = "No data received from API"
}
}
private fun saveResultsToStorage(definition: String, example: String) {
sharedPreferences.edit().apply {
putString("definition", definition)
putString("example", example)
putLong("lastFetchTime", System.currentTimeMillis())
apply()
}
}
//Function for finding an example in API
private fun findExample(jsonArray: JSONArray): String {
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
val meaningsArray = jsonObject.getJSONArray("meanings")
for (j in 0 until meaningsArray.length()) {
val meaningObject = meaningsArray.getJSONObject(j)
val definitionsArray = meaningObject.getJSONArray("definitions")
for (k in 0 until definitionsArray.length()) {
val definitionObject = definitionsArray.getJSONObject(k)
if (definitionObject.has("example")) {
return definitionObject.getString("example")
}
}
}
}
return "Example not found"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
ff8039911342124583cf8cd76215822766fe696e
| 8,382
|
LingCompanion
|
Apache License 2.0
|
app/src/main/java/com/ingoox/clicktochat/MainActivity.kt
|
pabloks97
| 368,352,351
| false
|
{"Kotlin": 10888}
|
package com.ingoox.clicktochat
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.animation.animateContentSize
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Clear
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.core.content.ContextCompat.startActivity
import com.ingoox.clicktochat.ui.theme.OpenChatTheme
import java.net.URLEncoder
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
OpenChatTheme {
// A surface container using the 'background' color from the theme
Surface(color = MaterialTheme.colors.background) {
App()
}
}
}
}
}
@Composable
fun App() {
val context = LocalContext.current
var phone by rememberSaveable { mutableStateOf("") }
var message by rememberSaveable { mutableStateOf("") }
var link by rememberSaveable { mutableStateOf("") }
fun onPhoneChange(value: String) {
phone = value
link = createLink(phone, message)
}
fun onMessageChange(value: String) {
message = value
link = createLink(phone, message)
}
fun clearPhoneHandler() {
phone = ""
link = createLink(phone, message)
}
fun clearMessageHandler() {
message = ""
link = createLink(phone, message)
}
Content(
phone = phone,
message = message,
link = link,
onPhoneChange = { onPhoneChange(it) },
onMessageChange = { onMessageChange(it) },
openChatHandler = { openLink(link, context) },
shareLinkHandler = { shareLink(link, context) },
clearMessageHandler = { clearMessageHandler() },
clearPhoneHandler = { clearPhoneHandler() }
)
}
@Composable
fun Content(
phone: String,
message: String,
link: String,
onPhoneChange: (String) -> Unit,
onMessageChange: (String) -> Unit,
openChatHandler: () -> Unit,
shareLinkHandler: () -> Unit,
clearMessageHandler: () -> Unit,
clearPhoneHandler: () -> Unit
) {
Column(
modifier = Modifier
.fillMaxHeight()
.padding(16.dp),
verticalArrangement = Arrangement.Center
) {
val focusRequester = FocusRequester()
Card(
modifier = Modifier.fillMaxWidth(),
elevation = 1.dp
) {
Column {
Text(
text = stringResource(R.string.card_title),
fontWeight = FontWeight.Medium,
modifier = Modifier.padding(16.dp, 16.dp, 16.dp, 0.dp)
)
Text(
text = link,
modifier = Modifier
.padding(16.dp, 8.dp, 16.dp, 8.dp)
.animateContentSize(),
maxLines = 5,
overflow = TextOverflow.Ellipsis
)
}
}
Spacer(Modifier.size(16.dp))
OutlinedTextField(
modifier = Modifier.fillMaxWidth(),
value = phone,
onValueChange = { onPhoneChange(it) },
label = { Text(stringResource(R.string.phone_label)) },
trailingIcon = {
if (phone.isNotEmpty()) {
ClearTextIcon(
onClick = { clearPhoneHandler() },
contentDescription = stringResource(R.string.clear_phone_description)
)
}
},
singleLine = true,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Phone,
imeAction = ImeAction.Next
),
keyboardActions = KeyboardActions(
onNext = { focusRequester.requestFocus() }
)
)
OutlinedTextField(
modifier = Modifier
.fillMaxWidth()
.focusRequester(focusRequester),
value = message,
onValueChange = { onMessageChange(it) },
label = { Text(stringResource(R.string.message_label)) },
trailingIcon = {
if (message.isNotEmpty()) {
ClearTextIcon(
onClick = { clearMessageHandler() },
contentDescription = stringResource(R.string.clear_message_description)
)
}
},
maxLines = 6
)
Spacer(Modifier.size(16.dp))
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.End
) {
OutlinedButton(onClick = { shareLinkHandler() }) {
Text(stringResource(R.string.share_link_button))
}
Spacer(Modifier.size(8.dp))
Button(onClick = { openChatHandler() }) {
Text(stringResource(R.string.open_chat_button))
}
}
}
}
@Composable
fun ClearTextIcon(
onClick: () -> Unit,
enabled: Boolean = true,
contentDescription: String = "Clear text"
) {
IconButton(
onClick = { onClick() },
enabled = enabled
) {
Icon(
imageVector = Icons.Rounded.Clear,
contentDescription = contentDescription
)
}
}
fun createLink(phone: String, message: String): String {
val phoneDigits = phone.filter { it.isDigit() }
if (phoneDigits.isBlank() and message.isBlank()) return ""
var link = "https://wa.me/"
if (phoneDigits.isNotBlank()) {
link += phoneDigits
}
if (message.isNotBlank()) {
val encodedMessage = URLEncoder.encode(message, "UTF-8")
link += "?text=$encodedMessage"
}
return link
}
fun openLink(link: String, context: Context) {
if (link.isNotBlank()) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(link))
startActivity(context, intent, null)
}
}
fun shareLink(link: String, context: Context) {
if (link.isNotBlank()) {
val intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, link)
type = "text/plain"
}
val chooserIntent = Intent.createChooser(intent, "")
startActivity(context, chooserIntent, null)
}
}
| 0
|
Kotlin
|
0
| 1
|
5316b6229226738f71e501824d823af5a1d5250a
| 7,456
|
click-to-chat
|
MIT License
|
HorizontalCalendarX/src/main/java/io/github/binishmanandhar23/horizontalcalendarx/utils/SnapToBlock.kt
|
binishmanandhar23
| 370,451,127
| false
| null |
package io.github.binishmanandhar23.horizontalcalendarx.utils
import android.util.DisplayMetrics
import android.util.Log
import android.view.View
import android.view.animation.Interpolator
import android.widget.Scroller
import androidx.core.view.ViewCompat
import androidx.recyclerview.widget.*
import kotlin.math.abs
import kotlin.math.max
import kotlin.math.roundToInt
/**@param maxFlingBlocks Maxim blocks to move during most vigorous fling*/
class SnapToBlock constructor(private val maxFlingBlocks: Int) : SnapHelper() {
private var recyclerView: RecyclerView? = null
// Total number of items in a block of view in the RecyclerView
private var blocksize: Int = 0
// Maximum number of positions to move on a fling.
private var maxPositionsToMove: Int = 0
// Width of a RecyclerView item if orientation is horizonal; height of the item if vertical
private var itemDimension: Int = 0
//Average Width of each items in RecyclerView
private var itemDimensionAverage: Int = 0
// Callback interface when blocks are snapped.
private var snapBlockCallback: SnapBlockCallback? = null
// When snapping, used to determine direction of snap.
private var priorFirstPosition = RecyclerView.NO_POSITION
// Our private scroller
private var scroller: Scroller? = null
// Horizontal/vertical layout helper
private var orientationHelper: OrientationHelper? = null
// LTR/RTL helper
private var layoutDirectionHelper: LayoutDirectionHelper? = null
@Throws(IllegalStateException::class)
override fun attachToRecyclerView(recyclerView: RecyclerView?) {
if (recyclerView != null) {
this.recyclerView = recyclerView
val layoutManager = recyclerView.layoutManager as LinearLayoutManager
orientationHelper = when {
layoutManager.canScrollHorizontally() -> OrientationHelper.createHorizontalHelper(layoutManager)
layoutManager.canScrollVertically() -> OrientationHelper.createVerticalHelper(layoutManager)
else -> throw IllegalStateException("RecyclerView must be scrollable")
}
scroller = Scroller(this.recyclerView!!.context, sInterpolator)
initItemDimensionIfNeeded(layoutManager)
}
super.attachToRecyclerView(recyclerView)
}
// Called when the target view is available and we need to know how much more
// to scroll to get it lined up with the side of the RecyclerView.
override fun calculateDistanceToFinalSnap(layoutManager: RecyclerView.LayoutManager, targetView: android.view.View): IntArray? {
val out = IntArray(2)
initLayoutDirectionHelperIfNeeded(layoutManager)
if (layoutManager.canScrollHorizontally())
out[0] = layoutDirectionHelper!!.getScrollToAlignView(targetView)
if (layoutManager.canScrollVertically())
out[1] = layoutDirectionHelper!!.getScrollToAlignView(targetView)
if (snapBlockCallback != null)
if (out[0] == 0 && out[1] == 0)
snapBlockCallback!!.onBlockSnapped(layoutManager.getPosition(targetView))
else
snapBlockCallback!!.onBlockSnap(layoutManager.getPosition(targetView))
return out
}
private fun initLayoutDirectionHelperIfNeeded(layoutManager: RecyclerView.LayoutManager) {
if (layoutDirectionHelper == null)
if (layoutManager.canScrollHorizontally())
layoutDirectionHelper = LayoutDirectionHelper()
else if (layoutManager.canScrollVertically())
// RTL doesn't matter for vertical scrolling for this class.
layoutDirectionHelper = LayoutDirectionHelper(false)
}
// We are flinging and need to know where we are heading.
override fun findTargetSnapPosition(layoutManager: RecyclerView.LayoutManager, velocityX: Int, velocityY: Int): Int {
initLayoutDirectionHelperIfNeeded(layoutManager)
val lm = layoutManager as LinearLayoutManager
initItemDimensionIfNeeded(layoutManager)
scroller!!.fling(0, 0, velocityX, velocityY, Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE)
return when {
velocityX != 0 -> layoutDirectionHelper!!.getPositionsToMove(lm, scroller!!.finalX, itemDimension)
else -> if (velocityY != 0)
layoutDirectionHelper!!.getPositionsToMove(lm, scroller!!.finalY, itemDimension)
else RecyclerView.NO_POSITION
}
}
// We have scrolled to the neighborhood where we will snap. Determine the snap position.
override fun findSnapView(layoutManager: RecyclerView.LayoutManager): android.view.View? {
// Snap to a view that is either 1) toward the bottom of the data and therefore on screen,
// or, 2) toward the top of the data and may be off-screen.
val snapPos = calcTargetPosition(layoutManager as LinearLayoutManager)
val snapView = if (snapPos == RecyclerView.NO_POSITION)
null
else
layoutManager.findViewByPosition(snapPos)
if (snapView == null)
Log.d(TAG, "<<<<findSnapView is returning null!")
Log.d(TAG, "<<<<findSnapView snapos=" + snapPos)
return snapView
}
// Does the heavy lifting for findSnapView.
private fun calcTargetPosition(layoutManager: LinearLayoutManager): Int {
val snapPos: Int
initLayoutDirectionHelperIfNeeded(layoutManager)
initItemDimensionIfNeeded(layoutManager)
val firstVisiblePos = layoutManager.findFirstVisibleItemPosition()
if (firstVisiblePos == RecyclerView.NO_POSITION)
return RecyclerView.NO_POSITION
if (firstVisiblePos >= priorFirstPosition) {
// Scrolling toward bottom of data
val firstCompletePosition = layoutManager.findFirstCompletelyVisibleItemPosition()
snapPos = if (firstCompletePosition != RecyclerView.NO_POSITION && firstCompletePosition % blocksize == 0)
firstCompletePosition
else
roundDownToBlockSize(firstVisiblePos + blocksize)
} else {
// Scrolling toward top of data
snapPos = roundDownToBlockSize(firstVisiblePos)
// Check to see if target view exists. If it doesn't, force a smooth scroll.
// SnapHelper only snaps to existing views and will not scroll to a non-existant one.
// If limiting fling to single block, then the following is not needed since the
// views are likely to be in the RecyclerView pool.
if (layoutManager.findViewByPosition(snapPos) == null) {
val toScroll = layoutDirectionHelper!!.calculateDistanceToScroll(layoutManager, snapPos)
Log.i("BlockSize","FirstVisiblePos: $firstVisiblePos PriorFirstPos: $priorFirstPosition SnapPos: $snapPos ToScrollX: ${toScroll[0]}")
recyclerView!!.smoothScrollBy(toScroll[0], toScroll[1], sInterpolator)
}
}
priorFirstPosition = firstVisiblePos
return snapPos
}
private fun initItemDimensionIfNeeded(layoutManager: RecyclerView.LayoutManager) {
if (itemDimension != 0)
return
val child = layoutManager.getChildAt(0) ?: return
if (layoutManager.canScrollHorizontally()) {
itemDimension = child.width
val size =
(getSpanCount(layoutManager) * (recyclerView!!.width.toDouble() / itemDimension.toDouble())).roundToInt()
blocksize = size
} else if (layoutManager.canScrollVertically()) {
itemDimension = child.height
val size =
(getSpanCount(layoutManager) * (recyclerView!!.width.toDouble() / itemDimension.toDouble())).roundToInt()
blocksize = size
}
maxPositionsToMove = blocksize * maxFlingBlocks
}
private fun getSpanCount(layoutManager: RecyclerView.LayoutManager): Int = (layoutManager as? GridLayoutManager)?.spanCount ?: 1
private fun roundDownToBlockSize(trialPosition: Int): Int = trialPosition - trialPosition % blocksize
private fun roundUpToBlockSize(trialPosition: Int): Int = roundDownToBlockSize(trialPosition + blocksize - 1)
override fun createScroller(layoutManager: RecyclerView.LayoutManager): LinearSmoothScroller? {
return if (layoutManager !is RecyclerView.SmoothScroller.ScrollVectorProvider)
null
else object : LinearSmoothScroller(recyclerView!!.context) {
override fun onTargetFound(
targetView: View,
state: RecyclerView.State,
action: Action
) {
val snapDistances = calculateDistanceToFinalSnap(recyclerView!!.layoutManager!!, targetView)
val dx = snapDistances!![0]
val dy = snapDistances[1]
val time = calculateTimeForDeceleration(max(abs(dx), abs(dy)))
if (time > 0)
action.update(dx, dy, time, sInterpolator)
}
override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float = MILLISECONDS_PER_INCH / displayMetrics.densityDpi
}
}
fun setSnapBlockCallback(callback: SnapBlockCallback?) {
snapBlockCallback = callback
}
/*
Helper class that handles calculations for LTR and RTL layouts.
*/
private inner class LayoutDirectionHelper {
// Is the layout an RTL one?
private val mIsRTL: Boolean
constructor() {
mIsRTL = ViewCompat.getLayoutDirection(recyclerView as View) == ViewCompat.LAYOUT_DIRECTION_RTL
}
constructor(isRTL: Boolean) {
mIsRTL = isRTL
}
/*
Calculate the amount of scroll needed to align the target view with the layout edge.
*/
fun getScrollToAlignView(targetView: android.view.View): Int = if (mIsRTL)
orientationHelper!!.getDecoratedEnd(targetView) - recyclerView!!.width
else
orientationHelper!!.getDecoratedStart(targetView)
/**
* Calculate the distance to final snap position when the view corresponding to the snap
* position is not currently available.
*
* @param layoutManager LinearLayoutManager or descendent class
* @param targetPos - Adapter position to snap to
* @return int[2] {x-distance in pixels, y-distance in pixels}
*/
fun calculateDistanceToScroll(layoutManager: LinearLayoutManager, targetPos: Int): IntArray {
val out = IntArray(2)
val firstVisiblePos = layoutManager.findFirstVisibleItemPosition()
if (layoutManager.canScrollHorizontally()) {
if (targetPos <= firstVisiblePos) // scrolling toward top of data
if (mIsRTL) {
val lastView = layoutManager.findViewByPosition(layoutManager.findLastVisibleItemPosition())
out[0] = orientationHelper!!.getDecoratedEnd(lastView) + (firstVisiblePos - targetPos) * itemDimensionAverage
} else {
val firstView = layoutManager.findViewByPosition(firstVisiblePos)
out[0] = orientationHelper!!.getDecoratedStart(firstView) - (firstVisiblePos - targetPos) * itemDimensionAverage
}
}
if (layoutManager.canScrollVertically() && targetPos <= firstVisiblePos) { // scrolling toward top of data
val firstView = layoutManager.findViewByPosition(firstVisiblePos)
out[1] = firstView!!.top - (firstVisiblePos - targetPos) * itemDimension
}
return out
}
/*
Calculate the number of positions to move in the RecyclerView given a scroll amount
and the size of the items to be scrolled. Return integral multiple of mBlockSize not
equal to zero.
*/
fun getPositionsToMove(llm: LinearLayoutManager, scroll: Int, itemSize: Int): Int {
var positionsToMove: Int
positionsToMove = roundUpToBlockSize(Math.abs(scroll) / itemSize)
if (positionsToMove < blocksize)
// Must move at least one block
positionsToMove = blocksize
else if (positionsToMove > maxPositionsToMove)
// Clamp number of positions to move so we don't get wild flinging.
positionsToMove = maxPositionsToMove
if (scroll < 0)
positionsToMove *= -1
if (mIsRTL)
positionsToMove *= -1
return if (layoutDirectionHelper!!.isDirectionToBottom(scroll < 0)) {
// Scrolling toward the bottom of data.
roundDownToBlockSize(llm.findFirstVisibleItemPosition()) + positionsToMove
} else roundDownToBlockSize(llm.findLastVisibleItemPosition()) + positionsToMove
// Scrolling toward the top of the data.
}
fun isDirectionToBottom(velocityNegative: Boolean): Boolean = if (mIsRTL) velocityNegative else !velocityNegative
}
fun itemDimensionAverage(average: Int){
itemDimensionAverage = average
}
interface SnapBlockCallback {
fun onBlockSnap(snapPosition: Int)
fun onBlockSnapped(snapPosition: Int)
}
companion object {
// Borrowed from ViewPager.java
private val sInterpolator = Interpolator { input ->
var t = input
// _o(t) = t * t * ((tension + 1) * t + tension)
// o(t) = _o(t - 1) + 1
t -= 1.0f
t * t * t + 1.0f
}
private val MILLISECONDS_PER_INCH = 100f
private val TAG = "SnapToBlock"
}
}
| 0
|
Kotlin
|
0
| 0
|
92a22c83a9da8bd8f43322390be986ebd82016fc
| 13,879
|
HorizontalCalendarX
|
Apache License 2.0
|
src/main/kotlin/core/component/physics/CircleCollisionBoxComponent.kt
|
nflsilva
| 521,306,727
| false
|
{"Kotlin": 72548, "GLSL": 3784}
|
package core.component.physics
import core.BaseEntity
import core.component.BaseComponent
import core.dto.UpdateContext
import physics.dto.CircleCollisionBox
import physics.dto.CollisionContext
import java.util.*
class CircleCollisionBoxComponent(entityId: UUID, private val centered: Boolean = true): BaseComponent(entityId) {
var collisions: List<CollisionContext> = mutableListOf()
init {
setUpdateObserver { entity: BaseEntity, context -> onUpdate(entity, context) }
}
private fun onUpdate(entity: BaseEntity, context: UpdateContext) {
context.physics.getCollisionsBox(entityId)?.let {
collisions = it
}
val radius = entity.transform.scale.x / 2f
val box = CircleCollisionBox(entity.transform.position, radius, entityId)
context.physics.addCollisionBox(box)
}
}
| 0
|
Kotlin
|
0
| 0
|
5047a234767efda80c0afec990bf27aec5b8effd
| 852
|
2DGT
|
MIT License
|
KotlinTest/app/src/test/java/com/example/kotlintest/SampleServiceForStringSpecTest.kt
|
sahara-ooga
| 217,847,767
| false
| null |
package com.example.kotlintest
import io.kotlintest.matchers.shouldBe
import io.kotlintest.specs.StringSpec
class SampleServiceForStringSpecTest: StringSpec() {
init {
val service = SampleService()
"executeでparamが1の場合oneが返る" {
service.execute(1) shouldBe "one"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
7ef68447df638bbd230bd298d6c3e456fbe4a203
| 315
|
Kotlin-Sample
|
MIT License
|
src/main/kotlin/com/davideagostini/di/MainModule.kt
|
davideagostini
| 433,145,293
| false
|
{"Kotlin": 37112}
|
package com.davideagostini.di
import com.davideagostini.data.repository.category.CategoryRepository
import com.davideagostini.data.repository.category.CategoryRepositoryImpl
import com.davideagostini.data.repository.note.NoteRepository
import com.davideagostini.data.repository.note.NoteRepositoryImpl
import com.davideagostini.data.repository.user.UserRepository
import com.davideagostini.data.repository.user.UserRepositoryImpl
import com.davideagostini.data.util.Constants
import com.davideagostini.service.CategoryService
import com.davideagostini.service.NoteService
import com.davideagostini.service.UserService
import com.google.gson.Gson
import org.koin.dsl.module
import org.litote.kmongo.coroutine.coroutine
import org.litote.kmongo.reactivestreams.KMongo
val mainModule = module {
single {
val client = KMongo.createClient().coroutine
client.getDatabase(Constants.DATABASE_NAME)
}
single<UserRepository> {
UserRepositoryImpl(get())
}
single<CategoryRepository> {
CategoryRepositoryImpl(get())
}
single<NoteRepository> {
NoteRepositoryImpl(get())
}
single { UserService(get()) }
single { CategoryService(get()) }
single { NoteService(get()) }
single { Gson() }
}
| 0
|
Kotlin
|
0
| 3
|
f8a1eafcc796f4e0e442caccc41e3c33f7c38340
| 1,265
|
notyze
|
Apache License 2.0
|
app/src/main/java/com/solocatapps/mvvmproductlistapp/service/ProductApi.kt
|
abdurrahimkizilkaya
| 624,117,768
| false
| null |
package com.solocatapps.mvvmproductlistapp.service
import com.solocatapps.mvvmproductlistapp.model.ProductResponse
import com.solocatapps.mvvmproductlistapp.util.Constants.GET_ALL_PRODUCTS
import io.reactivex.rxjava3.core.Single
import retrofit2.http.GET
interface ProductApi {
@GET(GET_ALL_PRODUCTS)
fun getAllProducts() : Single<ProductResponse>
}
| 0
|
Kotlin
|
0
| 0
|
bd8ce0b4f02b6728cd6a82dc716af084c2957bc2
| 360
|
MVVM_Retrofit_RxJava_ProductApp
|
MIT License
|
androidApp/src/main/java/com/amsavarthan/note/android/screens/notesList/NotesListScreen.kt
|
amsavarthan
| 574,365,043
| false
|
{"Kotlin": 43830, "Swift": 10071}
|
package com.amsavarthan.note.android.screens.notesList
import android.annotation.SuppressLint
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import com.amsavarthan.note.android.R
import com.amsavarthan.note.android.screens.Screen
import com.amsavarthan.note.android.screens.components.NoteView
import com.amsavarthan.note.android.screens.components.SearchBar
@SuppressLint("UnusedMaterial3ScaffoldPaddingParameter")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NotesListScreen(
navController: NavController,
viewModel: NotesListViewModel = hiltViewModel()
) {
val state by viewModel.state.collectAsState()
LaunchedEffect(true) {
viewModel.getAllNotes()
}
Scaffold(
modifier = Modifier.imePadding(),
floatingActionButton = {
LargeFloatingActionButton(
onClick = { navController.navigate(Screen.toNoteDetailDirection()) }
) {
Icon(
imageVector = Icons.Default.Add,
contentDescription = stringResource(id = R.string.add)
)
}
},
floatingActionButtonPosition = FabPosition.Center,
containerColor = MaterialTheme.colorScheme.surface
) {
Box {
LazyColumn(
contentPadding = PaddingValues(top = 24.dp, bottom = 160.dp)
) {
item {
SearchBar(
modifier = Modifier.statusBarsPadding(),
value = state.searchQuery,
onChange = viewModel::onSearch,
onClear = viewModel::onSearch
)
}
items(state.notes, key = { note -> note.id!! }) { note ->
NoteView(note = note) { id ->
navController.navigate(Screen.toNoteDetailDirection(id))
}
}
}
if (state.notes.isEmpty()) {
Column(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(
6.dp,
Alignment.CenterVertically
),
horizontalAlignment = Alignment.CenterHorizontally
) {
val title = if (state.searchQuery.isNotBlank())
stringResource(id = R.string.no_results_placeholder_title)
else
stringResource(id = R.string.placeholder_title)
val content = if (state.searchQuery.isNotBlank())
stringResource(id = R.string.no_results_placeholder_content)
.format(state.searchQuery)
else
stringResource(id = R.string.placeholder_content)
Text(
text = title,
style = MaterialTheme.typography.titleLarge,
color = MaterialTheme.colorScheme.onSurface,
)
Text(
text = content,
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.7f),
textAlign = TextAlign.Center
)
}
}
}
}
}
| 0
|
Kotlin
|
1
| 3
|
7cdcf6564c712e345a3f3d8f29324490bfb8dcb4
| 4,065
|
NotesKmm
|
MIT License
|
src/main/kotlin/CEffectLightning.kt
|
argcc
| 777,572,651
| false
|
{"Kotlin": 451601}
|
package org.example
class CEffectLightning : CEffect() {
override fun GetTypeId(): UInt {
return 0x4du
}
}
| 0
|
Kotlin
|
0
| 0
|
7e58b1b74515577b14423443009bc2d04594184a
| 124
|
ei_reverse_consp
|
MIT License
|
me-api/src/main/kotlin/shop/hyeonme/domain/exercise/service/ExerciseService.kt
|
TEAM-hyeonme
| 776,784,109
| false
|
{"Kotlin": 120635, "Dockerfile": 204}
|
package shop.hyeonme.domain.exercise.service
import shop.hyeonme.common.annotation.FacadeService
@FacadeService
class ExerciseService(
commandExerciseService: CommandExerciseService,
queryExerciseService: QueryExerciseService
) : CommandExerciseService by commandExerciseService,
QueryExerciseService by queryExerciseService
| 0
|
Kotlin
|
0
| 0
|
646621f5577418523de44ed3a229d19879ee7193
| 338
|
ME-server
|
MIT License
|
core/src/main/kotlin/project/ProjectStorage.kt
|
amplitude
| 519,022,661
| false
|
{"Kotlin": 112962, "Makefile": 531, "Dockerfile": 342}
|
package com.amplitude.project
import com.amplitude.RedisConfiguration
import com.amplitude.util.RedisConnection
import com.amplitude.util.RedisKey
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
internal interface ProjectStorage {
val projects: Flow<Set<String>>
suspend fun getProjects(): Set<String>
suspend fun putProject(projectId: String)
suspend fun removeProject(projectId: String)
}
internal fun getProjectStorage(redisConfiguration: RedisConfiguration?): ProjectStorage {
val uri = redisConfiguration?.uri
return if (uri == null) {
InMemoryProjectStorage()
} else {
RedisProjectStorage(redisConfiguration.prefix, RedisConnection(uri))
}
}
internal class InMemoryProjectStorage : ProjectStorage {
override val projects = MutableSharedFlow<Set<String>>(
extraBufferCapacity = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
private val mutex = Mutex()
private val projectStorage = mutableSetOf<String>()
override suspend fun getProjects(): Set<String> = mutex.withLock {
projectStorage.toSet()
}
override suspend fun putProject(projectId: String): Unit = mutex.withLock {
projectStorage.add(projectId)
projects.emit(projectStorage.toSet())
}
override suspend fun removeProject(projectId: String): Unit = mutex.withLock {
projectStorage.remove(projectId)
projects.emit(projectStorage.toSet())
}
}
internal class RedisProjectStorage(
private val prefix: String,
private val redis: RedisConnection
) : ProjectStorage {
override val projects = MutableSharedFlow<Set<String>>(
extraBufferCapacity = 1,
onBufferOverflow = BufferOverflow.DROP_OLDEST
)
override suspend fun getProjects(): Set<String> {
return redis.smembers(RedisKey.Projects(prefix)) ?: emptySet()
}
override suspend fun putProject(projectId: String) {
redis.sadd(RedisKey.Projects(prefix), setOf(projectId))
projects.emit(getProjects())
}
override suspend fun removeProject(projectId: String) {
redis.srem(RedisKey.Projects(prefix), projectId)
projects.emit(getProjects())
}
}
| 0
|
Kotlin
|
1
| 0
|
7cb7f042beabb60cb61b48940cf72a46f1278216
| 2,366
|
evaluation-proxy
|
MIT License
|
app/src/main/java/com/theapache64/reky/data/local/model/Contact.kt
|
theapache64
| 371,929,313
| false
| null |
package com.theapache64.reky.data.local.model
/**
* Created by theapache64 : May 31 Mon,2021 @ 02:47
*/
data class Contact(
val id: String?,
val name: String,
val number: String?
)
| 1
|
Kotlin
|
2
| 12
|
2200ff8061809c012d7f018fc602dd9f757592d8
| 196
|
reky
|
Apache License 2.0
|
src/test/kotlin/io/taff/spek/expekt/iterable/ContainSpek.kt
|
tpasipanodya
| 352,117,533
| false
|
{"Kotlin": 45617, "Shell": 426}
|
package io.taff.spek.expekt.iterable
import io.taff.spek.expekt.should
import io.taff.spek.expekt.shouldNot
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object ContainSpek : Spek({
val actual by memoized { listOf(1, 2) }
val expected by memoized { listOf(1, 2) }
describe("invoke") {
it("correctly matches") {
actual should containInOrder(*expected.toTypedArray())
actual should containInAnyOrder(*expected.toTypedArray())
}
context("with entries out of order") {
val actual by memoized { listOf(2, 1) }
it("correctly matches") {
actual should containInOrder(*expected.toTypedArray()).not()
actual should containInAnyOrder(*expected.toTypedArray())
}
}
context("with nested ordered matching") {
val actual by memoized { listOf(1, listOf(2)) }
val expected by memoized { listOf(1, containInAnyOrder(2)) }
it("correctly matches") {
actual should containInOrder(*expected.toTypedArray())
actual should containInAnyOrder(*expected.toTypedArray())
}
context("with several levels of nesting") {
val actual by memoized { listOf(1, listOf(2, listOf(3))) }
val expected by memoized { listOf(1, containInAnyOrder(2, containInOrder(3))) }
it("correctly matches") {
actual should containInOrder(*expected.toTypedArray())
actual should containInAnyOrder(*expected.toTypedArray())
}
}
}
context("with nested unordered matching") {
val actual by memoized { listOf(listOf(2), 1) }
val expected by memoized { listOf(1, containInAnyOrder(2)) }
it("correctly matches") {
actual should containInOrder(*expected.toTypedArray()).not()
actual should containInAnyOrder(*expected.toTypedArray())
}
context("with several levels of nesting") {
val actual by memoized { listOf(1, listOf(2, listOf(3))) }
val expected by memoized { listOf(1, containInAnyOrder(containInOrder(3), 2)) }
it("correctly matches") {
actual should containInOrder(*expected.toTypedArray())
actual should containInAnyOrder(*expected.toTypedArray())
}
context("when the ordering mismatches are nested") {
val actual by memoized { listOf(1, listOf(2, listOf(3))) }
val expected by memoized { listOf(1, containInOrder(containInAnyOrder(3), 2)) }
it("correctly mismatches") {
actual should containInOrder(*expected.toTypedArray()).not()
actual should containInAnyOrder(*expected.toTypedArray()).not()
}
}
context("when nested types don't match") {
val actual by memoized { listOf(1, listOf(2, 3)) }
val expected by memoized { listOf(1, containInOrder(containInAnyOrder(3), 2)) }
it("correctly matches") {
actual should containInOrder(*expected.toTypedArray()).not()
actual shouldNot containInAnyOrder(*expected.toTypedArray())
}
}
}
}
}
})
| 0
|
Kotlin
|
0
| 1
|
76230f7ddc4796dc67e492fd1f58f07d84bcd035
| 3,559
|
spek-expekt
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.