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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
browser-kotlin/src/jsMain/kotlin/web/events/ProgressEvent.types.kt
|
karakum-team
| 393,199,102 | false |
{"Kotlin": 6328455}
|
// Automatically generated - do not modify!
package web.events
import seskar.js.JsValue
sealed external class ProgressEventTypes :
ProgressEventTypes_deprecated {
@JsValue("abort")
val ABORT: EventType<ProgressEvent>
@JsValue("error")
val ERROR: EventType<ProgressEvent>
@JsValue("load")
val LOAD: EventType<ProgressEvent>
@JsValue("loadend")
val LOAD_END: EventType<ProgressEvent>
@JsValue("loadstart")
val LOAD_START: EventType<ProgressEvent>
@JsValue("progress")
val PROGRESS: EventType<ProgressEvent>
@JsValue("timeout")
val TIMEOUT: EventType<ProgressEvent>
}
| 1 |
Kotlin
|
8
| 35 |
6c553c67c6cbf77a802c137d010b143895c7da60
| 635 |
types-kotlin
|
Apache License 2.0
|
common/data/src/commonMain/kotlin/com/a_blekot/shlokas/common/data/ListId.kt
|
a-blekot
| 522,545,932 | false | null |
package com.a_blekot.shlokas.common.data
import com.a_blekot.shlokas.common.data.ListId.SB_1
import com.arkivanov.essenty.parcelable.Parcelable
import com.arkivanov.essenty.parcelable.Parcelize
import kotlinx.serialization.Serializable
@Serializable
@Parcelize
enum class ListId(val id: String): Parcelable {
BG("BG"),
NI("NI"),
NK("NK"),
ISO("ISO"),
NOD("NOD"),
SB_1("SB_1"),
SB_2("SB_2"),
SB_3("SB_3"),
SB_4("SB_4"),
SB_5("SB_5"),
SB_6("SB_6"),
}
fun String.toListType() =
ListId.values().firstOrNull { it.id == this } ?: SB_1
| 0 |
Kotlin
|
0
| 2 |
3f281ac4c5d7d2593b85c9ed1bb656ea8b34f9f1
| 579 |
memorize_shloka
|
Apache License 2.0
|
common/src/main/kotlin/dev/capybaralabs/d4j/store/common/repository/noop/NoopMessageRepository.kt
|
CapybaraLabs
| 378,490,057 | false |
{"Kotlin": 376455}
|
package dev.capybaralabs.d4j.store.common.repository.noop
import dev.capybaralabs.d4j.store.common.repository.MessageRepository
import discord4j.discordjson.json.MessageData
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
class NoopMessageRepository : MessageRepository {
override fun save(message: MessageData, shardId: Int): Mono<Void> {
return Mono.empty()
}
override fun delete(messageId: Long, channelId: Long): Mono<Long> {
return Mono.just(0)
}
override fun deleteByIds(messageIds: List<Long>, channelId: Long): Mono<Long> {
return Mono.just(0)
}
override fun deleteByShardId(shardId: Int): Mono<Long> {
return Mono.just(0)
}
override fun deleteByChannelId(channelId: Long): Mono<Long> {
return Mono.just(0)
}
override fun deleteByChannelIds(channelIds: List<Long>): Mono<Long> {
return Mono.just(0)
}
override fun countMessages(): Mono<Long> {
return Mono.just(0)
}
override fun countMessagesInChannel(channelId: Long): Mono<Long> {
return Mono.just(0)
}
override fun getMessages(): Flux<MessageData> {
return Flux.empty()
}
override fun getMessagesInChannel(channelId: Long): Flux<MessageData> {
return Flux.empty()
}
override fun getMessageById(messageId: Long): Mono<MessageData> {
return Mono.empty()
}
override fun getMessagesByIds(messageIds: List<Long>): Flux<MessageData> {
return Flux.empty()
}
}
| 2 |
Kotlin
|
0
| 4 |
a9ecc4e0ead1f7ec73aa99034df6d25bf1efa10d
| 1,397 |
d4j-store
|
MIT License
|
api/src/main/kotlin/com/projectfawkes/api/dataClass/Profile.kt
|
Justin9four
| 320,391,812 | false | null |
package com.projectfawkes.api.dataClass
data class Profile(val uid: String?, val firstName: String?, val lastName: String?, val createdDate: String?, val dob: String?) {
fun getProfileMap(): Map<String, String> {
val profileMap = mutableMapOf<String, String>()
if (!firstName.isNullOrBlank()) profileMap["firstName"] = firstName
if (!lastName.isNullOrBlank()) profileMap["lastName"] = lastName
if (!dob.isNullOrBlank()) profileMap["dob"] = dob
if (!createdDate.isNullOrBlank()) profileMap["createdDate"] = createdDate
return profileMap
}
}
| 0 |
Kotlin
|
0
| 2 |
0a313f6e95f22570bca2d364de027974aa3602f1
| 596 |
NarwhalNotesAPI
|
MIT License
|
app/src/main/java/tech/medina/tvshows/domain/model/Show.kt
|
eamedina87
| 395,739,952 | false | null |
package tech.medina.tvshows.domain.model
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
interface IData {
val id: Long
val name: String
val summary: String
val imageMedium: String
val imageOriginal: String
}
@Parcelize
data class Show(
override val id: Long,
override val name: String,
override val summary: String,
override val imageMedium: String,
override val imageOriginal: String,
val rating: Double,
val episodeList: List<Episode>,
val castList: List<Cast>
) : IData, Parcelable
@Parcelize
data class Episode(
override val id: Long,
override val name: String,
override val summary: String,
val seasonNumber: Int,
val episodeNumber: Int,
override val imageMedium: String,
override val imageOriginal: String
) : IData, Parcelable
| 0 |
Kotlin
|
0
| 0 |
da89c83a441a511e0cc35c7eb9afa542ada1fb32
| 834 |
tv-shows
|
The Unlicense
|
app/src/main/java/com/ekenya/rnd/baseapp/SpaceXApp.kt
|
JMDev2
| 704,673,197 | false |
{"Kotlin": 63475, "Java": 14180}
|
package com.ekenya.rnd.baseapp
import android.app.Activity
import androidx.fragment.app.Fragment
import com.ekenya.rnd.baseapp.di.AppComponent
import com.ekenya.rnd.baseapp.di.BaseModuleInjector
import com.ekenya.rnd.baseapp.di.DaggerAppComponent
import com.ekenya.rnd.baseapp.di.helpers.features.FeatureModule
import com.ekenya.rnd.common.abstractions.BaseApplication
import dagger.android.AndroidInjector
import dagger.android.DispatchingAndroidInjector
import dagger.android.HasActivityInjector
import dagger.android.support.HasSupportFragmentInjector
import javax.inject.Inject
class SpaceXApp: BaseApplication(), HasActivityInjector, HasSupportFragmentInjector {
// ActivityInjector / FragmentInjector used in the main module
@Inject
lateinit var dispatchingActivityInjector: DispatchingAndroidInjector<Activity>
@Inject
lateinit var dispatchingFragmentInjector: DispatchingAndroidInjector<Fragment>
// List of ActivityInjector / FragmentInjector used in each Feature module
private val moduleActivityInjectors = mutableListOf<DispatchingAndroidInjector<Activity>>()
private val moduleFragmentInjectors = mutableListOf<DispatchingAndroidInjector<Fragment>>()
// AndroidInjector <Activity> that actually injects
private val activityInjector = AndroidInjector<Activity> { instance ->
// If true is returned by maybeInject, Inject is successful
// Main module
if (dispatchingActivityInjector.maybeInject(instance)) {
return@AndroidInjector
}
// Each Feature module
moduleActivityInjectors.forEach { injector ->
if (injector.maybeInject(instance)) {
return@AndroidInjector
}
}
throw IllegalStateException("Injector not found for $instance")
}
// AndroidInjector <Fragment> that actually injects each
private val fragmentInjector = AndroidInjector<Fragment> { instance ->
// If true is returned by maybeInject, Inject is successful
// Main module
if (dispatchingFragmentInjector.maybeInject(instance)) {
return@AndroidInjector
}
// Each Feature module
moduleFragmentInjectors.forEach { injector ->
if (injector.maybeInject(instance)) {
return@AndroidInjector
}
}
throw IllegalStateException("Injector not found for $instance")
}
// Set for determining whether the Injector of the Feature module has been generated
private val injectedModules = mutableSetOf<FeatureModule>()
// Used from AppComponent and Component of each Feature module
val appComponent by lazy {
DaggerAppComponent.builder().create(this) as AppComponent
}
override fun onCreate() {
super.onCreate()
appComponent.inject(this)
}
override fun activityInjector(): AndroidInjector<Activity> {
// Returns the actual Injector
return activityInjector
}
override fun supportFragmentInjector(): AndroidInjector<Fragment> {
// Returns the actual Injector
return fragmentInjector
}
// Add Injector for Feature module
// Called just before the Feature module is used after installation
fun addModuleInjector(module: FeatureModule) {
if (injectedModules.contains(module)) {
// Do nothing if added
return
}
// Generate Injector for Feature module
val clazz = Class.forName(module.injectorName)
val moduleInjector = clazz.newInstance() as BaseModuleInjector
// Inject Dispatching Android Injector of Injector of Feature module
moduleInjector.inject(this)
// Add to list
moduleActivityInjectors.add(moduleInjector.activityInjector())
moduleFragmentInjectors.add(moduleInjector.fragmentInjector())
injectedModules.add(module)
}
}
| 0 |
Kotlin
|
1
| 0 |
bb59eab46ff3b08906e412854a9a7c9d5cfcd0b1
| 3,915 |
ShipX
|
MIT License
|
src/main/kotlin/no/nav/helse/flex/varsler/PlanlagtVarselRepository.kt
|
navikt
| 369,170,453 | false |
{"Kotlin": 90172, "Dockerfile": 172, "Shell": 142}
|
package no.nav.helse.flex.varsler
import no.nav.helse.flex.varsler.domain.PlanlagtVarsel
import no.nav.helse.flex.varsler.domain.PlanlagtVarselStatus
import org.springframework.data.jdbc.repository.query.Query
import org.springframework.data.repository.CrudRepository
import org.springframework.stereotype.Repository
import java.time.Instant
@Repository
interface PlanlagtVarselRepository : CrudRepository<PlanlagtVarsel, String> {
fun findBySykepengesoknadId(sykepengesoknadId: String): List<PlanlagtVarsel>
fun findFirst300ByStatusAndSendesIsBefore(
status: PlanlagtVarselStatus,
sendes: Instant,
): List<PlanlagtVarsel>
fun findBySykepengesoknadIdAndStatus(
sykepengesoknadId: String,
status: PlanlagtVarselStatus,
): List<PlanlagtVarsel>
@Query(
"""
SELECT *
FROM planlagt_varsel
WHERE sykepengesoknad_id = :id
AND varsel_type = :type
AND dine_sykmeldte_hendelse_opprettet IS NOT NULL
""",
)
fun findMedSendtDineSykmeldteHendelse(
id: String,
type: String,
): List<PlanlagtVarsel>
}
| 0 |
Kotlin
|
0
| 0 |
d8f4187ca838416d2bb406cd3e0b9d228e2ad3a2
| 1,139 |
sykepengesoknad-narmesteleder-varsler
|
MIT License
|
app/src/main/java/com/seven_sheesh/greventure/domain/model/Thread.kt
|
ahargunyllib
| 846,841,295 | false |
{"Kotlin": 453189}
|
package com.seven_sheesh.greventure.domain.model
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class Comment(
@SerialName("id") val id: String,
@SerialName("thread_id") val threadId: String? = null,
@SerialName("user_id") val userId: String? = null,
@SerialName("content") val content: String,
@SerialName("created_at") val createdAt: String? = null
)
| 0 |
Kotlin
|
1
| 0 |
8735831666609ec8f4e017c5120dbe6fbe241916
| 428 |
Greventure
|
MIT License
|
src/main/kotlin/com/mcstarrysky/veronica/choose/ChooseListener.kt
|
Micalhl
| 669,109,912 | false | null |
package com.mcstarrysky.veronica.choose
import com.mcstarrysky.veronica.lib.listener.MiraiListener
import net.mamoe.mirai.event.EventHandler
import net.mamoe.mirai.event.SimpleListenerHost
import net.mamoe.mirai.event.events.GroupMessageEvent
import net.mamoe.mirai.message.data.at
import net.mamoe.mirai.message.data.content
import taboolib.common.util.random
/**
* Veronica
* com.mcstarrysky.veronica.choose.ChooseListener
*
* @author Mical
* @since 2023/7/21 20:29
*/
@MiraiListener
object ChooseListener : SimpleListenerHost() {
@EventHandler
suspend fun GroupMessageEvent.onMessage() {
if (!message.content.startsWith("@${bot.id} ")) return
val content = message.content.removePrefix("@${bot.id} ")
if (!content.contains("่ฟๆฏ")) return
if (content == "่ฟๆฏ") return
if (content.startsWith("่ฟๆฏ") || content.endsWith("่ฟๆฏ")) return
val select = if (random(100) <= 50) "ๅ่
" else "ๅ่
"
group.sendMessage("${sender.at().getDisplay(group)} ้$select!")
}
}
| 0 |
Kotlin
|
0
| 0 |
2df8d3571a5741748f47cb3a1b7fb0c77651f927
| 1,026 |
Veronica
|
Creative Commons Zero v1.0 Universal
|
app/src/test/java/com/todo/app/viewmodel/RecipeListViewModelTest.kt
|
maanbhati
| 426,370,550 | false |
{"Kotlin": 38469}
|
package com.todo.app.viewmodel
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import com.todo.app.repository.RecipeRepository
import io.mockk.MockKAnnotations
import io.mockk.impl.annotations.MockK
import io.mockk.verify
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runBlockingTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@ExperimentalCoroutinesApi
class RecipeListViewModelTest {
@get:Rule
val instantTaskExecutorRule = InstantTaskExecutorRule()
@MockK
private lateinit var repository: RecipeRepository
private lateinit var viewModel: RecipeListViewModel
@Before
fun setUp() {
MockKAnnotations.init(this, relaxed = true)
viewModel = RecipeListViewModel(repository)
}
@Test
fun when_get_saved_recipe_called_verify_method_call_from_repository() = runBlockingTest {
val query = "query"
viewModel.getSavedRecipes(query)
verify { repository.getSavedRecipe(query) }
}
@Test
fun when_search_recipe_called_verify_method_call_from_repository() = runBlockingTest {
val query = "query"
viewModel.searchRecipe(query)
Thread.sleep(500L)
verify { runBlockingTest { repository.getItems(query) } }
}
@Test
fun when_get_save_recipe_called_do_not_call_api_method_from_repository() =
runBlockingTest {
val query = "query"
viewModel.getSavedRecipes(query)
verify(inverse = true) { runBlockingTest { repository.getItems(query) } }
}
}
| 0 |
Kotlin
|
0
| 1 |
e534969fd066687c07edfa2d658d09818aa2c3c3
| 1,599 |
TodoMvvmApp
|
Apache License 2.0
|
app/src/main/java/lt/getpet/getpet/adapters/PetPhotosAdapter.kt
|
v4i
| 171,261,055 | true |
{"Kotlin": 74808}
|
package lt.getpet.getpet.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.viewpager.widget.PagerAdapter
import com.bumptech.glide.Glide
import kotlinx.android.synthetic.main.pet_photo.view.*
import lt.getpet.getpet.R
class PetPhotosAdapter(private val context: Context, private val photos: List<String>) : PagerAdapter() {
private val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
override fun isViewFromObject(view: View, `object`: Any): Boolean {
return view == `object`
}
override fun getCount(): Int {
return photos.size
}
override fun instantiateItem(container: ViewGroup, position: Int): Any {
val view = inflater.inflate(R.layout.pet_photo, container, false)
Glide.with(context).load(photos[position]).into(view.pet_photo)
container.addView(view)
return view
}
override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
container.removeView(`object` as View)
}
}
| 0 |
Kotlin
|
0
| 0 |
e0ba37368f47a6873eef85719fea876a3cb6c6d7
| 1,133 |
getpet-android
|
MIT License
|
team_api/src/main/java/ru/flowernetes/team/api/domain/entity/NoSuchTeamException.kt
|
b1nd
| 252,335,785 | false | null |
package ru.flowernetes.team.api.domain.entity
class NoSuchTeamException(teamId: Long) : NoSuchElementException("There is no team with id: $teamId")
| 0 |
Kotlin
|
1
| 2 |
8eef7e3324642fa4b26a69be69525d79a4873ea4
| 148 |
flowernetes
|
MIT License
|
library/src/main/java/com/github/pelmenstar1/rangecalendar/decoration/LazyCellDataArray.kt
|
pelmenstar1
| 454,918,220 | false | null |
@file:Suppress("UNCHECKED_CAST")
package com.github.pelmenstar1.rangecalendar.decoration
import com.github.pelmenstar1.rangecalendar.selection.Cell
import java.util.*
/**
* Represents a special array wrapper, which internal array is allocated only on writing.
*/
internal class LazyCellDataArray<T : Any> {
@PublishedApi
internal var elements = EMPTY_ARRAY
var notNullElementsLength = 0
private set
inline fun forEachNotNull(action: (cell: Cell, value: T) -> Unit) {
// Check if there's need to iterate through each element.
if(notNullElementsLength == 0) {
return
}
for(i in 0 until 42) {
val value = elements[i] as T?
if(value != null) {
action(Cell(i), value)
}
}
}
operator fun get(cell: Cell): T? {
// If elements are not initialized,
// then writing to array was never happened, meaning all the elements must be null
return if(elements.isEmpty()) null else elements[cell.index] as T?
}
fun clear() {
Arrays.fill(elements, null)
notNullElementsLength = 0
}
operator fun set(cell: Cell, value: T?) {
var elements = elements
if(elements.isEmpty()) {
elements = arrayOfNulls(42)
this.elements = elements
}
val index = cell.index
val oldValue = elements[index]
if(oldValue != value) {
// Update not-null elements counter. I haven't found better way.
if((oldValue == null) and (value != null)) {
notNullElementsLength++
} else if((oldValue != null) and (value == null)) {
notNullElementsLength--
}
elements[cell.index] = value
}
}
companion object {
private val EMPTY_ARRAY = emptyArray<Any?>()
}
}
| 5 |
Kotlin
|
0
| 10 |
0fb2b7760a29ac76f17c93347f3b61371a0ef037
| 1,901 |
RangeCalendar
|
MIT License
|
src/com/dengzii/plugin/adb/utils/CmdResult.kt
|
asdlei99
| 304,285,245 | true |
{"Kotlin": 31136, "Java": 17917}
|
package com.dengzii.plugin.adb.utils
/**
* <pre>
* author : dengzi
* e-mail : <EMAIL>
* github : https://github.com/MrDenua
* time : 2019/10/8
* desc :
* </pre>
*/
class CmdResult(
var exitCode: Int = 0,
var output: String = "",
var success: Boolean = false
)
| 0 | null |
0
| 0 |
b09331d422543f66eb1b90192258a6de640e4f9f
| 296 |
WiFiADB
|
MIT License
|
app/src/main/java/ru/nikstep/alarm/service/alarm/android/reminder/AlarmReminderReceiver.kt
|
nikita715
| 224,504,692 | false | null |
package ru.nikstep.alarm.service.alarm.android.reminder
import android.app.NotificationManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.ContextWrapper
import android.content.Intent
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import ru.nikstep.alarm.AlarmApp
import ru.nikstep.alarm.model.Alarm
import ru.nikstep.alarm.service.alarm.AlarmController
import ru.nikstep.alarm.service.notification.NotificationService
import ru.nikstep.alarm.ui.main.MainActivity.Companion.ALARM_ID_EXTRA
import ru.nikstep.alarm.util.data.Result
import ru.nikstep.alarm.util.data.Status
import ru.nikstep.alarm.util.data.emitLiveData
import javax.inject.Inject
class AlarmReminderReceiver : BroadcastReceiver() {
@Inject
lateinit var notificationService: NotificationService
@Inject
lateinit var alarmController: AlarmController
override fun onReceive(context: Context, intent: Intent) {
if (context is ContextWrapper) {
(context.baseContext as AlarmApp).androidInjector.inject(this)
} else {
(context as AlarmApp).androidInjector.inject(this)
}
startAlarmService(context, intent)
}
private fun startAlarmService(context: Context, intent: Intent) {
val alarmId = intent.getLongExtra(ALARM_ID_EXTRA, -1L)
val notificationManager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
val liveData = emitLiveData {
alarmController.getAlarm(alarmId)
}
val observer = AlarmNotificationObserver(liveData, notificationManager, notificationService)
liveData.observeForever(observer)
}
class AlarmNotificationObserver(
private val liveData: LiveData<Result<Alarm?>>,
private val notificationManager: NotificationManager,
private val notificationService: NotificationService
) : Observer<Result<Alarm?>> {
override fun onChanged(t: Result<Alarm?>?) {
when (t?.status) {
Status.LOADING -> {
}
Status.SUCCESS -> {
liveData.removeObserver(this)
t.data?.let { alarm ->
notificationManager.notify(
1,
notificationService.buildAlarmReminderNotification(alarm.id, alarm.getTimeAsString())
)
}
Log.i("AlarmRemRec", "Notification is sent")
}
Status.ERROR -> {
liveData.removeObserver(this)
Log.e("AlarmRemRec", t.exception?.message, t.exception)
}
}
}
}
}
| 0 |
Kotlin
|
0
| 1 |
5eae531ba4a8184f4f8abfefcbab2c4486efc003
| 2,795 |
spotify-alarm-clock
|
Apache License 2.0
|
src/main/kotlin/com/colinodell/advent2022/Day06.kt
|
colinodell
| 572,710,708 | false |
{"Kotlin": 105421}
|
package com.colinodell.advent2022
import java.lang.Integer.min
class Day06(private val input: String) {
fun solvePart1() = findMarker(4)
fun solvePart2() = findMarker(14)
private fun findMarker(markerSize: Int): Int {
for (i in input.indices) {
val possibleMarker = input.substring(i, min(input.length - 1, i + markerSize))
if (possibleMarker.toSet().size == markerSize) {
return i + markerSize
}
}
error("No marker found!")
}
}
| 0 |
Kotlin
|
0
| 1 |
32da24a888ddb8e8da122fa3e3a08fc2d4829180
| 525 |
advent-2022
|
MIT License
|
bilimiao-download/src/main/java/cn/a10miaomiao/bilimiao/download/DownloadService.kt
|
10miaomiao
| 142,169,120 | false | null |
package cn.a10miaomiao.bilimiao.download
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.IBinder
import cn.a10miaomiao.bilimiao.download.entry.BiliDownloadEntryAndPathInfo
import cn.a10miaomiao.bilimiao.download.entry.BiliDownloadEntryInfo
import cn.a10miaomiao.bilimiao.download.entry.BiliDownloadMediaFileInfo
import cn.a10miaomiao.bilimiao.download.entry.CurrentDownloadInfo
import com.a10miaomiao.bilimiao.comm.network.MiaoHttp
import com.a10miaomiao.bilimiao.comm.utils.DebugMiao
import com.google.gson.Gson
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.io.InputStream
import kotlin.coroutines.CoroutineContext
class DownloadService: Service(), CoroutineScope, DownloadManager.Callback {
companion object {
private const val TAG = "DownloadService"
private val channel = Channel<DownloadService>()
private var _instance: DownloadService? = null
val instance get() = _instance
suspend fun getService(context: Context): DownloadService{
_instance?.let { return it }
startService(context)
return channel.receive().also {
_instance = it
}
}
fun startService(context: Context) {
val intent = Intent(context, DownloadService::class.java)
context.startService(intent)
}
}
private var job: Job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.IO + job
private var downloadNotify: DownloadNotify? = null
private var downloadManager: DownloadManager? = null
private var audioDownloadManager: DownloadManager? = null
private var audioDownloadManagerCallback = object : DownloadManager.Callback {
override fun onTaskRunning(info: CurrentDownloadInfo) {
// TODO("Not yet implemented")
}
override fun onTaskComplete(info: CurrentDownloadInfo) {
// TODO("Not yet implemented")
}
override fun onTaskError(info: CurrentDownloadInfo, error: Throwable) {
// TODO("Not yet implemented")
}
}
var downloadList = mutableListOf<BiliDownloadEntryAndPathInfo>()
var downloadListVersion = MutableStateFlow(0)
val curDownload = MutableStateFlow<CurrentDownloadInfo?>(null)
private val curBiliDownloadEntryAndPathInfo: BiliDownloadEntryAndPathInfo?
get() = curDownload.value?.let { cur ->
downloadList.find { it.entry.key == cur.id }
}
private var curMediaFile: File? = null
private var curMediaFileInfo: BiliDownloadMediaFileInfo? = null
override fun onCreate() {
super.onCreate()
job = Job()
launch {
readDownloadList()
channel.send(this@DownloadService)
}
downloadNotify = DownloadNotify(this)
}
override fun onDestroy() {
super.onDestroy()
job.cancel()
_instance = null
}
private fun readDownloadList() {
val downloadDir = File(getDownloadPath())
val list = mutableListOf<BiliDownloadEntryAndPathInfo>()
downloadDir.listFiles()
.filter { it.isDirectory }
.forEach {
list.addAll(readDownloadDirectory(it))
}
downloadList = list.reversed().toMutableList()
}
fun readDownloadDirectory(dir: File): List<BiliDownloadEntryAndPathInfo>{
if (!dir.exists() || !dir.isDirectory) {
return emptyList()
}
return dir.listFiles()
.filter { pageDir -> pageDir.isDirectory }
.map { File(it.path, "entry.json") }
.filter { it.exists() }
.map {
val entryJson = it.readText()
val entry = Gson().fromJson(entryJson, BiliDownloadEntryInfo::class.java)
BiliDownloadEntryAndPathInfo(
entry = entry,
entryDirPath = it.parent,
pageDirPath = it.parentFile.parent
)
}
}
/**
* ๅๅปบไปปๅก
*/
fun createDownload(
biliEntry: BiliDownloadEntryInfo
) {
val entryDir = getDownloadFileDir(biliEntry)
// ไฟๅญ่ง้ขไฟกๆฏ
val entryJsonFile = File(entryDir, "entry.json")
val entryJsonStr = Gson().toJson(biliEntry)
entryJsonFile.writeText(entryJsonStr)
val biliDownInfo = BiliDownloadEntryAndPathInfo(
entry = biliEntry,
pageDirPath = entryDir.parent,
entryDirPath = entryDir.absolutePath,
)
val index = downloadList.indexOfFirst {
if (biliEntry.avid != null) {
biliEntry.avid == it.entry.avid
} else {
biliEntry.season_id == it.entry.season_id
}
}
downloadList.add(index + 1, biliDownInfo)
downloadListVersion.value++
if (curDownload.value == null) {
startDownload(biliDownInfo)
}
}
fun startDownload(entryDirPath: String) {
val biliDownInfo = downloadList.find {
it.entryDirPath == entryDirPath
}
if (biliDownInfo != null) {
startDownload(biliDownInfo)
} else {
val entryFile = File(entryDirPath, "entry.json")
if (entryFile.exists()) {
}
}
}
/**
* ๅผๅงไปปๅก
*/
fun startDownload(biliDownInfo: BiliDownloadEntryAndPathInfo) = launch {
// ๅๆถๅฝๅไปปๅก
downloadManager?.cancel()
audioDownloadManager?.cancel()
downloadManager = null
audioDownloadManager = null
// ๅผๅงไปปๅก/็ปง็ปญไปปๅก
val entryDir = File(biliDownInfo.entryDirPath)
val danmakuXMLFile = File(entryDir, "danmaku.xml")
val entry = biliDownInfo.entry
val parentId = entry.season_id ?: entry.avid?.toString() ?: ""
val id = entry.page_data?.cid ?: entry.ep?.episode_id ?: 0L
val currentDownloadInfo = CurrentDownloadInfo(
parentId = parentId,
id = id,
name = entry.name,
url = "",
header = mapOf(),
size = 0,
length = 0
)
if (!danmakuXMLFile.exists()) {
try {
// ่ทๅๅผนๅนๅนถไธ่ฝฝ
curDownload.value = currentDownloadInfo.copy(
status = CurrentDownloadInfo.STATUS_GET_DANMAKU,
)
val res = MiaoHttp.request {
url = BiliPalyUrlHelper.danmakuXMLUrl(biliDownInfo.entry)
}.awaitCall()
val inputStream = res.body!!.byteStream()
inputStream.inputStreamToFile(danmakuXMLFile)
} catch (e: Exception){
curDownload.value = currentDownloadInfo.copy(
status = CurrentDownloadInfo.STATUS_FAIL_DANMAKU,
)
e.printStackTrace()
return@launch
}
}
downloadVideo(currentDownloadInfo, biliDownInfo)
}
private suspend fun downloadVideo(
currentDownloadInfo: CurrentDownloadInfo,
biliDownInfo: BiliDownloadEntryAndPathInfo,
) {
val entry = biliDownInfo.entry
val entryDir = File(biliDownInfo.entryDirPath)
val videoDir = File(entryDir, entry.type_tag)
if (!videoDir.exists()) {
videoDir.mkdir()
}
try {
curDownload.value = currentDownloadInfo.copy(
status = CurrentDownloadInfo.STATUS_GET_PLAYURL,
)
//่ทๅๆญๆพๅฐๅๅนถไธ่ฝฝ
val mediaFileInfo = BiliPalyUrlHelper.playUrl(entry)
val httpHeader = BiliPalyUrlHelper.httpHeader(entry)
val mediaJsonFile = File(videoDir, "index.json")
val mediaJsonStr = Gson().toJson(mediaFileInfo)
mediaJsonFile.writeText(mediaJsonStr)
curMediaFile = mediaJsonFile
curMediaFileInfo = mediaFileInfo
when(mediaFileInfo) {
is BiliDownloadMediaFileInfo.Type1 -> {
downloadManager = DownloadManager(this, currentDownloadInfo.copy(
url = mediaFileInfo.segment_list[0].url,
header = httpHeader,
size = mediaFileInfo.segment_list[0].bytes,
length = mediaFileInfo.segment_list[0].duration
), this).also {
it.start(File(videoDir, "0" + "." + mediaFileInfo.format))
}
curDownload.value = currentDownloadInfo
}
is BiliDownloadMediaFileInfo.Type2 -> {
downloadManager = DownloadManager(this, currentDownloadInfo.copy(
url = mediaFileInfo.video[0].base_url,
header = httpHeader,
size = entry.total_bytes,
length = mediaFileInfo.duration
), this)
downloadManager?.start(File(videoDir, "video.m4s"))
curDownload.value = currentDownloadInfo
val audio = mediaFileInfo.audio
if (audio != null && audio.isNotEmpty()) {
audioDownloadManager = DownloadManager(this, CurrentDownloadInfo(
parentId = currentDownloadInfo.parentId,
id = currentDownloadInfo.id,
name = entry.name,
url = audio[0].base_url,
header = httpHeader,
size = audio[0].size,
length = mediaFileInfo.duration
), audioDownloadManagerCallback)
audioDownloadManager?.start(File(videoDir, "audio.m4s"))
}
}
else -> {
}
}
} catch (e: Exception) {
curDownload.value = currentDownloadInfo.copy(
status = CurrentDownloadInfo.STATUS_FAIL_PLAYURL,
)
e.printStackTrace()
}
}
fun cancelDownload() {
DebugMiao.log("cancelDownload", curDownload.value)
downloadManager?.cancel()
audioDownloadManager?.cancel()
downloadManager = null
audioDownloadManager = null
stopDownload()
}
/**
* ็ปๆๅฝๅไปปๅก
*/
fun stopDownload () {
curDownload.value?.let { cur ->
val entryAndPathInfo = downloadList.find {
cur.id == it.entry.key
}
if (entryAndPathInfo != null) {
entryAndPathInfo.entry.total_bytes = cur.size
entryAndPathInfo.entry.downloaded_bytes = cur.progress
val entryJsonFile = File(entryAndPathInfo.entryDirPath, "entry.json")
val entryJsonStr = Gson().toJson(entryAndPathInfo.entry)
entryJsonFile.writeText(entryJsonStr)
downloadManager?.cancel()?.let {
curDownload.value = it
}
}
}
curDownload.value = null
curMediaFile = null
curMediaFileInfo = null
}
/**
* ๅ ้คๅฝๅไปปๅก
*/
fun deleteDownload (
pageDirPath: String,
entryDirPath: String,
) {
val index = downloadList.indexOfFirst {
it.pageDirPath == pageDirPath && it.entryDirPath == entryDirPath
}
if (index != -1) {
// ๅฆๆไธบๅฝๅไธ่ฝฝไปปๅกๅๅ
ๅๆญขไปปๅก
val entryAndPathInfo = downloadList[index]
if (curDownload.value?.id == entryAndPathInfo.entry.key) {
cancelDownload()
}
}
val downloadDir = File(pageDirPath)
if (downloadDir.exists()) {
val entryDir = File(entryDirPath)
if (entryDir.exists()) {
entryDir.deleteRecursively()
}
if (downloadDir.listFiles().size === 0) {
downloadDir.delete()
}
}
if (index != -1) {
// ไปๅ่กจ็งป้ค
downloadList.removeAt(index)
downloadListVersion.value++
}
}
private fun nextDownload() {
downloadList.find {
// !it.entry.is_completed
it.entry.total_bytes == 0L
}?.let {
startDownload(it)
}
}
override fun onBind(p0: Intent?): IBinder? {
return null
}
override fun onTaskRunning(info: CurrentDownloadInfo) {
// ่ทๅ่ง้ขๆไปถ้ฟๅบฆ
if (info.progress == 0L && info.size != 0L) {
(curMediaFileInfo as BiliDownloadMediaFileInfo.Type2)?.let {
if (it.video[0].size == 0L && info.size != 0L) {
it.video[0].size = info.size
val mediaJsonStr = Gson().toJson(it)
curMediaFile?.writeText(mediaJsonStr)
}
}
}
curDownload.value = info.copy()
downloadNotify?.notifyData(info)
}
override fun onTaskComplete(info: CurrentDownloadInfo) {
if (info.size != 0L && info.size == info.progress) {
val (_, entryDirPath, entry) = curBiliDownloadEntryAndPathInfo ?: return
entry.downloaded_bytes = info.progress
entry.total_bytes = info.size
entry.is_completed = true
val entryJsonFile = File(entryDirPath, "entry.json")
val entryJsonStr = Gson().toJson(entry)
entryJsonFile.writeText(entryJsonStr)
// downloadList.removeAt(index)
downloadListVersion.value++
curDownload.value = null
curMediaFile = null
curMediaFileInfo = null
} else {
}
// TODO: ่ง้ขไธ่ฝฝๅฎๆ๏ผไฝ้ณ้ขๆชๅฎๆ็ๆ
ๅต
downloadNotify?.notifyData(info)
nextDownload()
}
override fun onTaskError(info: CurrentDownloadInfo, error: Throwable) {
DebugMiao.log(TAG, "onTaskError", info)
error.printStackTrace()
downloadNotify?.notifyData(info)
}
private fun getDownloadPath(): String {
var file = File(getExternalFilesDir(null), "../download")
if (!file.exists()) {
file.mkdir()
}
return file.canonicalPath
}
private fun getDownloadFileDir(biliEntry: BiliDownloadEntryInfo): File {
var dirName = ""
var pageDirName = ""
val ep = biliEntry.ep
if (ep != null) {
dirName = biliEntry.season_id!!
pageDirName = ep.episode_id.toString()
}
val page = biliEntry.page_data
if (page != null) {
dirName = biliEntry.avid!!.toString()
pageDirName = "c_" + page.cid
}
val downloadDir = File(getDownloadPath(), dirName)
// ๅๅปบๆไปถๅคน
if (!downloadDir.exists()) {
downloadDir.mkdir()
}
val pageDir = File(downloadDir, pageDirName)
if (!pageDir.exists()) {
pageDir.mkdir()
}
return pageDir
}
@Throws(IOException::class)
private fun InputStream.inputStreamToFile(file: File) {
val outputStream = FileOutputStream(file)
var read = -1
outputStream.use {
while (read().also { read = it } != -1) {
it.write(read)
}
}
}
}
| 25 |
Kotlin
|
20
| 568 |
87dd1e5eec74c2b4c1d7d032df8fa14406688649
| 15,597 |
bilimiao2
|
Apache License 2.0
|
src/main/kotlin/com/msg/gcms/domain/notice/service/DeleteNoticeService.kt
|
GSM-MSG
| 592,816,374 | false |
{"Kotlin": 407938, "Shell": 1448, "Dockerfile": 115}
|
package com.msg.gcms.domain.notice.service
interface DeleteNoticeService {
fun execute(id: Long)
}
| 10 |
Kotlin
|
0
| 11 |
8b932629102e0cf5447c076a6a54c8fe423f52bf
| 103 |
GCMS-BackEnd
|
MIT License
|
samples/src/main/java/com/google/ai/client/generative/samples/text_generation.kt
|
google-gemini
| 727,310,537 | false |
{"Kotlin": 297005, "Shell": 1948}
|
/*
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.google.ai.client.generative.samples
import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import com.google.ai.client.generativeai.GenerativeModel
import com.google.ai.client.generativeai.type.content
import com.google.ai.sample.R
// Set up your API Key
// ====================
//
// To use the Gemini API, you'll need an API key. To learn more, see
// the "Set up your API Key section" in the [Gemini API
// quickstart](https://ai.google.dev/gemini-api/docs/quickstart?lang=android#set-up-api-key).
suspend fun textGenTextOnlyPrompt() {
// [START text_gen_text_only_prompt]
val generativeModel =
GenerativeModel(
// Specify a Gemini model appropriate for your use case
modelName = "gemini-1.5-flash",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
apiKey = BuildConfig.apiKey)
val prompt = "Write a story about a magic backpack."
val response = generativeModel.generateContent(prompt)
print(response.text)
// [END text_gen_text_only_prompt]
}
suspend fun textGenTextOnlyPromptStreaming() {
// [START text_gen_text_only_prompt_streaming]
val generativeModel =
GenerativeModel(
// Specify a Gemini model appropriate for your use case
modelName = "gemini-1.5-flash",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
apiKey = BuildConfig.apiKey)
val prompt = "Write a story about a magic backpack."
// Use streaming with text-only input
generativeModel.generateContentStream(prompt).collect { chunk -> print(chunk.text) }
// [END text_gen_text_only_prompt_streaming]
}
suspend fun textGenMultimodalOneImagePrompt(context: Context) {
// [START text_gen_multimodal_one_image_prompt]
val generativeModel =
GenerativeModel(
// Specify a Gemini model appropriate for your use case
modelName = "gemini-1.5-flash",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
apiKey = BuildConfig.apiKey)
val image: Bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.image)
val inputContent = content {
image(image)
text("What's in this picture?")
}
val response = generativeModel.generateContent(inputContent)
print(response.text)
// [END text_gen_multimodal_one_image_prompt]
}
suspend fun textGenMultimodalOneImagePromptStreaming(context: Context) {
// [START text_gen_multimodal_one_image_prompt_streaming]
val generativeModel =
GenerativeModel(
// Specify a Gemini model appropriate for your use case
modelName = "gemini-1.5-flash",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
apiKey = BuildConfig.apiKey)
val image: Bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.image)
val inputContent = content {
image(image)
text("What's in this picture?")
}
generativeModel.generateContentStream(inputContent).collect { chunk -> print(chunk.text) }
// [END text_gen_multimodal_one_image_prompt_streaming]
}
suspend fun textGenMultimodalMultiImagePrompt(context: Context) {
// [START text_gen_multimodal_multi_image_prompt]
val generativeModel =
GenerativeModel(
// Specify a Gemini model appropriate for your use case
modelName = "gemini-1.5-flash",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
apiKey = BuildConfig.apiKey)
val image1: Bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.image1)
val image2: Bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.image2)
val inputContent = content {
image(image1)
image(image2)
text("What's the difference between these pictures?")
}
val response = generativeModel.generateContent(inputContent)
print(response.text)
// [END text_gen_multimodal_multi_image_prompt]
}
suspend fun textGenMultimodalMultiImagePromptStreaming(context: Context) {
// [START text_gen_multimodal_multi_image_prompt_streaming]
val generativeModel =
GenerativeModel(
// Specify a Gemini model appropriate for your use case
modelName = "gemini-1.5-flash",
// Access your API key as a Build Configuration variable (see "Set up your API key" above)
apiKey = BuildConfig.apiKey)
val image1: Bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.image1)
val image2: Bitmap = BitmapFactory.decodeResource(context.resources, R.drawable.image2)
val inputContent = content {
image(image1)
image(image2)
text("What's the difference between these pictures?")
}
generativeModel.generateContentStream(inputContent).collect { chunk -> print(chunk.text) }
// [END text_gen_multimodal_multi_image_prompt_streaming]
}
suspend fun textGenMultimodalVideoPrompt() {
// [START text_gen_multimodal_video_prompt]
// TODO
// [END text_gen_multimodal_video_prompt]
}
suspend fun textGenMultimodalVideoPromptStreaming() {
// [START text_gen_multimodal_video_prompt_streaming]
// TODO
// [END text_gen_multimodal_video_prompt_streaming]
}
| 26 |
Kotlin
|
153
| 708 |
b5d2e5610d19522ad10e6dc7e98236689aaa3587
| 5,900 |
generative-ai-android
|
Apache License 2.0
|
features/bankroll/presentation/withdraw/src/test/java/com/mctech/pokergrinder/bankroll/presentation/withdraw/WithdrawViewModelTest.kt
|
MayconCardoso
| 539,349,342 | false | null |
package com.mctech.pokergrinder.bankroll.presentation.withdraw
import com.mctech.architecture_testing.BaseViewModelTest
import com.mctech.architecture_testing.extensions.TestObserverScenario
import com.mctech.pokergrinder.bankroll.domain.entities.BankrollTransactionType
import com.mctech.pokergrinder.bankroll.domain.error.BankrollException
import com.mctech.pokergrinder.bankroll.domain.usecases.WithdrawUseCase
import io.mockk.coEvery
import io.mockk.coVerifyOrder
import io.mockk.confirmVerified
import io.mockk.mockk
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
internal class WithdrawViewModelTest : BaseViewModelTest() {
private val withdrawUseCase = mockk<WithdrawUseCase>(relaxed = true)
private val target = WithdrawViewModel(
withdrawUseCase = withdrawUseCase,
)
@Test
fun `should withdraw money`() = TestObserverScenario.observerScenario {
whenAction {
target.interact(
WithdrawInteraction.SaveDeposit(amount = 100.0, title = "Tournament Profit")
)
}
thenAssertLiveData(target.commandObservable) { commands ->
assertThat(commands).containsExactly(WithdrawCommand.CloseScreen)
}
thenAssert {
coVerifyOrder {
withdrawUseCase(
amount = 100.0,
description = "Tournament Profit",
type = BankrollTransactionType.WITHDRAW)
}
confirmVerified(withdrawUseCase)
}
}
@Test
fun `should not withdraw money when out of balance`() = TestObserverScenario.observerScenario {
givenScenario {
coEvery { withdrawUseCase(any(), any(), any()) } throws BankrollException.InsufficientBalance
}
whenAction {
target.interact(
WithdrawInteraction.SaveDeposit(amount = 100.0, title = "Tournament Profit")
)
}
thenAssertLiveData(target.commandObservable) { commands ->
assertThat(commands).containsExactly(WithdrawCommand.InsufficientBalanceError)
}
thenAssert {
coVerifyOrder {
withdrawUseCase(
amount = 100.0,
description = "Tournament Profit",
type = BankrollTransactionType.WITHDRAW)
}
confirmVerified(withdrawUseCase)
}
}
}
| 2 |
Kotlin
|
0
| 4 |
2670519c8ffd23826c7d2670443c3a08c345da5f
| 2,195 |
poker-grinder
|
Apache License 2.0
|
app/src/main/kotlin/io/mochadwi/view/HomeActivity.kt
|
mochadwi
| 189,831,173 | false | null |
package io.mochadwi.ui
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import io.mochadwi.R
import io.mochadwi.databinding.HomeActivityBinding
import io.mochadwi.util.base.BaseActivity
/**
*
* In syaa Allah created & modified
* by mochadwi on 10/08/19
* dedicated to build etalase-app
*
*/
class HomeActivity : BaseActivity() {
private val viewBinding: HomeActivityBinding by lazy {
DataBindingUtil.setContentView<HomeActivityBinding>(this, R.layout.home_activity)
}
private lateinit var mNavHost: NavHostFragment
private lateinit var mNavController: NavController
private lateinit var appBarConfiguration: AppBarConfiguration
override fun onCreate(savedInstanceState: Bundle?) {
setTheme(R.style.AppTheme_Launcher)
super.onCreate(savedInstanceState)
viewBinding.executePendingBindings()
setupNavController()
setupAppBar()
if (::mNavController.isInitialized && ::appBarConfiguration.isInitialized) {
setupActionBar(mNavController, appBarConfiguration)
}
}
override fun onBackPressed() {
if (::mNavHost.isInitialized) {
val fragmentsSize = mNavHost.childFragmentManager.fragments.size
if (fragmentsSize >= 1) {
super.onBackPressed()
} else {
findNavController(R.id.navHostFragment).navigateUp(appBarConfiguration)
}
}
}
override fun onSupportNavigateUp(): Boolean {
return if (::mNavHost.isInitialized) {
findNavController(R.id.navHostFragment).navigateUp(appBarConfiguration)
} else {
false
}
}
private fun setupNavController() {
mNavHost = supportFragmentManager
.findFragmentById(R.id.navHostFragment) as NavHostFragment? ?: return
mNavController = mNavHost.navController
}
private fun setupAppBar() {
appBarConfiguration = AppBarConfiguration(
setOf(R.id.postFragment),
null
)
}
private fun setupActionBar(
navController: NavController,
appBarConfig: AppBarConfiguration
) {
setupToolbar(viewBinding.toolbar.tbCustom)
setupActionBarWithNavController(navController, appBarConfig)
}
}
| 0 | null |
1
| 29 |
65afc6ec314c39d09211cdac52d6be34a52c1c0e
| 2,627 |
android-social-app
|
Apache License 2.0
|
src/main/kotlin/org/skellig/plugin/language/feature/steps/reference/java/JavaToSkelligTestStepReferenceContributor.kt
|
skellig-framework
| 309,154,374 | false |
{"Kotlin": 219539, "Lex": 2218}
|
package org.skellig.plugin.language.feature.steps.reference.java
import com.intellij.openapi.util.TextRange
import com.intellij.patterns.PlatformPatterns
import com.intellij.psi.*
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.util.ProcessingContext
import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
import org.skellig.plugin.language.feature.psi.SkelligUtil
import org.skellig.plugin.language.feature.steps.reference.SkelligStepReference
import org.skellig.plugin.language.teststep.psi.reference.SkelligTestStepToFeatureReference
class JavaToSkelligTestStepReferenceContributor : PsiReferenceContributor() {
override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) {
registrar.registerReferenceProvider(
PlatformPatterns.psiElement(PsiLiteralExpression::class.java),
object : PsiReferenceProvider() {
override fun getReferencesByElement(
element: PsiElement,
context: ProcessingContext
): Array<PsiReference> {
val testStepName = getTestStepName(element)
if (!testStepName.isNullOrEmpty()) {
val textRange = TextRange(1, testStepName.length + 1)
return arrayOf(SkelligStepReference(element, textRange))
} else {
PsiTreeUtil.getParentOfType(element, PsiAnnotation::class.java)?.let {
if (it.nameReferenceElement?.text == "TestStep") {
val testStepDef = SkelligUtil.getTestStepName(it)
if (testStepDef.isNotEmpty()) {
val textRange = TextRange(1, testStepDef.length + 1)
return arrayOf(SkelligTestStepToFeatureReference(element, textRange))
}
}
}
}
return PsiReference.EMPTY_ARRAY
}
})
}
private fun getTestStepName(element: PsiElement): String? {
val literalExpression = element as PsiLiteralExpression
val value = literalExpression.value
return if (value is String && value.isNotEmpty()) {
PsiTreeUtil.getParentOfType(element, PsiMethodCallExpression::class.java)?.let {
if (it.children.isNotEmpty() && it.children[0].getChildOfType<PsiIdentifier>()?.text == "run")
value
else null
}
} else null
}
}
| 0 |
Kotlin
|
0
| 1 |
1f99c61d6c5deb44d684e98a413d9f991b9b2da7
| 2,616 |
skellig-intellij-plugin
|
Apache License 2.0
|
app/src/main/java/com/babylon/wallet/android/data/transaction/ROLAClient.kt
|
radixdlt
| 513,047,280 | false | null |
package com.babylon.wallet.android.domain.usecases.signing
import com.babylon.wallet.android.domain.model.signing.SignPurpose
import com.babylon.wallet.android.domain.model.signing.SignRequest
import com.babylon.wallet.android.domain.usecases.assets.GetEntitiesOwnerKeysUseCase
import com.babylon.wallet.android.domain.usecases.transaction.GenerateAuthSigningFactorInstanceUseCase
import com.babylon.wallet.android.presentation.accessfactorsources.AccessFactorSourcesInput
import com.babylon.wallet.android.presentation.accessfactorsources.AccessFactorSourcesProxy
import com.radixdlt.sargon.HierarchicalDeterministicFactorInstance
import com.radixdlt.sargon.PublicKey
import com.radixdlt.sargon.PublicKeyHash
import com.radixdlt.sargon.SignatureWithPublicKey
import com.radixdlt.sargon.TransactionManifest
import com.radixdlt.sargon.extensions.ProfileEntity
import com.radixdlt.sargon.extensions.hex
import com.radixdlt.sargon.extensions.init
import com.radixdlt.sargon.extensions.setOwnerKeysHashes
import rdx.works.core.domain.TransactionManifestData
import rdx.works.core.sargon.transactionSigningFactorInstance
import javax.inject.Inject
class ROLAClient @Inject constructor(
private val getEntitiesOwnerKeysUseCase: GetEntitiesOwnerKeysUseCase,
private val generateAuthSigningFactorInstanceUseCase: GenerateAuthSigningFactorInstanceUseCase,
private val accessFactorSourcesProxy: AccessFactorSourcesProxy
) {
suspend fun generateAuthSigningFactorInstance(entity: ProfileEntity): Result<HierarchicalDeterministicFactorInstance> {
return generateAuthSigningFactorInstanceUseCase(entity)
}
suspend fun createAuthKeyManifest(
entity: ProfileEntity,
authSigningFactorInstance: HierarchicalDeterministicFactorInstance
): Result<TransactionManifestData> {
val transactionSigningPublicKey = entity.securityState.transactionSigningFactorInstance.publicKey.publicKey
val authSigningPublicKey = authSigningFactorInstance.publicKey.publicKey
return getEntitiesOwnerKeysUseCase(listOf(entity)).mapCatching { ownerKeysPerEntity ->
val ownerKeys = ownerKeysPerEntity[entity].orEmpty()
val publicKeys = mutableListOf<PublicKey>()
if (ownerKeys.none { it.hex == authSigningPublicKey.hex }) {
publicKeys.add(authSigningPublicKey)
}
if (ownerKeys.none { it.hex == transactionSigningPublicKey.hex }) {
publicKeys.add(transactionSigningPublicKey)
}
publicKeys
}.mapCatching { publicKeys ->
TransactionManifest.setOwnerKeysHashes(
addressOfAccountOrPersona = entity.address,
ownerKeyHashes = publicKeys.map { PublicKeyHash.init(it) }
)
}.mapCatching {
TransactionManifestData.from(manifest = it)
}
}
suspend fun signAuthChallenge(
signRequest: SignRequest.SignAuthChallengeRequest,
entities: List<ProfileEntity>
): Result<Map<ProfileEntity, SignatureWithPublicKey>> {
return accessFactorSourcesProxy.getSignatures(
accessFactorSourcesInput = AccessFactorSourcesInput.ToGetSignatures(
signPurpose = SignPurpose.SignAuth,
signRequest = signRequest,
signers = entities
)
).mapCatching { output ->
output.signersWithSignatures
}
}
}
| 7 | null |
6
| 9 |
36c670dd32d181e462e9962d476cb8a370fbe4fe
| 3,442 |
babylon-wallet-android
|
Apache License 2.0
|
examples/android-weather-app/src/main/kotlin/fr/ekito/myweatherapp/data/room/WeatherDAO.kt
|
wiryadev
| 396,206,386 | true | null |
package fr.ekito.myweatherapp.data.room
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import io.reactivex.rxjava3.core.Single
import java.util.Date
@Dao
interface WeatherDAO {
@Insert
fun saveAll(entities: List<WeatherEntity>)
@Query("SELECT * FROM weather WHERE id = :id")
fun findWeatherById(id: String): Single<WeatherEntity>
@Query("SELECT * FROM weather WHERE location = :location AND date = :date")
fun findAllBy(location: String, date: Date): Single<List<WeatherEntity>>
@Query("SELECT * FROM weather ORDER BY date DESC")
fun findLatestWeather(): Single<List<WeatherEntity>>
}
| 0 | null |
0
| 0 |
61d0df88a7f6b2f78b236e3eb67672d4efdf42d0
| 655 |
koin-samples
|
Apache License 2.0
|
src/main/kotlin/com/y9san9/b0mb3r/service/ServiceFactory.kt
|
y9san9
| 275,688,996 | false | null |
package com.y9san9.b0mb3r.service
object ServiceFactory {
fun build() = mutableListOf<Service>().apply(servicesInitializer)
}
| 0 |
Kotlin
|
1
| 12 |
23576a7ec22bec0daf4879852d13b329ff8d852a
| 132 |
kb0mb3r
|
MIT License
|
src/commonMain/kotlin/com.github.ikovalyov.model/Article.kt
|
ikovalyov
| 355,338,939 | false | null |
@file:OptIn(ExperimentalSerializationApi::class)
@file:UseSerializers(UuidSerializer::class)
package com.github.ikovalyov.model
import com.benasher44.uuid.Uuid
import com.benasher44.uuid.uuidFrom
import com.github.ikovalyov.model.markers.IEditable
import com.github.ikovalyov.model.security.User
import com.github.ikovalyov.model.serializer.UuidSerializer
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
import kotlinx.serialization.UseSerializers
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
@Serializable
@OptIn(ExperimentalSerializationApi::class)
data class Article(
override val id: Uuid,
val name: String,
val abstract: String,
val body: String,
val author: User,
val tags: List<String>?,
val meta: List<String>?,
val template: Template?, // Template uuid
val userList: List<User>,
val templateList: List<Template>
) : IEditable {
override fun getMetadata(): List<IEditable.EditableMetadata<*, Article>> {
return listOf(
IEditable.EditableMetadata(
fieldType = IEditable.FieldType.Id,
readOnly = true,
serialize = {
it.toString()
},
deserialize = {
uuidFrom(it)
},
update = {
copy(id = it)
},
get = {
id
},
fieldName = "Id",
predefinedList = null
),
IEditable.EditableMetadata(
fieldType = IEditable.FieldType.Name,
readOnly = false,
serialize = {
it
},
deserialize = {
it
},
update = {
copy(name = it)
},
get = {
name
},
fieldName = "Name",
predefinedList = null
),
IEditable.EditableMetadata(
fieldType = IEditable.FieldType.Abstract,
readOnly = false,
serialize = {
it
},
deserialize = {
it
},
update = {
copy(abstract = it)
},
get = {
abstract
},
fieldName = "Abstract",
predefinedList = null
),
IEditable.EditableMetadata(
fieldType = IEditable.FieldType.Body,
readOnly = false,
serialize = {
it
},
deserialize = {
it
},
update = {
copy(body = it)
},
get = {
body
},
fieldName = "Body",
predefinedList = null
),
IEditable.EditableMetadata(
fieldType = IEditable.FieldType.Author,
readOnly = false,
serialize = {
it.id.toString()
},
deserialize = { uuid ->
userList.first {
it.id.toString() == uuid
}
},
update = {
copy(author = it)
},
get = {
author
},
fieldName = "Author",
predefinedList = userList
),
IEditable.EditableMetadata(
fieldType = IEditable.FieldType.Tags,
readOnly = false,
serialize = {
it.joinToString(separator = ",")
},
deserialize = {
it.split(",")
},
update = {
copy(tags = it)
},
get = {
tags
},
fieldName = "Tags",
predefinedList = null
),
IEditable.EditableMetadata(
fieldType = IEditable.FieldType.StringListFiledType,
readOnly = false,
serialize = {
it.joinToString(separator = ",")
},
deserialize = {
it.split(",")
},
update = {
copy(meta = it)
},
get = {
meta
},
fieldName = "Meta",
predefinedList = null
),
IEditable.EditableMetadata(
fieldType = IEditable.FieldType.Template,
readOnly = false,
serialize = {
it.id.toString()
},
deserialize = { uuid ->
templateList.first {
it.id.toString() == uuid
}
},
update = {
copy(template = it)
},
get = {
template
},
fieldName = "Template",
predefinedList = templateList
)
)
}
override fun serialize(): String {
return Json.encodeToString(this)
}
}
| 16 |
Kotlin
|
0
| 2 |
81830ed91f528043da381233bae4d31eaffdaccc
| 5,659 |
kotlin-blogpost-engine
|
MIT License
|
src/main/kotlin/io/fdeitylink/util/FileUtils.kt
|
fdeitylink
| 125,763,801 | false | null |
/*
* Copyright 2018 Brian "FDeityLink" Christian
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.fdeitylink.util
import java.nio.file.Path
/**
* The [filename][Path.getFileName] of `this` [Path] as a [String]
*/
val Path.name get() = this.fileName.toString()
/**
* The [name][Path.getFileName] of `this` [Path] in all lower case
*/
val Path.lowerCaseName get() = name.toLowerCase()
/**
* The extension of the [name][Path.getFileName] of `this` [Path], or `""` if there is none
*/
val Path.extension get() = this.fileName.toString().substringAfterLast('.', "")
/**
* The extension of the [name][Path.getFileName] of `this` [Path] in all lower case, or `""` if there is none
*/
val Path.lowerCaseExtension get() = extension.toLowerCase()
/**
* The [name][Path.getFileName] of `this` [Path] minus its [extension][Path.extension]
*/
val Path.nameSansExtension get() = name.removeSuffix(extension)
/**
* The [name][Path.getFileName] of `this` [Path] minus its [extension][Path.extension] in all lowe case
*/
val Path.lowerCaseNameSansExtension get() = nameSansExtension.toLowerCase()
| 0 |
Kotlin
|
0
| 1 |
8c8eb8afce1c043cbcf465371f3b9380e7201b55
| 1,651 |
kero-edit-kt
|
Apache License 2.0
|
fourthline/src/main/java/de/solarisbank/sdk/fourthline/data/location/LocationDataSourceImpl.kt
|
Solarisbank
| 336,233,277 | false |
{"Kotlin": 468986, "Java": 6478, "Shell": 1215}
|
package de.solarisbank.sdk.fourthline.data.location
import android.annotation.SuppressLint
import android.content.Context
import android.location.LocationManager
import androidx.core.location.LocationCompat
import com.google.android.gms.location.LocationRequest.PRIORITY_HIGH_ACCURACY
import com.google.android.gms.location.LocationServices
import com.google.android.gms.tasks.CancellationTokenSource
import de.solarisbank.sdk.fourthline.data.dto.Location
import de.solarisbank.sdk.fourthline.data.dto.LocationResult
import io.reactivex.Single
import io.reactivex.subjects.SingleSubject
import timber.log.Timber
class LocationDataSourceImpl(private val applicationContext: Context) : LocationDataSource {
private val locationManager =
applicationContext.getSystemService(Context.LOCATION_SERVICE) as LocationManager
private var locationResultSubject: SingleSubject<LocationResult>? = null
private var count = 0
@SuppressLint("MissingPermission")
private fun dispatchLocationRequest() {
Timber.d("dispatchLocationRequest() 00")
count++
LocationServices
.getFusedLocationProviderClient(applicationContext).getCurrentLocation(PRIORITY_HIGH_ACCURACY, CancellationTokenSource().token)
.addOnSuccessListener {
if (!LocationCompat.isMock(it)) {
Timber.d("dispatchLocationRequest() 1")
count = 0
locationResultSubject!!.onSuccess(LocationResult.Success(Location(it)))
locationResultSubject!!.onSuccess(LocationResult.Success(Location(it)))
} else {
if (count < FETCHING_LOCATION_AMOUNT) {
Timber.d("dispatchLocationRequest() 2")
dispatchLocationRequest()
} else {
Timber.d("dispatchLocationRequest() 3")
count = 0
locationResultSubject!!.onSuccess(LocationResult.LocationFetchingError)
}
}
}
}
@SuppressLint("MissingPermission")
private fun obtainLocationDto() {
var isGpsEnabled = false
var isNetworkEnabled = false
Timber.d("obtainLocation() 0")
try {
Timber.d("obtainLocation() 1")
isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
} catch (ex: Exception) {
Timber.d("obtainLocation() 2")
locationResultSubject!!.onSuccess(LocationResult.LocationClientNotEnabledError)
}
try {
Timber.d("obtainLocation() 3")
isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
} catch (ex: Exception) {
Timber.d("obtainLocation() 4")
locationResultSubject!!.onSuccess(LocationResult.NetworkNotEnabledError)
}
if (!isGpsEnabled) {
Timber.d("obtainLocation() 5")
locationResultSubject!!.onSuccess(LocationResult.LocationClientNotEnabledError)
} else if (!isNetworkEnabled) {
Timber.d("obtainLocation() 6")
locationResultSubject!!.onSuccess(LocationResult.NetworkNotEnabledError)
} else {
Timber.d("obtainLocation() 7")
dispatchLocationRequest()
}
}
@Synchronized
override fun getLocation(): Single<LocationResult> {
Timber.d("getLocation() 0")
locationResultSubject = SingleSubject.create()
obtainLocationDto()
return locationResultSubject!!
}
companion object {
private const val FETCHING_LOCATION_AMOUNT = 2
}
}
| 0 |
Kotlin
|
0
| 6 |
1d3ffe547767d49c6a81c4198469c2b491648c83
| 3,707 |
identhub-android
|
MIT License
|
graphql-kotlin-spring-server/src/main/kotlin/com/expediagroup/graphql/spring/execution/ApolloSubscriptionSessionState.kt
|
babyfish-ct
| 247,506,424 | false | null |
/*
* Copyright 2019 Expedia, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.expediagroup.graphql.spring.execution
import com.expediagroup.graphql.spring.model.SubscriptionOperationMessage
import com.expediagroup.graphql.spring.model.SubscriptionOperationMessage.ServerMessages.GQL_COMPLETE
import org.reactivestreams.Subscription
import org.springframework.web.reactive.socket.WebSocketSession
import reactor.core.publisher.Flux
import java.util.concurrent.ConcurrentHashMap
internal class ApolloSubscriptionSessionState {
// Sessions are saved by web socket session id
internal val activeKeepAliveSessions = ConcurrentHashMap<String, Subscription>()
// Operations are saved by web socket session id, then operation id
internal val activeOperations = ConcurrentHashMap<String, ConcurrentHashMap<String, Subscription>>()
/**
* Save the session that is sending keep alive messages.
* This will override values without cancelling the subscription so it is the responsbility of the consumer to cancel.
* These messages will be stopped on [terminateSession].
*/
fun saveKeepAliveSubscription(session: WebSocketSession, subscription: Subscription) {
activeKeepAliveSessions[session.id] = subscription
}
/**
* Save the operation that is sending data to the client.
* This will override values without cancelling the subscription so it is the responsbility of the consumer to cancel.
* These messages will be stopped on [stopOperation].
*/
fun saveOperation(session: WebSocketSession, operationMessage: SubscriptionOperationMessage, subscription: Subscription) {
if (operationMessage.id != null) {
val operationsForSession: ConcurrentHashMap<String, Subscription> = activeOperations.getOrPut(session.id) { ConcurrentHashMap() }
operationsForSession[operationMessage.id] = subscription
}
}
/**
* Stop the subscription sending data. Does NOT terminate the session.
*/
fun stopOperation(session: WebSocketSession, operationMessage: SubscriptionOperationMessage): Flux<SubscriptionOperationMessage> {
if (operationMessage.id != null) {
val operationsForSession = activeOperations[session.id]
operationsForSession?.get(operationMessage.id)?.let {
it.cancel()
operationsForSession.remove(operationMessage.id)
if (operationsForSession.isEmpty()) {
activeOperations.remove(session.id)
}
return Flux.just(SubscriptionOperationMessage(type = GQL_COMPLETE.type, id = operationMessage.id))
}
}
return Flux.empty()
}
/**
* Terminate the session, cancelling the keep alive messages and all operations active for this session.
*/
fun terminateSession(session: WebSocketSession) {
activeOperations[session.id]?.forEach { _, subscription -> subscription.cancel() }
activeOperations.remove(session.id)
activeKeepAliveSessions[session.id]?.cancel()
activeKeepAliveSessions.remove(session.id)
session.close()
}
/**
* Looks up the operation for the client, to check if it already exists
*/
fun operationExists(session: WebSocketSession, operationMessage: SubscriptionOperationMessage): Boolean =
activeOperations[session.id]?.containsKey(operationMessage.id) ?: false
}
| 0 | null |
0
| 2 |
270c0b147753fc5c624de3601e3c064fc8d23946
| 3,982 |
graphql-kotlin
|
Apache License 2.0
|
features/finances/impl/src/test/kotlin/br/com/mob1st/features/finances/impl/domain/entities/CalculatorPreferencesTest.kt
|
mob1st
| 526,655,668 | false |
{"Kotlin": 674473, "Shell": 1558}
|
package br.com.mob1st.features.finances.impl.domain.entities
import br.com.mob1st.core.kotlinx.structures.Money
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.params.ParameterizedTest
import org.junit.jupiter.params.provider.Arguments
import org.junit.jupiter.params.provider.MethodSource
import kotlin.test.Test
class CalculatorPreferencesTest {
@ParameterizedTest
@MethodSource("appendSourceWithCentsDisabled")
fun `GIVEN a edit cents disabled WHEN append number THEN assert it is multiplied by 100 And number times 100 is added`(
initialAmount: Long,
numberToAppend: Int,
expectedResult: Long,
) {
// Given
val preferences = CalculatorPreferences(false)
val amount = Money(initialAmount)
val expected = Money(expectedResult)
// When
val actual = preferences.append(amount, numberToAppend)
// Then
assertEquals(expected, actual)
}
@ParameterizedTest
@MethodSource("appendSourceWithCentsEnabled")
fun `GIVEN a edit cents enabled WHEN append number THEN assert it is multiplied by 1 And number times 1 is added`(
initialAmount: Long,
numberToAppend: Int,
expectedResult: Long,
) {
// Given
val preferences = CalculatorPreferences(true)
val amount = Money(initialAmount)
val expected = Money(expectedResult)
// When
val actual = preferences.append(amount, numberToAppend)
// Then
assertEquals(expected, actual)
}
@ParameterizedTest
@MethodSource("eraseWithCentsEnabledSource")
fun `GIVEN a edit cents enabled WHEN erase THEN assert it is divided by 10`(
initialAmount: Long,
expectedResult: Long,
) {
// Given
val preferences = CalculatorPreferences(true)
val amount = Money(initialAmount)
val expected = Money(expectedResult)
// When
val actual = preferences.erase(amount)
// Then
assertEquals(expected, actual)
}
@ParameterizedTest
@MethodSource("eraseWithCentsDisabledSource")
fun `GIVEN a edit cents disabled WHEN erase THEN assert it is divided by 100`(
initialAmount: Long,
expectedResult: Long,
) {
// Given
val preferences = CalculatorPreferences(false)
val amount = Money(initialAmount)
val expected = Money(expectedResult)
// When
val actual = preferences.erase(amount)
// Then
assertEquals(expected, actual)
}
@Test
fun `GIVEN a edit cents enabled WHEN toggle amount THEN assert amount is divided by 100`() {
// Given
val preferences = CalculatorPreferences(true)
val amount = Money(100)
val expected = Money(1)
// When
val actual = preferences.toggleAmount(amount)
// Then
assertEquals(expected, actual)
}
@Test
fun `GIVEN a edit cents disabled WHEN toggle amount THEN assert amount is multiplied by 100`() {
// Given
val preferences = CalculatorPreferences(false)
val amount = Money(1)
val expected = Money(100)
// When
val actual = preferences.toggleAmount(amount)
// Then
assertEquals(expected, actual)
}
@Test
fun `GIVEN a edit cents enabled WHEN toggle THEN assert it is toggled`() {
// Given
val preferences = CalculatorPreferences(true)
val expected = CalculatorPreferences(false)
// When
val actual = preferences.toggleEditCents()
// Then
assertEquals(expected, actual)
}
@Test
fun `GIVEN a edit cents disabled WHEN toggle THEN assert it is toggled`() {
// Given
val preferences = CalculatorPreferences(false)
val expected = CalculatorPreferences(true)
// When
val actual = preferences.toggleEditCents()
// Then
assertEquals(expected, actual)
}
companion object {
@JvmStatic
fun appendSourceWithCentsDisabled() = listOf(
// initial state, number to append, expected state
Arguments.arguments(0L, 0, 0L),
Arguments.arguments(0L, 1, 100),
Arguments.arguments(100L, 1, 1100L),
)
@JvmStatic
fun appendSourceWithCentsEnabled() = listOf(
// initial state, number to append, expected state
Arguments.arguments(0L, 0, 0L),
Arguments.arguments(0L, 1, 1L),
Arguments.arguments(1L, 1, 11L),
Arguments.arguments(100L, 1, 1001L),
)
@JvmStatic
fun eraseWithCentsEnabledSource() = listOf(
// initial state, expected state
Arguments.arguments(0L, 0L),
Arguments.arguments(900L, 90L),
Arguments.arguments(99L, 9L),
Arguments.arguments(9L, 0L),
)
@JvmStatic
fun eraseWithCentsDisabledSource() = listOf(
// initial state, expected state
Arguments.arguments(0L, 0L),
Arguments.arguments(100L, 0L),
Arguments.arguments(900L, 0L),
Arguments.arguments(990L, 0L),
Arguments.arguments(9900L, 900L),
Arguments.arguments(99900L, 9900L),
)
}
}
| 11 |
Kotlin
|
0
| 3 |
6860644926fbc9f8fb686d6b14d9ef0545c139c0
| 5,339 |
bet-app-android
|
Apache License 2.0
|
gui-app/src/main/kotlin/dev/robocode/tankroyale/gui/util/EndpointChecker.kt
|
robocode-dev
| 457,523,927 | false |
{"Kotlin": 553807, "Java": 424635, "C#": 409918, "SCSS": 1367, "TypeScript": 1241, "Shell": 83}
|
package dev.robocode.tankroyale.gui.util
import java.net.InetAddress
import java.net.Inet6Address
import java.net.URI
import java.net.UnknownHostException
fun isRemoteEndpoint(endpoint: String) = !isLocalEndpoint(endpoint)
fun isLocalEndpoint(endpoint: String): Boolean {
val cleanEndpoint = endpoint.lowercase().trim()
// Handle special cases
if (cleanEndpoint == "localhost" || cleanEndpoint.startsWith("localhost:")) {
return true
}
// Try to parse as URI first
val uri = try {
URI(cleanEndpoint)
} catch (_: Exception) {
// If it's not a valid URI, try to parse it as an IP address or hostname
return isLocalIpAddressWithOptionalPort(cleanEndpoint)
}
// Extract host from URI
val host = uri.host ?: return isLocalIpAddressWithOptionalPort(cleanEndpoint)
return isLocalIpAddressWithOptionalPort(host)
}
private fun isLocalIpAddressWithOptionalPort(ipWithOptionalPort: String): Boolean {
val parts = ipWithOptionalPort.split(":")
val ip = when {
parts.size == 2 -> parts[0] // IPv4 with port
ipWithOptionalPort.startsWith("[") && ipWithOptionalPort.contains("]:") ->
ipWithOptionalPort.substringBefore("]").substring(1) // IPv6 with port
else -> ipWithOptionalPort // IP without port
}
return isLocalIpAddress(ip)
}
private fun isLocalIpAddress(ip: String): Boolean =
try {
val strippedIp = ip.split("%")[0].replace("[", "").replace("]", "")
val addr = InetAddress.getByName(strippedIp)
when {
addr.isLoopbackAddress -> true
addr.isSiteLocalAddress -> true
addr.isLinkLocalAddress -> true
addr.isAnyLocalAddress -> true
addr is Inet6Address -> isLocalIpv6(addr)
else -> false
}
} catch (_: UnknownHostException) {
false // If we can't resolve the host, assume it's not local
}
private fun isLocalIpv6(addr: Inet6Address): Boolean {
val bytes = addr.address
// Check for fc00::/7 (Unique Local IPv6 Unicast Addresses)
return (bytes[0].toInt() and 0xfe) == 0xfc
}
| 7 |
Kotlin
|
28
| 140 |
46da509668526e399b4bcd376a3518337153d8ba
| 2,138 |
tank-royale
|
Apache License 2.0
|
app/src/main/java/com/akb/journal/Util.kt
|
chineapplepunks
| 509,684,874 | false |
{"Kotlin": 46037}
|
package com.akb.journal
import android.app.Activity
import android.content.Context
import android.view.View
import android.view.inputmethod.InputMethodManager
import androidx.fragment.app.Fragment
import java.security.MessageDigest
import java.text.SimpleDateFormat
import java.util.*
/**
* A bunch of static utility functions.
* This is considered bad OO design, but I don't care. :-D
*
* @author Adam Brooke
*
*/
class Util {
companion object {
/**
* Hides the keyboard on a fragment.
*/
fun Fragment.hideKeyboard() {
view?.let { activity?.hideKeyboard(it) }
}
/**
* Hides the keyboard on an activity.
*/
fun Activity.hideKeyboard() {
hideKeyboard(currentFocus ?: View(this))
}
/**
* Hides the keyboard on a view.
*
* @param view The view that you want to hide the keyboard from.
*/
fun Context.hideKeyboard(view: View) {
val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
/**
* Simple function that formats a string based on a date.
*
* @param year The year of the date.
* @param month The month of the date. (0 Jan - 11 Dec)
* @param day The day of the month (1 - 31)
*
* @return The string formatted in "dd-MM-yyyy" form
*/
fun formatDate(year: Int, month: Int, day: Int) : String {
val cal = Calendar.getInstance()
cal.set(year,month,day)
val date = cal.time
val sdf = SimpleDateFormat("dd-MM-yyyy", Locale.getDefault())
return sdf.format(date)
}
/**
* Function that generates a SHA-256 hash based on a plan text string.
*
* @param plainText The string to generate the hash from.
*
* @return a SHA-256 encoded hash string.
*/
fun generateHash(plainText: String) : String {
val hexArray = "0123456789ABCDEF"
val bytes = MessageDigest
.getInstance("SHA-256")
.digest(plainText.toByteArray())
val hash = StringBuilder(bytes.size * 2)
bytes.forEach {
val i = it.toInt()
hash.append(hexArray[i shr 4 and 0x0f])
hash.append(hexArray[i and 0x0f])
}
return hash.toString()
}
}
}
| 0 |
Kotlin
|
0
| 0 |
ec2968e7ecd9939959b0da0cebb970003756238c
| 2,586 |
AKBasicJournal
|
MIT License
|
src/smartwatch/WorkoutTracker/app/src/main/java/com/example/workouttracker/presentation/RequiredFieldsSplashScreen.kt
|
NHutch2002
| 708,031,276 | false |
{"Kotlin": 175430, "TeX": 69852}
|
package com.example.workouttracker.presentation
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import androidx.wear.compose.material.Text
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
@Composable
fun RequiredFieldsSplashScreen(navController: NavController) {
val coroutineScope = rememberCoroutineScope()
LaunchedEffect(Unit) {
delay(2000)
coroutineScope.launch(Dispatchers.Main) {
navController.navigate("profile_view")
}
}
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.fillMaxSize(),
) {
Text(
text = "Please Fill\nOut All\nRequired Fields!",
textAlign = TextAlign.Center,
fontSize = 24.sp
)
}
}
| 4 |
Kotlin
|
0
| 1 |
f4001f21d0a63f330c566087294f8d2cef1a8fd3
| 1,323 |
ticwatch-heart-tracker
|
MIT License
|
src/main/kotlin/org/jetbrains/numkt/core/None.kt
|
Kotlin
| 225,367,588 | false | null |
/*
* Copyright 2019 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.numkt.core
class None {
companion object {
operator fun rangeTo(other: Int): Slice = Slice.fromClosedSlice(null, other, 1)
operator fun rangeTo(other: Companion): Slice =
Slice.fromClosedSlice(null, null, 1)
const val value: String = "None"
val none = None()
}
override fun toString(): String {
return value
}
}
| 11 | null |
11
| 313 |
2f1421883c201df60c57eaa4db4c3ee74dc40413
| 1,002 |
kotlin-numpy
|
Apache License 2.0
|
PullDownView/src/main/java/com/santi/pulldownview/contracts/ContentCallback.kt
|
saantiaguilera
| 63,188,036 | false | null |
package com.santi.pulldownview.contracts
/**
*
* Created by saguilera on 7/15/16.
*/
//With kotlin 1.1 we can do typedefs and change this for OnContentShown = () -> Unit
interface ContentCallback {
fun onContentShown() {}
fun onContentHidden() {}
}
| 0 |
Kotlin
|
0
| 0 |
2575f287806b81b9b834f918eabfd7ecb3ec7ca3
| 260 |
android-view-pull-down-layout
|
MIT License
|
src/test/kotlin/com/github/mohamead/spiderlog/plugin/SpiderlogIconsTest.kt
|
mohamead
| 475,413,657 | false |
{"Kotlin": 23147}
|
package com.github.mohamead.spiderlog.plugin
import com.github.mohamead.spiderlog.plugin.icons.SpiderlogIcons
import org.junit.jupiter.api.Assertions.assertAll
import org.junit.jupiter.api.Assertions.assertNotNull
import org.junit.jupiter.api.Test
class SpiderlogIconsTest {
@Test
fun toolWindowIconTest() {
val icon = SpiderlogIcons.spiderlog
assertAll(
{ assertNotNull(icon) }
)
}
}
| 0 |
Kotlin
|
0
| 3 |
696adcb4abbfd0aa2273fd58b1f950bf903fadf2
| 436 |
spiderlog-plugin
|
Apache License 2.0
|
client/slack-api-client/src/main/kotlin/com/kreait/slack/api/group/chat/ChatMethodGroup.kt
|
ramyaravi-opsmx
| 317,497,071 | true |
{"Kotlin": 1216622, "Shell": 935}
|
package com.kreait.slack.api.group.chat
/**
* Convenience class to handle the chat operations
*
* [Slack Api Documentation](https://api.slack.com/methods)
*/
interface ChatMethodGroup {
/**
* Deletes a Message from the chat
* https://api.slack.com/methods/chat.delete
*/
fun delete(authToken: String): ChatDeleteMethod
/**
* Retrieve a permalink URL for a specific extant message
* https://api.slack.com/methods/chat.getPermalink
*/
fun getPermalink(authToken: String): ChatGetPermalinkMethod
/**
* Shares a me message into a channel.
* https://api.slack.com/methods/chat.meMessage
*/
fun meMessage(authToken: String): ChatMeMessageMethod
/**
* Sends an ephemeral message a channel
* Ephemeral messages are not persisted in the slack-database and can't be updated
* If possible, use slackclient.respond() with the response-url of e.g. a slack-command in order to be context independent
* https://api.slack.com/methods/chat.postEphemeral
*/
fun postEphemeral(authToken: String): ChatPostEphemeralMethod
/**
* sends a message to a channel
* https://api.slack.com/methods/chat.postMessage
*/
fun postMessage(authToken: String): ChatPostMessageMethod
/**
* Provide custom unfurl behavior for user-posted URLs
* https://api.slack.com/methods/chat.unfurl
*/
fun unfurl(authToken: String): ChatUnfurlMethod
/**
* Updates a message.
* hint: ephemeral messages can't be updated, since they are not persisted in the Slack-Database
* https://api.slack.com/methods/chat.update
*/
fun update(authToken: String): ChatUpdateMethod
}
| 0 | null |
0
| 0 |
d2eb88733f0513665b8a625351b599feba926b69
| 1,707 |
slack-spring-boot-starter
|
MIT License
|
src/com/android/adblib/utils/AutoCloseableUtils.kt
|
DevOculus-Meta-Quest
| 831,217,289 | false |
{"Kotlin": 1110908, "Starlark": 15263}
|
package com.android.adblib.utils
/**
* Ensure [AutoCloseable.close] is called if [block] throws an exception. This method can be used
* to prevent leaking [AutoCloseable] during initialization, i.e. before they are visible to
* callers.
*/
inline fun <T : AutoCloseable, R> T.closeOnException(block: (T) -> R): R {
try {
return block(this)
} catch (e: Throwable) {
this.safeClose(e)
throw e
}
}
fun AutoCloseable.safeClose(cause: Throwable) {
try {
close()
} catch (closeException: Throwable) {
cause.addSuppressed(closeException)
}
}
| 0 |
Kotlin
|
0
| 1 |
417de93b668ebdae1aa5d822616e3e6b17b4a2e9
| 605 |
AdbLib-Google-PlatformTools
|
MIT License
|
src/main/kotlin/jay/spawn/utils/Colour.kt
|
j4ys4j4
| 670,200,941 | false | null |
package jay.spawn.utils
enum class Colour(private val code: String) {
RESET("\u001B[0m"),
BLACK("\u001B[30m"),
RED("\u001B[31m"),
GREEN("\u001B[32m"),
YELLOW("\u001B[33m"),
BLUE("\u001B[34m"),
PURPLE("\u001B[35m"),
CYAN("\u001B[36m"),
WHITE("\u001B[37m");
fun apply(text: String): String {
return "$code$text${RESET.code}"
}
}
| 0 |
Kotlin
|
0
| 0 |
3dc092d5f46e4e3e05a35c9b027996118037d7ad
| 380 |
Spawn
|
Apache License 2.0
|
app/src/main/kotlin/com/absinthe/libchecker/features/applist/detail/ui/view/DetailsTitleView.kt
|
LibChecker
| 248,400,799 | false |
{"Kotlin": 1106890, "Java": 57146, "AIDL": 1149}
|
package com.absinthe.libchecker.view.detail
import android.content.Context
import android.util.AttributeSet
import android.util.TypedValue
import android.view.ContextThemeWrapper
import android.view.ViewGroup
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.view.marginStart
import androidx.core.view.marginTop
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.absinthe.libchecker.R
import com.absinthe.libchecker.recyclerview.HorizontalSpacesItemDecoration
import com.absinthe.libchecker.recyclerview.adapter.detail.AbiLabelsAdapter
import com.absinthe.libchecker.utils.extensions.getColor
import com.absinthe.libchecker.utils.extensions.getColorByAttr
import com.absinthe.libchecker.utils.extensions.getDimensionPixelSize
import com.absinthe.libchecker.view.AViewGroup
import com.absinthe.libchecker.view.app.AlwaysMarqueeTextView
class DetailsTitleView(context: Context, attributeSet: AttributeSet? = null) :
AViewGroup(context, attributeSet) {
val iconView = AppCompatImageView(context).apply {
val iconSize = context.getDimensionPixelSize(R.dimen.lib_detail_icon_size)
layoutParams = LayoutParams(iconSize, iconSize)
addView(this)
}
val appNameView = AlwaysMarqueeTextView(
ContextThemeWrapper(
context,
R.style.TextView_SansSerifMedium
)
).apply {
layoutParams = LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
).also {
it.marginStart = context.getDimensionPixelSize(R.dimen.normal_padding)
}
setTextColor(context.getColorByAttr(com.google.android.material.R.attr.colorOnSurface))
setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
addView(this)
}
val packageNameView =
AppCompatTextView(ContextThemeWrapper(context, R.style.TextView_SansSerif)).apply {
layoutParams = LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
setTextColor(context.getColorByAttr(com.google.android.material.R.attr.colorOnSurface))
setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
addView(this)
}
val versionInfoView = AppCompatTextView(
ContextThemeWrapper(
context,
R.style.TextView_SansSerifCondensed
)
).apply {
layoutParams = LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
setTextColor(android.R.color.darker_gray.getColor(context))
setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f)
addView(this)
}
val extraInfoView = AppCompatTextView(
ContextThemeWrapper(
context,
R.style.TextView_SansSerifCondensedMedium
)
).apply {
layoutParams = LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT
)
setTextColor(android.R.color.darker_gray.getColor(context))
setTextSize(TypedValue.COMPLEX_UNIT_SP, 12f)
addView(this)
}
val abiLabelsAdapter = AbiLabelsAdapter()
val abiLabelsRecyclerView = RecyclerView(context).apply {
layoutParams = LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT
).also {
it.topMargin = 4.dp
it.marginStart = (-4).dp
}
overScrollMode = RecyclerView.OVER_SCROLL_NEVER
adapter = abiLabelsAdapter
layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
isHorizontalScrollBarEnabled = false
clipToPadding = false
clipChildren = false
isNestedScrollingEnabled = false
setHasFixedSize(true)
addItemDecoration(HorizontalSpacesItemDecoration(4.dp))
[email protected](this)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
iconView.autoMeasure()
val textWidth =
measuredWidth - paddingStart - paddingEnd - iconView.measuredWidth - appNameView.marginStart
appNameView.measure(
textWidth.toExactlyMeasureSpec(),
appNameView.defaultHeightMeasureSpec(this)
)
packageNameView.measure(
textWidth.toExactlyMeasureSpec(),
packageNameView.defaultHeightMeasureSpec(this)
)
versionInfoView.measure(
textWidth.toExactlyMeasureSpec(),
versionInfoView.defaultHeightMeasureSpec(this)
)
extraInfoView.measure(
textWidth.toExactlyMeasureSpec(),
extraInfoView.defaultHeightMeasureSpec(this)
)
abiLabelsRecyclerView.measure(
textWidth.toExactlyMeasureSpec(),
abiLabelsRecyclerView.defaultHeightMeasureSpec(this)
)
val basicInfoTotalHeight =
appNameView.measuredHeight +
packageNameView.measuredHeight +
versionInfoView.measuredHeight +
extraInfoView.measuredHeight +
abiLabelsRecyclerView.measuredHeight +
abiLabelsRecyclerView.marginTop
setMeasuredDimension(
measuredWidth,
paddingTop +
(basicInfoTotalHeight).coerceAtLeast(iconView.measuredHeight) +
paddingBottom
)
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
iconView.layout(paddingStart, paddingTop)
appNameView.layout(iconView.right + appNameView.marginStart, paddingTop)
packageNameView.layout(appNameView.left, appNameView.bottom)
versionInfoView.layout(appNameView.left, packageNameView.bottom)
extraInfoView.layout(appNameView.left, versionInfoView.bottom)
abiLabelsRecyclerView.layout(appNameView.left + abiLabelsRecyclerView.marginStart, extraInfoView.bottom + abiLabelsRecyclerView.marginTop)
}
companion object {
private const val MEGA_BYTE_SI_UNITS = 1000 * 1000
}
}
| 38 |
Kotlin
|
293
| 3,870 |
0b59e409b47336ad0e29b7c078a17dd3061ade2c
| 5,767 |
LibChecker
|
Apache License 2.0
|
core.feature/src/main/java/lac/core/feature/core/utils/rx/ApplicationSchedulerProvider.kt
|
bandysik
| 143,031,693 | false | null |
package lac.core.feature.core.utils.rx
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
class ApplicationSchedulerProvider : SchedulerProvider {
override fun io() =
Schedulers.io()
override fun ui() =
AndroidSchedulers.mainThread()
override fun computation() =
Schedulers.computation()
}
| 0 |
Kotlin
|
0
| 1 |
c2e0478c93eb5eaf7ec1632d2257427a9174443e
| 389 |
LAC
|
Apache License 2.0
|
app/src/main/java/ar/edu/unlam/structureexample/ui/main/MainActivity.kt
|
Max-UNLaM
| 416,010,069 | false |
{"Kotlin": 6110}
|
package ar.edu.unlam.structureexample.ui.main
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.room.Room
import ar.edu.unlam.structureexample.AppDatabase
import ar.edu.unlam.structureexample.MIGRATION_1_2
import ar.edu.unlam.structureexample.RobotAdapter
import ar.edu.unlam.structureexample.databinding.ActivityMainBinding
import ar.edu.unlam.structureexample.data.RobotDao
class MainActivity : AppCompatActivity() {
private lateinit var database: AppDatabase
private lateinit var robotDao: RobotDao
private lateinit var robotAdapter: RobotAdapter
private lateinit var robotBinding: ActivityMainBinding
companion object {
private fun buildDatabase(context: Context): AppDatabase {
return Room.databaseBuilder(
context,
AppDatabase::class.java,
"room-showroom-db"
)
.allowMainThreadQueries()
.addMigrations(MIGRATION_1_2)
.build()
}
}
/**
* Manual dependency injection
*/
private fun injectDependencies() {
this.database = buildDatabase(this.applicationContext)
this.robotDao = this.database.robotDao()
this.robotAdapter = RobotAdapter { }
}
private fun setupRecyclerView() {
robotBinding.recyclerView.layoutManager =
LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false)
robotBinding.recyclerView.adapter = robotAdapter
}
private fun populate() {
var robots = robotDao.getAll()
if (robots.isEmpty()) {
this.robotDao.populate()
robots = this.robotDao.getAll()
}
robotAdapter.updateRobots(robots)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
robotBinding = ActivityMainBinding.inflate(LayoutInflater.from(this))
injectDependencies()
setContentView(robotBinding.root)
setupRecyclerView()
populate()
}
}
| 0 |
Kotlin
|
0
| 0 |
61bb9f2a85bda2d972362c68afa8cdaf9f7c7283
| 2,186 |
structure-example
|
MIT License
|
domain/src/main/java/com/jyproject/domain/features/login/NaverLoginUseCase.kt
|
JunYeong0314
| 778,833,940 | false |
{"Kotlin": 24204}
|
package com.jyproject.domain.features.login
import javax.inject.Inject
class NaverLoginUseCase @Inject constructor(
private val naverLoginRepository: NaverLoginRepository
){
operator fun invoke(context: Any, updateSocialToken: (String?) -> Unit) {
naverLoginRepository.startNaverLogin(context = context) { updateSocialToken(it) }
}
}
| 0 |
Kotlin
|
0
| 0 |
c3ed6f7a4ba8edc7873f0fe189ab8b667538d836
| 356 |
PlacePick
|
MIT License
|
api/src/main/kotlin/io/sparkled/viewmodel/ScheduledTaskViewModel.kt
|
sparkled
| 53,776,686 | false | null |
package io.sparkled.viewmodel
import io.sparkled.model.entity.ScheduledJobAction
import io.sparkled.model.entity.v2.ScheduledTaskEntity
import io.sparkled.model.util.IdUtils
data class ScheduledTaskViewModel(
var id: Int = IdUtils.NO_ID,
var action: ScheduledJobAction,
var cronExpression: String,
var value: String? = null,
var playlistId: Int? = null
) {
fun toModel() = ScheduledTaskEntity(
id = id,
action = action,
cronExpression = cronExpression,
value = value,
playlistId = playlistId
)
companion object {
fun fromModel(model: ScheduledTaskEntity) = ScheduledTaskViewModel(
id = model.id,
action = model.action,
cronExpression = model.cronExpression,
value = model.value,
playlistId = model.playlistId
)
}
}
| 20 |
Kotlin
|
21
| 72 |
562e917af188c2ebf98c8e729446cde101f96dc2
| 870 |
sparkled
|
MIT License
|
core/src/main/java/intensigame/util/FixedMath.kt
|
DanielLukic
| 760,124,404 | false |
{"Kotlin": 139190, "Java": 110585}
|
package intensigame.util
import intensigame.graphics.Position
object FixedMath {
const val FIXED_SHIFT = 12
const val FIXED_MULTIPLIER = 1 shl FIXED_SHIFT
const val FIXED_MASK = FIXED_MULTIPLIER - 1
const val FIXED_ONE = FIXED_MULTIPLIER
const val FIXED_HALF = FIXED_ONE shr 1
const val FIXED_0 = 0
const val FIXED_0_1 = FIXED_ONE / 10
const val FIXED_0_2 = FIXED_ONE / 5
const val FIXED_0_25 = FIXED_ONE / 4
const val FIXED_0_5 = FIXED_ONE / 2
const val FIXED_1 = FIXED_ONE
const val FIXED_5 = FIXED_ONE * 5
const val FIXED_10 = FIXED_ONE * 10
const val FIXED_25 = FIXED_ONE * 25
const val FIXED_30 = FIXED_ONE * 30
const val FIXED_50 = FIXED_ONE * 50
const val FIXED_100 = FIXED_ONE * 100
const val FIXED_180 = FIXED_ONE * 180
const val FIXED_360 = FIXED_ONE * 360
fun toFixed(aInteger: Int): Int {
return aInteger shl FIXED_SHIFT
}
fun toInt(aFixedDecimal: Int): Int {
return aFixedDecimal shr FIXED_SHIFT
}
fun toInt(aFixedDecimal: Long): Long {
return aFixedDecimal shr FIXED_SHIFT
}
fun toIntRounded(aFixedDecimal: Int): Int {
return aFixedDecimal + FIXED_HALF shr FIXED_SHIFT
}
fun toFixed(aPosition: Position) {
aPosition.x = toFixed(aPosition.x)
aPosition.y = toFixed(aPosition.y)
}
fun toInt(aFixedPosition: Position) {
aFixedPosition.x = toInt(aFixedPosition.x)
aFixedPosition.y = toInt(aFixedPosition.y)
}
fun toIntRounded(aFixedPosition: Position) {
aFixedPosition.x = toIntRounded(aFixedPosition.x)
aFixedPosition.y = toIntRounded(aFixedPosition.y)
}
fun fraction(aFixedDecimal: Int): Int {
return aFixedDecimal and FIXED_MASK
}
fun mul(aFixedDecimal1: Int, aFixedDecimal2: Int): Int {
val a = aFixedDecimal1.toLong() * aFixedDecimal2.toLong()
return (a shr FIXED_SHIFT).toInt()
}
fun div(aFixedDecimal1: Int, aFixedDecimal2: Int): Int {
val a = aFixedDecimal1.toLong()
val b = aFixedDecimal2.toLong()
return ((a shl FIXED_SHIFT) / b).toInt()
}
fun length(aFixedDeltaX: Int, aFixedDeltaY: Int): Int {
val a2 = mul(aFixedDeltaX, aFixedDeltaX).toLong()
val b2 = mul(aFixedDeltaY, aFixedDeltaY).toLong()
val c2 = toInt(a2 + b2 shl LENGTH_PRE_SHIFT)
val length = IntegerSquareRoot.sqrt(c2.toInt())
return toFixed(length) shr LENGTH_POST_SHIFT
}
fun toString(aFixedValue: Int): String {
return Integer.toString(toInt(aFixedValue))
}
private const val LENGTH_PRE_SHIFT = FIXED_SHIFT
private const val LENGTH_POST_SHIFT = LENGTH_PRE_SHIFT / 2
}
| 0 |
Kotlin
|
0
| 0 |
fb6af1efb8276bd40f282d1a18b6b1d0336794a7
| 2,722 |
gdx-js-dash
|
MIT License
|
src/main/kotlin/net/rebux/jumpandrun/item/impl/RestartItem.kt
|
7rebux
| 402,599,961 | false |
{"Kotlin": 51117}
|
package net.rebux.jumpandrun.item.impl
import net.rebux.jumpandrun.Instance
import net.rebux.jumpandrun.data
import net.rebux.jumpandrun.item.Item
import net.rebux.jumpandrun.item.ItemRegistry
import org.bukkit.Material
import org.bukkit.entity.Player
import org.bukkit.inventory.ItemStack
object RestartItem : Item() {
val id = ItemRegistry.register(this)
// TODO: find a way to remove this
private val plugin = Instance.plugin
override fun createItemStack(): ItemStack {
return Builder()
.material(Material.REDSTONE)
.displayName(plugin.config.getString("items.restart"))
.build()
}
override fun onInteract(player: Player) {
if (!player.data.isInParkour()) {
return
}
val startLocation = player.data.parkour!!.location
player.data.checkpoint = startLocation
player.data.timer.stop()
player.teleport(startLocation)
}
}
| 0 |
Kotlin
|
0
| 1 |
762e83ce4ae91a166bf26ce722997b2aea9be50e
| 960 |
jump-and-run
|
MIT License
|
app/src/main/java/tech/rollw/player/audio/AudioContent.kt
|
Roll-W
| 743,429,922 | false |
{"Kotlin": 463344, "C++": 77604, "Java": 5904, "CMake": 2981, "C": 1523}
|
/*
* Copyright (C) 2024 RollW
*
* 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 tech.rollw.player.audio
import tech.rollw.support.io.ContentPath
import java.io.Serializable
/**
* Combine audio and its content path for
* easy access to the audio file.
*
* @author RollW
*/
data class AudioContent(
val audio: Audio,
val path: ContentPath
) : Serializable {
companion object {
fun Audio.toAudioContent(path: ContentPath) = AudioContent(this, path)
fun List<Audio>.toAudioContentList(
audioPaths: List<AudioPath>,
checkNonNull: Boolean = false
) = map {
val audioPath = audioPaths.find { path -> path.id == it.id }
if (audioPath == null && checkNonNull) {
throw IllegalArgumentException("Audio path cannot found for audio: ${it.id}.")
}
AudioContent(it, audioPath?.path ?: ContentPath.EMPTY)
}
val EMPTY = AudioContent(Audio.EMPTY, ContentPath.EMPTY)
}
}
| 0 |
Kotlin
|
0
| 1 |
614e7c055d22602dc75e524af2ca67e09f5842ab
| 1,529 |
sound-source-player
|
Apache License 2.0
|
ospf-kotlin-utils/src/main/fuookami/ospf/kotlin/utils/physics/dimension/DerivedQuantity.kt
|
fuookami
| 359,831,793 | false |
{"Kotlin": 2440181, "Python": 6629}
|
package fuookami.ospf.kotlin.utils.physics.dimension
class DerivedQuantity(val quantities: List<FundamentalQuantity>) {
constructor(dimension: FundamentalQuantityDimension) : this(arrayListOf(FundamentalQuantity(dimension))) {}
}
| 0 |
Kotlin
|
0
| 4 |
b34cda509b31884e6a15d77f00a6134d001868de
| 235 |
ospf-kotlin
|
Apache License 2.0
|
presentation/notification/src/main/java/com/depromeet/threedays/notification/NotificationHistoryUI.kt
|
depromeet12th
| 548,194,728 | false | null |
package com.depromeet.threedays.notification
import com.depromeet.threedays.domain.entity.notification.NotificationHistory
import com.depromeet.threedays.domain.entity.notification.NotificationHistoryStatus
import java.time.LocalDateTime
data class NotificationHistoryUI(
val id: Long,
val title: String,
val content: String,
var status: NotificationHistoryStatus,
val createdAt: LocalDateTime,
) {
companion object {
fun from(notificationHistory: NotificationHistory) = NotificationHistoryUI(
id = notificationHistory.notificationHistoryId,
title = notificationHistory.title,
content = notificationHistory.content,
status = notificationHistory.status,
createdAt = notificationHistory.createdAt,
)
}
fun copyOf(
status: NotificationHistoryStatus?,
): NotificationHistoryUI {
return NotificationHistoryUI(
id = this.id,
title = this.title,
content = this.content,
status = status ?: this.status,
createdAt = this.createdAt,
)
}
}
| 0 |
Kotlin
|
1
| 15 |
1cc08fcf2b038924ab0fe5feaaff548974f40f4d
| 1,132 |
three-days-android
|
MIT License
|
Droidcon-Boston/app/src/main/java/com/mentalmachines/droidcon_boston/views/agenda/AgendaDayPagerAdapter.kt
|
anandwana001
| 165,459,731 | true |
{"Kotlin": 110647}
|
package com.mentalmachines.droidcon_boston.views.agenda
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.mentalmachines.droidcon_boston.data.Schedule
class AgendaDayPagerAdapter internal constructor(
fm: FragmentManager,
private val myAgenda: Boolean
) :
FixedFragmentStatePagerAdapter(fm) {
private val PAGE_COUNT = 2
private val tabTitles = arrayOf("Day 1", "Day 2")
override fun getCount(): Int {
return PAGE_COUNT
}
override fun getItem(position: Int): Fragment {
return AgendaDayFragment.newInstance(
myAgenda,
if (position == 0) Schedule.MONDAY else Schedule.TUESDAY
)
}
override fun getPageTitle(position: Int): CharSequence? {
return tabTitles[position]
}
override fun updateFragmentItem(position: Int, fragment: Fragment) {
if (fragment is AgendaDayFragment) {
fragment.updateList()
}
}
override fun getFragmentItem(position: Int): Fragment {
return getItem(position)
}
}
| 0 |
Kotlin
|
0
| 0 |
69b361fd398ce04cd77c65125dda9915fe3b4cca
| 1,085 |
conference-app-android
|
Apache License 2.0
|
pstatus-graphql-ktor/src/main/kotlin/gov/cdc/ocio/processingstatusapi/loaders/ReportLoader.kt
|
CDCgov
| 679,761,337 | false |
{"Kotlin": 592830, "Java": 27506, "TypeScript": 7647, "Python": 6204, "JavaScript": 2382}
|
package gov.cdc.ocio.processingstatusapi.loaders
import com.azure.cosmos.models.CosmosQueryRequestOptions
import gov.cdc.ocio.processingstatusapi.exceptions.BadRequestException
import gov.cdc.ocio.processingstatusapi.models.Report
import gov.cdc.ocio.processingstatusapi.models.dao.ReportDao
import gov.cdc.ocio.processingstatusapi.models.DataStream
import gov.cdc.ocio.processingstatusapi.models.SortOrder
import graphql.schema.DataFetchingEnvironment
import io.ktor.server.auth.*
import io.ktor.server.auth.jwt.*
class ForbiddenException(message: String) : RuntimeException(message)
/**
* Report loader for graphql
*/
class ReportLoader: CosmosLoader() {
/**
* Get all reports associated with the provided upload id.
*
* @param dataFetchingEnvironment DataFetchingEnvironment
* @param uploadId String
* @param reportsSortedBy String?
* @param sortOrder SortOrder?
* @return List<Report>
*/
fun getByUploadId(dataFetchingEnvironment: DataFetchingEnvironment,
uploadId: String,
reportsSortedBy: String?,
sortOrder: SortOrder?
): List<Report> {
// Obtain the data streams available to the user from the data fetching env.
val authContext = dataFetchingEnvironment.graphQlContext.get<AuthenticationContext>("AuthContext")
var dataStreams: List<DataStream>? = null
authContext?.run {
val principal = authContext.principal<JWTPrincipal>()
dataStreams = principal?.payload?.getClaim("dataStreams")?.asList(DataStream::class.java)
}
val reportsSqlQuery = StringBuilder()
reportsSqlQuery.append("select * from r where r.uploadId = '$uploadId'")
when (reportsSortedBy) {
"timestamp" -> {
val sortOrderVal = when (sortOrder) {
SortOrder.Ascending -> "asc"
SortOrder.Descending -> "desc"
else -> "asc" // default
}
reportsSqlQuery.append(" order by r.timestamp $sortOrderVal")
}
null -> {
// nothing to sort by
}
else -> {
throw BadRequestException("Reports can not be sorted by '$reportsSortedBy'")
}
}
val reportItems = reportsContainer?.queryItems(
reportsSqlQuery.toString(), CosmosQueryRequestOptions(),
ReportDao::class.java
)
// Convert the report DAOs to reports and ensure the user has access to them.
val reports = mutableListOf<Report>()
reportItems?.forEach { reportItem ->
val report = reportItem.toReport()
dataStreams?.run {
if (dataStreams?.firstOrNull { ds -> ds.name == report.dataStreamId && ds.route == report.dataStreamRoute } == null)
throw ForbiddenException("You are not allowed to access this resource.")
}
reports.add(report)
}
return reports
}
/**
* Search for reports with the provided ids.
*
* @param ids List<String>
* @return List<Report>
*/
fun search(ids: List<String>): List<Report> {
val quotedIds = ids.joinToString("\",\"", "\"", "\"")
val reportsSqlQuery = "select * from r where r.id in ($quotedIds)"
val reportItems = reportsContainer?.queryItems(
reportsSqlQuery, CosmosQueryRequestOptions(),
ReportDao::class.java
)
val reports = mutableListOf<Report>()
reportItems?.forEach { reports.add(it.toReport()) }
return reports
}
}
| 1 |
Kotlin
|
0
| 1 |
86ef47c67c15ec84c4686fc3e4d2512cb6bbe8a3
| 3,684 |
data-exchange-processing-status
|
Apache License 2.0
|
libs/utils/src/main/java/me/pxq/utils/extensions/Extensions.kt
|
drkingwater
| 279,571,591 | false | null |
package me.pxq.utils.extensions
import android.content.res.Resources
import android.graphics.Bitmap
import android.util.TypedValue
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.Transformation
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions
import com.bumptech.glide.request.RequestOptions
/**
* Description: kotlinๆฉๅฑๆนๆณ
* Author : pxq
* Date : 2020/8/2 6:10 PM
*/
/**
* ๆ นๆฎๆๆบ็ๅ่พจ็ๅฐdp่ฝฌๆไธบpxใ
*/
val Float.dp2px
get() = TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
this,
Resources.getSystem().displayMetrics
)
/**
* ๅพ็ๅ ่ฝฝๆฉๅฑๆนๆณ
*/
fun ImageView.load(
url: String,
trans: Transformation<Bitmap>? = null,
placeHolderId: Int = 0
) {
if (trans == null) {
Glide.with(this)
.load(url)
.placeholder(placeHolderId)
.transition(DrawableTransitionOptions.withCrossFade())
.into(this)
} else {
Glide.with(this)
.load(url)
.placeholder(placeHolderId)
.apply(
RequestOptions.bitmapTransform(trans)
)
.into(this)
}
}
/**
* ๅพ็ๅ ่ฝฝๆฉๅฑๆนๆณ
*/
fun ImageView.load(
resId: Int,
trans: Transformation<Bitmap>? = null,
placeHolderId: Int = 0,
) {
if (trans == null) {
Glide.with(this)
.load(resId)
.placeholder(placeHolderId)
.transition(DrawableTransitionOptions.withCrossFade())
.into(this)
} else {
Glide.with(this)
.load(resId)
.placeholder(placeHolderId)
.apply(
RequestOptions.bitmapTransform(trans)
)
.into(this)
}
}
| 0 |
Kotlin
|
4
| 15 |
0feb6ce3cbd9d396ef79d7bd4e6da60f11a13f2c
| 1,750 |
eyepetizer-kotlin
|
Apache License 2.0
|
app/src/main/java/com/sama/connection/domain/DiscoveredUserListRepository.kt
|
sama-app
| 363,692,054 | false | null |
package com.sama.connection.domain
import com.sama.common.DomainRepository
import com.sama.users.domain.UserId
import org.springframework.data.repository.Repository
@DomainRepository
interface DiscoveredUserListRepository: Repository<DiscoveredUserList, UserId> {
fun findById(userId: UserId): DiscoveredUserList
fun save(discoveredUserList: DiscoveredUserList)
}
| 0 |
Kotlin
|
1
| 2 |
a73319e26a22bf09aeb6bcc1cc2feaf3723ba0b9
| 374 |
sama-service
|
Apache License 2.0
|
blockchain-tezos/src/main/java/it/airgap/beaconsdk/blockchain/tezos/internal/creator/V2BeaconMessageTezosCreator.kt
|
airgap-it
| 303,679,512 | false | null |
package it.airgap.beaconsdk.blockchain.tezos.internal.creator
import it.airgap.beaconsdk.blockchain.tezos.internal.message.v2.V2TezosMessage
import it.airgap.beaconsdk.core.internal.blockchain.creator.V2BeaconMessageBlockchainCreator
import it.airgap.beaconsdk.core.internal.message.v2.V2BeaconMessage
import it.airgap.beaconsdk.core.message.BeaconMessage
internal class V2BeaconMessageTezosCreator : V2BeaconMessageBlockchainCreator {
override fun from(senderId: String, message: BeaconMessage): Result<V2BeaconMessage> = runCatching { V2TezosMessage.from(senderId, message) }
}
| 4 |
Kotlin
|
7
| 8 |
cf129f2437a3c7498f2b6b5e401b0134e58fe3b0
| 585 |
beacon-android-sdk
|
MIT License
|
src/main/kotlin/com/jonaswanke/unicorn/script/Command.kt
|
JonasWanke
| 166,664,826 | false | null |
package com.jonaswanke.unicorn.script
import com.jonaswanke.unicorn.console.ConsoleRunContext
import com.jonaswanke.unicorn.core.BaseCommand
import com.jonaswanke.unicorn.script.parameters.UnicornParameter
import com.jonaswanke.unicorn.utils.MarkupBuilder
import com.jonaswanke.unicorn.utils.buildMarkup
class UnicornCommandBuilder(
val name: String,
val aliases: List<String>
) {
// region Help
@UnicornMarker
var help: String = ""
@UnicornMarker
fun help(message: MarkupBuilder) {
help = buildMarkup(message).toConsoleString()
}
// endregion
// region Body
var bodyBuilder: () -> BaseCommand = {
object : BaseCommand(name, aliases, help, invokeWithoutSubcommand = false) {}
}
@UnicornMarker
fun run(body: Command0Body) {
bodyBuilder = {
object : BaseCommand(name, aliases, help, invokeWithoutSubcommand = true) {
override fun execute(context: ConsoleRunContext) = context.body()
}
}
}
@UnicornMarker
fun <P1> run(param1: UnicornParameter<P1>, body: Command1Body<P1>) {
bodyBuilder = {
object : BaseCommand(name, aliases, help, invokeWithoutSubcommand = true) {
val p1: P1 by param1
override fun execute(context: ConsoleRunContext) = context.body(p1)
}
}
}
@UnicornMarker
fun <P1, P2> run(
param1: UnicornParameter<P1>,
param2: UnicornParameter<P2>,
body: Command2Body<P1, P2>
) {
bodyBuilder = {
object : BaseCommand(name, aliases, help, invokeWithoutSubcommand = true) {
val p1: P1 by param1
val p2: P2 by param2
override fun execute(context: ConsoleRunContext) = context.body(p1, p2)
}
}
}
@UnicornMarker
fun <P1, P2, P3> run(
param1: UnicornParameter<P1>,
param2: UnicornParameter<P2>,
param3: UnicornParameter<P3>,
body: Command3Body<P1, P2, P3>
) {
bodyBuilder = {
object : BaseCommand(name, aliases, help, invokeWithoutSubcommand = true) {
val p1: P1 by param1
val p2: P2 by param2
val p3: P3 by param3
override fun execute(context: ConsoleRunContext) = context.body(p1, p2, p3)
}
}
}
@UnicornMarker
fun <P1, P2, P3, P4> run(
param1: UnicornParameter<P1>,
param2: UnicornParameter<P2>,
param3: UnicornParameter<P3>,
param4: UnicornParameter<P4>,
body: Command4Body<P1, P2, P3, P4>
) {
bodyBuilder = {
object : BaseCommand(name, aliases, help, invokeWithoutSubcommand = true) {
val p1: P1 by param1
val p2: P2 by param2
val p3: P3 by param3
val p4: P4 by param4
override fun execute(context: ConsoleRunContext) = context.body(p1, p2, p3, p4)
}
}
}
@UnicornMarker
fun <P1, P2, P3, P4, P5> run(
param1: UnicornParameter<P1>,
param2: UnicornParameter<P2>,
param3: UnicornParameter<P3>,
param4: UnicornParameter<P4>,
param5: UnicornParameter<P5>,
body: Command5Body<P1, P2, P3, P4, P5>
) {
bodyBuilder = {
object : BaseCommand(name, aliases, help, invokeWithoutSubcommand = true) {
val p1: P1 by param1
val p2: P2 by param2
val p3: P3 by param3
val p4: P4 by param4
val p5: P5 by param5
override fun execute(context: ConsoleRunContext) = context.body(p1, p2, p3, p4, p5)
}
}
}
@UnicornMarker
fun <P1, P2, P3, P4, P5, P6> run(
param1: UnicornParameter<P1>,
param2: UnicornParameter<P2>,
param3: UnicornParameter<P3>,
param4: UnicornParameter<P4>,
param5: UnicornParameter<P5>,
param6: UnicornParameter<P6>,
body: Command6Body<P1, P2, P3, P4, P5, P6>
) {
bodyBuilder = {
object : BaseCommand(name, aliases, help, invokeWithoutSubcommand = true) {
val p1: P1 by param1
val p2: P2 by param2
val p3: P3 by param3
val p4: P4 by param4
val p5: P5 by param5
val p6: P6 by param6
override fun execute(context: ConsoleRunContext) = context.body(p1, p2, p3, p4, p5, p6)
}
}
}
// endregion
// region Subcommands
private val subcommands = mutableListOf<BaseCommand>()
@UnicornMarker
fun command(name: String, vararg aliases: String, commandBuilder: CommandBuilder) {
val command = UnicornCommandBuilder(name, aliases.asList())
.apply { commandBuilder() }
.build()
subcommands += command
}
// endregion
fun build(): BaseCommand {
return bodyBuilder().apply {
subcommands.forEach { addSubcommand(it) }
}
}
}
typealias CommandBuilder = UnicornCommandBuilder.() -> Unit
typealias Command0Body = ConsoleRunContext.() -> Unit
typealias Command1Body<P1> = ConsoleRunContext.(P1) -> Unit
typealias Command2Body<P1, P2> = ConsoleRunContext.(P1, P2) -> Unit
typealias Command3Body<P1, P2, P3> = ConsoleRunContext.(P1, P2, P3) -> Unit
typealias Command4Body<P1, P2, P3, P4> = ConsoleRunContext.(P1, P2, P3, P4) -> Unit
typealias Command5Body<P1, P2, P3, P4, P5> = ConsoleRunContext.(P1, P2, P3, P4, P5) -> Unit
typealias Command6Body<P1, P2, P3, P4, P5, P6> = ConsoleRunContext.(P1, P2, P3, P4, P5, P6) -> Unit
@UnicornMarker
fun Unicorn.command(name: String, vararg aliases: String, commandBuilder: CommandBuilder) {
val command = UnicornCommandBuilder(name, aliases.asList())
.apply { commandBuilder() }
.build()
addCommand(command)
}
| 14 |
Kotlin
|
1
| 9 |
ad66dae01b56f6a11ce7e144497b1067a8a66663
| 5,956 |
Unicorn
|
Apache License 2.0
|
src/main/kotlin/com/ssafy/mmbot/vo/MsgWithPreTextVO.kt
|
ToLoad
| 539,874,759 | false |
{"Kotlin": 39414, "Dockerfile": 157}
|
package com.ssafy.mmbot.vo
data class MsgWithPreTextVO(
val pretext: String,
val color: String,
val author_name: String,
val author_icon: String,
val author_link: String,
val title: String,
val text: String,
val image_url: String,
val footer: String
)
| 0 |
Kotlin
|
0
| 0 |
cd41086fb16f3abbecfad6a8c75a1430c6ce38b6
| 288 |
MatterMost_BOT_KotlinSpring_SSAFY
|
MIT License
|
app/src/main/java/com/jnj/vaccinetracker/common/data/database/repositories/DraftParticipantBiometricsTemplateRepository.kt
|
johnsonandjohnson
| 503,902,626 | false |
{"Kotlin": 1690434}
|
package com.jnj.vaccinetracker.common.data.database.repositories
import com.jnj.vaccinetracker.common.data.database.daos.base.deleteByParticipantUuid
import com.jnj.vaccinetracker.common.data.database.daos.base.findAll
import com.jnj.vaccinetracker.common.data.database.daos.base.findAllByPhoneNullable
import com.jnj.vaccinetracker.common.data.database.daos.base.forEachAll
import com.jnj.vaccinetracker.common.data.database.daos.draft.DraftParticipantBiometricsTemplateDao
import com.jnj.vaccinetracker.common.data.database.entities.draft.DraftParticipantBiometricsEntity
import com.jnj.vaccinetracker.common.data.database.helpers.pagingQueryList
import com.jnj.vaccinetracker.common.data.database.models.draft.update.RoomUpdateParticipantDraftStateWithDateModel
import com.jnj.vaccinetracker.common.data.database.repositories.base.DeleteByDraftParticipant
import com.jnj.vaccinetracker.common.data.database.repositories.base.DraftBiometricsTemplateRepositoryBase
import com.jnj.vaccinetracker.common.data.database.transaction.ParticipantDbTransactionRunner
import com.jnj.vaccinetracker.common.data.database.typealiases.DateEntity
import com.jnj.vaccinetracker.common.domain.entities.DraftParticipantBiometricsTemplateFile
import com.jnj.vaccinetracker.common.domain.entities.DraftState
import com.jnj.vaccinetracker.common.exceptions.InsertEntityException
import com.jnj.vaccinetracker.common.helpers.logInfo
import com.jnj.vaccinetracker.common.helpers.rethrowIfFatal
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.yield
import javax.inject.Inject
class DraftParticipantBiometricsTemplateRepository @Inject constructor(
private val draftParticipantBiometricsTemplateDao: DraftParticipantBiometricsTemplateDao,
private val transactionRunner: ParticipantDbTransactionRunner,
) : DraftBiometricsTemplateRepositoryBase<DraftParticipantBiometricsTemplateFile>, DeleteByDraftParticipant {
private fun DraftParticipantBiometricsEntity.toDomain() = DraftParticipantBiometricsTemplateFile(
participantUuid = participantUuid,
fileName = biometricsTemplateFileName,
draftState = draftState,
dateLastUploadAttempt = dateLastUploadAttempt
)
private fun DraftParticipantBiometricsTemplateFile.toPersistence() = DraftParticipantBiometricsEntity(
participantUuid = participantUuid,
biometricsTemplateFileName = fileName,
draftState = draftState,
dateLastUploadAttempt = dateLastUploadAttempt
)
override suspend fun findAll(): List<DraftParticipantBiometricsTemplateFile> {
logInfo("findAll")
return draftParticipantBiometricsTemplateDao.findAll().map { it.toDomain() }
}
override suspend fun forEachAll(onPageResult: suspend (List<DraftParticipantBiometricsTemplateFile>) -> Unit) {
draftParticipantBiometricsTemplateDao.forEachAll { entities ->
val items = entities.map { it.toDomain() }
onPageResult(items)
}
}
suspend fun findAllByDateLastUploadAttemptLesserThan(date: DateEntity): List<DraftParticipantBiometricsTemplateFile> {
return pagingQueryList(pageSize = 5_000) { offset, limit ->
draftParticipantBiometricsTemplateDao.findAllByDateLastUploadAttemptLesserThan(date, DraftState.UPLOAD_PENDING, offset, limit)
}.map { it.toDomain() }
}
override fun observeChanges(): Flow<Long> {
return draftParticipantBiometricsTemplateDao.observeChanges()
}
override suspend fun findByParticipantUuid(participantUuid: String): DraftParticipantBiometricsTemplateFile? {
return draftParticipantBiometricsTemplateDao.findByParticipantUuid(participantUuid)?.toDomain()
}
override suspend fun updateDraftState(draft: DraftParticipantBiometricsTemplateFile) {
draftParticipantBiometricsTemplateDao.updateDraftStateWithDate(
RoomUpdateParticipantDraftStateWithDateModel(participantUuid = draft.participantUuid,
draftState = draft.draftState,
dateLastUploadAttempt = draft.dateLastUploadAttempt)
)
}
override suspend fun findAllByPhone(phone: String?): List<DraftParticipantBiometricsTemplateFile> {
return draftParticipantBiometricsTemplateDao.findAllByPhoneNullable(phone).map { it.toDomain() }
}
override suspend fun findByParticipantId(participantId: String): DraftParticipantBiometricsTemplateFile? {
return draftParticipantBiometricsTemplateDao.findByParticipantId(participantId)?.toDomain()
}
override suspend fun deleteByParticipantUuid(participantUuid: String): Boolean {
val success = draftParticipantBiometricsTemplateDao.deleteByParticipantUuid(participantUuid) > 0
logInfo("deleteByParticipantId: $success")
return success
}
override suspend fun insert(model: DraftParticipantBiometricsTemplateFile, orReplace: Boolean) = transactionRunner.withTransaction {
try {
val entity = model.toPersistence()
val insertedIrisTemplate = (if (orReplace) draftParticipantBiometricsTemplateDao.insertOrReplace(entity) else draftParticipantBiometricsTemplateDao.insert(entity)) > 0
if (!insertedIrisTemplate) {
throw InsertEntityException("Cannot save draft participant irisTemplate: ${model.participantUuid}", orReplace = orReplace)
}
} catch (throwable: Throwable) {
yield()
throwable.rethrowIfFatal()
if (throwable is InsertEntityException)
throw throwable
else
throw InsertEntityException(cause = throwable, message = "Something went wrong during save draft participant irisTemplate", orReplace = orReplace)
}
}
override suspend fun deleteAllUploaded() {
val countDeleted = draftParticipantBiometricsTemplateDao.deleteAllByDraftState(DraftState.UPLOADED)
logInfo("deleteAllUploaded: countDeleted $countDeleted")
}
override suspend fun findAllUploaded(offset: Int, limit: Int): List<DraftParticipantBiometricsTemplateFile> {
return draftParticipantBiometricsTemplateDao.findAllByDraftState(DraftState.UPLOADED, offset, limit).map { it.toDomain() }
}
override suspend fun countByDraftState(draftState: DraftState): Long {
return draftParticipantBiometricsTemplateDao.countByDraftState(draftState)
}
}
| 2 |
Kotlin
|
1
| 1 |
dbf657c7fb7cb1233ed5c26bc554a1032afda3e0
| 6,402 |
vxnaid
|
Apache License 2.0
|
kotlin-node/src/jsMain/generated/node/util/types/isSymbolObject.contract.kt
|
JetBrains
| 93,250,841 | false |
{"Kotlin": 12635434, "JavaScript": 423801}
|
// Generated by Karakum - do not modify it manually!
package node.util.types
import js.symbol.Symbol
import kotlin.contracts.contract
@Suppress("NOTHING_TO_INLINE", "CANNOT_CHECK_FOR_EXTERNAL_INTERFACE")
inline fun isSymbolObject(value: Any?): Boolean /* object is Symbol */ {
contract {
returns(true) implies (value is Symbol)
}
return isSymbolObjectRaw(value)
}
| 38 |
Kotlin
|
162
| 1,347 |
997ed3902482883db4a9657585426f6ca167d556
| 389 |
kotlin-wrappers
|
Apache License 2.0
|
restdoc-web/src/main/kotlin/restdoc/web/model/TestMode.kt
|
Maple-mxf
| 283,354,797 | false |
{"Kotlin": 3578500, "Java": 741741, "Dockerfile": 1079, "Shell": 1000, "Python": 714}
|
package restdoc.web.model
enum class TestMode {
RPC,
PUBLIC_NET
}
| 13 |
Kotlin
|
0
| 2 |
3cdf9de7593c78c819b3dadc9b583e736041d55f
| 75 |
rest-doc
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/ArrowLeft.kt
|
localhostov
| 808,861,591 | false |
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.group
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Filled.ArrowLeft: ImageVector
get() {
if (_arrowLeft != null) {
return _arrowLeft!!
}
_arrowLeft = Builder(name = "ArrowLeft", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
group {
path(fill = SolidColor(Color(0xFF374957)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(23.9998f, 13.0f)
verticalLineTo(11.0f)
lineTo(2.5548f, 11.031f)
lineTo(6.8768f, 6.707f)
lineTo(5.4628f, 5.293f)
lineTo(0.8768f, 9.879f)
curveTo(0.3144f, 10.4416f, -0.0015f, 11.2045f, -0.0015f, 12.0f)
curveTo(-0.0015f, 12.7955f, 0.3144f, 13.5584f, 0.8768f, 14.121f)
lineTo(5.4628f, 18.707f)
lineTo(6.8768f, 17.293f)
lineTo(2.6148f, 13.031f)
lineTo(23.9998f, 13.0f)
close()
}
}
}
.build()
return _arrowLeft!!
}
private var _arrowLeft: ImageVector? = null
| 1 |
Kotlin
|
0
| 5 |
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 1,953 |
icons
|
MIT License
|
documentscanner/src/main/java/nz/mega/documentscanner/DocumentScannerViewModel.kt
|
andres-mejia
| 307,508,541 | true |
{"C++": 5019460, "Java": 2901327, "CMake": 258354, "C": 238229, "Kotlin": 76955, "Objective-C": 9024, "HTML": 6526, "Makefile": 4813}
|
package nz.mega.documentscanner
import android.content.Context
import android.graphics.Bitmap
import android.graphics.PointF
import android.net.Uri
import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.map
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.launch
import nz.mega.documentscanner.data.Document
import nz.mega.documentscanner.data.Document.FileType
import nz.mega.documentscanner.data.Document.Quality
import nz.mega.documentscanner.data.Image
import nz.mega.documentscanner.data.Page
import nz.mega.documentscanner.openCV.ImageScanner
import nz.mega.documentscanner.utils.DocumentGenerator.generateJpg
import nz.mega.documentscanner.utils.DocumentGenerator.generatePdf
import nz.mega.documentscanner.utils.DocumentUtils.deleteAllPages
import nz.mega.documentscanner.utils.DocumentUtils.deletePage
import nz.mega.documentscanner.utils.ImageUtils
import nz.mega.documentscanner.utils.ImageUtils.deleteFile
import nz.mega.documentscanner.utils.ImageUtils.getBitmap
import nz.mega.documentscanner.utils.ImageUtils.rotate
import nz.mega.documentscanner.utils.LiveDataUtils.notifyObserver
class DocumentScannerViewModel : ViewModel() {
companion object {
private const val TAG = "MainViewModel"
}
private val document: MutableLiveData<Document> = MutableLiveData(Document())
private val saveDestinations: MutableLiveData<Array<String>> = MutableLiveData()
private val currentPagePosition: MutableLiveData<Int> = MutableLiveData(0)
private val resultDocument: MutableLiveData<Uri> = MutableLiveData()
fun getResultDocument(): LiveData<Uri> =
resultDocument
fun getDocumentTitle(): LiveData<String> =
document.map { it.title }
fun getDocumentQuality(): LiveData<Quality> =
document.map { it.quality }
fun getDocumentFileType(): LiveData<FileType> =
document.map { it.fileType }
fun getSaveDestinations(): LiveData<List<Pair<String, Boolean>>> =
saveDestinations.map { destinations ->
val currentSaveDestination = document.value?.saveDestination
destinations.map { destination ->
destination to (currentSaveDestination == destination)
}
}
fun getSaveDestination(): String? =
document.value?.saveDestination
fun getDocumentPages(): LiveData<List<Page>> =
document.map { it.pages.toList() }
fun getCurrentPage(): LiveData<Page?> =
currentPagePosition.map { document.value?.pages?.elementAtOrNull(it) }
fun getCurrentPagePosition(): Int =
currentPagePosition.value ?: 0
fun getPagesCount(): Int =
document.value?.pages?.size ?: 0
fun setCurrentPagePosition(position: Int) {
if (currentPagePosition.value != position) {
currentPagePosition.value = position
}
}
fun setDocumentTitle(title: String) {
if (title.isBlank() || document.value?.title == title) return
document.value?.title = title.trim()
document.notifyObserver()
}
fun setDocumentFileType(fileType: FileType) {
if (document.value?.fileType == fileType) return
document.value?.fileType = fileType
document.notifyObserver()
}
fun setDocumentQuality(quality: Quality) {
if (document.value?.quality == quality) return
document.value?.quality = quality
document.notifyObserver()
}
fun setDocumentSaveDestination(saveDestination: String) {
if (document.value?.saveDestination == saveDestination) return
document.value?.saveDestination = saveDestination
document.notifyObserver()
}
fun setSaveDestinations(destinations: Array<String>) {
document.value?.saveDestination = destinations.firstOrNull()
saveDestinations.value = destinations
}
fun addPage(context: Context, originalBitmap: Bitmap): LiveData<Boolean> {
val operationResult = MutableLiveData<Boolean>()
viewModelScope.launch {
try {
val originalImage = ImageUtils.createImageFromBitmap(context, originalBitmap)
var cropPoints: List<PointF>? = null
var croppedImage: Image? = null
val cropResult = ImageScanner.getCroppedImage(originalBitmap, cropPoints)
if (cropResult != null) {
cropPoints = cropResult.cropPoints
croppedImage = ImageUtils.createImageFromBitmap(context, cropResult.bitmap)
}
val page = Page(
originalImage = originalImage,
croppedImage = croppedImage,
cropPoints = cropPoints
)
document.value?.pages?.add(page)
originalBitmap.recycle()
cropResult?.bitmap?.recycle()
updateDocumentFileType()
document.notifyObserver()
operationResult.postValue(true)
} catch (error: Exception) {
Log.e(TAG, error.stackTraceToString())
operationResult.postValue(false)
}
}
return operationResult
}
fun rotateCurrentPage(context: Context): LiveData<Boolean> {
val operationResult = MutableLiveData<Boolean>()
val currentPosition = currentPagePosition.value ?: 0
document.value?.pages?.get(currentPosition)?.let { currentPage ->
viewModelScope.launch {
try {
val image = currentPage.getImageToPrint()
val rotatedImage = image.rotate(context)
image.deleteFile()
val updatedPage = currentPage.copy(
croppedImage = rotatedImage
)
document.value?.pages?.set(currentPosition, updatedPage)
document.notifyObserver()
operationResult.postValue(true)
} catch (error: Exception) {
Log.e(TAG, error.stackTraceToString())
operationResult.postValue(false)
}
}
}
return operationResult
}
fun cropCurrentPage(context: Context, cropPoints: List<PointF>): LiveData<Boolean> {
val operationResult = MutableLiveData<Boolean>()
val currentPosition = currentPagePosition.value ?: 0
document.value?.pages?.get(currentPosition)?.let { currentPage ->
viewModelScope.launch {
try {
if (cropPoints == currentPage.cropPoints) return@launch
val image = currentPage.originalImage
val originalImageBitmap = image.getBitmap(context, null)
val cropResult = ImageScanner.getCroppedImage(originalImageBitmap, cropPoints)
val croppedBitmap = cropResult!!.bitmap
val croppedImage = ImageUtils.createImageFromBitmap(context, croppedBitmap)
currentPage.croppedImage?.deleteFile()
val updatedPage = currentPage.copy(
croppedImage = croppedImage,
cropPoints = cropResult.cropPoints
)
document.value?.pages?.set(currentPosition, updatedPage)
originalImageBitmap.recycle()
croppedBitmap.recycle()
document.notifyObserver()
operationResult.postValue(true)
} catch (error: Exception) {
Log.e(TAG, error.stackTraceToString())
operationResult.postValue(false)
}
}
}
return operationResult
}
fun generateDocument(context: Context): MutableLiveData<Boolean> {
val operationResult = MutableLiveData<Boolean>()
viewModelScope.launch {
try {
val currentDocument = requireNotNull(document.value)
val generatedDocumentUri = when (currentDocument.fileType) {
FileType.JPG -> currentDocument.generateJpg(context)
else -> currentDocument.generatePdf(context)
}
resultDocument.value = generatedDocumentUri
operationResult.postValue(true)
} catch (error: Exception) {
Log.e(TAG, error.stackTraceToString())
operationResult.postValue(false)
}
}
return operationResult
}
fun deleteCurrentPage() {
viewModelScope.launch {
val currentPosition = currentPagePosition.value ?: 0
document.value?.deletePage(currentPosition)
document.notifyObserver()
}
}
fun deleteAllPages() {
viewModelScope.launch {
document.value?.deleteAllPages()
document.notifyObserver()
}
}
private fun updateDocumentFileType() {
if (document.value?.pages?.size ?: 0 > 1) {
document.value?.fileType = FileType.PDF
}
}
}
| 0 | null |
0
| 0 |
ebad1e490cea13b83b3809377d9456d81a2e9d23
| 9,254 |
AndroidDocumentScanner
|
MIT License
|
app/src/main/java/com/example/app/data/store/store/ItemListStore.kt
|
apoi
| 258,803,528 | false | null |
package com.example.app.data.store.store
import com.example.app.data.repository.repository.ItemList
import com.example.app.data.store.SingleStore
import com.example.app.data.store.StoreCore
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
/**
* Store for lists of items. Keeps index of the items in one core, and items themselves in another
* core. This allows each item to exist in multiple indexes and be queried independently.
*
* @param <I> Type of index keys.
* @param <K> Type of keys.
* @param <V> Type of values.
*/
open class ItemListStore<I, K, V : Any>(
private val indexKey: I,
private val getKey: (V) -> K,
private val indexCore: StoreCore<I, ItemList<I, K>>,
private val valueCore: StoreCore<K, V>
) : SingleStore<List<V>> {
override suspend fun get(): List<V> {
return withContext(Dispatchers.IO) {
indexCore.get(indexKey)?.values
?.let { valueCore.get(it) }
?: emptyList()
}
}
override fun getStream(): Flow<List<V>> {
return indexCore.getStream(indexKey)
.map { index -> index.values }
.map(valueCore::get)
.flowOn(Dispatchers.IO)
}
/**
* Put all values to store, and add index to keep track of all the values.
*/
@Suppress("PARAMETER_NAME_CHANGED_ON_OVERRIDE")
override suspend fun put(values: List<V>): Boolean {
return withContext(Dispatchers.IO) {
// Put values first in case there's a listener for the index. This way values
// already exist for any listeners to query.
val newValues = values
.map { value -> Pair(getKey(value), value) }
.let { items -> valueCore.put(items.toMap()) }
val indexChanged = indexCore.put(indexKey, ItemList(indexKey, values.map(getKey)))
newValues.isNotEmpty() || indexChanged != null
}
}
/**
* Deletes key from the index store. Does not delete any of the values,
* as they may be referenced in other indexes.
*/
override suspend fun delete(): Boolean {
return withContext(Dispatchers.IO) {
indexCore.delete(indexKey)
}
}
}
| 0 |
Kotlin
|
0
| 1 |
e711db16942b0338e7528673debeb9a87655a027
| 2,352 |
android-kotlin-flow-template
|
Apache License 2.0
|
app/src/main/java/com/no5ing/bbibbi/presentation/feature/view/main/post_upload/PostUploadPageImagePreview.kt
|
bibbi-team
| 738,807,741 | false |
{"Kotlin": 912967, "Ruby": 4093}
|
package com.no5ing.bbibbi.presentation.feature.view.main.post_upload
import android.net.Uri
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import coil.compose.rememberAsyncImagePainter
import com.no5ing.bbibbi.R
import com.no5ing.bbibbi.presentation.theme.bbibbiScheme
import com.no5ing.bbibbi.presentation.theme.bbibbiTypo
import com.no5ing.bbibbi.util.toCodePointList
@Composable
fun PostUploadPageImagePreview(
previewImgUrl: Uri?,
imageTextState: State<String>,
onTapImageTextButton: () -> Unit = {},
) {
val imageText by imageTextState
Box(
modifier = Modifier.fillMaxWidth()
) {
Box(
modifier = Modifier.fillMaxWidth()
) {
Column(
modifier = Modifier.fillMaxWidth()
) {
Image(
modifier = Modifier
.aspectRatio(1.0f)
.fillMaxWidth()
.clip(RoundedCornerShape(48.dp))
.background(MaterialTheme.bbibbiScheme.backgroundHover),
painter = rememberAsyncImagePainter(model = previewImgUrl),
contentDescription = null,
)
}
}
Box(
modifier = Modifier
.align(Alignment.BottomCenter)
.padding(bottom = 20.dp)
.clickable {
onTapImageTextButton()
}
) {
if (imageText.isEmpty()) {
Box(
modifier = Modifier
.background(
color = Color.Black.copy(alpha = 0.3f),
RoundedCornerShape(10.dp)
)
.padding(horizontal = 10.dp, vertical = 8.dp)
) {
Row(
horizontalArrangement = Arrangement.spacedBy(
5.dp,
Alignment.CenterHorizontally
),
verticalAlignment = Alignment.CenterVertically,
) {
Icon(
painter = painterResource(id = R.drawable.write_icon),
contentDescription = null,
tint = MaterialTheme.bbibbiScheme.textPrimary,
modifier = Modifier.size(24.dp)
)
Text(
text = stringResource(id = R.string.post_upload_text_description),
color = MaterialTheme.bbibbiScheme.textPrimary,
style = MaterialTheme.bbibbiTypo.headTwoBold,
)
}
}
} else {
Row(
horizontalArrangement = Arrangement.spacedBy(2.dp)
) {
imageText.toCodePointList().forEach { character ->
Box(
modifier = Modifier
.clip(RoundedCornerShape(10.dp))
.background(Color.Black.copy(alpha = 0.3f))
.size(width = 28.dp, height = 41.dp),
contentAlignment = Alignment.Center
) {
Text(
text = character,
color = MaterialTheme.bbibbiScheme.white,
style = MaterialTheme.bbibbiTypo.headTwoBold,
)
}
}
}
}
}
}
}
| 0 |
Kotlin
|
0
| 9 |
dc75ae13e29067e1cb78959421f7fc0cde7f56b6
| 4,844 |
bibbi-android
|
MIT License
|
chess/src/main/java/com/ajcm/chess/board/PlayerStatus.kt
|
jassielcastro
| 364,715,505 | false | null |
package com.ajcm.chess.board
enum class PlayerStatus {
WAITING,
MOVING
}
| 0 |
Kotlin
|
0
| 9 |
621e9f7f77fac0f82a067f0843a2196e21e22226
| 82 |
ChessApp
|
MIT License
|
src/main/kotlin/io/github/mikheevshow/nmt/metrics/JvmNativeMemoryTrackingParser.kt
|
mikheevshow
| 587,999,729 | false | null |
/*
MIT License
Copyright (c) 2023 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
package io.github.mikheevshow.nmt.metrics
open class JvmNativeMemoryTrackingParser {
private val NMT_START_RE = "^[0-9]+\\:".toRegex()
private val NMT_TOTAL_RE = "^Total: reserved=(.*), committed=(.*)".toRegex()
private val NMT_SECTION_RE = "^-\\s+([A-Za-z0-9 -]+) \\(reserved=(.*), committed=(.*)\\)".toRegex()
private val NMT_SECTION_MMAP_RE = "\\(mmap: reserved=(.*), committed=(.*)\\)".toRegex()
private val NMT_CLASSES_RE = "(classes #([0-9]+))".toRegex()
private val NMT_CLASS_INSTANCES_RE = "\\( *instance classes \\#([0-9]+), array classes \\#([0-9]+)\\)".toRegex()
private val NMT_MALLOC_RE = "\\(malloc=(.*) #([0-9]+)\\)".toRegex()
private val NMT_THREADS_RE = "\\(thread #([0-9]+)\\)".toRegex()
private val NMT_STATS_SECTION_START_RE = "\\( ([a-zA-Z ]+)\\: *\\)".toRegex()
private val NMT_STATS_SECTION_MEMORY_RE = "\\( reserved=(.*), committed=(.*)\\)".toRegex()
private val NMT_STATS_SECTION_ATTR_RE = "\\( ([a-zA-Z ]+)=([0-9]+[A-Z]+)\\)".toRegex()
private val NMT_STATS_SECTION_ATTR_PERCENTAGE_RE = "\\( ([a-zA-Z ]+)=([0-9]+[A-Z]+) .([0-9\\.\\%]+)\\)".toRegex()
private val NMT_ARENA_RE = "\\(arena=(.*) \\#([0-9]+)\\)".toRegex()
private val NMT_STACK_RE = "\\(stack: reserved=(.*), committed=(.*)\\)".toRegex()
fun parse(s: String): Map<String, Any> {
val lines = s.split(System.getProperty("line.separator"))
val map = HashMap<String, Any>()
var section = ""
var innerSection = ""
var attr: String
var groups: MatchGroupCollection?
for (line in lines) {
if (line.matches(NMT_START_RE) || line.contains("Native Memory Tracking:") || line.isEmpty()) {
section = ""
continue
}
groups = NMT_TOTAL_RE.find(line)?.groups
if (groups?.isNotEmpty() == true) {
map.putMemoryValue("total.reserved", groups[1]!!.value)
map.putMemoryValue("total.committed", groups[2]!!.value)
continue
}
groups = NMT_SECTION_RE.find(line)?.groups
if (groups?.isNotEmpty() == true) {
section = groups[1]!!.value.slugify()
map.putMemoryValue("$section.reserved", groups[2]!!.value)
map.putMemoryValue("$section.committed", groups[3]!!.value)
continue
}
groups = NMT_SECTION_MMAP_RE.find(line)?.groups
if (groups?.isNotEmpty() == true) {
map.putMemoryValue("$section.mmap.reserved", groups[1]!!.value)
map.putMemoryValue("$section.mmap.committed", groups[2]!!.value)
continue
}
groups = NMT_CLASSES_RE.find(line)?.groups
if (groups?.isNotEmpty() == true) {
map["$section.classes.total"] = groups[1]!!.value
continue
}
groups = NMT_CLASS_INSTANCES_RE.find(line)?.groups
if (groups?.isNotEmpty() == true) {
map["$section.classes.instances"] = groups[1]!!.value
map["$section.classes.arrays"] = groups[2]!!.value
continue
}
groups = NMT_MALLOC_RE.find(line)?.groups
if (groups?.isNotEmpty() == true) {
map.putMemoryValue("$section.malloc.allocated", groups[1]!!.value)
map["$section.malloc.allocations"] = groups[2]!!.value
continue
}
groups = NMT_STATS_SECTION_START_RE.find(line)?.groups
if (groups?.isNotEmpty() == true) {
innerSection = groups[1]!!.value.slugify()
continue
}
groups = NMT_STATS_SECTION_MEMORY_RE.find(line)?.groups
if (groups?.isNotEmpty() == true) {
map.putMemoryValue("$section.$innerSection.reserved", groups[1]!!.value)
map.putMemoryValue("$section.$innerSection.committed", groups[2]!!.value)
continue
}
groups = NMT_STATS_SECTION_ATTR_RE.find(line)?.groups
if (groups?.isNotEmpty() == true) {
attr = groups[1]!!.value.slugify()
map.putMemoryValue("$section.$innerSection.$attr", groups[2]!!.value)
continue
}
groups = NMT_STATS_SECTION_ATTR_PERCENTAGE_RE.find(line)?.groups
if (groups?.isNotEmpty() == true) {
attr = groups[1]!!.value.slugify()
map.putMemoryValue("$section.$innerSection.$attr", groups[2]!!.value)
map["$section.$innerSection.$attr.percentage"] = groups[3]!!.value
continue
}
groups = NMT_ARENA_RE.find(line)?.groups
if (groups?.isNotEmpty() == true) {
map.putMemoryValue("$section.arena.allocated", groups[1]!!.value)
map["$section.arena.allocations"] = groups[2]!!.value
continue
}
groups = NMT_THREADS_RE.find(line)?.groups
if (groups?.isNotEmpty() == true) {
map["$section.threads.total"] = groups[1]!!.value
continue
}
groups = NMT_STACK_RE.find(line)?.groups
if (groups?.isNotEmpty() == true) {
map.putMemoryValue("$section.stack.reserved", groups[1]!!.value)
map.putMemoryValue("$section.stack.committed", groups[2]!!.value)
continue
}
}
return map
}
private fun HashMap<String, Any>.putMemoryValue(key: String, value: String) {
val valueAsInt = value.substringBeforeLast("KB").toInt()
this[key] = valueAsInt
this["$key.kb"] = valueAsInt
this["$key.mb"] = valueAsInt / 1024
this["$key.gb"] = valueAsInt / 1024 / 1024
}
}
| 1 |
Kotlin
|
0
| 4 |
8f8113dfd6056147df69a477fa22deba1f591483
| 6,974 |
nmt-metrics-spring-boot-starter
|
MIT License
|
gi/src/commonMain/kotlin/org/anime_game_servers/multi_proto/gi/data/activity/roguelike_dungeon/RoguelikeEffectViewRsp.kt
|
Anime-Game-Servers
| 642,871,918 | false |
{"Kotlin": 1651536}
|
package org.anime_game_servers.multi_proto.gi.data.activity.roguelike_dungeon
import org.anime_game_servers.core.base.Version.GI_2_2_0
import org.anime_game_servers.core.base.annotations.AddedIn
import org.anime_game_servers.core.base.annotations.proto.CommandType.*
import org.anime_game_servers.core.base.annotations.proto.ProtoCommand
import org.anime_game_servers.multi_proto.gi.data.general.Retcode
@AddedIn(GI_2_2_0)
@ProtoCommand(RESPONSE)
internal interface RoguelikeEffectViewRsp {
var retcode: Retcode
}
| 0 |
Kotlin
|
2
| 6 |
7639afe4f546aa5bbd9b4afc9c06c17f9547c588
| 520 |
anime-game-multi-proto
|
MIT License
|
app/src/main/java/com/flexcode/pix/feature_image/data/remote/ImageApiService.kt
|
Felix-Kariuki
| 484,367,165 | false | null |
package com.flexcode.pix.feature_image.data.remote
import com.flexcode.pix.BuildConfig
import com.flexcode.pix.feature_image.data.remote.dto.ImageResponse
import com.flexcode.pix.core.util.Constants
import retrofit2.http.GET
import retrofit2.http.Query
interface ImageApiService {
@GET("?key=${BuildConfig.API_KEY}")
suspend fun getImages(@Query("q") query: String): ImageResponse
}
| 0 |
Kotlin
|
1
| 3 |
0be09e5e5e0c5dba178129371138239f2f7bce25
| 394 |
Pix
|
MIT License
|
chanceapi-kotlin/src/main/kotlin/ru/dverkask/chance/ChanceType.kt
|
DverkaSK
| 783,054,297 | false |
{"Gradle": 4, "INI": 1, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "Java Properties": 1, "Java": 6, "Kotlin": 6}
|
package ru.dverkask.chance
enum class ChanceType {
PERCENTAGE,
WEIGHT
}
| 0 |
Java
|
0
| 0 |
8bb1066219b79a3e1db2c38725493a979283716e
| 80 |
chances
|
MIT License
|
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/opmodes/SmallbotProductionStickDrift.kt
|
XaverianTeamRobotics
| 356,899,269 | false |
{"Java Properties": 2, "PowerShell": 2, "XML": 25, "Shell": 3, "Gradle": 7, "Markdown": 6, "Batchfile": 1, "Text": 4, "Ignore List": 1, "Java": 206, "CODEOWNERS": 1, "YAML": 3, "Kotlin": 157}
|
package org.firstinspires.ftc.teamcode.opmodes
import org.firstinspires.ftc.teamcode.features.FourMotorArmNoManualLevel
import org.firstinspires.ftc.teamcode.features.Hand
import org.firstinspires.ftc.teamcode.features.PowerplayMecanumDrivetrain
import org.firstinspires.ftc.teamcode.internals.registration.OperationMode
import org.firstinspires.ftc.teamcode.internals.registration.TeleOperation
class SmallbotProductionStickDrift : OperationMode(), TeleOperation {
override fun construct() {
registerFeature(PowerplayMecanumDrivetrain(false, true))
registerFeature(FourMotorArmNoManualLevel())
registerFeature(Hand())
}
override fun run() {}
}
| 1 | null |
1
| 1 |
349cadebeacc12b05476b3f7ca557916be253cd7
| 684 |
FtcRobotController
|
BSD 3-Clause Clear License
|
sdk/src/main/java/io/stipop/models/response/StickerPackagesResponse.kt
|
stipop-development
| 372,351,610 | false | null |
package io.stipop.models.response
import androidx.annotation.Keep
import com.google.gson.annotations.SerializedName
import io.stipop.models.StickerPackage
@Keep
internal class StickerPackagesResponse(
@SerializedName("header") val header: ResponseHeader,
@SerializedName("body") val body: ResponseBody?
) {
@Keep
data class ResponseBody(
@SerializedName("packageList") val packageList: List<StickerPackage>? = emptyList(),
@SerializedName("pageMap") val pageMap: PageMapInfo
)
}
| 0 |
Kotlin
|
3
| 9 |
98ab3c8ebc153270d3265c9a08c884deb2126d9f
| 516 |
stipop-android-sdk
|
MIT License
|
app/src/main/java/com/example/busschedule/screens/BusScheduleEditViewModel.kt
|
Chriztey
| 814,187,546 | false |
{"Kotlin": 61371}
|
package com.example.busschedule.screens
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.busschedule.data.BusSchedulerRepo
import com.example.busschedule.data.NonNetworkBusSchedulerRepo
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
class BusScheduleEditViewModel(
private val busSchedulerRepo: BusSchedulerRepo,
savedStateHandle: SavedStateHandle,
) : ViewModel() {
private val id: Int = checkNotNull(savedStateHandle[EditScheduleDestination.EditRouteArg])
fun validate(schedule: BusScheduleDetails): Boolean {
return with(schedule) {
id.toString().isNotBlank() && stopName.isNotBlank() && arrivalTimeInMillis.toString().isNotBlank()
}
}
var editUiState by mutableStateOf(BusScheduleEntry())
private set
init {
viewModelScope.launch {
editUiState = busSchedulerRepo
.getItemById(id)
.filterNotNull()
.first()
.toBusScheduleEntry(true)
}
}
fun updateUiState(schedule: BusScheduleDetails) {
editUiState = BusScheduleEntry(schedule, validate(schedule))
}
suspend fun updateSchedule() {
busSchedulerRepo.update(editUiState.entry.toBusSchedule())
}
}
| 0 |
Kotlin
|
0
| 0 |
efb4e149c5f480d8ac3f413f6199c31a719c2a3f
| 1,553 |
BusScheduler
|
Apache License 2.0
|
src/test/kotlin/dev/ekvedaras/laravelquery/edgeCases/EdgeCasesTest.kt
|
ekvedaras
| 325,768,601 | false | null |
package dev.ekvedaras.laravelquery.edgeCases
import com.intellij.database.dialects.oracle.debugger.success
import com.intellij.database.model.ObjectKind
import com.intellij.database.util.DasUtil
import com.intellij.database.util.DbImplUtil
import com.intellij.database.util.DbUtil
import com.intellij.openapi.application.ApplicationManager
import com.intellij.testFramework.UsefulTestCase
import dev.ekvedaras.laravelquery.BaseTestCase
import dev.ekvedaras.laravelquery.inspection.UnknownColumnInspection
import dev.ekvedaras.laravelquery.inspection.UnknownTableOrViewInspection
internal class EdgeCasesTest : BaseTestCase() {
fun testClassCastException1() {
myFixture.configureByFile("edgeCases/classCastException1.php")
myFixture.completeBasic()
assertCompletion("email")
}
fun testClassCastException2() {
myFixture.configureByFile("edgeCases/classCastException2.php")
if (ApplicationManager.getApplication().isReadAccessAllowed) {
myFixture.completeBasic()
assertCompletion("email")
} else {
success(1)
}
}
fun testNonQueryBuilderTableMethod() {
val file = myFixture.configureByFile("edgeCases/nonQueryBuilderTableMethod.php")
val schema = DasUtil.getSchemas(db).first()
val dbSchema = DbImplUtil.findElement(DbUtil.getDataSources(project).first(), schema)
?: return fail("Failed to resolve DB schema")
myFixture.completeBasic()
assertEmpty(myFixture.lookupElementStrings?.toList() ?: listOf<String>())
assertEmpty(myFixture.findUsages(dbSchema))
assertInspection(file!!, UnknownTableOrViewInspection())
}
fun testNonQueryBuilderColumnMethod() {
val file = myFixture.configureByFile("edgeCases/nonQueryBuilderColumnMethod.php")
val schema = DasUtil.getSchemas(db).first()
val dbSchema = DbImplUtil.findElement(DbUtil.getDataSources(project).first(), schema)
?: return fail("Failed to resolve DB schema")
myFixture.completeBasic()
assertEmpty(myFixture.lookupElementStrings?.toList() ?: listOf<String>())
assertEmpty(myFixture.findUsages(dbSchema))
assertInspection(file!!, UnknownColumnInspection())
}
fun testDoesNotResolveColumnReferenceIfStringContainsDollarSign() {
myFixture.configureByFile("edgeCases/nonCompletableArrayValue.php")
myFixture.completeBasic()
assertEmpty(myFixture.lookupElementStrings?.toList() ?: listOf<String>())
}
fun testJoinClause() {
myFixture.configureByFile("edgeCases/joinClause.php")
myFixture.completeBasic()
assertCompletion("billable_id", "billable_type")
}
fun testWhenClause() {
myFixture.configureByFile("edgeCases/whenClause.php")
myFixture.completeBasic()
assertCompletion("first_name", "last_name")
assertNoCompletion("trial_ends_at")
}
/* Code works, but test fails due to some internal code
fun testDbTable() {
myFixture.configureByFile("edgeCases/dbTable.php")
myFixture.completeBasic()
assertCompletion("testProject1", "users", "testProject2")
assertNoCompletion("created_at")
}*/
/* Code works, but test fails due to some internal code
fun testDbFacadeAliasTable() {
myFixture.configureByFile("edgeCases/dbFacadeAliasTable.php")
myFixture.completeBasic()
assertCompletion("testProject1", "users", "testProject2")
assertNoCompletion("created_at")
}*/
fun testDbTableColumn() {
myFixture.configureByFile("edgeCases/dbTableColumn.php")
myFixture.completeBasic()
assertCompletion("first_name", "last_name")
assertNoCompletion("trial_ends_at")
}
fun testDbTableAliasColumn() {
myFixture.configureByFile("edgeCases/dbTableAliasColumn.php")
myFixture.completeBasic()
assertCompletion("first_name", "last_name")
assertNoCompletion("trial_ends_at")
}
fun testItOnlyCompletesColumnsOnModelCreateMethod() {
myFixture.configureByFile("edgeCases/createModel.php")
myFixture.completeBasic()
assertCompletion("first_name", "last_name")
assertNoCompletion("trial_ends_at")
assertNoCompletion("customers", "testProject1", "testProject2", "migrations", "failed_jobs")
}
fun testItOnlyCompletesColumnsOnModelCreateMethodWhenOnlyTheKeyIsPresent() {
myFixture.configureByFile("edgeCases/createModelNewKey.php")
myFixture.completeBasic()
assertCompletion("first_name", "last_name")
assertNoCompletion("trial_ends_at")
assertNoCompletion("customers", "testProject1", "testProject2", "migrations", "failed_jobs")
}
fun testItOnlyCompletesColumnsOnRelationCreateMethodWhenOnlyTheKeyIsPresent() {
myFixture.configureByFile("edgeCases/createRelationNewKey.php")
myFixture.completeBasic()
assertCompletion("trial_ends_at", "billable_id")
assertNoCompletion("email", "name")
assertNoCompletion("customers", "testProject1", "testProject2", "migrations", "failed_jobs")
}
fun testItDoesNotCompleteColumnsOnModelCreateMethodWhenCaretIsInValue() {
myFixture.configureByFile("edgeCases/createModelCaretInValue.php")
myFixture.completeBasic()
assertSame(0, myFixture.lookupElements?.size ?: 0)
}
fun testDoesNotWarnAboutUnknownOperatorInNestedArrayWhere() {
assertInspection("edgeCases/arrayNestedWhere.php", UnknownColumnInspection())
}
fun testDoesNotWarnAboutUnknownTableInCreateMethod() {
assertInspection("edgeCases/createModel.php", UnknownTableOrViewInspection())
}
fun testItDoesNotResolveColumnsFromOtherTablesBecauseOfTheContext() {
myFixture.configureByFile("edgeCases/createModelValueAsColumnName.php")
val column = DasUtil.getTables(dataSource())
.first { it.name == "users" }
.getDasChildren(ObjectKind.COLUMN)
.first { it.name == "email" }
val dbColumn = DbImplUtil.findElement(
DbUtil.getDataSources(project).first(),
column
) ?: return fail("Failed to resolve DB column")
val usages = myFixture.findUsages(dbColumn)
UsefulTestCase.assertSize(0, usages)
}
fun testItDoesNotResolveTablesInEloquentMethodArrayKeysAndValues() {
myFixture.configureByFile("edgeCases/createModelKeyAndValueAsTableName.php")
val table = DasUtil.getTables(dataSource()).first { it.name == "users" }
val dbTable = DbImplUtil.findElement(
DbUtil.getDataSources(project).first(),
table
) ?: return fail("Failed to resolve DB table")
val usages = myFixture.findUsages(dbTable)
UsefulTestCase.assertSize(0, usages)
}
fun testItDoesNotReportUnknownColumnForArraysAsValuesWithinCreate() {
assertInspection("edgeCases/arrayWithinCreate.php", UnknownColumnInspection())
}
fun testItDoesNotReportUnknownColumnValuesWithQuotesWithinUpdate() {
assertInspection("edgeCases/updateWithQuotesInValue.php", UnknownColumnInspection())
}
fun testItDoesNotReportUnknownColumnValuesWithQuotesInConcatenatedValueWithinUpdate() {
assertInspection("edgeCases/updateWithQuotesInConcatenatedValue.php", UnknownColumnInspection())
}
}
| 3 | null |
4
| 42 |
4f8b4822eaa329e2f643c8d6b4299f7d99861c1c
| 7,430 |
laravel-query-intellij
|
MIT License
|
adoptium-updater-parent/adoptium-api-v3-updater/src/test/kotlin/net/adoptium/api/testDoubles/InMemoryInternalDbStore.kt
|
adoptium
| 349,432,712 | false |
{"Kotlin": 632435, "HTML": 8785, "Shell": 2518, "Dockerfile": 2080, "CSS": 2037}
|
package net.adoptium.api.testDoubles
import jakarta.annotation.Priority
import jakarta.enterprise.context.ApplicationScoped
import jakarta.enterprise.inject.Alternative
import kotlinx.coroutines.Job
import net.adoptium.api.v3.dataSources.mongo.CacheDbEntry
import net.adoptium.api.v3.dataSources.mongo.InternalDbStore
import java.time.ZonedDateTime
@Priority(1)
@Alternative
@ApplicationScoped
class InMemoryInternalDbStore : InternalDbStore {
private val cache: MutableMap<String, CacheDbEntry> = HashMap()
override fun putCachedWebpage(url: String, lastModified: String?, date: ZonedDateTime, data: String?): Job {
cache[url] = CacheDbEntry(url, lastModified, date, data)
return Job()
}
override suspend fun getCachedWebpage(url: String): CacheDbEntry? {
return cache[url]
}
override suspend fun updateCheckedTime(url: String, dateTime: ZonedDateTime) {
val cachedValue = cache[url]
if (cachedValue != null) {
cache[url] = CacheDbEntry(url, cachedValue.lastModified, dateTime, cachedValue.data)
}
}
}
| 24 |
Kotlin
|
26
| 34 |
391b090eae115016fa8cc223c26e03bbd1612ab4
| 1,095 |
api.adoptium.net
|
Apache License 2.0
|
adoptium-updater-parent/adoptium-api-v3-updater/src/test/kotlin/net/adoptium/api/testDoubles/InMemoryInternalDbStore.kt
|
adoptium
| 349,432,712 | false |
{"Kotlin": 632435, "HTML": 8785, "Shell": 2518, "Dockerfile": 2080, "CSS": 2037}
|
package net.adoptium.api.testDoubles
import jakarta.annotation.Priority
import jakarta.enterprise.context.ApplicationScoped
import jakarta.enterprise.inject.Alternative
import kotlinx.coroutines.Job
import net.adoptium.api.v3.dataSources.mongo.CacheDbEntry
import net.adoptium.api.v3.dataSources.mongo.InternalDbStore
import java.time.ZonedDateTime
@Priority(1)
@Alternative
@ApplicationScoped
class InMemoryInternalDbStore : InternalDbStore {
private val cache: MutableMap<String, CacheDbEntry> = HashMap()
override fun putCachedWebpage(url: String, lastModified: String?, date: ZonedDateTime, data: String?): Job {
cache[url] = CacheDbEntry(url, lastModified, date, data)
return Job()
}
override suspend fun getCachedWebpage(url: String): CacheDbEntry? {
return cache[url]
}
override suspend fun updateCheckedTime(url: String, dateTime: ZonedDateTime) {
val cachedValue = cache[url]
if (cachedValue != null) {
cache[url] = CacheDbEntry(url, cachedValue.lastModified, dateTime, cachedValue.data)
}
}
}
| 24 |
Kotlin
|
26
| 34 |
391b090eae115016fa8cc223c26e03bbd1612ab4
| 1,095 |
api.adoptium.net
|
Apache License 2.0
|
arrow-libs/core/arrow-core/src/jvmTest/kotlin/examples/example-either-23.kt
|
lukaszkalnik
| 427,116,886 | true |
{"Kotlin": 1928099, "SCSS": 99659, "JavaScript": 83153, "HTML": 25306, "Java": 7691, "Ruby": 917, "Shell": 98}
|
// This file was automatically generated from Either.kt by Knit tool. Do not edit.
package arrow.core.examples.exampleEither23
import arrow.core.Either
val value =
Either.conditionally(false, { "Error" }, { 42 })
fun main() {
println(value)
}
| 0 |
Kotlin
|
0
| 1 |
73fa3847df1f04e634a02bba527917389b59d7df
| 247 |
arrow
|
Apache License 2.0
|
app/src/main/java/info/guardianproject/notepadbot/NoteCipher.kt
|
Theaninova
| 357,319,804 | true |
{"Java": 103885, "Kotlin": 95898}
|
/*
* Copyright (C) 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")savedInstanceState;
* 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 info.guardianproject.notepadbot
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Bundle
import android.util.Log
import android.view.*
import android.view.ContextMenu.ContextMenuInfo
import android.widget.*
import android.widget.AdapterView.AdapterContextMenuInfo
import android.widget.AdapterView.OnItemClickListener
import androidx.appcompat.app.AppCompatActivity
import androidx.loader.app.LoaderManager
import androidx.loader.content.CursorLoader
import androidx.loader.content.Loader
import info.guardianproject.notepadbot.NoteEdit.NoteContentLoader
import info.guardianproject.notepadbot.cacheword.CacheWordActivityHandler
import info.guardianproject.notepadbot.cacheword.ICacheWordSubscriber
import net.sqlcipher.database.SQLiteDatabase
import java.io.IOException
class NoteCipher : AppCompatActivity(), ICacheWordSubscriber {
private var mDbHelper: NotesDbAdapter? = null
private var dataStream: Uri? = null
private var mCacheWord: CacheWordActivityHandler? = null
private var notesListView: ListView? = null
private var notesCursorAdapter: SimpleCursorAdapter? = null
/**
* Called when the activity is first created.
*/
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (intent != null) {
dataStream = if (intent.hasExtra(Intent.EXTRA_STREAM)) {
intent.extras!![Intent.EXTRA_STREAM] as Uri?
} else {
intent.data
}
}
SQLiteDatabase.loadLibs(this)
setContentView(R.layout.notes_list)
notesListView = findViewById<View>(R.id.notesListView) as ListView
notesListView!!.onItemClickListener =
OnItemClickListener { _, _, _, id ->
val i = Intent(this, NoteEdit::class.java)
i.putExtra(NotesDbAdapter.KEY_ROW_ID, id)
startActivityForResult(i, ACTIVITY_EDIT)
}
// registerForContextMenu(notesListView)
mCacheWord = CacheWordActivityHandler(this, (application as App).cWSettings)
// Create an array to specify the fields we want to display in the list (only TITLE)
val from = arrayOf(NotesDbAdapter.KEY_TITLE)
// and an array of the fields we want to bind those fields to (in this
// case just text1)
val to = intArrayOf(R.id.row_text)
// Now create an empty simple cursor adapter that later will display the notes
notesCursorAdapter = SimpleCursorAdapter(
this, R.layout.notes_row, null, from, to,
SimpleCursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER
)
notesListView!!.adapter = notesCursorAdapter
}
override fun onPause() {
super.onPause()
mCacheWord!!.onPause()
}
override fun onResume() {
super.onResume()
mCacheWord!!.onResume()
}
private fun closeDatabase() {
mDbHelper?.let {
it.close()
mDbHelper = null
}
}
private fun unlockDatabase() {
if (mCacheWord!!.isLocked) return
mDbHelper = NotesDbAdapter(mCacheWord!!, this)
try {
mDbHelper!!.open()
if (dataStream != null) importDataStream() else fillData()
} catch (e: Exception) {
e.printStackTrace()
// TODO
// Snackbar.make(view, getString(R.string.err_pass), Snackbar.LENGTH_LONG)
}
}
private fun fillData() {
if (mCacheWord!!.isLocked) return
@Suppress("DEPRECATION")
supportLoaderManager.restartLoader(
VIEW_ID,
null,
object : LoaderManager.LoaderCallbacks<Cursor> {
override fun onCreateLoader(arg0: Int, arg1: Bundle?): Loader<Cursor> {
return NotesLoader(this@NoteCipher, mDbHelper)
}
override fun onLoadFinished(loader: Loader<Cursor>, cursor: Cursor) {
notesCursorAdapter!!.swapCursor(cursor)
/*val emptyTV = findViewById<View>(R.id.emptytext) as TextView
if (notesCursorAdapter!!.isEmpty) {
Toast.makeText(this@NoteCipher, R.string.on_start, Toast.LENGTH_LONG).show()
emptyTV.setText(R.string.no_notes)
} else {
emptyTV.text = ""
}*/
}
override fun onLoaderReset(loader: Loader<Cursor>) {}
})
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
menuInflater.inflate(R.menu.notes_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.lockScreenFragment -> {
if (!mCacheWord!!.isLocked) mCacheWord!!.manuallyLock()
return true
}
R.id.settingsFragment -> {
if (!mCacheWord!!.isLocked) {
startActivity(Intent(this, Settings::class.java))
}
return true
}
}
return super.onOptionsItemSelected(item)
}
override fun onCreateContextMenu(
menu: ContextMenu, v: View,
menuInfo: ContextMenuInfo
) {
super.onCreateContextMenu(menu, v, menuInfo)
menu.add(0, SHARE_ID, 0, R.string.menu_share)
menu.add(0, DELETE_ID, 0, R.string.menu_delete)
}
override fun onContextItemSelected(item: MenuItem): Boolean {
val info: AdapterContextMenuInfo
when (item.itemId) {
DELETE_ID -> {
info = item.menuInfo as AdapterContextMenuInfo
mDbHelper!!.deleteNote(info.id)
fillData()
return true
}
SHARE_ID -> {
info = item.menuInfo as AdapterContextMenuInfo
shareEntry(info.id)
return true
}
VIEW_ID -> {
info = item.menuInfo as AdapterContextMenuInfo
viewEntry(info.id)
return true
}
}
return super.onContextItemSelected(item)
}
private fun shareEntry(id: Long) {
if (mCacheWord!!.isLocked) {
return
}
@Suppress("DEPRECATION")
supportLoaderManager.restartLoader(
SHARE_ID,
null,
object : LoaderManager.LoaderCallbacks<Cursor> {
override fun onCreateLoader(arg0: Int, arg1: Bundle?): Loader<Cursor> {
return NoteContentLoader(this@NoteCipher, mDbHelper, id)
}
override fun onLoadFinished(loader: Loader<Cursor>, note: Cursor) {
val blob = note.getBlob(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_DATA))
val title = note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE))
var mimeType =
note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TYPE))
if (mimeType == null) mimeType = "text/plain"
if (blob != null) {
try {
NoteUtils.shareData(this@NoteCipher, title, mimeType, blob)
} catch (e: IOException) {
Toast.makeText(
this@NoteCipher,
getString(R.string.err_export, e.message),
Toast.LENGTH_LONG
)
.show()
}
} else {
val body =
note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY))
NoteUtils.shareText(this@NoteCipher, body)
}
note.close()
}
override fun onLoaderReset(loader: Loader<Cursor>) {}
})
}
private fun viewEntry(id: Long) {
if (mCacheWord!!.isLocked) return
@Suppress("DEPRECATION")
supportLoaderManager.restartLoader(
VIEW_ID,
null,
object : LoaderManager.LoaderCallbacks<Cursor> {
override fun onCreateLoader(arg0: Int, arg1: Bundle?): Loader<Cursor> {
return NoteContentLoader(this@NoteCipher, mDbHelper, id)
}
override fun onLoadFinished(loader: Loader<Cursor>, note: Cursor) {
val blob = note.getBlob(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_DATA))
var mimeType =
note.getString(note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TYPE))
if (mimeType == null) mimeType = "text/plain"
if (blob != null) {
val title = note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)
)
NoteUtils.savePublicFile(this@NoteCipher, title, mimeType, blob)
}
note.close()
}
override fun onLoaderReset(loader: Loader<Cursor>) {}
})
}
private fun createNote() {
if (mCacheWord!!.isLocked) return
val i = Intent(this, NoteEdit::class.java)
startActivityForResult(i, ACTIVITY_CREATE)
}
/*
* Called after the return from creating a new note (non-Javadoc)
* @see android.app.Activity#onActivityResult(int, int,
* android.content.Intent)
*/
override fun onActivityResult(
requestCode: Int, resultCode: Int,
intent: Intent?
) {
super.onActivityResult(requestCode, resultCode, intent)
mDbHelper = NotesDbAdapter(mCacheWord!!, this)
fillData()
}
override fun onDestroy() {
super.onDestroy()
closeDatabase()
NoteUtils.cleanupTmp(this)
}
private fun importDataStream() {
if (mCacheWord!!.isLocked) return
try {
val contentResolver = contentResolver
val inputStream = contentResolver.openInputStream(dataStream!!)
val mimeType = contentResolver.getType(dataStream!!)
val data = NoteUtils.readBytesAndClose(inputStream)
if (data!!.size > NConstants.MAX_STREAM_SIZE) {
Toast.makeText(this, R.string.err_size, Toast.LENGTH_LONG).show()
} else {
val title = dataStream!!.lastPathSegment
val body = dataStream!!.path
NotesDbAdapter(mCacheWord!!, this).createNote(title, body, data, mimeType)
Toast.makeText(this, getString(R.string.on_import, title), Toast.LENGTH_LONG).show()
// handleDelete();
dataStream = null
System.gc()
fillData()
}
} catch (e: IOException) {
Log.e(NConstants.TAG, e.message, e)
} catch (e: OutOfMemoryError) {
Toast.makeText(this, R.string.err_size, Toast.LENGTH_LONG).show()
} finally {
dataStream = null
}
}
/*
* Call this to delete the original image, will ask the user
*/
private fun handleDelete() {
if (mCacheWord!!.isLocked) return
AlertDialog.Builder(this).apply {
setIcon(android.R.drawable.ic_dialog_alert)
setTitle(R.string.app_name)
setMessage(R.string.confirm_delete)
setPositiveButton(android.R.string.ok) { _, _ -> // User clicked OK so go ahead and delete
contentResolver?.delete(dataStream!!, null, null)
?: Toast.makeText(
this@NoteCipher,
R.string.unable_to_delete_original,
Toast.LENGTH_SHORT
).show()
}
setNegativeButton(android.R.string.cancel) { _, _ -> }
}.show()
}
private fun showLockScreen() {
// findNavController().navigate(R.id.lock_screen)
val intent = Intent(this, LockScreenActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP)
intent.putExtra("originalIntent", getIntent())
startActivity(intent)
finish()
}
private fun clearViewsAndLock() {
closeDatabase()
notesListView!!.adapter = null
System.gc()
showLockScreen()
}
override fun onCacheWordUninitialized() {
Log.d(NConstants.TAG, "onCacheWordUninitialized")
clearViewsAndLock()
}
override fun onCacheWordLocked() {
Log.d(NConstants.TAG, "onCacheWordLocked")
clearViewsAndLock()
}
override fun onCacheWordOpened() {
Log.d(NConstants.TAG, "onCacheWordOpened")
unlockDatabase()
if (mDbHelper!!.isOpen) {
if (dataStream != null) importDataStream() else fillData()
}
}
class NotesLoader(context: Context?, var db: NotesDbAdapter?) : CursorLoader(context!!) {
override fun loadInBackground(): Cursor? {
return db?.fetchAllNotes()
}
}
companion object {
private const val ACTIVITY_CREATE = 0
private const val ACTIVITY_EDIT = 1
private const val INSERT_ID = Menu.FIRST
private const val DELETE_ID = Menu.FIRST + 1
private const val RE_KEY_ID = Menu.FIRST + 2
private const val SHARE_ID = Menu.FIRST + 3
private const val VIEW_ID = Menu.FIRST + 4
private const val LOCK_ID = Menu.FIRST + 5
private const val SETTINGS_ID = Menu.FIRST + 6
}
}
| 0 |
Java
|
0
| 0 |
445fdde8fd02f7a7d15d73186544d590186a2b71
| 14,560 |
notecipher
|
Apache License 2.0
|
app/src/main/java/com/kotlin/sacalabici/framework/views/fragments/ActivityActionDialogFragment.kt
|
Saca-la-Bici
| 849,110,267 | false |
{"Kotlin": 595596}
|
package com.kotlin.sacalabici.framework.views.fragments
import android.app.Activity.RESULT_OK
import android.app.AlertDialog
import android.app.Dialog
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity.MODE_PRIVATE
import androidx.fragment.app.DialogFragment
import androidx.fragment.app.setFragmentResult
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.kotlin.sacalabici.R
import com.kotlin.sacalabici.framework.viewmodel.ActivitiesViewModel
import com.kotlin.sacalabici.framework.views.activities.activities.ModifyActivityActivity
import kotlinx.coroutines.launch
import kotlin.properties.Delegates
class ActivityActionDialogFragment: DialogFragment() {
private lateinit var viewModel: ActivitiesViewModel
private var permissions: List<String> = emptyList()
private lateinit var id: String
private lateinit var title: String
private lateinit var date: String
private lateinit var hour: String
private lateinit var ubi: String
private lateinit var desc: String
private lateinit var hourDur: String
private var url: String? = null
private var peopleEnrolled: Int by Delegates.notNull()
private var state: Boolean by Delegates.notNull()
private var foro: String? = null
private var register: ArrayList<String>? = null
private lateinit var typeAct: String
private var idRoute: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProvider(this).get(ActivitiesViewModel::class.java)
arguments?.let {
id = it.getString("id") ?: throw IllegalArgumentException("ID is required")
title = it.getString("title") ?: throw IllegalArgumentException("Title is required")
date = it.getString("date") ?: throw IllegalArgumentException("Date is required")
hour = it.getString("hour") ?: throw IllegalArgumentException("Hour is required")
ubi = it.getString("ubi") ?: throw IllegalArgumentException("Ubi is required")
desc = it.getString("desc") ?: throw IllegalArgumentException("Description is required")
hourDur = it.getString("hourDur") ?: throw IllegalArgumentException("Hour duration is required")
typeAct = it.getString("typeAct") ?: throw IllegalArgumentException("Type duration is required")
url = it.getString("url")
peopleEnrolled = it.getInt("peopleEnrolled") ?: throw IllegalArgumentException("People enrolled is required")
state = it.getBoolean("state") ?: throw IllegalArgumentException("State is required")
foro = it.getString("foro")
register = it.getStringArrayList("register")
idRoute = it.getString("idRoute")
permissions = it.getStringArrayList("permissions") ?: emptyList()
} ?: throw IllegalArgumentException("Arguments are required")
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val dialog = super.onCreateDialog(savedInstanceState)
dialog.window?.apply {
setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT)
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
setGravity(Gravity.BOTTOM)
clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
}
dialog.setCanceledOnTouchOutside(true)
return dialog
}
override fun onStart() {
super.onStart()
dialog?.window?.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.item_action_buttons, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val tvDelete: TextView = view.findViewById(R.id.TVDelete)
val tvModify: TextView = view.findViewById(R.id.TVModify)
tvDelete.text = "Eliminar actividad"
tvModify.text = "Modificar actividad"
tvDelete.setOnClickListener {
showDeleteConfirmationDialog()
}
tvModify.setOnClickListener {
val intent = Intent(requireContext(), ModifyActivityActivity::class.java).apply {
putExtra("id", id)
putExtra("title", title)
putExtra("date", date)
putExtra("hour", hour)
putExtra("ubi", ubi)
putExtra("desc", desc)
putExtra("hourDur", hourDur)
putExtra("url", url)
putExtra("typeAct", typeAct)
putExtra("peopleEnrolled", peopleEnrolled)
putExtra("state", state)
putExtra("foro", foro)
putExtra("register", register)
putExtra("idRoute", idRoute)
}
startActivity(intent)
dismiss()
}
}
private fun showDeleteConfirmationDialog() {
val inflater = LayoutInflater.from(requireContext())
val dialogView = inflater.inflate(R.layout.item_delete_activity, null)
val builder = AlertDialog.Builder(requireContext())
builder.setView(dialogView)
val alertDialog = builder.create()
alertDialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialogView.findViewById<Button>(R.id.btn_cancel).setOnClickListener {
alertDialog.dismiss()
}
dialogView.findViewById<Button>(R.id.btn_confirm).setOnClickListener { button ->
// Desactivar el botรณn para evitar mรบltiples clics
button.isEnabled = false
deleteActivity { success ->
// Si la eliminaciรณn fue exitosa, cerrar el diรกlogo
if (success) {
alertDialog.dismiss()
[email protected]()
} else {
// Si hubo un error, volver a habilitar el botรณn
button.isEnabled = true
Toast.makeText(requireContext(), "Error al eliminar el anuncio", Toast.LENGTH_SHORT).show()
}
}
}
alertDialog.show()
}
private fun deleteActivity(onComplete: (Boolean) -> Unit) {
viewModel.viewModelScope.launch {
viewModel.deleteActivity(id, typeAct) { result ->
result.fold(
onSuccess = {
if (isAdded) {
Toast.makeText(requireContext(), "Actividad eliminada exitosamente", Toast.LENGTH_SHORT).show()
val sharedPreferences = requireContext().getSharedPreferences("activity_prefs", MODE_PRIVATE)
val editor = sharedPreferences.edit()
editor.putBoolean("activity_updated", true)
editor.apply()
setFragmentResult("activityActionDialogResult", Bundle().apply {
putInt("resultCode", RESULT_OK)
})
onComplete(true) // Llamar onComplete con รฉxito
}
},
onFailure = { error ->
if (isAdded) {
Toast.makeText(requireContext(), "Error al eliminar la actividad: ${error.message}", Toast.LENGTH_LONG).show()
}
onComplete(false) // Llamar onComplete con fallo
}
)
}
}
}
companion object {
const val TAG = "ActivityActionDialogFragment"
fun newInstance(
id: String,
title: String,
date: String,
hour: String,
ubi: String,
desc: String,
hourDur: String,
url: String?,
typeAct: String,
peopleEnrolled: Int,
state: Boolean,
foro: String?,
register: ArrayList<String>?,
idRoute: String?,
permissions: List<String>
): ActivityActionDialogFragment {
val fragment = ActivityActionDialogFragment()
val args = Bundle()
args.putString("id", id)
args.putString("title", title)
args.putString("date", date)
args.putString("hour", hour)
args.putString("ubi", ubi)
args.putString("desc", desc)
args.putString("hourDur", hourDur)
args.putString("url", url)
args.putString("typeAct", typeAct)
args.putInt("peopleEnrolled", peopleEnrolled)
args.putBoolean("state", state)
args.putString("foro", foro)
args.putStringArrayList("register", register)
args.putString("idRoute", idRoute)
args.putStringArrayList("permissions", ArrayList(permissions))
fragment.arguments = args
return fragment
}
}
}
| 1 |
Kotlin
|
1
| 1 |
b8a06baa119ffb0d355d1ae7fe7e607bb8f1c52c
| 9,628 |
app-android
|
MIT License
|
feature/books/src/main/java/com/githukudenis/comlib/feature/books/BooksUiState.kt
|
DenisGithuku
| 707,847,935 | false |
{"Kotlin": 416771, "Java": 95753, "Roff": 12367}
|
package com.githukudenis.comlib.feature.books
import com.githukudenis.comlib.core.model.book.Book
import com.githukudenis.comlib.core.model.genre.Genre
sealed class BooksUiState {
data object Loading : BooksUiState()
data class Success(
val searchState: GenreSearchState = GenreSearchState(),
val selectedGenres: List<GenreUiModel>,
val bookListUiState: BookListUiState,
val genreListUiState: GenreListUiState
) : BooksUiState()
data class Error(val message: String) : BooksUiState()
}
sealed class BookListUiState {
data object Loading : BookListUiState()
data class Success(val books: List<BookItemUiModel>) : BookListUiState()
data class Error(val message: String) : BookListUiState()
data object Empty: BookListUiState()
}
sealed class GenreListUiState {
data object Loading : GenreListUiState()
data class Success(
val genres: List<GenreUiModel>,
) : GenreListUiState()
data class Error(val message: String) : GenreListUiState()
}
fun Genre.toGenreUiModel(): GenreUiModel {
return GenreUiModel(
name = name, id = id
)
}
data class GenreUiModel(
val name: String, val id: String
)
fun Book.toBookItemUiModel(): BookItemUiModel {
return BookItemUiModel(
id = id, title = title, authors = authors, imageUrl = image, genres = genre_ids
)
}
data class BookItemUiModel(
val id: String,
val title: String,
val authors: List<String>,
val genres: List<String>,
val imageUrl: String,
)
data class GenreSearchState(
val query: String = ""
)
| 3 |
Kotlin
|
1
| 0 |
0c0b0d364b329ca40b5d39bcacf8ca9e70b0874e
| 1,593 |
comlib-android-client
|
Apache License 2.0
|
app/src/main/java/com/aristidevs/androidmaster/MenuActivity.kt
|
ArisGuimera
| 572,907,048 | false | null |
package com.aristidevs.androidmaster
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import com.aristidevs.androidmaster.firstapp.FirstAppActivity
import com.aristidevs.androidmaster.imccalculator.ImcCalculatorActivity
import com.aristidevs.androidmaster.superheroapp.SuperHeroListActivity
import com.aristidevs.androidmaster.todoapp.TodoActivity
class MenuActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_menu)
val btnSaludApp = findViewById<Button>(R.id.btnSaludApp)
val btnImcApp = findViewById<Button>(R.id.btnIMCApp)
val btnTODO = findViewById<Button>(R.id.btnTODO)
val btnSuperhero = findViewById<Button>(R.id.btnSuperhero)
btnSaludApp.setOnClickListener { navigateToSaludApp() }
btnImcApp.setOnClickListener { navigateToImcApp() }
btnTODO.setOnClickListener { navigateToTodoApp() }
btnSuperhero.setOnClickListener { navigateToSuperheroApp() }
}
private fun navigateToTodoApp() {
val intent = Intent(this, TodoActivity::class.java)
startActivity(intent)
}
private fun navigateToImcApp() {
val intent = Intent(this, ImcCalculatorActivity::class.java)
startActivity(intent)
}
private fun navigateToSaludApp(){
val intent = Intent(this, FirstAppActivity::class.java)
startActivity(intent)
}
private fun navigateToSuperheroApp(){
val intent = Intent(this, SuperHeroListActivity::class.java)
startActivity(intent)
}
}
| 0 | null |
2
| 129 |
64e9f362e889dc636d2dacac32d7129baa810880
| 1,698 |
Android-Expert
|
Apache License 2.0
|
engine/src/main/java/com/ivan/todoengine/networking/converters/ZonedDateTimeConverter.kt
|
IvanSimovic
| 237,819,921 | false | null |
package com.ivan.todoengine.networking.converters
import com.google.gson.*
import java.lang.reflect.Type
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAccessor
class ZonedDateTimeConverter : JsonSerializer<ZonedDateTime?>,
JsonDeserializer<ZonedDateTime> {
override fun serialize(
src: ZonedDateTime?,
typeOfSrc: Type,
context: JsonSerializationContext
): JsonElement {
return JsonPrimitive(FORMATTER.format(src))
}
@Throws(JsonParseException::class)
override fun deserialize(
json: JsonElement,
typeOfT: Type,
context: JsonDeserializationContext
): ZonedDateTime {
return FORMATTER.parse(
json.asString
) { temporalAccessor: TemporalAccessor? ->
ZonedDateTime.from(
temporalAccessor
)
}
}
companion object {
private val FORMATTER =
DateTimeFormatter.ISO_DATE_TIME
}
}
| 0 |
Java
|
1
| 1 |
5705012f912f7884434abda2381ec6b82322da81
| 1,026 |
AndroidUltimateExample
|
MIT License
|
app/src/main/java/com/hope/guanjiapo/fragment/HomeFragment.kt
|
kazeik
| 172,053,633 | false | null |
package com.hope.guanjiapo.fragment
import android.annotation.SuppressLint
import android.support.v7.widget.GridLayoutManager
import android.text.TextUtils
import android.view.View
import com.hope.guanjiapo.R
import com.hope.guanjiapo.activity.OrderInfoActivity
import com.hope.guanjiapo.activity.SubscribeActivity
import com.hope.guanjiapo.activity.WaybillActivity
import com.hope.guanjiapo.activity.WaybillControlActivity
import com.hope.guanjiapo.adapter.DataAdapter
import com.hope.guanjiapo.base.BaseFragment
import com.hope.guanjiapo.base.BaseModel
import com.hope.guanjiapo.iter.OnItemEventListener
import com.hope.guanjiapo.model.AdapterItemModel
import com.hope.guanjiapo.model.VehicleModel
import com.hope.guanjiapo.net.HttpNetUtils
import com.hope.guanjiapo.net.NetworkScheduler
import com.hope.guanjiapo.net.ProgressSubscriber
import com.hope.guanjiapo.utils.ApiUtils.loginModel
import com.hope.guanjiapo.utils.ApiUtils.vehicleModel
import kotlinx.android.synthetic.main.fragment_data.*
import kotlinx.android.synthetic.main.view_title.*
import org.jetbrains.anko.support.v4.startActivity
class HomeFragment : BaseFragment(), OnItemEventListener {
override fun onItemEvent(pos: Int) {
when (pos) {
0 -> startActivity<OrderInfoActivity>()
1 -> startActivity<WaybillActivity>()
2 -> startActivity<WaybillControlActivity>()
3 -> startActivity<SubscribeActivity>()
}
}
override fun initView(): Int {
return R.layout.fragment_data
}
@SuppressLint("SetTextI18n")
override fun bindData() {
tvTitle.text = "้ฆ้กต"
ivBackup.visibility = View.GONE
val itemArr = resources.getStringArray(R.array.homedata)
val iconArr = arrayOf<Int>(R.drawable.icon1, R.drawable.icon2, R.drawable.icon3, R.drawable.icon4)
val allItem = arrayListOf<AdapterItemModel>()
for (i in 0 until itemArr.size) {
val item = AdapterItemModel()
item.items = itemArr[i]
item.imgs = iconArr[i]
allItem.add(item)
}
val adapter = DataAdapter<AdapterItemModel>()
rcvData.layoutManager = GridLayoutManager(activity, 3)
rcvData.adapter = adapter
adapter.setDataEntityList(allItem)
adapter.itemListener = this
getInfo()
}
private fun getInfo() {
HttpNetUtils.getInstance().getManager()?.getCompanyInfo(
hashMapOf(
"id" to loginModel?.id!!
)
)?.compose(NetworkScheduler.compose())
?.subscribe(object : ProgressSubscriber<BaseModel<VehicleModel>>(activity) {
@SuppressLint("SetTextI18n")
override fun onSuccess(data: BaseModel<VehicleModel>?) {
vehicleModel = data?.data
version.text =
"${if (TextUtils.isEmpty(vehicleModel?.companyname)) "" else vehicleModel?.companyname}\n${loginModel?.userName} ${when (loginModel?.userType) {
1 -> "็ป็"
2 -> "ๅๅทฅ"
10 -> "VIP ๅฎขๆท"
else -> ""
}}\n็ๆฌ๏ผ1.0"
}
})
}
}
| 0 |
Kotlin
|
2
| 1 |
9c435adb7dfa134fdd016f26ee7817f971e2a11c
| 3,253 |
GuanJiaPo
|
Apache License 2.0
|
secureapp/src/main/java/com/applexis/secureapp/serializers/DoubleSerializer.kt
|
alent13
| 187,673,579 | false | null |
package com.applexis.secureapp.serializers
class DoubleSerializer {
fun serialize(value: Double): ByteArray = LongSerializer().serialize(value.toBits())
fun deserialize(bytes: ByteArray): Double = Double.fromBits(LongSerializer().deserialize(bytes))
}
| 0 |
Kotlin
|
0
| 0 |
cff8a85978116331b96e2adc526e5807b7d32ed6
| 262 |
aDialogClient
|
MIT License
|
src/test/kotlin/allbegray/spring/SpringBootTest.kt
|
allbegray
| 494,288,519 | false |
{"Kotlin": 13663}
|
package allbegray.spring
import allbegray.spring.boot.autoconfigure.minio.MinioAutoConfiguration
import allbegray.spring.boot.autoconfigure.minio.MinioListenerConfiguration
import allbegray.spring.boot.autoconfigure.minio.MinioProperties
import allbegray.spring.minio.MinioEventType
import allbegray.spring.minio.MinioTemplate
import allbegray.spring.minio.annotation.MinioListener
import io.minio.messages.Event
import org.junit.jupiter.api.Assertions
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.stereotype.Component
@Component
class TestMinioListener {
@MinioListener(MinioEventType.OBJECT_CREATED_PUT, "s3:ObjectCreated:Post")
fun putOrPostEvent(event: Event) {
println("putOrPostEvent : $event")
}
@MinioListener("s3:ObjectRemoved:*")
fun deleteEvent(event: Event) {
println("deleteEvent : $event")
}
}
@SpringBootTest(classes = [MinioAutoConfiguration::class, MinioListenerConfiguration::class, TestMinioListener::class])
class SpringBootTest {
@Autowired
lateinit var minioTemplate: MinioTemplate
@Autowired
lateinit var minioProperties: MinioProperties
@Test
fun listenerTest() {
try {
minioTemplate.putObject("text.txt", "test")
Thread.sleep(1 * 1000)
minioTemplate.removeObject("text.txt")
Thread.sleep(1 * 1000)
} finally {
minioTemplate.removeBucket(minioProperties.defaultBucket)
}
}
@Test
fun listBucketsTest() {
val listBuckets = minioTemplate.listBuckets()
Assertions.assertTrue(listBuckets.isNotEmpty())
}
}
| 0 |
Kotlin
|
1
| 0 |
558f62676da4c49174fae3425228657ae730b2cf
| 1,751 |
spring-boot-starter-minio
|
MIT License
|
app/src/main/kotlin/me/zhiyao/waterever/ui/plant/create/name/NewPlantNameFragment.kt
|
WangZhiYao
| 243,558,800 | false | null |
package me.zhiyao.waterever.ui.plant.create.name
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.inputmethod.EditorInfo
import androidx.core.widget.doAfterTextChanged
import androidx.fragment.app.activityViewModels
import androidx.navigation.fragment.findNavController
import dagger.hilt.android.AndroidEntryPoint
import me.zhiyao.waterever.R
import me.zhiyao.waterever.databinding.FragmentNewPlantNameBinding
import me.zhiyao.waterever.ui.base.BaseFragment
import me.zhiyao.waterever.ui.plant.create.NewPlantViewModel
/**
*
* @author WangZhiYao
* @date 2020/9/3
*/
@AndroidEntryPoint
class NewPlantNameFragment : BaseFragment() {
private lateinit var binding: FragmentNewPlantNameBinding
private val viewModel by activityViewModels<NewPlantViewModel>()
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
binding = FragmentNewPlantNameBinding.inflate(layoutInflater, container, false)
initView()
initData()
return binding.root
}
private fun initView() {
binding.etNewPlantName.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_NEXT) {
next()
true
} else {
false
}
}
binding.etNewPlantName.doAfterTextChanged {
binding.fabNext.isEnabled = !it.isNullOrBlank()
binding.etNewPlantName.error = if (!it.isNullOrBlank()) {
null
} else {
getString(R.string.new_plant_name_can_not_be_empty)
}
}
binding.fabNext.setOnClickListener { next() }
}
private fun initData() {
viewModel.plantName?.let {
binding.etNewPlantName.setText(it)
}
}
private fun next() {
if (binding.etNewPlantName.text.isNullOrBlank()) {
binding.etNewPlantName.requestFocus()
binding.etNewPlantName.error = getString(R.string.new_plant_name_can_not_be_empty)
} else {
binding.fabNext.isEnabled = false
viewModel.plantName = binding.etNewPlantName.text.toString()
findNavController().navigate(R.id.action_name_to_feature_image)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
232f20d623209eb2b9fb889aeb05af6ec3fee535
| 2,406 |
WaterEver
|
Apache License 2.0
|
app/src/main/java/com/example/cinego/MovieAdapter.kt
|
Zhaoshan-Duan
| 453,903,162 | false |
{"Kotlin": 10541}
|
package com.example.cinego
import android.content.Context
import android.content.Intent
import android.util.Log
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.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
const val MOVIE_EXTRA = "MOVIE_EXTRA"
class MovieAdapter(private val context: Context, private val movies: List<Movie>) :
RecyclerView.Adapter<MovieAdapter.ViewHolder>() {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(context).inflate(R.layout.item_movie, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val movie = movies[position]
holder.bind(movie)
}
override fun getItemCount() = movies.size
inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView),
View.OnClickListener {
private val ivPostser = itemView.findViewById<ImageView>(R.id.ivPoster)
private val tvTitle = itemView.findViewById<TextView>(R.id.tvTitle)
private val tvOverview = itemView.findViewById<TextView>(R.id.tvOverview)
init {
itemView.setOnClickListener(this)
}
fun bind(movie: Movie) {
tvTitle.text = movie.title
tvOverview.text = movie.overview
Glide.with(context)
.load(movie.posterImageUrl)
.placeholder(R.drawable.loading)
.override(400, 600)
.transform(RoundedCorners(60))
.into(ivPostser)
}
override fun onClick(p0: View?) {
// 1. get notified of the particular movie when tapped
val movie = movies[adapterPosition]
// 2. use Intent to navigate to the new activity
val intent = Intent(context, DetailActivity::class.java)
intent.putExtra(MOVIE_EXTRA, movie)
context.startActivity(intent)
}
}
}
| 0 |
Kotlin
|
0
| 0 |
64a65190b2967657e1e8ade281e1e61ce5e1e833
| 2,179 |
FlixsterApp
|
Apache License 2.0
|
gradle/build-logic/convention/src/main/kotlin/io/filmtime/gradle/plugins/LibraryJvmPlugin.kt
|
moallemi
| 633,160,161 | false |
{"Kotlin": 522936, "Shell": 3102}
|
package io.filmtime.gradle.plugins
import io.filmtime.gradle.configureKotlinJvm
import org.gradle.api.Plugin
import org.gradle.api.Project
class LibraryJvmPlugin : Plugin<Project> {
override fun apply(target: Project) {
with(target) {
with(pluginManager) {
apply("org.jetbrains.kotlin.jvm")
}
configureKotlinJvm()
}
}
}
| 21 |
Kotlin
|
14
| 87 |
ad3eeed30bed20216a9fa12e34f06e43b70a74cc
| 360 |
Film-Time
|
MIT License
|
app/src/test/java/com/philuvarov/flickr/remote/model/PhotosResponseTypeAdapterTest.kt
|
Kistamushken
| 107,904,491 | false | null |
package com.philuvarov.flickr.remote.model
import com.google.gson.GsonBuilder
import com.philuvarov.flickr.Is
import org.intellij.lang.annotations.Language
import org.junit.Assert.assertThat
import org.junit.Test
@Suppress("IllegalIdentifier")
class PhotosResponseTypeAdapterTest {
private val gson = GsonBuilder()
.registerTypeAdapter(PhotosResponse::class.java, PhotosResponseTypeAdapter())
.create()
@Test
fun `parse photos response`() {
val response = gson.fromJson(RESPONSE, PhotosResponse::class.java)
assertThat(response.totalPages, Is(2))
assertThat(response.photos.isEmpty(), Is(false))
}
}
@Language("JavaScript")
private val RESPONSE = """
{
"photos": {
"page": 1,
"pages": 2,
"perpage": 3,
"total": "4",
"photo": [
{
"id": "23963189578",
"owner": "45491220@N03",
"secret": "<KEY>",
"server": "4494",
"farm": 5,
"title": "turtzioz",
"ispublic": 1,
"isfriend": 0,
"isfamily": 0,
"url_n": "https://farm5.staticflickr.com/4494/23963189578_c203d51993.jpg",
"height_m": "281",
"width_m": "500"
}
]
}
}
"""
| 0 |
Kotlin
|
0
| 0 |
85f5913494a304d7ce30b84278470bed6f78c7fe
| 1,531 |
Flickr
|
MIT License
|
src/test/kotlin/uk/gov/justice/digital/hmpps/calculatereleasedatesapi/resource/OffenceSDSReleaseArrangementLookupServiceIntTest.kt
|
ministryofjustice
| 387,841,000 | false |
{"Kotlin": 1393943, "Shell": 7185, "Dockerfile": 1397}
|
package uk.gov.justice.digital.hmpps.calculatereleasedatesapi.resource
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.springframework.beans.factory.annotation.Autowired
import uk.gov.justice.digital.hmpps.calculatereleasedatesapi.config.UserContext
import uk.gov.justice.digital.hmpps.calculatereleasedatesapi.exceptions.CouldNotGetMoOffenceInformation
import uk.gov.justice.digital.hmpps.calculatereleasedatesapi.integration.IntegrationTestBase
import uk.gov.justice.digital.hmpps.calculatereleasedatesapi.model.NormalisedSentenceAndOffence
import uk.gov.justice.digital.hmpps.calculatereleasedatesapi.model.external.OffenderOffence
import uk.gov.justice.digital.hmpps.calculatereleasedatesapi.model.external.SentenceCalculationType
import uk.gov.justice.digital.hmpps.calculatereleasedatesapi.model.external.SentenceTerms
import uk.gov.justice.digital.hmpps.calculatereleasedatesapi.service.OffenceSDSReleaseArrangementLookupService
import java.time.LocalDate
class OffenceSDSReleaseArrangementLookupServiceIntTest : IntegrationTestBase() {
@Autowired
lateinit var offenceSDSReleaseArrangementLookupService: OffenceSDSReleaseArrangementLookupService
@Test
fun `Test Call to MO Service Matching SEC_250 Offence marked as SDS+`() {
// S250 over 7 years and sentenced after PCSC date
val inputOffenceList = listOf(
NormalisedSentenceAndOffence(
1,
1,
1,
1,
null,
"TEST",
"TEST",
SentenceCalculationType.SEC250.toString(),
"TEST",
LocalDate.of(2022, 8, 29),
listOf(SentenceTerms(8, 4, 1, 1)),
OffenderOffence(
1,
LocalDate.of(2022, 1, 1),
null,
"COML025A",
"TEST OFFENSE",
),
null,
null,
null,
),
)
UserContext.setAuthToken("<PASSWORD>")
val markedUp = offenceSDSReleaseArrangementLookupService.populateReleaseArrangements(inputOffenceList)
assertTrue(markedUp[0].isSDSPlus)
}
@Test
fun `Test exception is thrown on 500 MO response`() {
assertTrue(
assertThrows<Exception> {
val inputOffenceList = listOf(
NormalisedSentenceAndOffence(
1,
1,
1,
1,
null,
"TEST",
"TEST",
SentenceCalculationType.SEC250.toString(),
"TEST",
LocalDate.of(2022, 8, 29),
listOf(SentenceTerms(8, 4, 1, 1)),
OffenderOffence(
1,
LocalDate.of(2022, 1, 1),
null,
"500Response",
"TEST OFFENSE",
),
null,
null,
null,
),
)
UserContext.setAuthToken("<PASSWORD>")
offenceSDSReleaseArrangementLookupService.populateReleaseArrangements(inputOffenceList)
}.cause is CouldNotGetMoOffenceInformation,
)
}
@Test
fun `Test Call to MO Service Matching SEC_250 multiple offences marked as SDS+ `() {
// S250 over 7 years and sentenced after PCSC date
val inputOffenceList = listOf(
NormalisedSentenceAndOffence(
1,
1,
1,
1,
null,
"TEST",
"TEST",
SentenceCalculationType.SEC250.toString(),
"TEST",
LocalDate.of(2022, 8, 29),
listOf(SentenceTerms(8, 4, 1, 1)),
OffenderOffence(
1,
LocalDate.of(2022, 1, 1),
null,
"COML025A",
"TEST OFFENSE",
),
null,
null,
null,
),
NormalisedSentenceAndOffence(
1,
1,
1,
1,
null,
"TEST",
"TEST",
SentenceCalculationType.SEC250.toString(),
"TEST",
LocalDate.of(2022, 8, 29),
listOf(SentenceTerms(8, 4, 1, 1)),
OffenderOffence(
1,
LocalDate.of(2022, 1, 1),
null,
"COML022",
"TEST OFFENSE",
),
null,
null,
null,
),
)
UserContext.setAuthToken("<PASSWORD>")
val markedUp = offenceSDSReleaseArrangementLookupService.populateReleaseArrangements(inputOffenceList)
assertTrue(markedUp[0].isSDSPlus)
}
}
| 3 |
Kotlin
|
0
| 4 |
21fbc925927afb2e10ddbeea415921e33a46845a
| 4,355 |
calculate-release-dates-api
|
MIT License
|
book-network/src/main/kotlin/com/egi/book/auth/AuthenticationRequest.kt
|
EgiKarakashi
| 792,352,694 | false |
{"Kotlin": 60439, "HTML": 1566, "Dockerfile": 166}
|
package com.egi.book.auth
import jakarta.validation.constraints.Email
import jakarta.validation.constraints.NotBlank
import jakarta.validation.constraints.NotEmpty
import jakarta.validation.constraints.Size
data class AuthenticationRequest(
@field:Email(message = "Email is not well formatted")
@field:NotEmpty(message = "Email is mandatory")
@field:NotBlank(message = "Email is mandatory")
val email: String,
@field:Size(min = 8, message = "Password should be more than 8 characters")
@field:NotEmpty(message = "Password is mandatory")
@field:NotBlank(message = "Password is mandatory")
val password: String,
)
| 0 |
Kotlin
|
0
| 0 |
01a919dd48ee0609722144841391a0f418fae804
| 646 |
book-social-network
|
Apache License 2.0
|
buildSrc/src/main/kotlin/Common.kt
|
unveloper
| 529,228,570 | false | null |
object BuildPlugins {
const val androidApplication = "com.android.application"
const val androidLibrary = "com.android.library"
const val kotlinAndroid = "org.jetbrains.kotlin.android"
const val kotlinKapt = "kotlin-kapt"
const val gradleVersionPlugin = "com.github.ben-manes.versions"
const val hilt = "dagger.hilt.android.plugin"
const val javaLibrary = "java-library"
const val kotlin = "org.jetbrains.kotlin.jvm"
const val mavenPublish = "maven-publish"
const val gradleNexusPublishPlugin = "io.github.gradle-nexus.publish-plugin"
}
object Android {
const val testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
}
object Modules {
const val Data = ":data"
const val Domain = ":domain"
}
| 0 |
Kotlin
|
0
| 1 |
a902f7f90e047d9d8a4aa471039b063c26fdcf0d
| 724 |
slf4j-timber
|
Apache License 2.0
|
components/gateway/src/test/kotlin/net/corda/p2p/gateway/messaging/mtls/DynamicCertificateSubjectStoreTest.kt
|
corda
| 346,070,752 | false | null |
package net.corda.p2p.gateway.messaging.mtls
import net.corda.data.p2p.mtls.gateway.ClientCertificateSubjects
import net.corda.libs.configuration.SmartConfig
import net.corda.lifecycle.LifecycleCoordinatorFactory
import net.corda.lifecycle.LifecycleCoordinatorName
import net.corda.lifecycle.domino.logic.util.SubscriptionDominoTile
import net.corda.messaging.api.processor.CompactedProcessor
import net.corda.messaging.api.records.Record
import net.corda.messaging.api.subscription.CompactedSubscription
import net.corda.messaging.api.subscription.factory.SubscriptionFactory
import net.corda.v5.base.types.MemberX500Name
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.Test
import org.mockito.Mockito
import org.mockito.kotlin.any
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
class DynamicCertificateSubjectStoreTest {
private companion object {
const val TOPIC = "Topic"
const val KEY_1 = "key1"
const val KEY_2 = "key2"
const val SUBJECT_1 = "O=Alice, L=London, C=GB"
const val SUBJECT_2 = "O=Bob, L=London, C=GB"
const val SUBJECT_3 = "O=Carol, L=London, C=GB"
}
private val lifecycleCoordinatorFactory = mock<LifecycleCoordinatorFactory>()
private val nodeConfiguration = mock<SmartConfig>()
private val subscription = mock<CompactedSubscription<String, ClientCertificateSubjects>>()
private val processor = argumentCaptor<CompactedProcessor<String, ClientCertificateSubjects>>()
private val subscriptionFactory = mock<SubscriptionFactory> {
on { createCompactedSubscription(any(), processor.capture(), eq(nodeConfiguration)) } doReturn subscription
}
private val subscriptionDominoTile = Mockito.mockConstruction(SubscriptionDominoTile::class.java) { mock, context ->
whenever(mock.coordinatorName).doReturn(LifecycleCoordinatorName("", ""))
@Suppress("UNCHECKED_CAST")
(context.arguments()[1] as (() -> CompactedSubscription<String, ClientCertificateSubjects>)).invoke()
}
private val dynamicCertificateSubjectStore =
DynamicCertificateSubjectStore(lifecycleCoordinatorFactory, subscriptionFactory, nodeConfiguration)
@AfterEach
fun cleanUp() {
subscriptionDominoTile.close()
}
@Test
fun `onSnapshot adds subjects to the store`() {
processor.firstValue.onSnapshot(mapOf(KEY_1 to ClientCertificateSubjects(SUBJECT_1), KEY_2 to ClientCertificateSubjects(SUBJECT_2)))
assertThat(dynamicCertificateSubjectStore.subjectAllowed(MemberX500Name.parse(SUBJECT_1))).isTrue
assertThat(dynamicCertificateSubjectStore.subjectAllowed(MemberX500Name.parse(SUBJECT_2))).isTrue
assertThat(dynamicCertificateSubjectStore.subjectAllowed(MemberX500Name.parse(SUBJECT_3))).isFalse
}
@Test
fun `onNext adds subjects to the store`() {
processor.firstValue.onNext(Record(TOPIC, KEY_1, ClientCertificateSubjects(SUBJECT_1)), null, emptyMap())
processor.firstValue.onNext(Record(TOPIC, KEY_2, ClientCertificateSubjects(SUBJECT_2)), null, emptyMap())
assertThat(dynamicCertificateSubjectStore.subjectAllowed(MemberX500Name.parse(SUBJECT_1))).isTrue
assertThat(dynamicCertificateSubjectStore.subjectAllowed(MemberX500Name.parse(SUBJECT_2))).isTrue
assertThat(dynamicCertificateSubjectStore.subjectAllowed(MemberX500Name.parse(SUBJECT_3))).isFalse
}
@Test
fun `onNext removes subjects from the store after a tombstone record for every key`() {
processor.firstValue.onNext(Record(TOPIC, KEY_1, ClientCertificateSubjects(SUBJECT_1)), null, emptyMap())
processor.firstValue.onNext(Record(TOPIC, KEY_2, ClientCertificateSubjects(SUBJECT_1)), null, emptyMap())
assertThat(dynamicCertificateSubjectStore.subjectAllowed(MemberX500Name.parse(SUBJECT_1))).isTrue
processor.firstValue.onNext(Record(TOPIC, KEY_1, null), ClientCertificateSubjects(SUBJECT_1), emptyMap())
assertThat(dynamicCertificateSubjectStore.subjectAllowed(MemberX500Name.parse(SUBJECT_1))).isTrue
processor.firstValue.onNext(Record(TOPIC, KEY_2, null), ClientCertificateSubjects(SUBJECT_1), emptyMap())
assertThat(dynamicCertificateSubjectStore.subjectAllowed(MemberX500Name.parse(SUBJECT_1))).isFalse
}
@Test
fun `onNext will add the normalized subject`() {
processor.firstValue.onNext(
Record(
TOPIC,
KEY_1,
ClientCertificateSubjects(
"C=GB, O=Alice, L=London",
),
),
null,
emptyMap(),
)
assertThat(dynamicCertificateSubjectStore.subjectAllowed(MemberX500Name.parse(SUBJECT_1))).isTrue
}
@Test
fun `onNext will remove the normalized subject`() {
processor.firstValue.onNext(
Record(
TOPIC,
KEY_1,
ClientCertificateSubjects(
SUBJECT_1,
),
),
null,
emptyMap(),
)
processor.firstValue.onNext(
Record(
TOPIC,
KEY_1,
null,
),
ClientCertificateSubjects(
"C=GB, O=Alice, L=London",
),
emptyMap(),
)
assertThat(dynamicCertificateSubjectStore.subjectAllowed(MemberX500Name.parse(SUBJECT_1))).isFalse
}
}
| 32 | null |
27
| 69 |
d478e119ab288af663910f9a2df42a7a7b9f5bce
| 5,645 |
corda-runtime-os
|
Apache License 2.0
|
app/src/main/java/it/uniparthenope/parthenopeddit/android/GroupChatActivity.kt
|
GruppoProgettoTMM201920-Parthenopeddit
| 264,177,213 | false | null |
package it.uniparthenope.parthenopeddit.android
import android.os.Bundle
import it.uniparthenope.parthenopeddit.LoginRequiredActivity
import it.uniparthenope.parthenopeddit.R
import it.uniparthenope.parthenopeddit.model.Group
import it.uniparthenope.parthenopeddit.util.toObject
class GroupChatActivity : LoginRequiredActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_groupchat)
val extras = intent.extras
var group: Group? = extras?.getString("group")?.toObject()
/*val type = "user"//= intent.getParcelableExtra<String>(NewMessageActivity.USER_KEY)
val groupID = null//intent.getParcelableExtra<Int>(NewMessageActivity.USER_KEY)
//groupname_chat_textview.text = group?.name
if(group==null){
finish()
} else {
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction()
.replace(
R.id.container,
//if(type=="user") UserChatFragment.newInstance(user) else GroupChatFragment.newInstance(groupID))
GroupChatFragment.newInstance(group)
)
.commitNow()
}
}
}
*/
}
}
| 0 |
Kotlin
|
0
| 0 |
efd306b99cf3f0c6b42a033a161aee6a0fbcc933
| 1,357 |
AndroidAPP
|
Apache License 2.0
|
app/src/main/java/com/meuus90/daumbooksearch/di/helper/AppInjector.kt
|
meuus90
| 291,686,119 | false |
{"Kotlin": 119457}
|
package com.meuus90.daumbooksearch.di.helper
import android.app.Activity
import android.app.Application
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import com.meuus90.daumbooksearch.DaumBookSearch
import com.meuus90.daumbooksearch.di.Injectable
import com.meuus90.daumbooksearch.di.component.DaggerAppComponent
import dagger.android.AndroidInjection
import dagger.android.HasAndroidInjector
import dagger.android.support.AndroidSupportInjection
object AppInjector {
fun init(app: DaumBookSearch) {
DaggerAppComponent.factory().create(app).inject(app)
app.registerActivityLifecycleCallbacks(object : Application.ActivityLifecycleCallbacks {
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
handleActivity(activity)
}
override fun onActivityStarted(activity: Activity) {
}
override fun onActivityResumed(activity: Activity) {
}
override fun onActivityPaused(activity: Activity) {
}
override fun onActivityStopped(activity: Activity) {
}
override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {
}
override fun onActivityDestroyed(activity: Activity) {
}
})
}
private fun handleActivity(activity: Activity) {
if (activity is HasAndroidInjector) {
AndroidInjection.inject(activity)
}
(activity as? FragmentActivity)?.supportFragmentManager?.registerFragmentLifecycleCallbacks(
object : FragmentManager.FragmentLifecycleCallbacks() {
override fun onFragmentCreated(
fm: FragmentManager,
f: Fragment,
savedInstanceState: Bundle?
) {
if (f is Injectable) {
AndroidSupportInjection.inject(f)
}
}
}, true
)
}
}
| 0 |
Kotlin
|
0
| 0 |
43c119347a45d21cfe85744916dbb2b7216cf60d
| 2,143 |
DaumBookSearch
|
MIT License
|
src/test/kotlin/dev/paulshields/lok/internal/internallogger/ConditionalInternalLoggerTest.kt
|
Pkshields
| 354,123,889 | false | null |
package dev.paulshields.lok.internal.internallogger
import assertk.assertThat
import assertk.assertions.isEmpty
import dev.paulshields.lok.LogLevel
import dev.paulshields.lok.internal.internalLogIfEqual
import dev.paulshields.lok.internal.internalLogIfNotEqual
import dev.paulshields.lok.internal.internalLogIfNotNull
import dev.paulshields.lok.internal.internalLogIfNull
import dev.paulshields.lok.testcommon.containsAll
import org.junit.jupiter.api.Test
class ConditionalInternalLoggerTest : BaseInternalLoggerTest() {
@Test
fun `should output log line if items are equal`() {
val item1 = 1
val item2 = 1
internalLogIfEqual(anyClassName, item1, item2, message, LogLevel.INFO)
assertThat(stdOutOutput()).containsAll("INFO", message)
}
@Test
fun `should not output log line if items are not equal`() {
val item1 = 1
val item2 = 2
internalLogIfEqual(anyClassName, item1, item2, message, LogLevel.INFO)
assertThat(stdOutOutput()).isEmpty()
}
@Test
fun `should output log line if items are not equal`() {
val item1 = 1
val item2 = 2
internalLogIfNotEqual(anyClassName, item1, item2, message, LogLevel.INFO)
assertThat(stdOutOutput()).containsAll("INFO", message)
}
@Test
fun `should not output log line if items are equal`() {
val item1 = 1
val item2 = 1
internalLogIfNotEqual(anyClassName, item1, item2, message, LogLevel.INFO)
assertThat(stdOutOutput()).isEmpty()
}
@Test
fun `should output log line if item is null`() {
internalLogIfNull(anyClassName, null, message, LogLevel.INFO)
assertThat(stdOutOutput()).containsAll("INFO", message)
}
@Test
fun `should not output log line if item is not null`() {
internalLogIfNull(anyClassName, 1, message, LogLevel.INFO)
assertThat(stdOutOutput()).isEmpty()
}
@Test
fun `should output log line if item is not null`() {
internalLogIfNotNull(anyClassName, 1, message, LogLevel.INFO)
assertThat(stdOutOutput()).containsAll("INFO", message)
}
@Test
fun `should not output log line if item is null`() {
internalLogIfNotNull(anyClassName, null, message, LogLevel.INFO)
assertThat(stdOutOutput()).isEmpty()
}
}
| 0 |
Kotlin
|
0
| 0 |
387453778d0658d04e32cd2caf22fdc4d9af34f6
| 2,354 |
Lok
|
MIT License
|
io/grpc/src/main/kotlin/io/bluetape4k/protobuf/MoneySupport.kt
|
debop
| 625,161,599 | false |
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
|
package io.bluetape4k.protobuf
import org.javamoney.moneta.Money as JavaMoney
/**
* ๊ตฌ๊ธ grpc์ Money ํ์
์ ๊ฐ์ฒด๋ฅผ Java์ ํ์ค Money ์ํ์ผ๋ก ๋ณํํฉ๋๋ค.
*
* @return [JavaMoney] ์ธ์คํด์ค
*/
fun ProtoMoney.toJavaMoney(): JavaMoney {
val number = units.toBigDecimal() + (nanos.toDouble() / 1.0e9).toBigDecimal()
return JavaMoney.of(number, currencyCode)
}
/**
* Java ํ์ค Money ์ํ์ ๊ตฌ๊ธ grpc ์ Money ์ํ์ผ๋ก ๋ณํํฉ๋๋ค.
*
* @return
*/
fun JavaMoney.toProtoMoney(): ProtoMoney {
val units = this.number.longValueExact()
val nanos = ((this.number.doubleValueExact() - units) * 1.0e9).toInt()
return ProtoMoney.newBuilder()
.setCurrencyCode(currency.currencyCode)
.setUnits(units)
.setNanos(nanos)
.build()
}
| 0 |
Kotlin
|
0
| 1 |
ce3da5b6bddadd29271303840d334b71db7766d2
| 732 |
bluetape4k
|
MIT License
|
hibernate-provider/src/test/kotlin/Models.kt
|
ariga
| 715,482,920 | false |
{"Kotlin": 32351}
|
import jakarta.persistence.Entity
import jakarta.persistence.GeneratedValue
import jakarta.persistence.GenerationType
import jakarta.persistence.Id
@Entity
open class WithGenerationTypeSequence {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
var id: Long? = null
}
@Entity
open class WithGenerationTypeTable {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
var id: Long? = null
}
@Entity
open class WithGenerationTypeAuto {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
var id: Long? = null
}
@Entity
open class WithGenerationTypeIdentity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
var id: Long? = null
}
@Entity
open class WithoutGenerationType {
@Id
var id: Long? = null
}
| 1 |
Kotlin
|
1
| 3 |
14c524c667404984946cc669780105a43fe35d4e
| 772 |
atlas-provider-hibernate
|
Apache License 2.0
|
src/main/kotlin/org/jetbrains/teamcity/impl/RestApiFacade.kt
|
JetBrains
| 67,422,865 | false | null |
/*
* Copyright 2000-2020 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.teamcity.impl
import jetbrains.buildServer.controllers.BaseController
import jetbrains.buildServer.log.Loggers
import jetbrains.buildServer.serverSide.SecurityContextEx
import jetbrains.buildServer.users.SUser
import jetbrains.buildServer.users.UserModel
import jetbrains.buildServer.users.UserModelEx
import jetbrains.buildServer.web.util.SessionUser
import jetbrains.spring.web.UrlMapping
import org.jetbrains.teamcity.impl.fakes.FakeHttpRequestsFactory
import org.jetbrains.teamcity.impl.fakes.FakeHttpServletResponse
import java.util.Collections.emptyMap
class RestApiFacade(private val myUrlMapping: UrlMapping,
private val myFakeHttpRequestsFactory: FakeHttpRequestsFactory,
userModel: UserModelEx,
private val mySecurityContext: SecurityContextEx) {
private val myUserModel: UserModel
private val myRestController: BaseController? by lazy {
val handler = myUrlMapping.handlerMap["/app/rest/**"]
if (handler == null) {
Loggers.SERVER.error("Unable to initialize internal Rest Api Facade: no controllers are found for the '/app/rest/**' path. UI will not refresh.")
return@lazy null
}
if (handler !is BaseController) {
Loggers.SERVER.error("Unable to initialize internal Rest Api Facade: unexpected handler was found for the '/app/rest/**' path: $handler. UI will not refresh.")
return@lazy null
}
return@lazy handler as BaseController?
}
init {
myUserModel = userModel
}
/**
* Execute the request under a super user.
*/
@Throws(InternalRestApiCallException::class)
fun getJson(path: String, query: String): String? {
return getJson(myUserModel.superUser, path, query, emptyMap())
}
/**
* Execute the request under the specified user.
*/
@Throws(InternalRestApiCallException::class)
fun getJson(user: SUser, path: String, query: String, requestAttrs: Map<String, Any>): String? {
return get(user, "application/json", path, query, requestAttrs)
}
/**
* Execute the request under the specified user.
*/
@Throws(InternalRestApiCallException::class)
fun get(user: SUser, contentType: String, path: String, query: String, requestAttrs: Map<String, Any>): String? {
return request("GET", user, contentType, path, query, requestAttrs)
}
/**
* Execute the request under the specified user.
*/
@Throws(InternalRestApiCallException::class)
fun request(method: String, user: SUser, contentType: String, path: String, query: String, requestAttrs: Map<String, Any>): String? {
try {
return mySecurityContext.runAs<String>(user) {
val controller = myRestController ?: return@runAs null
val request = myFakeHttpRequestsFactory.get(path, query)
request.setHeader("Accept", contentType)
request.method = method
val response = FakeHttpServletResponse()
request.setAttribute("INTERNAL_REQUEST", true)
SessionUser.setUser(request, user)
requestAttrs.forEach(request::setAttribute)
try {
controller.handleRequestInternal(request, response)
} catch (e: Exception) {
throw InternalRestApiCallException(400, e)
}
if (response.status >= 400) {
Loggers.SERVER.warn("Unexpected response while executing internal Rest API request:" + path + "?" + query + ", response: " + response.returnedContent)
throw InternalRestApiCallException(response.status, response.returnedContent)
}
response.returnedContent
}
} catch (e: InternalRestApiCallException) {
throw e
} catch (throwable: Throwable) {
throw InternalRestApiCallException(400, throwable)
}
}
class InternalRestApiCallException : Exception {
val statusCode: Int
constructor(statusCode: Int, message: String) : super(message) {
this.statusCode = statusCode
}
constructor(statusCode: Int, message: String, cause: Throwable) : super(message, cause) {
this.statusCode = statusCode
}
constructor(statusCode: Int, throwable: Throwable) : super(throwable) {
this.statusCode = statusCode
}
}
}
| 1 |
Kotlin
|
19
| 27 |
f4bac7d082d4e40a98bbfcaa0651a74eb98dc110
| 5,156 |
teamcity-commit-hooks
|
Apache License 2.0
|
app/src/main/java/luyao/wanandroid/compose/model/bean/SystemParent.kt
|
lulululbj
| 221,170,029 | false | null |
package luyao.wanandroid.compose.model.bean
import java.io.Serializable
/**
* Created by Lu
* on 2018/3/26 21:26
*/
data class SystemParent(val children: List<SystemChild>,
val courseId: Int,
val id: Int,
val name: String,
val order: Int,
val parentChapterId: Int,
val visible: Int,
val userControlSetTop: Boolean) : Serializable
| 0 |
Kotlin
|
4
| 31 |
f323b541ac6a89b79f66a3b91bfca85a7a5cc590
| 502 |
Wanandroid-Compose
|
Apache License 2.0
|
lib/src/main/kotlin/be/zvz/klover/container/wav/WavFileInfo.kt
|
organization
| 673,130,266 | false | null |
package be.zvz.klover.container.wav
/**
* WAV file format information.
*
* @param channelCount Number of channels.
* @param sampleRate Sample rate.
* @param bitsPerSample Bits per sample (currently only 16 supported).
* @param blockAlign Size of a block (one sample for each channel + padding).
* @param blockCount Number of blocks in the file.
* @param startOffset Starting position of the raw PCM samples in the file.
*/
class WavFileInfo(
/**
* Number of channels.
*/
val channelCount: Int,
/**
* Sample rate.
*/
val sampleRate: Int,
/**
* Bits per sample (currently only 16 supported).
*/
val bitsPerSample: Int,
/**
* Size of a block (one sample for each channel + padding).
*/
val blockAlign: Int,
/**
* Number of blocks in the file.
*/
val blockCount: Long,
/**
* Starting position of the raw PCM samples in the file.
*/
val startOffset: Long,
) {
val duration: Long
/**
* @return Duration of the file in milliseconds.
*/
get() = blockCount * 1000L / sampleRate
val padding: Int
/**
* @return The size of padding in a sample block in bytes.
*/
get() = blockAlign - channelCount * (bitsPerSample shr 3)
}
| 1 |
Kotlin
|
0
| 2 |
06e801808933ff8c627543d579c4be00061eb305
| 1,305 |
Klover
|
Apache License 2.0
|
app/src/main/java/com/nqmgaming/furniture/domain/usecase/impl/user/GetUserInfoUseCaseImpl.kt
|
nqmgaming
| 803,271,824 | false |
{"Kotlin": 323752}
|
package com.nqmgaming.furniture.domain.usecase.impl.user
import com.nqmgaming.furniture.domain.repository.AuthenticationRepository
import com.nqmgaming.furniture.domain.usecase.user.GetUserInfoUseCase
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import javax.inject.Inject
class GetUserInfoUseCaseImpl @Inject constructor(
private val authenticationRepository: AuthenticationRepository
) : GetUserInfoUseCase {
override suspend fun execute(input: GetUserInfoUseCase.Input): GetUserInfoUseCase.Output {
return try {
withContext(Dispatchers.IO) {
val result = authenticationRepository.getInformationByEmail(input.email)
if (result != null) {
GetUserInfoUseCase.Output.Success(result)
} else {
GetUserInfoUseCase.Output.Failure
}
}
} catch (
e: Exception
) {
e.printStackTrace()
GetUserInfoUseCase.Output.Failure
}
}
}
| 0 |
Kotlin
|
0
| 1 |
1d90f9378bd316a3b2c8259706682546001dd818
| 1,059 |
furniture-shopping-asm
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.