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
src/test/kotlin/dev/ramadhani/jwttemplate/JwtTemplateApplicationTests.kt
dhani14jan
522,699,064
false
{"Kotlin": 15136}
package dev.ramadhani.jwttemplate import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class JwtTemplateApplicationTests { @Test fun contextLoads() { } }
0
Kotlin
0
0
2e9e3bebb42a4cf7ce3e2c16349461e0dea6f5ac
218
Spring-JWT-Template
Apache License 2.0
android/src/main/java/org/ergoplatform/android/wallet/addresses/WalletAddressesViewModel.kt
ergoplatform
376,102,125
false
null
package org.ergoplatform.android.wallet.addresses import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.CoroutineScope import org.ergoplatform.android.AppDatabase import org.ergoplatform.android.Preferences import org.ergoplatform.android.RoomWalletDbProvider import org.ergoplatform.api.AesEncryptionManager import org.ergoplatform.api.AndroidEncryptionManager import org.ergoplatform.deserializeSecrets import org.ergoplatform.persistance.Wallet import org.ergoplatform.persistance.WalletAddress import org.ergoplatform.uilogic.wallet.addresses.WalletAddressesUiLogic class WalletAddressesViewModel : ViewModel() { val uiLogic = AndroidWalletAddressesUiLogic() var numAddressesToAdd: Int = 1 val wallet: Wallet? get() = uiLogic.wallet private val _addresses = MutableLiveData<List<WalletAddress>>() val addresses: LiveData<List<WalletAddress>> = _addresses private val _lockProgress = MutableLiveData<Boolean>() val lockProgress: LiveData<Boolean> = _lockProgress fun init(ctx: Context, walletId: Int) { uiLogic.init(RoomWalletDbProvider(AppDatabase.getInstance(ctx)), walletId) } fun addNextAddresses(ctx: Context, mnemonic: String?) { uiLogic.addNextAddresses( RoomWalletDbProvider(AppDatabase.getInstance(ctx)), Preferences(ctx), numAddressesToAdd, mnemonic ) } fun addAddressWithBiometricAuth(ctx: Context) { wallet?.walletConfig?.secretStorage?.let { val decryptData = AndroidEncryptionManager.decryptDataWithDeviceKey(it) deserializeSecrets(String(decryptData!!))?.let { mnemonic -> addNextAddresses(ctx, mnemonic) } } } fun addAddressWithPass(ctx: Context, password: String): Boolean { wallet?.walletConfig?.secretStorage?.let { try { val decryptData = AesEncryptionManager.decryptData(password, it) deserializeSecrets(String(decryptData!!))?.let { mnemonic -> addNextAddresses(ctx, mnemonic) return true } } catch (t: Throwable) { // Password wrong } } return false } inner class AndroidWalletAddressesUiLogic : WalletAddressesUiLogic() { override val coroutineScope: CoroutineScope get() = viewModelScope override fun notifyNewAddresses() { _addresses.postValue(addresses) } override fun notifyUiLocked(locked: Boolean) { _lockProgress.postValue(locked) } } }
21
null
21
58
810bcb3c9cad0cf6c28b405ec001ef6a0466ec62
2,766
ergo-wallet-android
Apache License 2.0
kmdc/kmdc-select/src/jsMain/kotlin/anchor/Anchor.kt
mpetuska
430,798,310
false
null
package dev.petuska.kmdc.select.anchor import androidx.compose.runtime.Composable import dev.petuska.kmdc.core.* import dev.petuska.kmdc.floating.label.MDCFloatingLabelLayout import dev.petuska.kmdc.line.ripple.MDCLineRippleLayout import dev.petuska.kmdc.notched.outline.Leading import dev.petuska.kmdc.notched.outline.MDCNotchedOutlineLayout import dev.petuska.kmdc.notched.outline.Notch import dev.petuska.kmdc.notched.outline.Trailing import dev.petuska.kmdc.select.* import org.jetbrains.compose.web.dom.* import org.w3c.dom.HTMLDivElement import org.w3c.dom.HTMLElement public interface MDCSelectAnchorScope : ElementScope<HTMLDivElement> /** * [JS API](https://github.com/material-components/material-components-web/tree/v14.0.0/packages/mdc-select) */ @MDCContentDsl @Composable public fun MDCSelectScope.Anchor( label: String, attrs: MDCAttrsRaw<HTMLDivElement>? = null, leadingIcon: MDCContent<MDCSelectAnchorScope>? = null, ) { val id = rememberUniqueDomElementId("anchor") val labelId = "$id-label" val selectedId = "$id-selected-text" val type = MDCSelectTypeLocal.current val helperTextId = MDCSelectHelperTextIdLocal.current Div( attrs = { classes("mdc-select__anchor") role("button") aria("haspopup", "listbox") aria("labelledby", "$labelId $selectedId") if (helperTextId != null) { aria("controls", helperTextId) aria("describedby", helperTextId) } applyAttrs(attrs) } ) { val floatingLabel = @Composable { MDCFloatingLabelLayout(id = labelId) { Text(label) } } when (type) { MDCSelectType.Filled -> { Span(attrs = { classes("mdc-select__ripple") }) floatingLabel() } MDCSelectType.Outlined -> MDCNotchedOutlineLayout { Leading() Notch { floatingLabel() } Trailing() } } applyContent(leadingIcon) Span(attrs = { classes("mdc-select__selected-text-container") }) { Span(attrs = { id(selectedId) classes("mdc-select__selected-text") }) } DownDownIcon() if (type == MDCSelectType.Filled) MDCLineRippleLayout() } } /** * [JS API](https://github.com/material-components/material-components-web/tree/v14.0.0/packages/mdc-select) */ @MDCContentDsl @Composable public fun MDCSelectAnchorScope.LeadingIcon( clickable: Boolean = true, attrs: MDCAttrsRaw<HTMLElement>? = null, content: MDCContentRaw<HTMLElement>? = null, ) { I( attrs = { classes("mdc-select__icon") if (clickable) { tabIndex(0) role("button") } applyAttrs(attrs) }, ) { MDCProvider(::MDCSelectIcon, clickable) { applyContent(content) } } }
9
Kotlin
13
99
c1ba9cf15d091916f1e253c4c37cc9f9c643f5e3
2,718
kmdc
Apache License 2.0
src/main/kotlin/com/github/abslib/asche/service/dispatcher/DispatcherDeclarations.kt
abslib
304,833,714
false
null
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.abslib.asche.service.dispatcher import com.github.abslib.asche.base.concurrent.CoroutinePool import com.github.abslib.asche.base.event.* import com.github.abslib.asche.base.process.ProcessEvent import kotlinx.coroutines.ObsoleteCoroutinesApi import java.lang.reflect.Type interface MailBoxFactory<E : BaseEvent> { fun create(id: Long): MailBox<E> } internal val processMailBoxFactory = ProcessMailBoxFactory() data class TargetEvent<E : BaseEvent>(val targetId: Long, val event: E) : BaseEvent @ObsoleteCoroutinesApi internal val eventBus: EventBus<BaseEvent> = object : EventBus<BaseEvent> by AsyncEventBus(CoroutinePool(1024)) { override fun compareType(event: BaseEvent, eventType: Type): Boolean { return when (event) { is TargetEvent<*> -> event.event::class.java == eventType else -> event::class.java == eventType } } }.also { it.register(object : EventListener<TargetEvent<ProcessEvent>>() { override suspend fun handle(event: TargetEvent<ProcessEvent>) { retrieveProcessMailBox(event.targetId).send(event.event) } }) } @ObsoleteCoroutinesApi suspend fun sendEvent(targetId: Long, event: BaseEvent) { sendEvent(TargetEvent(targetId, event)) } @ObsoleteCoroutinesApi suspend fun sendEvent(event: BaseEvent) { eventBus.send(event) } @ObsoleteCoroutinesApi fun register(listener: EventListener<BaseEvent>) { eventBus.register(listener) } @ObsoleteCoroutinesApi fun unregister(listener: EventListener<BaseEvent>) { eventBus.unregister(listener) } fun retrieveProcessMailBox(id: Long): MailBox<ProcessEvent> { return processMailBoxFactory.create(id) }
0
Kotlin
0
0
ba228993ee3c784ae4ed705759513499692c139e
2,283
asche
Apache License 2.0
app/src/main/java/com/saeed/themovie/ui/base/BaseFragment.kt
SaeidAzimi92
210,120,188
false
null
package com.saeed.themovie.ui.base import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ProgressBar import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import com.saeed.themovie.data.models.ServiceStatus import com.saeed.themovie.ui.main.MainActivity import com.saeed.themovie.ui.main.viewmodels.BaseViewModel import com.saeed.themovie.utils.extensions.hide import com.saeed.themovie.utils.extensions.show import kotlinx.android.synthetic.main.loading.* abstract class BaseFragment : Fragment() { var onViewModel: BaseViewModel? = null abstract fun onLayout(): Int abstract fun initView(view: View) abstract fun getViewModel(): BaseViewModel abstract fun reloadService() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setHasOptionsMenu(true) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { super.onCreateView(inflater, container, savedInstanceState) return inflater.inflate(onLayout(), container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initView(view) getViewModel().onServiceStatus.observe(this, Observer { status -> loading?.let { progress -> when (status) { ServiceStatus.ONLOADING -> onLoadingAction(progress) ServiceStatus.SUCCESS -> onSuccessAction(progress) ServiceStatus.FAIELD -> onErrorAction(progress) } } }) } private fun onLoadingAction(progress: ProgressBar) { progress.show() errMsg.visibility = View.GONE btnRetry.visibility = View.GONE } private fun onErrorAction(progress: ProgressBar) { progress.hide() btnRetry.setOnClickListener { reloadService() } btnRetry.visibility = View.VISIBLE errMsg.visibility = View.VISIBLE } private fun onSuccessAction(progress: ProgressBar) { progress.hide() errMsg.visibility = View.GONE btnRetry.visibility = View.GONE } inline fun <reified F : BaseFragment> goToFragment( bundle: Bundle? = null ) { (activity as MainActivity).goToFragment<F>(hasAnimation = true, bundle = bundle) } }
0
Kotlin
0
0
2fd9bff848bde9e6aa7fbcedee32c9e41042ab95
2,533
TheMovies
MIT License
app/src/main/java/io/isometrik/sample/chatbot/MyApplication.kt
isometrikai
876,037,691
false
{"Kotlin": 104329, "Java": 6604}
package io.isometrik.sample.chatbot import android.app.Application import io.isometrik.androidchatbot.presentation.AiChatBotSdk class MyApplication : Application() { override fun onCreate() { super.onCreate() AiChatBotSdk.instance?.sdkInitialize(this) AiChatBotSdk.instance?.createConfiguration( getString(R.string.chat_bot_id).toInt(), getString(R.string.app_secret), getString(R.string.license_key), getString(R.string.user_id), getString(R.string.store_category_id), getString(R.string.location), getString(R.string.latitude), getString(R.string.longitude) ) } override fun onTerminate() { super.onTerminate() AiChatBotSdk.instance?.onTerminate() } }
0
Kotlin
0
0
2ca9176e4d898334c20ba6a9c4d7be776aa27777
817
android-ai-chatbot
Freetype Project License
exposed-dao/src/main/kotlin/org/jetbrains/exposed/dao/exceptions/EntityNotFoundException.kt
JetBrains
11,765,017
false
null
package org.jetbrains.exposed.dao.exceptions import org.jetbrains.exposed.dao.EntityClass import org.jetbrains.exposed.dao.id.EntityID class EntityNotFoundException(val id: EntityID<*>, val entity: EntityClass<*, *>) : Exception("Entity ${entity.klass.simpleName}, id=$id not found in the database")
216
null
649
7,770
77f68b9408a39aabaadec2dc0f141881a99a15d3
306
Exposed
Apache License 2.0
app/src/main/java/com/example/vino/ui/home/VineyardMapFragmentViewModel.kt
juanm707
373,001,324
false
null
package com.example.vino.ui.home import android.util.Log import androidx.lifecycle.* import com.example.vino.model.Block import com.example.vino.model.BlockWithCoordinates import com.example.vino.model.Vineyard import com.example.vino.network.VinoApiStatus import com.example.vino.repository.VinoRepository import kotlinx.coroutines.* class VineyardMapFragmentViewModel(private val repository: VinoRepository) : ViewModel() { private val _status = MutableLiveData<VinoApiStatus>() private val _vineyard = MutableLiveData<Vineyard>() private val _blocks = MutableLiveData<List<BlockWithCoordinates>>() val apiStatus: LiveData<VinoApiStatus> = _status val vineyard: LiveData<Vineyard> = _vineyard val blocks: LiveData<List<BlockWithCoordinates>> = _blocks fun setVineyard(vineyardId: Int) { viewModelScope.launch { _vineyard.value = repository.getVineyard(vineyardId) } } fun refreshBlocks(vineyardId: Int) { getDataLoad { repository.refreshBlocks() val unsortedCoordinateBlocks = repository.getBlocksForVineyardId(vineyardId) withContext(Dispatchers.Default) { unsortedCoordinateBlocks.forEach { block -> val sortedCoordinates = block.coordinates.sortedBy { coordinate -> coordinate.coordinateId } block.coordinates = sortedCoordinates } } _blocks.value = unsortedCoordinateBlocks } } private fun getDataLoad(getData: suspend () -> Unit): Job { return viewModelScope.launch { _status.value = VinoApiStatus.LOADING try { //delay(5000) // for slow connection getData() _status.value = VinoApiStatus.DONE } catch (e: Exception) { Log.d("NetworkError", "$e handled!") _status.value = VinoApiStatus.ERROR } } } fun getBlockForName(name: String?): Block? { return if (name == null) null else { _blocks.value?.find { parentBlock -> parentBlock.block.name == name }?.block } } } class VineyardMapFragmentViewModelFactory(private val repository: VinoRepository) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if (modelClass.isAssignableFrom(VineyardMapFragmentViewModel::class.java)) { @Suppress("UNCHECKED_CAST") return VineyardMapFragmentViewModel(repository) as T } throw IllegalArgumentException("Unknown ViewModel class") } }
0
null
0
1
58774aea692460513de9eda6c99a77e2416d5a7d
2,709
Vino
MIT License
Kotlin/P36.kt
deveshp007
535,653,594
false
{"Kotlin": 84827}
package alpha.dex.one import android.app.AlarmManager import android.app.PendingIntent import android.app.job.JobInfo import android.app.job.JobParameters import android.app.job.JobScheduler import android.app.job.JobService import android.content.ComponentName import android.content.Intent import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Button import android.widget.Toast class JobSchedulerEx : AppCompatActivity() { var jobScheduler: JobScheduler? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_job_scheduler_ex) val stopJob = findViewById<Button>(R.id.stopJob) val startJob = findViewById<Button>(R.id.startJob) startJob.setOnClickListener { jobScheduler = getSystemService(JOB_SCHEDULER_SERVICE) as JobScheduler val componentName = ComponentName(this, MyJobService::class.java) val builder = JobInfo.Builder(123, componentName) builder.setMinimumLatency(8000) builder.setOverrideDeadline(10000) builder.setPersisted(true) builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY) builder.setRequiresCharging(false) jobScheduler!!.schedule(builder.build()) } stopJob.setOnClickListener { if (jobScheduler != null) { jobScheduler!!.cancel(123) jobScheduler = null Toast.makeText(this, "Job Cancelled", Toast.LENGTH_SHORT).show() } } } } class MyJobService : JobService() { override fun onStartJob(p0: JobParameters?): Boolean { Log.d("TAG", "onStartJob:") val intent = Intent(this@MyJobService, AlarmManagerBroadcast::class.java) val pendingIntent = PendingIntent.getBroadcast(this@MyJobService, 234, intent, 0) val alarmManager = getSystemService(ALARM_SERVICE) as AlarmManager alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), pendingIntent) Toast.makeText(this@MyJobService, "Alarm Set ", Toast.LENGTH_LONG).show() return true } override fun onStopJob(p0: JobParameters?): Boolean { Log.d("TAG", "onStopJob:") return true } }
0
Kotlin
6
24
a5d62d97081826a35308defd9641bb9552f5e789
2,358
Android-App-Development
MIT License
lib/src/main/java/com/nuclominus/diffadapter/helpers/viewholders/LoadingViewHolder.kt
Nuclominus
481,985,568
false
{"Kotlin": 24354}
package com.nuclominus.diffadapter.helpers.viewholders import androidx.viewbinding.ViewBinding import com.nuclominus.diffadapter.base.BaseViewHolder import com.nuclominus.diffadapter.base.IModel import com.nuclominus.diffadapter.base.ListObserver import com.nuclominus.diffadapter.helpers.AdapterConstants import com.nuclominus.diffadapter.selectable.BaseSelectableViewHolder /** * Base loading view holder implementation */ class LoadingViewHolder<TView : ViewBinding, TModel: IModel>(binding: TView) : BaseViewHolder<TModel>(binding) class LoadingSelectableViewHolder<TView : ViewBinding, TModel : IModel>(binding: TView) : BaseSelectableViewHolder<TModel, String>(binding, object : ListObserver<TModel>() {}) { override fun resolveKey(model: TModel): String? { return AdapterConstants.BaseSelectableKey.BASE_LOADING_ITEM_KEY } }
0
Kotlin
0
2
51c7924d686b8c669911c9b80c538c320080a123
860
recyclerDiffAdapter
Apache License 2.0
src/commonMain/kotlin/lexer/Parser.kt
waterstopper
452,776,841
false
{"Kotlin": 301038, "JavaScript": 239}
package lexer import token.Token import token.TokenBlock /** * Parses created tokens into AST * * Changes with Go implementation: * 1. [advance] changed * 2. [block] supports one statement block without braces */ class Parser(text: String, val filePath: String) { var lexer: Lexer init { lexer = Lexer(text, filePath) } fun expression(rbp: Int): Token { var t = lexer.next() var left = t.nud?.let { it(t, this) } ?: throw PositionalException( "Expected variable or prefix operator", position = t.position, length = t.value.length, fileName = filePath ) while (rbp < lexer.peek().bindingPower) { t = lexer.next() left = t.led?.let { it(t, this, left) } ?: throw PositionalException( "Expected infix or suffix operator", position = t.position, length = t.value.length, fileName = filePath ) } return left } fun advance(symbol: String): Token { val token = lexer.next() if (token.symbol == symbol) { return token } throw PositionalException( "Expected $symbol", position = token.position, length = token.symbol.length, fileName = filePath ) } fun advanceSeparator() { lexer.moveAfterSeparator() } fun statements(): List<Token> { val statements = mutableListOf<Token>() var next = lexer.peek() while (next.symbol != "(EOF)" && next.symbol != "}") { statements.add(statement()) next = lexer.peek() } return statements.filter { it.symbol != "(SEP)" } } fun statement(): Token { if (lexer.peek().symbol == "(SEP)") { return lexer.next() } var token = lexer.peek() if (token.std != null) { token = lexer.next() return token.std?.let { it(token, this) } ?: throw PositionalException( "Expected statement", position = token.position, length = token.value.length, fileName = filePath ) } token = expression(0) val peeked = lexer.peek() if (peeked.symbol != "}") { advanceSeparator() } return token } fun block(canBeSingleStatement: Boolean = false): Token { val token = lexer.next() if (token.symbol != "{") { if (canBeSingleStatement) { lexer.prev() val res = TokenBlock(Pair(token.position.first - 1, token.position.second)) res.children.add(statement()) if (res.children.first().symbol == "(SEP)") { res.children.clear() } return res } throw PositionalException( "Expected a block start '{'", position = token.position, length = token.value.length, fileName = filePath ) } return token.std?.let { it(token, this) } ?: throw PositionalException( "Expected statement", position = token.position, length = token.value.length, fileName = filePath ) } }
8
Kotlin
1
3
6ad6ea19c3a79b19c3f747a40a12d64c159997f1
3,512
Regina
MIT License
extension/core/src/main/kotlin/io/holunda/camunda/bpm/correlate/correlation/metadata/extractor/HeaderMessageMetaDataSnippetExtractor.kt
holunda-io
450,565,449
false
null
package io.holunda.camunda.bpm.correlate.correlation.metadata.extractor import io.holunda.camunda.bpm.correlate.correlation.metadata.MessageMetaDataSnippet import io.holunda.camunda.bpm.correlate.correlation.metadata.MessageMetaDataSnippetExtractor import io.holunda.camunda.bpm.correlate.correlation.metadata.TypeInfo import io.holunda.camunda.bpm.correlate.correlation.metadata.extractor.HeaderMessageMetaDataSnippetExtractor.HeaderNames.EXPIRATION import io.holunda.camunda.bpm.correlate.correlation.metadata.extractor.HeaderMessageMetaDataSnippetExtractor.HeaderNames.ID import io.holunda.camunda.bpm.correlate.correlation.metadata.extractor.HeaderMessageMetaDataSnippetExtractor.HeaderNames.PAYLOAD_ENCODING import io.holunda.camunda.bpm.correlate.correlation.metadata.extractor.HeaderMessageMetaDataSnippetExtractor.HeaderNames.PAYLOAD_TYPE_CLASS_NAME import io.holunda.camunda.bpm.correlate.correlation.metadata.extractor.HeaderMessageMetaDataSnippetExtractor.HeaderNames.PAYLOAD_TYPE_NAME import io.holunda.camunda.bpm.correlate.correlation.metadata.extractor.HeaderMessageMetaDataSnippetExtractor.HeaderNames.PAYLOAD_TYPE_NAMESPACE import io.holunda.camunda.bpm.correlate.correlation.metadata.extractor.HeaderMessageMetaDataSnippetExtractor.HeaderNames.PAYLOAD_TYPE_REVISION import io.holunda.camunda.bpm.correlate.correlation.metadata.extractor.HeaderMessageMetaDataSnippetExtractor.HeaderNames.TIMESTAMP import io.holunda.camunda.bpm.correlate.correlation.metadata.extractor.HeaderMessageMetaDataSnippetExtractor.HeaderNames.TTL import io.holunda.camunda.bpm.correlate.ingress.message.ChannelMessage import io.holunda.camunda.bpm.data.CamundaBpmData.reader import io.holunda.camunda.bpm.data.CamundaBpmData.stringVariable import org.camunda.bpm.engine.variable.Variables.createVariables import java.time.Instant import java.time.format.DateTimeParseException /** * Implementation of a metadata extractor from message headers. */ open class HeaderMessageMetaDataSnippetExtractor( private val enforceMessageId: Boolean, private val enforceTypeInfo: Boolean ) : MessageMetaDataSnippetExtractor { /** * Names of the message headers. */ object HeaderNames { /** * Header for the full-qualified class name of the payload type. */ const val PAYLOAD_TYPE_CLASS_NAME = "X-CORRELATE-PayloadType-FQCN" /** * Header for the namespace of the payload type. */ const val PAYLOAD_TYPE_NAMESPACE = "X-CORRELATE-PayloadType-Namespace" /** * Header for the name of the payload type. */ const val PAYLOAD_TYPE_NAME = "X-CORRELATE-PayloadType-Name" /** * Header for the revision of the payload type. */ const val PAYLOAD_TYPE_REVISION = "X-CORRELATE-PayloadType-Revision" /** * Header for the payload encoding. */ const val PAYLOAD_ENCODING = "X-CORRELATE-Payload-Encoding" /** * Header for the message time-to-live. */ const val TTL = "X-CORRELATE-TTL" /** * Header for the message expiration. */ const val EXPIRATION = "X-CORRELATE-Expiration" /** * Header for the message id. */ const val ID = "X-CORRELATE-ID" /** * Header for the message timestamp. */ const val TIMESTAMP = "X-CORRELATE-Timestamp" } companion object { val HEADER_MESSAGE_PAYLOAD_TYPE_CLASS_NAME = stringVariable(PAYLOAD_TYPE_CLASS_NAME) val HEADER_MESSAGE_PAYLOAD_TYPE_NAMESPACE = stringVariable(PAYLOAD_TYPE_NAMESPACE) val HEADER_MESSAGE_PAYLOAD_TYPE_NAME = stringVariable(PAYLOAD_TYPE_NAME) val HEADER_MESSAGE_PAYLOAD_TYPE_REVISION = stringVariable(PAYLOAD_TYPE_REVISION) val HEADER_MESSAGE_PAYLOAD_ENCODING = stringVariable(PAYLOAD_ENCODING) val HEADER_MESSAGE_TTL = stringVariable(TTL) val HEADER_MESSAGE_EXPIRATION = stringVariable(EXPIRATION) val HEADER_MESSAGE_ID = stringVariable(ID) val HEADER_MESSAGE_TIMESTAMP = stringVariable(TIMESTAMP) } override fun <P> extractMetaData(message: ChannelMessage<P>): MessageMetaDataSnippet? { val snippet = readMetaDataSnippet(message.headers) return if (snippet.isEmpty()) { null } else { snippet } } override fun supports(headers: Map<String, Any>): Boolean { val snippet = readMetaDataSnippet(headers) val messageIdCheck = if (enforceMessageId) { snippet.messageId != null } else { true } val typeCheck = if (enforceTypeInfo) { snippet.payloadTypeInfo != TypeInfo.UNKNOWN } else { true } return messageIdCheck && typeCheck } private fun readMetaDataSnippet(headers: Map<String, Any>): MessageMetaDataSnippet { val reader = reader(createVariables().apply { this.putAll(headers) }) return MessageMetaDataSnippet( messageId = reader.getOrNull(HEADER_MESSAGE_ID), payloadTypeInfo = extractTypeInfo(headers), payloadEncoding = reader.getOrNull(HEADER_MESSAGE_PAYLOAD_ENCODING), timeToLive = reader.getOrNull(HEADER_MESSAGE_TTL), expiration = extractInstant(reader.getOrNull(HEADER_MESSAGE_EXPIRATION)), messageTimestamp = extractInstant(reader.getOrNull(HEADER_MESSAGE_TIMESTAMP)) ) } private fun extractInstant(value: String?): Instant? { return if (value != null) { try { Instant.parse(value) } catch (e: DateTimeParseException) { null } } else { null } } private fun extractTypeInfo(headers: Map<String, Any>): TypeInfo { val reader = reader(createVariables().apply { this.putAll(headers) }) val fullQualifiedClassName = reader.getOrNull(HEADER_MESSAGE_PAYLOAD_TYPE_CLASS_NAME) return if (fullQualifiedClassName != null) { // got a class name TypeInfo.fromFQCN(fullQualifiedClassName) } else { // try from coordinates val namespace = reader.getOrNull(HEADER_MESSAGE_PAYLOAD_TYPE_NAMESPACE) val name = reader.getOrNull(HEADER_MESSAGE_PAYLOAD_TYPE_NAME) val revision = reader.getOrNull(HEADER_MESSAGE_PAYLOAD_TYPE_REVISION) TypeInfo.from(namespace = namespace, name = name, revision = revision) } } }
4
Kotlin
1
9
2c48ef15b91fde72e47aae9221f60c59927a9f61
6,111
camunda-bpm-correlate
Apache License 2.0
src/main/kotlin/io/c6/justmoveitkotlin/IntervalRunner.kt
chandu-io
129,123,786
false
null
package io.c6.justmoveitkotlin internal interface IntervalRunner { fun isDone(): Boolean fun stop() }
0
Kotlin
0
0
2de7bf8cfe38c6f1368d569c7d411e1cfea25436
107
just-move-it-kotlin
The Unlicense
app/src/main/java/io/agora/flat/http/model/CloudListFilesResp.kt
netless-io
358,147,122
false
{"Kotlin": 1090689, "Shell": 2529, "HTML": 452}
package io.agora.flat.http.model import io.agora.flat.data.model.CloudFile data class CloudListFilesResp constructor( val totalUsage: Long, val files: List<CloudFile>, val canCreateDirectory: Boolean, )
0
Kotlin
60
99
989efad4ad2b05d8c106c9eb66a068c30127e35c
218
flat-android
MIT License
lib/src/integrationTest/kotlin/com/lemonappdev/konsist/core/declaration/koclass/forkomodifier/KoClassDeclarationForKoSealedModifierProviderTest.kt
LemonAppDev
621,181,534
false
null
package com.lemonappdev.konsist.core.declaration.koclass.forkomodifier import com.lemonappdev.konsist.TestSnippetProvider.getSnippetKoScope import org.amshove.kluent.shouldBeEqualTo import org.junit.jupiter.api.Test class KoClassDeclarationForKoSealedModifierProviderTest { @Test fun `class-without-sealed-modifier`() { // given val sut = getSnippetFile("class-without-sealed-modifier") .classes() .first() // then sut.hasSealedModifier shouldBeEqualTo false } @Test fun `sealed-class`() { // given val sut = getSnippetFile("sealed-class") .classes() .first() // then sut.hasSealedModifier shouldBeEqualTo true } private fun getSnippetFile(fileName: String) = getSnippetKoScope("core/declaration/koclass/forkomodifier/snippet/forkosealedmodifierprovider/", fileName) }
5
null
26
995
603d19e179f59445c5f4707c1528a438e4595136
923
konsist
Apache License 2.0
src/main/kotlin/com/kuvaszuptime/kuvasz/factories/EmailFactory.kt
bkovari
290,007,789
true
{"Kotlin": 169166, "TSQL": 2370, "Shell": 766, "Dockerfile": 523}
package com.kuvaszuptime.kuvasz.factories import com.kuvaszuptime.kuvasz.config.handlers.EmailEventHandlerConfig import com.kuvaszuptime.kuvasz.models.MonitorDownEvent import com.kuvaszuptime.kuvasz.models.MonitorUpEvent import com.kuvaszuptime.kuvasz.models.UptimeMonitorEvent import com.kuvaszuptime.kuvasz.models.toEmoji import com.kuvaszuptime.kuvasz.models.toStructuredMessage import com.kuvaszuptime.kuvasz.models.toUptimeStatus import org.simplejavamail.api.email.Email import org.simplejavamail.email.EmailBuilder class EmailFactory(private val config: EmailEventHandlerConfig) { fun fromUptimeMonitorEvent(event: UptimeMonitorEvent): Email = createEmailBase() .withSubject(event.getSubject()) .withPlainText(event.toMessage()) .buildEmail() private fun UptimeMonitorEvent.getSubject(): String = "[kuvasz-uptime] - ${toEmoji()} [${monitor.name}] ${monitor.url} is ${toUptimeStatus()}" private fun createEmailBase() = EmailBuilder .startingBlank() .to(config.to, config.to) .from(config.from, config.from) private fun UptimeMonitorEvent.toMessage() = when (this) { is MonitorUpEvent -> toStructuredMessage().let { details -> listOfNotNull( details.summary, details.latency, details.previousDownTime.orNull() ) } is MonitorDownEvent -> toStructuredMessage().let { details -> listOfNotNull( details.summary, details.error, details.previousUpTime.orNull() ) } }.joinToString("\n") }
0
null
0
0
ba093a4f52d79589c1cb952b16e7bcd88ed6079b
1,753
kuvasz
Apache License 2.0
androidApp/src/main/java/com/vickikbt/gistagram/ui/screens/auth/AuthViewModel.kt
VictorKabata
451,854,817
false
{"Kotlin": 211021, "Swift": 19405, "Ruby": 2077}
package com.vickikbt.gistagram.ui.screens.auth import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.vickikbt.shared.domain.models.User import com.vickikbt.shared.domain.repositories.AuthRepository import com.vickikbt.shared.presentation.UiState import io.github.aakira.napier.Napier import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch class AuthViewModel constructor(private val authRepository: AuthRepository) : ViewModel() { private val _userUiState = MutableStateFlow<UiState<User?>?>(null) val userUiState = _userUiState.asStateFlow() fun fetchAccessToken(code: String) { _userUiState.value = UiState.Loading() viewModelScope.launch { try { val response = authRepository.fetchAccessToken(code = code) Napier.e("Fetched access token: $response") Napier.e("Code: $code") fetchUserProfile() } catch (e: Exception) { _userUiState.value = UiState.Error(error = e.localizedMessage) } } } private fun fetchUserProfile() { _userUiState.value = UiState.Loading() viewModelScope.launch { try { val response = authRepository.fetchUserProfile() Napier.e("User fetched: $response") _userUiState.value = UiState.Success(data = response) } catch (e: Exception) { _userUiState.value = UiState.Error(error = e.localizedMessage) } } } }
1
Kotlin
4
39
c076838dd5daab9025041025fbeb5e151fd68e10
1,626
Gistagram
MIT License
domain/src/main/java/com/omni/domain/usecases/SearchUseCase.kt
OmneyaOsman
427,134,864
false
{"Kotlin": 73257}
package com.omni.domain.usecases import com.omni.domain.repository.LocalDatabaseRepository class SearchUseCase(private val localDatabaseRepository: LocalDatabaseRepository) { suspend operator fun invoke(query: String) = localDatabaseRepository.searchGames(query) }
0
Kotlin
2
3
01386277280da5c5c35c6a74bccc8318ff14cc9b
270
RAWGGames
Apache License 2.0
app/src/main/java/com/imcys/bilibilias/base/BaseActivity.kt
1250422131
280,332,208
false
{"Kotlin": 630637, "HTML": 81353, "Java": 67569}
package com.imcys.bilibilias.base import android.content.SharedPreferences import android.os.Bundle import androidx.preference.PreferenceManager import com.imcys.bilibilias.common.base.AbsActivity import dagger.hilt.android.AndroidEntryPoint open class BaseActivity : AbsActivity() { override val asSharedPreferences: SharedPreferences by lazy { PreferenceManager.getDefaultSharedPreferences(applicationContext) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // 沉浸式状态栏 statusBarOnly(this) } }
3
Kotlin
51
818
3e75157e4bda72061688b793bfb796e999504543
588
bilibilias
Apache License 2.0
app/src/main/java/com/duckduckgo/app/global/model/SiteFactoryImpl.kt
hojat72elect
822,396,044
false
{"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
package com.duckduckgo.app.global.model import android.util.LruCache import androidx.annotation.AnyThread import androidx.annotation.WorkerThread import com.duckduckgo.app.brokensite.RealBrokenSiteContext import com.duckduckgo.app.browser.DuckDuckGoUrlDetector import com.duckduckgo.app.browser.certificates.BypassedSSLCertificatesRepository import com.duckduckgo.app.di.AppCoroutineScope import com.duckduckgo.app.privacy.db.UserAllowListRepository import com.duckduckgo.app.trackerdetection.EntityLookup import com.duckduckgo.common.utils.DispatcherProvider import com.duckduckgo.di.scopes.AppScope import com.duckduckgo.privacy.config.api.ContentBlocking import com.squareup.anvil.annotations.ContributesBinding import dagger.SingleInstanceIn import javax.inject.Inject import kotlinx.coroutines.CoroutineScope @ContributesBinding(AppScope::class) @SingleInstanceIn(AppScope::class) class SiteFactoryImpl @Inject constructor( private val entityLookup: EntityLookup, private val contentBlocking: ContentBlocking, private val userAllowListRepository: UserAllowListRepository, private val bypassedSSLCertificatesRepository: BypassedSSLCertificatesRepository, @AppCoroutineScope private val appCoroutineScope: CoroutineScope, private val dispatcherProvider: DispatcherProvider, private val duckDuckGoUrlDetector: DuckDuckGoUrlDetector, ) : SiteFactory { private val siteCache = LruCache<String, Site>(1) /** * Builds a Site with minimal details; this is quick to build but won't contain the full details needed for all functionality * * @see [loadFullSiteDetails] to ensure full privacy details are loaded */ @AnyThread override fun buildSite( url: String, tabId: String, title: String?, httpUpgraded: Boolean, externalLaunch: Boolean, ): Site { val cacheKey = "$tabId|$url" val cachedSite = siteCache.get(cacheKey) return if (cachedSite == null) { SiteMonitor( url, title, httpUpgraded, externalLaunch, userAllowListRepository, contentBlocking, bypassedSSLCertificatesRepository, appCoroutineScope, dispatcherProvider, RealBrokenSiteContext(duckDuckGoUrlDetector), ).also { siteCache.put(cacheKey, it) } } else { cachedSite.upgradedHttps = httpUpgraded cachedSite.title = title cachedSite } } /** * Updates the given Site with the full details * * This can be expensive to execute. */ @WorkerThread override fun loadFullSiteDetails(site: Site) { val memberNetwork = entityLookup.entityForUrl(site.url) val siteDetails = SitePrivacyData(site.url, memberNetwork, memberNetwork?.prevalence ?: 0.0) site.updatePrivacyData(siteDetails) } }
0
Kotlin
0
0
b89591136b60933d6a03fac43a38ee183116b7f8
3,003
DuckDuckGo
Apache License 2.0
app/src/main/java/com/knowlgraph/speechtotextsimple/MainActivity.kt
excing
493,908,795
false
{"Kotlin": 31039, "Java": 10575}
package com.knowlgraph.speechtotextsimple import android.Manifest import android.annotation.SuppressLint import android.content.Intent import android.content.pm.PackageManager import android.media.AudioFormat import android.media.AudioRecord import android.media.MediaRecorder import android.net.Uri import android.os.Bundle import android.os.Handler import android.os.HandlerThread import android.util.Log import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Button import android.widget.Switch import android.widget.TextView import android.widget.ToggleButton import androidx.activity.result.contract.ActivityResultContracts.GetContent import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.os.HandlerCompat import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.google.android.material.snackbar.Snackbar import com.knowlgraph.speechtotextsimple.entity.RecognizeResultViewData import org.tensorflow.lite.DataType import org.tensorflow.lite.support.common.SupportPreconditions import org.tensorflow.lite.task.audio.classifier.AudioClassifier import org.vosk.Model import java.io.File import java.lang.Runnable as Runnable1 // 前进、后退、快来、快走、上下、左右、播放、暂停、快进、停止、工作、下一个、上一个、继续。 class MainActivity : AppCompatActivity(), RecognizeService.OnRecognizeResultListener, OncePlayerService.OnPlayStateListener { private lateinit var handler: Handler // background thread handler to run classification private var audioClassifier: AudioClassifier? = null private var audioRecord: AudioRecord? = null private var classificationInterval = 500L // how often should classification run in milli-secs private var voskModel: Model? = null private var recognizeService: RecognizeService? = null private var oncePlayerService = OncePlayerService(this) private lateinit var resultRecyclerView: RecyclerView private val recognizeResults = ArrayList<RecognizeResultViewData>() private lateinit var audioRecognizeToggleButton: ToggleButton override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val getContent = registerForActivityResult(GetContent()) { uri: Uri? -> // Handle the returned Uri Log.i(TAG, "openVoskModel: $uri") if (uri == null) { Snackbar.make(findViewById(R.id.container), "请选择一个模型", Snackbar.LENGTH_LONG).show() } else { loadVoskModel(uri) } } resultRecyclerView = findViewById(R.id.resultRecyclerView) resultRecyclerView.layoutManager = LinearLayoutManager(this) resultRecyclerView.adapter = resultRecyclerAdapter findViewById<Button>(R.id.openVoskModel).setOnClickListener { stopAudioClassification() getContent.launch("application/zip") } audioRecognizeToggleButton = findViewById(R.id.audioRecognize) audioRecognizeToggleButton.setOnCheckedChangeListener { _, isChecked -> if (isChecked) tryStartAudioClassification() else stopAudioClassification() } findViewById<Button>(R.id.playRecognizeAudio).setOnClickListener { downloadVoskModel() } // Create a handler to run classification in a background thread val handlerThread = HandlerThread("backgroundThread") handlerThread.start() handler = HandlerCompat.createAsync(handlerThread.looper) val cacheRecord = File(cacheDir, "record") deleteRecordCache(cacheRecord) } private val resultRecyclerAdapter = object : RecyclerView.Adapter<SimpleViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): SimpleViewHolder { val itemView = LayoutInflater.from(this@MainActivity) .inflate(R.layout.simple_layout_recognize_result, null) itemView.layoutParams = ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT ) return SimpleViewHolder(itemView) } override fun onBindViewHolder(holder: SimpleViewHolder, position: Int) { val textView: TextView = holder.get(R.id.recognizeResultTextView) val switch: Switch = holder.get(R.id.audioPlayStatusSwitch) val result = recognizeResults[position] textView.text = result.text switch.isEnabled = result.finished switch.isChecked = result.playing switch.text = if (switch.isChecked) "停止" else "播放" switch.setOnClickListener { if (switch.isChecked) { playRecognizeAudio( result.audio, result.startTime, result.entTime ) result.playing = true switch.text = "停止" } else { switch.text = "播放" oncePlayerService.stop() } } } override fun getItemCount(): Int { return recognizeResults.size } } private fun downloadVoskModel() { val intent = Intent() intent.action = Intent.ACTION_VIEW intent.data = Uri.parse("https://alphacephei.com/vosk/models") startActivity(intent) } private fun playRecognizeAudio(url: String, start: Float, end: Float) { if (audioRecognizeToggleButton.isChecked) { audioRecognizeToggleButton.performClick() } oncePlayerService.stop() oncePlayerService.play( url, (start * 1000).toInt(), (end * 1000).toInt() ) } override fun onTopResumedActivityChanged(isTopResumedActivity: Boolean) { // Handles "top" resumed event on multi-window environment if (!audioRecognizeToggleButton.isChecked) { return } if (isTopResumedActivity) tryStartAudioClassification() else stopAudioClassification() } private fun tryStartAudioClassification() { if (ContextCompat.checkSelfPermission( this, Manifest.permission.RECORD_AUDIO ) == PackageManager.PERMISSION_GRANTED ) { startAudioClassification() } else { requestPermissions(arrayOf(Manifest.permission.RECORD_AUDIO), REQUEST_RECORD_AUDIO) } } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray ) { if (requestCode == REQUEST_RECORD_AUDIO) { if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) { Log.i(TAG, "Audio permission granted :)") startAudioClassification() } else { Log.e(TAG, "Audio permission not granted :(") } } super.onRequestPermissionsResult(requestCode, permissions, grantResults) } @SuppressLint("MissingPermission") private fun startAudioClassification() { // 如果 Vosk 模型未加载,则什么都不做。 if (null == voskModel) return // If the audio classifier is initialized and running, do nothing. if (audioClassifier != null) return recognizeResults.clear() recognizeResults.add( RecognizeResultViewData( System.currentTimeMillis(), "(说点什么……)", "", 0f, 0f, finished = false, playing = false ) ) notifyDataSetChanged() val cacheRecord = File(cacheDir, "record") deleteRecordCache(cacheRecord) cacheRecord.mkdirs() // Initialize the audio classifier val classifier = AudioClassifier.createFromFile(this, MODEL_FILE) val audioTensor = classifier.createInputTensorAudio() val recognizer = RecognizeService(voskModel!!, cacheRecord, this) // Initialize the audio recorder val channelConfig: Byte = when (audioTensor.format.channels) { 1 -> 16 2 -> 12 else -> throw IllegalArgumentException( String.format( "Number of channels required by the model is %d. getAudioRecord method only supports 1 or 2 audio channels.", audioTensor.format.channels ) ) } var bufferSizeInBytes = AudioRecord.getMinBufferSize( audioTensor.format.sampleRate, channelConfig.toInt(), AudioFormat.ENCODING_PCM_FLOAT ) val record: AudioRecord if (bufferSizeInBytes != -1 && bufferSizeInBytes != -2) { val bufferSizeMultiplier = 2 val modelRequiredBufferSize = classifier.requiredInputBufferSize.toInt() * DataType.FLOAT32.byteSize() * bufferSizeMultiplier if (bufferSizeInBytes < modelRequiredBufferSize) { bufferSizeInBytes = modelRequiredBufferSize } record = AudioRecord( MediaRecorder.AudioSource.VOICE_RECOGNITION, audioTensor.format.sampleRate, channelConfig.toInt(), AudioFormat.ENCODING_PCM_FLOAT, bufferSizeInBytes ) SupportPreconditions.checkState( record.state == AudioRecord.STATE_INITIALIZED, "AudioRecord failed to initialize" ) } else { throw IllegalStateException( String.format( "AudioRecord.getMinBufferSize failed. Returned: %d", bufferSizeInBytes ) ) } record.startRecording() val audioClassifierBuffer = FloatArray(TF_AUDIO_CLASSIFIER_MINI_AUDIO_LENGTH) val newData = FloatArray(record.channelCount * record.bufferSizeInFrames) // Define the classification runnable val run = object : Runnable1 { override fun run() { val startTime = System.currentTimeMillis() // Load the latest audio sample val nidx = 0 var nread = record.read(newData, nidx, newData.size, AudioRecord.READ_NON_BLOCKING) val startSpeech = isSpeech(newData, nread) > 0 var speeching = startSpeech if (startSpeech) { recognizer.start() } var lastTime = System.currentTimeMillis() while (speeching && nread >= 0 && record.recordingState == AudioRecord.RECORDSTATE_RECORDING) { if (nread > 0) { Log.i(TAG, "startAudioClassification: $nread") recognizer.recognize(newData, nidx, nread) } nread = record.read(newData, 0, newData.size, AudioRecord.READ_NON_BLOCKING) if (System.currentTimeMillis() - lastTime > classificationInterval) { recognizer.copyArray( audioClassifierBuffer, TF_AUDIO_CLASSIFIER_MINI_AUDIO_LENGTH - nread ) System.arraycopy( newData, 0, audioClassifierBuffer, TF_AUDIO_CLASSIFIER_MINI_AUDIO_LENGTH - nread, nread ) speeching = isSpeech( audioClassifierBuffer, TF_AUDIO_CLASSIFIER_MINI_AUDIO_LENGTH ) > 0 if (speeching) { lastTime = System.currentTimeMillis() } } } if (startSpeech) { recognizer.stop() } val finishTime = System.currentTimeMillis() Log.d(TAG, "Latency = ${finishTime - startTime}ms") if (record.recordingState == AudioRecord.RECORDSTATE_RECORDING) { // Rerun the classification after a certain interval handler.postDelayed(this, classificationInterval) } } fun isSpeech(data: FloatArray, bufferLength: Int): Int { if (bufferLength <= 0) return bufferLength audioTensor.load(data, 0, bufferLength) val output = classifier.classify(audioTensor) // Filter out results above a certain threshold, and sort them descendingly val filteredModelOutput = output[0].categories.filter { it.score > MINIMUM_DISPLAY_THRESHOLD }.sortedBy { -it.score } val isSpeeching: Boolean = if (filteredModelOutput.isNotEmpty()) { "Speech" == filteredModelOutput[0].label } else { false } Log.i(TAG, "isSpeech($bufferLength): $filteredModelOutput") return if (isSpeeching) bufferLength else -1 } } // Start the classification process handler.post(run) // Save the instances we just created for use later audioClassifier = classifier audioRecord = record recognizeService = recognizer } private fun deleteRecordCache(cacheRecord: File) { if (!cacheRecord.delete()) { val files = cacheRecord.listFiles() if (files != null) { for (file in files) { if (!file.delete()) { Log.i(TAG, "startAudioClassification: delete ${file.name} failed") } } } } } private fun stopAudioClassification() { handler.removeCallbacksAndMessages(null) if (audioRecord != null) { audioRecord?.release() audioRecord = null } if (audioClassifier != null) { audioClassifier?.close() audioClassifier = null } if (recognizeService != null) { recognizeService?.release() recognizeService = null } } override fun onResult( id: Long, wavePath: String, text: String, startTime: Float, endTime: Float, finished: Boolean ) { // Log.d(TAG, "onResult: $id, $wavePath, $text, $startTime, $endTime, $finished") var ok = false for (item in recognizeResults) { if (item.id == id) { item.audio = wavePath item.text = text item.startTime = startTime item.entTime = endTime item.finished = finished ok = true break } } if (!ok) { recognizeResults.add( RecognizeResultViewData( id, text, wavePath, startTime, endTime, finished, false ) ) } runOnUiThread { notifyDataSetChanged() } } private fun notifyDataSetChanged() { resultRecyclerAdapter.notifyDataSetChanged() resultRecyclerView.scrollToPosition(resultRecyclerAdapter.itemCount - 1) } override fun onPlayState(playing: Boolean) { Log.d(TAG, "onPlayState: $playing") if (!playing) { for (result in recognizeResults) { if (result.playing) { result.playing = false } } runOnUiThread { resultRecyclerAdapter.notifyDataSetChanged() } } } private fun loadVoskModel(uri: Uri) { ModelService.unpack(this, uri, { _model -> voskModel = _model runOnUiThread { notifyDataSetChanged() audioRecognizeToggleButton.isEnabled = true } }, { s -> recognizeResults.add( RecognizeResultViewData( System.currentTimeMillis(), "($s)", "", 0f, 0f, finished = false, playing = false ) ) runOnUiThread { notifyDataSetChanged() } }) } companion object { const val REQUEST_RECORD_AUDIO = 1337 private const val TAG = "MainActivity" private const val MODEL_FILE = "yamnet.tflite" private const val MINIMUM_DISPLAY_THRESHOLD: Float = 0.3f private const val TF_AUDIO_CLASSIFIER_MINI_AUDIO_LENGTH = 9600 } }
0
Kotlin
3
1
5c2a01e9c85e549937848d7e199ef62bcac50cb1
17,310
AudioRecognizeAndroidDemo
MIT License
app/src/main/java/ch/admin/foitt/pilotwallet/platform/scaffold/presentation/ScreenViewModel.kt
e-id-admin
775,912,525
false
{"Kotlin": 1521284}
package ch.admin.foitt.pilotwallet.platform.scaffold.presentation import android.graphics.Color import androidx.activity.SystemBarStyle import androidx.compose.ui.graphics.toArgb import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import ch.admin.foitt.pilotwallet.platform.scaffold.domain.model.SystemBarsSetter import ch.admin.foitt.pilotwallet.platform.scaffold.domain.model.TopBarState import ch.admin.foitt.pilotwallet.platform.scaffold.domain.usecase.SetTopBarState import ch.admin.foitt.pilotwallet.theme.DefaultDarkScrim import ch.admin.foitt.pilotwallet.theme.DefaultLightScrim import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.stateIn abstract class ScreenViewModel( private val setTopBarState: SetTopBarState, val addBottomSystemBarPaddings: Boolean = true, ) : ViewModel() { protected abstract val topBarState: TopBarState fun syncScaffoldState(systemBarsSetter: SystemBarsSetter) { setTopBarState(topBarState) syncSystemBars(systemBarsSetter) } private fun syncSystemBars( systemBarsSetter: SystemBarsSetter ) { val topSystemBarStyle = SystemBarStyle.light(Color.TRANSPARENT, DefaultLightScrim.toArgb()) val bottomSystemBarStyle = if (addBottomSystemBarPaddings) { SystemBarStyle.light(Color.TRANSPARENT, Color.TRANSPARENT) } else { SystemBarStyle.dark(DefaultDarkScrim.toArgb()) } systemBarsSetter( statusBarStyle = topSystemBarStyle, navigationBarStyle = bottomSystemBarStyle, ) } protected fun <T> Flow<T>.toStateFlow(initialValue: T) = this.stateIn( viewModelScope, SharingStarted.WhileSubscribed(5000), initialValue, ) }
1
Kotlin
1
4
6572b418ec5abc5d94b18510ffa87a1e433a5c82
1,817
eidch-pilot-android-wallet
MIT License
src/test/kotlin/PrimTest.kt
spbu-coding-2023
800,988,857
false
{"Kotlin": 104827}
import model.algorithms.Prim import model.graph.UndirectedGraph import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.assertEquals import forTests.addVertices class PrimTest { private val undirGraph = UndirectedGraph<Int>() private var primGraph = Prim(undirGraph) @Test fun `construction of MST from a graph consisting of a single vertex must be correct`() { addVertices(undirGraph, 1) assertEquals(0, primGraph.weightPrim()) } @Test fun `construction of MST from 2 components must be correct`() { addVertices(undirGraph, 5) undirGraph.run { addEdge(1 to 2, 23) addEdge(2 to 3, 3) addEdge(1 to 3, 41) addEdge(4 to 5, 12) } assertEquals(38, primGraph.weightPrim()) } @Test fun `construction of MST from tree must be correct`() { //when building a MST from a tree, we need to get the original tree addVertices(undirGraph, 4) undirGraph.run { addEdge(3 to 1, 3) addEdge(3 to 2, 8) addEdge(3 to 4, 21) } assertEquals(32, primGraph.weightPrim()) } @Test fun `construction of MST from graph consisting of edges with equal weight must be correct`() { addVertices(undirGraph, 4) undirGraph.run { addEdge(1 to 2, 20) addEdge(1 to 4, 20) addEdge(3 to 2, 20) addEdge(3 to 4, 20) } assertEquals(60, primGraph.weightPrim()) } @Test fun `construction of MST from non-trivial(more complex) graph must be correct`() { addVertices(undirGraph, 10) undirGraph.run { addEdge(1 to 2, 5) addEdge(2 to 3, 11) addEdge(3 to 4, 25) addEdge(4 to 8, 24) addEdge(1 to 4, 1) addEdge(2 to 5, 42) addEdge(5 to 3, 11) addEdge(5 to 4, 54) addEdge(8 to 9, 73) addEdge(6 to 7, 130) addEdge(7 to 9, 4) addEdge(8 to 7, 9) addEdge(8 to 10, 42) } assertEquals(237, primGraph.weightPrim()) } }
1
Kotlin
1
0
856a9cfd55acbcd37182b5c360a8e4f424264abc
2,200
graphs-graphs-13
MIT License
app/src/main/java/in/technowolf/ipscanner/ui/home/HomeViewModel.kt
daksh7011
461,987,434
false
{"Kotlin": 44318, "Ruby": 956}
package `in`.technowolf.ipscanner.ui.home import `in`.technowolf.ipscanner.data.local.IpDetailsDao import `in`.technowolf.ipscanner.data.remote.IpDetailRS import `in`.technowolf.ipscanner.data.remote.IpScannerService import `in`.technowolf.ipscanner.data.remote.PublicIpService import `in`.technowolf.ipscanner.utils.Extensions.readOnly import `in`.technowolf.ipscanner.utils.safeCall import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.delay import kotlinx.coroutines.launch class HomeViewModel( private val ipScannerService: IpScannerService, private val publicIpService: PublicIpService, private val ipDetailsDao: IpDetailsDao, ) : ViewModel() { private val _ipDetail: MutableLiveData<IpDetailRS?> = MutableLiveData() val ipDetails = _ipDetail.readOnly() private val _errorLiveData: MutableLiveData<String> = MutableLiveData() val errorLiveData = _errorLiveData.readOnly() fun getIpDetails(ipAddress: String = "") { viewModelScope.launch { if (ipAddress.isEmpty()) { safeCall( { val response = publicIpService.getPublicIp() if (response.isSuccessful) { _ipDetail.value = retrieveIpDetails(response.body()?.ip.orEmpty()) } else { _errorLiveData.value = "Could not fetch your public IP." } }, { _errorLiveData.value = it.localizedMessage } ) } else { _ipDetail.value = retrieveIpDetails(ipAddress) } } } private suspend fun retrieveIpDetails(ipAddress: String): IpDetailRS? { return ipDetailsDao.getCachedIpAddress(ipAddress)?.toIpDetailRS() ?: getIpDetailsFromServer(ipAddress) } private suspend fun getIpDetailsFromServer(ipAddress: String): IpDetailRS? { return safeCall( { val response = ipScannerService.getIpDetails(ipAddress) if (response.isSuccessful) { response.body()?.let { delay(250L) ipDetailsDao.saveIpDetails(it.toIpDetailsEntity()) it } } else { _errorLiveData.value = "Could not fetch details. Please try again after a moment." null } }, { _errorLiveData.value = it.localizedMessage } ) } }
0
Kotlin
0
0
48eeae8fbb7f7d237a338f829c40bf6188f8deff
2,725
ip-scanner
MIT License
git-visu-back/src/main/kotlin/org/sixdouglas/git/environment/EnvironmentColor.kt
sixdouglas
255,264,370
false
{"Kotlin": 58539, "Vue": 42738, "JavaScript": 31009, "CSS": 41}
package org.sixdouglas.git.environment /** * Colors and names are picked from here: https://htmlcolorcodes.com/color-chart/flat-design-color-chart/ */ internal object EnvironmentColor { val colors: ArrayList<String> = arrayListOf( "#F9EBEA", "#F2D7D5", "#E6B0AA", "#D98880", "#CD6155", "#C0392B", "#A93226", "#922B21", "#7B241C", "#641E16", // POMEGRANATE "#FDEDEC", "#FADBD8", "#F5B7B1", "#F1948A", "#EC7063", "#E74C3C", "#CB4335", "#B03A2E", "#943126", "#78281F", // ALIZARIN "#F5EEF8", "#EBDEF0", "#D7BDE2", "#C39BD3", "#AF7AC5", "#9B59B6", "#884EA0", "#76448A", "#633974", "#512E5F", // AMETHYST "#F4ECF7", "#E8DAEF", "#D2B4DE", "#BB8FCE", "#A569BD", "#8E44AD", "#7D3C98", "#6C3483", "#5B2C6F", "#4A235A", // WISTERIA "#EAF2F8", "#D4E6F1", "#A9CCE3", "#7FB3D5", "#5499C7", "#2980B9", "#2471A3", "#1F618D", "#1A5276", "#154360", // BELIZE HOLE "#EBF5FB", "#D6EAF8", "#AED6F1", "#85C1E9", "#5DADE2", "#3498DB", "#2E86C1", "#2874A6", "#21618C", "#1B4F72", // PETER RIVER "#E8F8F5", "#D1F2EB", "#A3E4D7", "#76D7C4", "#48C9B0", "#1ABC9C", "#17A589", "#148F77", "#117864", "#0E6251", // TURQUOISE "#E8F6F3", "#D0ECE7", "#A2D9CE", "#73C6B6", "#45B39D", "#16A085", "#138D75", "#117A65", "#0E6655", "#0B5345", // GREEN SEA "#E9F7EF", "#D4EFDF", "#A9DFBF", "#7DCEA0", "#52BE80", "#27AE60", "#229954", "#1E8449", "#196F3D", "#145A32", // NEPHRITIS "#EAFAF1", "#D5F5E3", "#ABEBC6", "#82E0AA", "#58D68D", "#2ECC71", "#28B463", "#239B56", "#1D8348", "#186A3B", // EMERALD "#FEF9E7", "#FCF3CF", "#F9E79F", "#F7DC6F", "#F4D03F", "#F1C40F", "#D4AC0D", "#B7950B", "#9A7D0A", "#7D6608", // SUNFLOWER "#FEF5E7", "#FDEBD0", "#FAD7A0", "#F8C471", "#F5B041", "#F39C12", "#D68910", "#B9770E", "#9C640C", "#7E5109", // ORANGE "#FDF2E9", "#FAE5D3", "#F5CBA7", "#F0B27A", "#EB984E", "#E67E22", "#CA6F1E", "#AF601A", "#935116", "#784212", // CARROT "#FBEEE6", "#F6DDCC", "#EDBB99", "#E59866", "#DC7633", "#D35400", "#BA4A00", "#A04000", "#873600", "#6E2C00", // PUMPKIN "#FDFEFE", "#FBFCFC", "#F7F9F9", "#F4F6F7", "#F0F3F4", "#ECF0F1", "#D0D3D4", "#B3B6B7", "#979A9A", "#7B7D7D", // CLOUDS "#F8F9F9", "#F2F3F4", "#E5E7E9", "#D7DBDD", "#CACFD2", "#BDC3C7", "#A6ACAF", "#909497", "#797D7F", "#626567", // SILVER "#F4F6F6", "#EAEDED", "#D5DBDB", "#BFC9CA", "#AAB7B8", "#95A5A6", "#839192", "#717D7E", "#5F6A6A", "#4D5656", // CONCRETE "#F2F4F4", "#E5E8E8", "#CCD1D1", "#B2BABB", "#99A3A4", "#7F8C8D", "#707B7C", "#616A6B", "#515A5A", "#424949", // ASBESTOS "#EBEDEF", "#D6DBDF", "#AEB6BF", "#85929E", "#5D6D7E", "#34495E", "#2E4053", "#283747", "#212F3C", "#1B2631", // WET ASPHALT "#EAECEE", "#D5D8DC", "#ABB2B9", "#808B96", "#566573", "#2C3E50", "#273746", "#212F3D", "#1C2833", "#17202A" // MIDNIGHT BLUE ) fun randomColor(): String { return colors.shuffled().first() } }
2
Kotlin
0
0
31d4fa327a45a43c22790703ab3fb0dd790878aa
3,016
git-visu
Apache License 2.0
src/test/kotlin/no/nav/amt/deltaker/bff/deltaker/api/utils/InputvalideringTest.kt
navikt
701,285,451
false
{"Kotlin": 312686, "PLpgSQL": 635, "Dockerfile": 173}
package no.nav.amt.deltaker.bff.deltaker.api.utils import io.kotest.assertions.throwables.shouldNotThrow import io.kotest.assertions.throwables.shouldThrow import org.junit.Test class InputvalideringTest { @Test fun testValiderBakgrunnsinformasjon() { val forLang = input(MAX_BAKGRUNNSINFORMASJON_LENGDE + 1) val ok = input(MAX_BAKGRUNNSINFORMASJON_LENGDE - 1) shouldThrow<IllegalArgumentException> { validerBakgrunnsinformasjon(forLang) } shouldNotThrow<IllegalArgumentException> { validerBakgrunnsinformasjon(ok) } } @Test fun testValiderAnnetInnhold() { val forLang = input(MAX_ANNET_INNHOLD_LENGDE + 1) val ok = input(MAX_ANNET_INNHOLD_LENGDE - 1) shouldThrow<IllegalArgumentException> { validerAnnetInnhold(forLang) } shouldNotThrow<IllegalArgumentException> { validerAnnetInnhold(ok) } } @Test fun testValiderAarsaksBeskrivelse() { val forLang = input(MAX_AARSAK_BESKRIVELSE_LENGDE + 1) val ok = input(MAX_AARSAK_BESKRIVELSE_LENGDE - 1) shouldThrow<IllegalArgumentException> { validerAarsaksBeskrivelse(forLang) } shouldNotThrow<IllegalArgumentException> { validerAarsaksBeskrivelse(ok) } } @Test fun testValiderDagerPerUke() { shouldThrow<IllegalArgumentException> { validerDagerPerUke(MIN_DAGER_PER_UKE - 1) } shouldThrow<IllegalArgumentException> { validerDagerPerUke(MAX_DAGER_PER_UKE + 1) } shouldNotThrow<IllegalArgumentException> { validerDagerPerUke(MIN_DAGER_PER_UKE) } shouldNotThrow<IllegalArgumentException> { validerDagerPerUke(MAX_DAGER_PER_UKE) } } @Test fun testValiderDeltakelsesProsent() { shouldThrow<IllegalArgumentException> { validerDeltakelsesProsent(MIN_DELTAKELSESPROSENT - 1) } shouldThrow<IllegalArgumentException> { validerDeltakelsesProsent(MAX_DELTAKELSESPROSENT + 1) } shouldNotThrow<IllegalArgumentException> { validerDeltakelsesProsent(MIN_DELTAKELSESPROSENT) } shouldNotThrow<IllegalArgumentException> { validerDeltakelsesProsent(MAX_DELTAKELSESPROSENT) } } private fun input(n: Int) = (1..n).map { ('a'..'z').random() }.joinToString("") }
2
Kotlin
0
0
fa35df212e49bf7da951fcce27ac57da68023025
2,494
amt-deltaker-bff
MIT License
app/src/main/java/com/xyq/gayweatherkotlin/MainActivity.kt
xiayq1992
139,511,398
false
{"Kotlin": 13910}
package com.xyq.gayweatherkotlin import android.app.Activity import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.preference.PreferenceManager import android.support.v4.content.ContextCompat.startActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val preferences = PreferenceManager.getDefaultSharedPreferences(this) if (preferences.getString("weather", null) != null) { val intent = Intent(this, WeatherActivity::class.java) startActivity(intent) finish() } } }
0
Kotlin
0
0
1577a6e30c88e7b0fad328cbb664d6c946af6ce5
744
GayWeatherKotlin
Apache License 2.0
foodbanks/src/main/java/com/yuriisurzhykov/foodbanks/data/city/cache/CityCache.kt
yuriisurzhykov
524,002,724
false
{"Kotlin": 274520, "Java": 1023}
package com.yuriisurzhykov.foodbanks.data.city.cache import androidx.room.Entity import androidx.room.Index import androidx.room.PrimaryKey @Entity( tableName = "CityCache", indices = [ Index(name = "nameCode", value = ["nameCode"], unique = true), Index(name = "cityId", value = ["cityId"], unique = true) ] ) data class CityCache( @PrimaryKey(autoGenerate = true) val cityId: Long, val name: String, val nameCode: String, val region: String, val country: String )
1
Kotlin
0
2
f9b12ffa6dafe283dc8738e7f0eeb0328f7f547b
519
PointDetector
MIT License
Problems/Algorithms/297. Serialize and Deserialize Binary Tree/SerializeDeserialize.kt
xuedong
189,745,542
false
{"Kotlin": 332182, "Java": 293191, "Python": 233836, "C++": 87863, "Rust": 82753, "Go": 37320, "JavaScript": 12030, "Ruby": 3367, "C": 3121, "C#": 3117, "Swift": 2876, "Scala": 2868, "TypeScript": 2134, "Shell": 149, "Elixir": 130, "Racket": 107, "Erlang": 96, "Dart": 65}
/** * Definition for a binary tree node. * class TreeNode(var `val`: Int) { * var left: TreeNode? = null * var right: TreeNode? = null * } */ class Codec() { // Encodes a URL to a shortened URL. fun serialize(root: TreeNode?): String { if (root == null) return "" var sb = StringBuilder() val queue = mutableListOf<TreeNode?>() queue.add(root) while (queue.size > 0) { val node = queue.removeAt(0) if (node != null) { queue.add(node?.left) queue.add(node?.right) } sb.append(node?.`val`) sb.append(",") } sb.deleteCharAt(sb.length-1) return sb.toString() } // Decodes your encoded data to tree. fun deserialize(data: String): TreeNode? { if (data == null) return null var str = data.split(",") if (str[0].equals("null") || str[0].equals("")) return null var idx = 0 val root: TreeNode? = TreeNode(str[0].toInt()) val queue = ArrayDeque<TreeNode?>() queue.add(root) while (!queue.isEmpty()) { var node = queue.removeFirst() val leftIdx = idx * 2 + 1 val rightIdx = idx * 2 + 2 if (leftIdx < str.size) { val curr = str[leftIdx] if (!curr.equals("null")) { var left: TreeNode? = TreeNode(curr.toInt()) node?.left = left queue.add(left) } } if (rightIdx < str.size) { val curr = str[rightIdx] if (!curr.equals("null")) { var right: TreeNode? = TreeNode(curr.toInt()) node?.right = right queue.add(right) } } idx++ } return root } } /** * Your Codec object will be instantiated and called as such: * var ser = Codec() * var deser = Codec() * var data = ser.serialize(longUrl) * var ans = deser.deserialize(data) */
0
Kotlin
0
1
64e27269784b1a31258677ab03da00f341c2fa98
2,243
leet-code
MIT License
kdoc-access/src/main/kotlin/kdoc/access/rbac/api/dashboard/Rename.kt
perracodex
819,398,266
false
{"Kotlin": 496236, "Dockerfile": 3111, "CSS": 2640, "Java": 1017, "HTML": 487}
/* * Copyright (c) 2024-Present Perracodex. Use of this source code is governed by an MIT license. */ package kdoc.access.rbac.api.dashboard import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.html.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* import io.ktor.server.sessions.* import io.ktor.server.util.* import kdoc.access.rbac.plugin.annotation.RbacAPI import kdoc.access.rbac.service.RbacDashboardManager import kdoc.access.rbac.view.RbacDashboardView import kdoc.access.rbac.view.RbacLoginView import kdoc.base.env.CallContext import kdoc.base.persistence.utils.toUuid import kotlin.uuid.Uuid /** * Processes updates to RBAC settings based on actor submissions from the dashboard form. * Validates [CallContext] and authorizes modifications, redirecting to the login screen if unauthorized. */ @RbacAPI internal fun Route.rbacDashboardUpdateRoute() { /** * Processes updates to RBAC settings based on actor submissions from the dashboard form. * @OpenAPITag RBAC */ post("rbac/dashboard") { // Retrieve the CallContext or redirect to the login screen if it's missing. val callContext: CallContext = RbacDashboardManager.getCallContext(call = call) ?: return@post call.run { call.sessions.clear(name = CallContext.SESSION_NAME) call.respondRedirect(url = RbacLoginView.RBAC_LOGIN_PATH) } // Receive and process form parameters. val parameters: Parameters = call.receiveParameters() val currentRoleId: Uuid = parameters.getOrFail(name = RbacDashboardView.ROLE_KEY).toUuid() // Fetch the role-specific scope rules for the current role, // and update the rules based on the submitted parameters. RbacDashboardManager.processUpdate( callContext = callContext, roleId = currentRoleId, updates = parameters.entries().associate { it.key to it.value.first() } ).let { result -> when (result) { // If the update was successful, render the updated RBAC dashboard. is RbacDashboardManager.UpdateResult.Success -> call.respondHtml(HttpStatusCode.OK) { RbacDashboardView.build( html = this, isUpdated = true, dashboardContext = result.dashboardContext ) } // If the update was unauthorized, clear the session and redirect to the login screen. is RbacDashboardManager.UpdateResult.Unauthorized -> call.run { sessions.clear(name = CallContext.SESSION_NAME) respondRedirect(url = RbacLoginView.RBAC_LOGIN_PATH) } } } } }
0
Kotlin
0
0
3e6d9736222161fb9eaff2dec3c2d0b9396d01f1
2,872
kdoc
MIT License
app/src/test/java/com/hossainkhan/vision/model/VisionPhotosTest.kt
hossain-khan
262,681,367
false
{"Kotlin": 21899}
package com.hossainkhan.vision.model import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.core.IsEqual import org.junit.Before import org.junit.Test class VisionPhotosTest { private val moshi: Moshi = Moshi.Builder().build() private lateinit var sut: VisionPhotos @Before fun setUp() { val readText = VisionPhotosTest::class.java.getResource("/photos.json")!!.readText() val adapter: JsonAdapter<VisionPhotos> = moshi.adapter(VisionPhotos::class.java) sut = adapter.fromJson(readText)!! } @Test fun `given photos json - parses author information`() { assertThat( "Site source mismatch", "https://vision.hossainkhan.com/", IsEqual(sut.source), ) assertThat( "Site author mismatch", "<NAME>", IsEqual(sut.author), ) assertThat( "Site copyright mismatch", "All rights reserved.", IsEqual(sut.copyright), ) } @Test fun `given photos json - parses featured photos`() { assertThat( "Featured photos missing", 20, IsEqual(sut.featuredPhotos.size), ) } @Test fun `given photos json - parses blog photos`() { assertThat( "Featured photos missing", 17, IsEqual(sut.blogPhotos.size), ) } @Test fun `given photos json - parses fourth feature photo metadata`() { val photo = sut.featuredPhotos[3] assertThat( "Title mismatch", "⛰ Mountain Falls", IsEqual(photo.title), ) assertThat( "Sub-title mismatch", "f: 4.5, t: 1/100s, l: 28mm, Sony RX-100", IsEqual(photo.subtitle), ) assertThat( "Date mismatch", "2017-12-28 13:34:11", IsEqual(photo.date), ) assertThat( "Web URL mismatch", "https://vision.hossainkhan.com/project/jamaica-mountain-falls", IsEqual(photo.webUrl), ) assertThat( "Image Source mismatch", "https://vision.hossainkhan.com/images/front-page/DSC_20171228_04001-jamaica-mountain-falls-1600x1100.jpg", IsEqual(photo.imageSource), ) assertThat( "RAW Image Source mismatch", "https://vision.hossainkhan.com/images/front-page/DSC_20171228_04001-jamaica-mountain-falls.jpg", IsEqual(photo.rawSource), ) } @Test fun `given photos json - parses first feature photo metadata`() { val photo = sut.featuredPhotos[0] assertThat( "Title mismatch", "Love ❤ meter", IsEqual(photo.title), ) assertThat( "Sub-title mismatch", "f: 5.6, t: 1/320s, l: 47mm, Canon REBEL XTi", IsEqual(photo.subtitle), ) assertThat( "Date mismatch", "2010-09-05 14:20:56", IsEqual(photo.date), ) assertThat( "Web URL mismatch", "https://vision.hossainkhan.com/project/love-meter", IsEqual(photo.webUrl), ) assertThat( "Image Source mismatch", "https://vision.hossainkhan.com/images/front-page/IMG_20100905_1857-love-meter-montreal-landscape-cropped-1600x1100.jpg", IsEqual(photo.imageSource), ) assertThat( "RAW Image Source mismatch", "https://vision.hossainkhan.com/images/front-page/IMG_20100905_1857-love-meter-montreal-landscape-cropped-1600x1100.jpg", IsEqual(photo.rawSource), ) } @Test fun `given first blog photo - parses metadata`() { val photo = sut.blogPhotos[0] assertThat( "Title mismatch", "Cusco City", IsEqual(photo.title), ) assertThat( "Sub-title mismatch", "", IsEqual(photo.subtitle), ) assertThat( "Date mismatch", "2020-01-21 13:48:00", IsEqual(photo.date), ) assertThat( "Web URL mismatch", "https://vision.hossainkhan.com/blog/exploring-small-town", IsEqual(photo.webUrl), ) assertThat( "Image Source mismatch", "https://vision.hossainkhan.com/images/2020-01/IMG_20200121_163328-PANO-01-cusco-hdr-1600x1100.jpg", IsEqual(photo.imageSource), ) assertThat( "RAW Image Source mismatch", "https://vision.hossainkhan.com/images/2020-01/IMG_20200121_163328-PANO-01-cusco-hdr.jpg", IsEqual(photo.rawSource), ) } }
6
Kotlin
0
5
c71d8012f4a60b06ee51087b9e35a59279a3b792
4,932
android-hk-vision-muzei-plugin
Apache License 2.0
app/src/main/java/com/ushatech/aestoreskotlin/ui/adapter/WishlistAdapter.kt
RedEyesNCode
602,876,907
false
null
package com.ushatech.aestoreskotlin.ui.adapter import android.content.Context import android.view.LayoutInflater import android.view.ViewGroup import android.widget.Toast import androidx.recyclerview.widget.RecyclerView import com.ushatech.aestoreskotlin.databinding.WishlistItemBinding class WishlistAdapter(var context:Context,var onEventWishlist:onEventWishlistAdapter):RecyclerView.Adapter<WishlistAdapter.WistlistViewHolder>() { lateinit var binding: WishlistItemBinding override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): WistlistViewHolder { binding = WishlistItemBinding.inflate(LayoutInflater.from(context),parent,false) return WistlistViewHolder(binding) } override fun onBindViewHolder(holder: WistlistViewHolder, position: Int) { Toast.makeText(context,"STATIC DATA SHOWN !",Toast.LENGTH_SHORT).show() binding.ivDelete.setOnClickListener { onEventWishlist.onDeleteClick() } binding.ivProductImage1.setOnClickListener { onEventWishlist.onProductClick() } } override fun getItemCount(): Int { return 8 } interface onEventWishlistAdapter{ fun onDeleteClick() fun onProductClick() } class WistlistViewHolder(var binding:WishlistItemBinding):RecyclerView.ViewHolder(binding.root) }
0
Kotlin
0
0
2721570afb9086dddcbb7e3ee6f77c42ec73beee
1,367
aestores.online_Kotlin
Apache License 2.0
app/src/main/java/com/husqvarna/popularmovies/ui/fragments/home/MoviesFragment.kt
zakirpervez
705,155,582
false
{"Kotlin": 85221}
package com.husqvarna.popularmovies.ui.fragments.home import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.paging.LoadState import com.husqvarna.popularmovies.R import com.husqvarna.popularmovies.api.models.response.ResultsItem import com.husqvarna.popularmovies.databinding.FragmentMoviesBinding import com.husqvarna.popularmovies.ui.fragments.home.paging.MoviesPagingAdapter import com.husqvarna.popularmovies.ui.viewmodel.MoviesViewModel import com.husqvarna.popularmovies.ui.viewmodel.SharedViewModel import com.husqvarna.popularmovies.util.showToast import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import javax.inject.Inject /** * [MoviesFragment] represent the movies list screen. */ @AndroidEntryPoint class MoviesFragment : Fragment() { private var _moviesBinding: FragmentMoviesBinding? = null private val moviesBinding by lazy { _moviesBinding!! } @Inject lateinit var moviesPagingAdapter: MoviesPagingAdapter private val moviesViewModel: MoviesViewModel by viewModels() private val sharedViewModel: SharedViewModel by activityViewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View { // Inflate the layout for this fragment _moviesBinding = FragmentMoviesBinding.inflate(inflater, container, false) moviesBinding.lifecycleOwner = viewLifecycleOwner moviesBinding.viewModel = moviesViewModel return moviesBinding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) observeData() setupViews() } /** * Observe the data from the [MoviesViewModel]. */ private fun observeData() { moviesViewModel.loaderLiveData.observe(viewLifecycleOwner) { sharedViewModel.showLoader(it) } moviesViewModel.errorLiveData.observe(viewLifecycleOwner) { sharedViewModel.showLoader(false) requireContext().showToast(it) } } /** * Setup the views. */ private fun setupViews() { with(moviesBinding.moviesRecyclerView) { itemAnimator = null adapter = moviesPagingAdapter moviesPagingAdapter.setOnMovieItemClickListener(object : MoviesPagingAdapter.OnMovieItemClickListener { override fun onMovieClick(movie: ResultsItem) { navigateToDetails(movie) } }) } lifecycleScope.launch { moviesViewModel.movies.collectLatest { pagedData -> moviesPagingAdapter.submitData(pagedData) } } moviesPagingAdapter.addLoadStateListener { loadState -> val isNoData = loadState.source.refresh is LoadState.Error && moviesPagingAdapter.itemCount < 1 moviesBinding.moviesRecyclerView.isVisible = !isNoData moviesBinding.noDataContainer.isVisible = isNoData } } /** * Navigate to the movie details screen. * @param movie The [ResultsItem] movie item. */ private fun navigateToDetails(movie: ResultsItem) { movie.id?.let { // Added bundle due to bug present in android giraffe where it won't recognize the safe args inside navigation graph. val args = Bundle() args.putInt("movieId", it) findNavController().navigate(R.id.action_moviesFragment_to_movieDetailFragment, args) } } override fun onDestroy() { _moviesBinding = null super.onDestroy() } }
0
Kotlin
0
0
8e1ff863f4396e105efdcd714f5fd7335e0c8175
4,082
PopularMovies
The Unlicense
ktmidi/src/commonTest/kotlin/dev/atsushieno/ktmidi/UmpTranslatorTest.kt
atsushieno
340,913,447
false
null
package dev.atsushieno.ktmidi import kotlin.test.Test import kotlin.test.assertContentEquals import kotlin.test.assertEquals class UmpTranslatorTest { @Test fun testConvertSingleUmpToMidi1 () { var ump = Ump(0L) val dst = MutableList<Byte>(16) { 0 } var size = 0 // MIDI1 Channel Voice Messages ump = Ump(UmpFactory.midi1NoteOff(0, 1, 40, 0x70)) size = UmpTranslator.translateSingleUmpToMidi1Bytes(dst, ump) assertEquals(3, size) assertContentEquals(listOf(0x81, 40, 0x70).map { it.toByte() }, dst.take(size)) ump = Ump(UmpFactory.midi1Program(0, 1, 40)) size = UmpTranslator.translateSingleUmpToMidi1Bytes(dst, ump) assertEquals(2, size) assertContentEquals(listOf(0xC1, 40).map { it.toByte() }, dst.take(size)) // MIDI2 Channel Voice Messages // rpn ump = Ump(UmpFactory.midi2RPN(0, 1, 2, 3, 517 * 0x40000)) // MIDI1 DTE 517, expanded to 32bit size = UmpTranslator.translateSingleUmpToMidi1Bytes(dst, ump) assertEquals(12, size) // 4 = 517 / 0x80, 5 = 517 % 0x80 assertContentEquals(listOf(0xB1, 101, 0x2, 0xB1, 100, 0x3, 0xB1, 6, 4, 0xB1, 38, 5).map { it.toByte() }, dst.take(size)) // nrpn ump = Ump(UmpFactory.midi2NRPN(0, 1, 2, 3, 0xFF000000)) size = UmpTranslator.translateSingleUmpToMidi1Bytes(dst, ump) assertEquals(12, size) assertContentEquals(listOf(0xB1, 99, 0x2, 0xB1, 98, 0x3, 0xB1, 6, 0x7F, 0xB1, 38, 0x40).map { it.toByte() }, dst.take(size)) // note off ump = Ump(UmpFactory.midi2NoteOff(0, 1, 40, 0, 0xE800, 0)) size = UmpTranslator.translateSingleUmpToMidi1Bytes(dst, ump) assertEquals(3, size) assertContentEquals(listOf(0x81, 40, 0x74).map { it.toByte() }, dst.take(size)) // note on ump = Ump(UmpFactory.midi2NoteOn(0, 1, 40, 0, 0xE800, 0)) size = UmpTranslator.translateSingleUmpToMidi1Bytes(dst, ump) assertEquals(3, size) assertContentEquals(listOf(0x91, 40, 0x74).map { it.toByte() }, dst.take(size)) // PAf ump = Ump(UmpFactory.midi2PAf(0, 1, 40, 0xE8000000)) size = UmpTranslator.translateSingleUmpToMidi1Bytes(dst, ump) assertEquals(3, size) assertContentEquals(listOf(0xA1, 40, 0x74).map { it.toByte() }, dst.take(size)) // CC ump = Ump(UmpFactory.midi2CC(0, 1, 10, 0xE8000000)) size = UmpTranslator.translateSingleUmpToMidi1Bytes(dst, ump) assertEquals(3, size) assertContentEquals(listOf(0xB1, 10, 0x74).map { it.toByte() }, dst.take(size)) // program change, without bank options ump = Ump(UmpFactory.midi2Program(0, 1, 0, 8, 16, 24)) size = UmpTranslator.translateSingleUmpToMidi1Bytes(dst, ump) assertEquals(2, size) assertContentEquals(listOf(0xC1, 8).map { it.toByte() }, dst.take(size)) // program change, with bank options ump = Ump(UmpFactory.midi2Program(0, 1, 1, 8, 16, 24)) size = UmpTranslator.translateSingleUmpToMidi1Bytes(dst, ump) assertEquals(8, size) assertContentEquals(listOf(0xB1, 0, 16, 0xB1, 32, 24, 0xC1, 8).map { it.toByte() }, dst.take(size)) // CAf ump = Ump(UmpFactory.midi2CAf(0, 1, 0xE8000000)) size = UmpTranslator.translateSingleUmpToMidi1Bytes(dst, ump) assertEquals(2, size) assertContentEquals(listOf(0xD1, 0x74).map { it.toByte() }, dst.take(size)) // PitchBend ump = Ump(UmpFactory.midi2PitchBendDirect(0, 1, 0xE8040000)) size = UmpTranslator.translateSingleUmpToMidi1Bytes(dst, ump) assertEquals(3, size) assertContentEquals(listOf(0xE1, 1, 0x74).map { it.toByte() }, dst.take(size)) } @Test fun testConvertUmpToMidi1Bytes1() { val umps = listOf( Ump(0x40904000E0000000), Ump(0x00201000), Ump(0x4080400000000000), ) val dst = MutableList<Byte>(9) { 0 } assertEquals(UmpTranslationResult.OK, UmpTranslator.translateUmpToMidi1Bytes(dst, umps.asSequence())) val expected = listOf(0, 0x90, 0x40, 0x70, 0x80, 0x20, 0x80, 0x40, 0).map { it.toByte() } assertContentEquals(expected, dst) } @Test fun testConvertMidi1ToUmpNoteOn() { val bytes = listOf(0x91, 0x40, 0x78) val context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) assertEquals(UmpTranslationResult.OK, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(3, context.midi1Pos) assertEquals(1, context.output.size) assertEquals(0x47914000, context.output[0].int1) assertEquals(0xF0000000u, context.output[0].int2.toUInt()) } @Test fun testConvertMidi1ToUmpPAf() { val bytes = listOf(0xA1, 0x40, 0x60) val context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) // PAf assertEquals(UmpTranslationResult.OK, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(3, context.midi1Pos) assertEquals(1, context.output.size) assertEquals(0x47A14000, context.output[0].int1) assertEquals(0xC0000000u, context.output[0].int2.toUInt()) } @Test fun testConvertMidi1ToUmpSimpleCC() { val bytes = listOf(0xB1, 0x07, 0x70) val context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) // PAf assertEquals(UmpTranslationResult.OK, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(3, context.midi1Pos) assertEquals(1, context.output.size) assertEquals(0x47B10700, context.output[0].int1) assertEquals(0xE0000000u, context.output[0].int2.toUInt()) } @Test fun testConvertMidi1ToUmpValidRPN() { val bytes = listOf(0xB1, 101, 1, 0xB1, 100, 2, 0xB1, 6, 0x10, 0xB1, 38, 0x20) val context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) // RPN assertEquals(UmpTranslationResult.OK, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(12, context.midi1Pos) assertEquals(1, context.output.size) assertEquals(0x47210102, context.output[0].int1) assertEquals(0x20800000u, context.output[0].int2.toUInt()) } @Test fun testConvertMidi1ToUmpValidNRPN() { val bytes = listOf(0xB1, 99, 1, 0xB1, 98, 2, 0xB1, 6, 0x10, 0xB1, 38, 0x20) val context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) // NRPN assertEquals(UmpTranslationResult.OK, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(12, context.midi1Pos) assertEquals(1, context.output.size) assertEquals(0x47310102, context.output[0].int1) assertEquals(0x20800000u, context.output[0].int2.toUInt()) } @Test fun testConvertMidi1ToUmpInvalidRPN() { var bytes = listOf(0xB1, 101, 1) var context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) // only RPN MSB -> error assertEquals(UmpTranslationResult.INVALID_DTE_SEQUENCE, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(3, context.midi1Pos) assertEquals(0, context.output.size) // only RPN MSB and LSB -> error bytes = listOf(0xB1, 101, 1, 0xB1, 100, 2) context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) assertEquals(UmpTranslationResult.INVALID_DTE_SEQUENCE, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(6, context.midi1Pos) assertEquals(0, context.output.size) // only RPN MSB and LSB, and DTE MSB -> error bytes = listOf(0xB1, 101, 1, 0xB1, 100, 2, 0xB1, 6, 3) context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) assertEquals(UmpTranslationResult.INVALID_DTE_SEQUENCE, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(9, context.midi1Pos) assertEquals(0, context.output.size) } @Test fun testConvertMidi1ToUmpInvalidNRPN() { var bytes = listOf(0xB1, 99, 1) var context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) // only NRPN MSB -> error assertEquals(UmpTranslationResult.INVALID_DTE_SEQUENCE, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(3, context.midi1Pos) assertEquals(0, context.output.size) // only NRPN MSB and LSB -> error bytes = listOf(0xB1, 99, 1, 0xB1, 98, 2) context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) assertEquals(UmpTranslationResult.INVALID_DTE_SEQUENCE, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(6, context.midi1Pos) assertEquals(0, context.output.size) // only NRPN MSB and LSB, and DTE MSB -> error bytes = listOf(0xB1, 99, 1, 0xB1, 98, 2, 0xB1, 6, 3) context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) assertEquals(UmpTranslationResult.INVALID_DTE_SEQUENCE, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(9, context.midi1Pos) assertEquals(0, context.output.size) } @Test fun testConvertMidi1ToUmpSimpleProgramChange() { var bytes = listOf(0xC1, 0x30) var context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) // simple program change assertEquals(UmpTranslationResult.OK, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(2, context.midi1Pos) assertEquals(1, context.output.size) assertEquals(0x47C10000, context.output[0].int1) assertEquals(0x30000000u, context.output[0].int2.toUInt()) } @Test fun testConvertMidi1ToUmpBankMsbLsbAndProgramChange() { var bytes = listOf(0xB1, 0x00, 0x12, 0xB1, 0x20, 0x22, 0xC1, 0x30) var context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) // bank select MSB, bank select LSB, program change assertEquals(UmpTranslationResult.OK, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(8, context.midi1Pos) assertEquals(1, context.output.size) assertEquals(0x47C10001, context.output[0].int1) assertEquals(0x30001222u, context.output[0].int2.toUInt()) } // Not sure if this should be actually accepted or rejected; we accept it for now. @Test fun testConvertMidi1ToUmpBankMsbAndProgramChange() { var bytes = listOf(0xB1, 0x00, 0x12, 0xC1, 0x30) var context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) // bank select MSB, then program change (LSB skipped) assertEquals(UmpTranslationResult.OK, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(5, context.midi1Pos) assertEquals(1, context.output.size) assertEquals(0x47C10001, context.output[0].int1) assertEquals(0x30001200u, context.output[0].int2.toUInt()) } // Not sure if this should be actually accepted or rejected; we accept it for now. @Test fun testConvertMidi1ToUmpBankLsbAndProgramChange() { val bytes = listOf(0xB1, 0x20, 0x12, 0xC1, 0x30) val context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) // bank select LSB, then program change (MSB skipped) assertEquals(UmpTranslationResult.OK, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(5, context.midi1Pos) assertEquals(1, context.output.size) assertEquals(0x47C10001, context.output[0].int1) assertEquals(0x30000012u, context.output[0].int2.toUInt()) } @Test fun testConvertMidi1ToUmpCAf() { val bytes = listOf(0xD1, 0x60) val context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) // CAf assertEquals(UmpTranslationResult.OK, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(2, context.midi1Pos) assertEquals(1, context.output.size) assertEquals(0x47D10000, context.output[0].int1) assertEquals(0xC0000000u, context.output[0].int2.toUInt()) } @Test fun testConvertMidi1ToUmpPitchBend() { val bytes = listOf(0xE1, 0x20, 0x30) val context = Midi1ToUmpTranslatorContext(bytes.map { it.toByte()}, group = 7) // Pitchbend assertEquals(UmpTranslationResult.OK, UmpTranslator.translateMidi1BytesToUmp(context)) assertEquals(3, context.midi1Pos) assertEquals(1, context.output.size) assertEquals(0x47E10000, context.output[0].int1) assertEquals(0x60800000u, context.output[0].int2.toUInt()) // note that source MIDI1 pitch bend is in littele endian. } }
9
null
6
69
48792a4826cea47edbec7eabcd62d5a489dd374e
12,971
ktmidi
MIT License
src/main/kotlin/com/github/ojacquemart/realtime/db/debezium/ChangeEventPayloadToJsonDocumentConverter.kt
ojacquemart
369,252,422
false
null
package com.github.ojacquemart.realtime.db.debezium import com.fasterxml.jackson.core.type.TypeReference import com.fasterxml.jackson.databind.ObjectMapper import com.github.ojacquemart.realtime.db.JsonDocument import org.jboss.logging.Logger class ChangeEventPayloadToJsonDocumentConverter { companion object { private val logger = Logger.getLogger(ChangeEventPayloadToJsonDocumentConverter::class.java) private val MAPPER = ObjectMapper() private val MAP_TYPE_REF: TypeReference<HashMap<String, Any>> = object : TypeReference<HashMap<String, Any>>() {} } /** * Transform an actual DebeziumChangeEvent to a JSON and replace any $oid occurrence by its String value if necessary. * Combine the filter, after and patch according to the change event. * * @see <a href="https://debezium.io/documentation/reference/connectors/mongodb.html#mongodb-change-events-value">Change Event Values</a> */ fun convert(event: ChangeEvent?): JsonDocument { return convert(event?.payload?.filter) + convert(event?.payload?.after) + convert(event?.payload?.patch) } private fun convert(maybeData: String?): Map<String, Any> { val data = maybeData ?: return emptyMap() return try { val map: MutableMap<String, Any> = MAPPER.readValue(data, MAP_TYPE_REF) if (shouldParseObjectId(map)) { map["_id"] = parseObjectId(map) } map } catch (e: Exception) { logger.error("Error while parsing the payload data: '$data'") emptyMap() } } private fun shouldParseObjectId(map: Map<String, Any>): Boolean { val id = map["_id"] return id is Map<*, *> } private fun parseObjectId(map: Map<String, Any>): String { val id = getId(map) return (id?.get("\$oid") as String?) ?: "" } private fun getId(map: Map<String, Any>) = map["_id"] as Map<*, *>? }
1
Kotlin
2
1
0293f8e892ed6702ae9a5964a89ccc2800661d01
1,856
quarkus-realtime-db
Apache License 2.0
shopping/src/main/java/com/sailer/shopping/presentation/navigation/ShoppingCoordinator.kt
mysangle
274,810,426
true
{"Kotlin": 75910}
package com.sailer.shopping.presentation.navigation import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.navArgs import com.sailer.core.di.scopes.FeatureScope import com.sailer.core.navigation.Coordinator import com.sailer.core.navigation.Displayable import com.sailer.core.navigation.FeatureNavigator import com.sailer.core.navigation.StartDestination import com.sailer.shopping.R import com.sailer.shopping.presentation.product.view.ProductsFragment import com.sailer.shopping.presentation.product.view.ProductsFragmentArgs import com.sailer.shopping.presentation.product.viewmodel.ProductsViewModelFactory import com.sailer.shopping.presentation.search.view.SearchFragment import com.sailer.shopping.presentation.search.viewmodel.SearchViewModelFactory import dagger.Lazy import javax.inject.Inject /** * Created by <NAME> on 5/5/20. */ @FeatureScope class ShoppingCoordinator @Inject constructor( featureNavigator: FeatureNavigator, private val productsViewModelFactory: Lazy<ProductsViewModelFactory.Factory>, private val searchViewModelFactory: Lazy<SearchViewModelFactory.Factory> ) : Coordinator(featureNavigator) { fun start(categoryId: Long): StartDestination { val args = ProductsFragmentArgs(categoryId = categoryId).toBundle() return StartDestination(R.id.productsFragment, args) } override fun onCreateViewModelFactory(screen: Displayable): ViewModelProvider.Factory { return when (screen) { is ProductsFragment -> { val args = screen.navArgs<ProductsFragmentArgs>().value productsViewModelFactory.get().create( categoryId = args.categoryId ) } is SearchFragment -> searchViewModelFactory.get().create() else -> throw IllegalArgumentException("Not supported fragment for the current coordinator") } } override fun onEvent(event: Any) { when (event) { is ShoppingCoordinatorEvent.Back -> back() is ShoppingCoordinatorEvent.Search -> search() is ShoppingCoordinatorEvent.Products -> products( categoryId = event.categoryId ) } } private fun products(categoryId: Long) { val args = ProductsFragmentArgs(categoryId = categoryId).toBundle() navController?.navigate(R.id.productsFragment, args) } private fun search() { navController?.navigate(R.id.searchFragment) } }
0
null
0
0
56a5c9aa5eac3f56d194604f2f9b77fdaddc6f4e
2,520
sailer
MIT License
src/main/java/com/adityaamolbavadekar/android/apps/culture/MainActivity.kt
amjadali070
583,661,723
false
null
package com.adityaamolbavadekar.android.apps.culture import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.drawerlayout.widget.DrawerLayout import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.adityaamolbavadekar.android.apps.culture.databinding.ActivityMainBinding import com.google.android.material.navigation.NavigationView class MainActivity : AppCompatActivity() { private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) // binding. val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout) val navView: NavigationView = findViewById(R.id.nav_view) val navController = findNavController(R.id.nav_host_fragment) setupActionBarWithNavController(navController) navView.setupWithNavController(navController) } /* override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { R.id.action_settings -> { startActivity(Intent(this, SettingsActivity::class.java)) true } else -> false } }*/ override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }
0
Kotlin
0
1
19e23e66fd2d8df713cd22b79126028905337e02
2,181
Notes_Keeper_MAD_Project
Apache License 2.0
app/src/main/java/com/rumeysaozer/roomiud/view/ListFragment.kt
rumeysaozer0
496,297,503
false
{"Kotlin": 12615}
package com.rumeysaozer.roomiud.view import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.view.ViewOutlineProvider import androidx.lifecycle.Observer import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.rumeysaozer.roomiud.adapter.UserAdapter import com.rumeysaozer.roomiud.databinding.FragmentListBinding import com.rumeysaozer.roomiud.viewModel.UserViewModel class ListFragment : Fragment() { private var _binding: FragmentListBinding? = null private val binding get() = _binding!! private lateinit var adapter : UserAdapter private lateinit var userViewModel: UserViewModel override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { _binding = FragmentListBinding.inflate(inflater, container, false) val view = binding.root return view } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) userViewModel = ViewModelProvider(this).get(UserViewModel::class.java) val recyclerView = binding.recyclerView recyclerView.layoutManager = LinearLayoutManager(context) adapter = UserAdapter() recyclerView.adapter = adapter observeLiveData() binding.floatingActionButton.setOnClickListener { val action = ListFragmentDirections.actionListFragmentToAddFragment() findNavController().navigate(action) } } fun observeLiveData(){ userViewModel.readAllData.observe(viewLifecycleOwner, Observer { user-> user?.let{ adapter.setData(it) } }) } }
0
Kotlin
0
0
a4810c960fd077f9ce3f3e51b7b2dc2f9a371e84
2,063
Room_User_Insert_Update_Delete
MIT License
lib/src/main/java/dev/tunnicliff/ui/theme/internal/Color.kt
Brent-Tunnicliff
772,944,800
false
{"Kotlin": 64959}
package dev.tunnicliff.ui.theme.internal import androidx.compose.ui.graphics.Color internal val md_theme_light_primary = Color(0xFF00658B) internal val md_theme_light_onPrimary = Color(0xFFFFFFFF) internal val md_theme_light_primaryContainer = Color(0xFFC4E7FF) internal val md_theme_light_onPrimaryContainer = Color(0xFF001E2D) internal val md_theme_light_secondary = Color(0xFF00639A) internal val md_theme_light_onSecondary = Color(0xFFFFFFFF) internal val md_theme_light_secondaryContainer = Color(0xFFCDE5FF) internal val md_theme_light_onSecondaryContainer = Color(0xFF001D32) internal val md_theme_light_tertiary = Color(0xFF615A7C) internal val md_theme_light_onTertiary = Color(0xFFFFFFFF) internal val md_theme_light_tertiaryContainer = Color(0xFFE7DEFF) internal val md_theme_light_onTertiaryContainer = Color(0xFF1D1736) internal val md_theme_light_error = Color(0xFFBA1A1A) internal val md_theme_light_errorContainer = Color(0xFFFFDAD6) internal val md_theme_light_onError = Color(0xFFFFFFFF) internal val md_theme_light_onErrorContainer = Color(0xFF410002) internal val md_theme_light_background = Color(0xFFFBFCFF) internal val md_theme_light_onBackground = Color(0xFF191C1E) internal val md_theme_light_surface = Color(0xFFFBFCFF) internal val md_theme_light_onSurface = Color(0xFF191C1E) internal val md_theme_light_surfaceVariant = Color(0xFFDDE3EA) internal val md_theme_light_onSurfaceVariant = Color(0xFF41484D) internal val md_theme_light_outline = Color(0xFF71787E) internal val md_theme_light_inverseOnSurface = Color(0xFFF0F1F3) internal val md_theme_light_inverseSurface = Color(0xFF2E3133) internal val md_theme_light_inversePrimary = Color(0xFF7DD0FF) internal val md_theme_light_shadow = Color(0xFF000000) internal val md_theme_light_surfaceTint = Color(0xFF00658B) internal val md_theme_light_outlineVariant = Color(0xFFC0C7CD) internal val md_theme_light_scrim = Color(0xFF000000) internal val md_theme_dark_primary = Color(0xFF7DD0FF) internal val md_theme_dark_onPrimary = Color(0xFF00344A) internal val md_theme_dark_primaryContainer = Color(0xFF004C6A) internal val md_theme_dark_onPrimaryContainer = Color(0xFFC4E7FF) internal val md_theme_dark_secondary = Color(0xFF95CCFF) internal val md_theme_dark_onSecondary = Color(0xFF003352) internal val md_theme_dark_secondaryContainer = Color(0xFF004A75) internal val md_theme_dark_onSecondaryContainer = Color(0xFFCDE5FF) internal val md_theme_dark_tertiary = Color(0xFFCBC1E9) internal val md_theme_dark_onTertiary = Color(0xFF322C4C) internal val md_theme_dark_tertiaryContainer = Color(0xFF494264) internal val md_theme_dark_onTertiaryContainer = Color(0xFFE7DEFF) internal val md_theme_dark_error = Color(0xFFFFB4AB) internal val md_theme_dark_errorContainer = Color(0xFF93000A) internal val md_theme_dark_onError = Color(0xFF690005) internal val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6) internal val md_theme_dark_background = Color(0xFF191C1E) internal val md_theme_dark_onBackground = Color(0xFFE1E2E5) internal val md_theme_dark_surface = Color(0xFF191C1E) internal val md_theme_dark_onSurface = Color(0xFFE1E2E5) internal val md_theme_dark_surfaceVariant = Color(0xFF41484D) internal val md_theme_dark_onSurfaceVariant = Color(0xFFC0C7CD) internal val md_theme_dark_outline = Color(0xFF8B9297) internal val md_theme_dark_inverseOnSurface = Color(0xFF191C1E) internal val md_theme_dark_inverseSurface = Color(0xFFE1E2E5) internal val md_theme_dark_inversePrimary = Color(0xFF00658B) internal val md_theme_dark_shadow = Color(0xFF000000) internal val md_theme_dark_surfaceTint = Color(0xFF7DD0FF) internal val md_theme_dark_outlineVariant = Color(0xFF41484D) internal val md_theme_dark_scrim = Color(0xFF000000) internal val seed = Color(0xFF133445)
0
Kotlin
0
0
b78d72a62c3bf8d9b1daf5bc4945f75f8d4bb3fb
3,753
lib-ui-android
MIT License
src/main/kotlin/cn/phakel/githubrequester/event/Event.kt
EvanLuo42
436,996,780
false
null
package cn.phakel.githubrequester.event import cn.phakel.githubrequester.bean.Installation import cn.phakel.githubrequester.bean.Organization import cn.phakel.githubrequester.bean.Repository import cn.phakel.githubrequester.bean.User open class Event( val action: String, val sender: User, val repository: Repository, val organization: Organization, val installation: Installation)
0
Kotlin
0
1
d00c2e6788f1233b248ff38607a7197d12f4703c
403
GithubRequester
MIT License
idea/tests/testData/intentions/convertNullablePropertyToLateinit/abstract.kt
JetBrains
278,369,660
false
null
// IS_APPLICABLE: false // DISABLE-ERRORS abstract class C { abstract var <caret>foo: String? = null }
0
Kotlin
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
106
intellij-kotlin
Apache License 2.0
src/main/kotlin/com/github/lppedd/cc/lookupElement/CommitBodyLookupElement.kt
cybernetics
298,378,217
true
{"Kotlin": 210342, "HTML": 11442, "Java": 5008}
package com.github.lppedd.cc.lookupElement import com.github.lppedd.cc.* import com.github.lppedd.cc.completion.providers.BodyProviderWrapper import com.github.lppedd.cc.psiElement.CommitBodyPsiElement import com.intellij.codeInsight.completion.InsertionContext import com.intellij.codeInsight.lookup.LookupElementPresentation /** * @author <NAME> */ internal class CommitBodyLookupElement( override val index: Int, override val provider: BodyProviderWrapper, private val psiElement: CommitBodyPsiElement, private val completionPrefix: String, ) : CommitLookupElement() { override val priority = PRIORITY_BODY override fun getPsiElement(): CommitBodyPsiElement = psiElement override fun getLookupString(): String = psiElement.commitBody.value override fun renderElement(presentation: LookupElementPresentation) { presentation.icon = ICON_BODY presentation.itemText = lookupString.flattenWhitespaces().abbreviate(100) presentation.isTypeIconRightAligned = true } override fun handleInsert(context: InsertionContext) { val document = context.document val caretOffset = context.startOffset val lineStart = document.getLineRangeByOffset(caretOffset).startOffset if (completionPrefix.isNotEmpty()) { val tempAdditionalLength = lookupString.length - completionPrefix.length val removeTo = context.tailOffset val removeFrom = context.tailOffset - tempAdditionalLength document.deleteString(removeFrom, removeTo) } for (i in document.getLineNumber(caretOffset) until document.lineCount) { val (_, end, isEmpty) = document.getLineRange(i) if (isEmpty) { document.replaceString(lineStart, end - 1, lookupString) context.editor.moveCaretToOffset(lineStart + lookupString.length) return } } } }
0
null
0
0
e43b346b69ff582caa02aa82695c9b5d4dfb135b
1,838
idea-conventional-commit
MIT License
yoonit-camera/src/main/java/ai/cyberlabs/yoonit/camera/analyzers/frame/FrameAnalyzer.kt
Yoonit-Labs
294,444,955
false
null
/** * ██╗ ██╗ ██████╗ ██████╗ ███╗ ██╗██╗████████╗ * ╚██╗ ██╔╝██╔═══██╗██╔═══██╗████╗ ██║██║╚══██╔══╝ * ╚████╔╝ ██║ ██║██║ ██║██╔██╗ ██║██║ ██║ * ╚██╔╝ ██║ ██║██║ ██║██║╚██╗██║██║ ██║ * ██║ ╚██████╔╝╚██████╔╝██║ ╚████║██║ ██║ * ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═╝ ╚═╝ * * https://yoonit.dev - <EMAIL> * * Yoonit Camera * The most advanced and modern Camera module for Android with a lot of awesome features * * <NAME>, <NAME>, <NAME> & <NAME> @ 2020-2021 */ package ai.cyberlabs.yoonit.camera.analyzers.frame import ai.cyberlabs.yoonit.camera.CameraGraphicView import ai.cyberlabs.yoonit.camera.controllers.ComputerVisionController import ai.cyberlabs.yoonit.camera.controllers.ImageQualityController import ai.cyberlabs.yoonit.camera.interfaces.CameraCallback import ai.cyberlabs.yoonit.camera.interfaces.CameraEventListener import ai.cyberlabs.yoonit.camera.models.CaptureOptions import ai.cyberlabs.yoonit.camera.utils.mirror import ai.cyberlabs.yoonit.camera.utils.rotate import ai.cyberlabs.yoonit.camera.utils.toRGBBitmap import ai.cyberlabs.yoonit.camera.utils.toYUVBitmap import android.annotation.SuppressLint import android.content.Context import android.graphics.Bitmap import android.os.Handler import android.os.Looper import androidx.camera.core.CameraSelector import androidx.camera.core.ImageAnalysis import androidx.camera.core.ImageProxy import java.io.File import java.io.FileOutputStream /** * Custom camera image analyzer based on frame bounded on [CameraController]. */ class FrameAnalyzer( private val context: Context, private val cameraEventListener: CameraEventListener?, private val graphicView: CameraGraphicView, private val cameraCallback: CameraCallback ) : ImageAnalysis.Analyzer { private var analyzerTimeStamp: Long = 0 private var numberOfImages = 0 /** * Receive image from CameraX API. * * @param imageProxy image from CameraX API. */ @SuppressLint("UnsafeExperimentalUsageError") override fun analyze(imageProxy: ImageProxy) { this.graphicView.clear() if (this.shouldAnalyze(imageProxy)) { val mediaImage = imageProxy.image mediaImage?.let { var frameBitmap: Bitmap = when (CaptureOptions.colorEncoding) { "YUV" -> mediaImage.toYUVBitmap() else -> mediaImage.toRGBBitmap(context) } if (CaptureOptions.cameraLens == CameraSelector.LENS_FACING_BACK) { frameBitmap = frameBitmap .rotate(180f) .mirror() } // Computer Vision Inference. var inferences: ArrayList<android.util.Pair<String, FloatArray>> = arrayListOf() if (CaptureOptions.ComputerVision.enable) { inferences = ComputerVisionController.getInferences( CaptureOptions.ComputerVision.modelMap, frameBitmap ) } // Save image captured. var imagePath = "" if (CaptureOptions.saveImageCaptured) { imagePath = this.handleSaveImage( frameBitmap, imageProxy.imageInfo.rotationDegrees.toFloat() ) } val imageQuality: Triple<Double, Double, Double> = ImageQualityController.processImage(frameBitmap, false) // Handle to emit image path and the inference. Handler(Looper.getMainLooper()).post { this.handleEmitImageCaptured(imagePath, inferences, imageQuality) } } } imageProxy.close() } /** * Check if image is to analyze. * * @param imageProxy image from CameraX API. */ @SuppressLint("UnsafeExperimentalUsageError") private fun shouldAnalyze(imageProxy: ImageProxy): Boolean { if ( !CaptureOptions.saveImageCaptured && !CaptureOptions.ComputerVision.enable ) { return false } if (this.cameraEventListener == null) { return false } if (imageProxy.image == null) { return false } // Process image only within interval equal ANALYZE_TIMER. val currentTimestamp = System.currentTimeMillis() if (currentTimestamp - this.analyzerTimeStamp < CaptureOptions.timeBetweenImages) { return false } this.analyzerTimeStamp = currentTimestamp return true } /** * Handle emit frame image file created. * * @param imagePath image file path. * @param inferences The computer vision inferences based in the models. */ private fun handleEmitImageCaptured( imagePath: String, inferences: ArrayList<android.util.Pair<String, FloatArray>>, imageQuality: Triple<Double, Double, Double> ) { // process face number of images. if (CaptureOptions.numberOfImages > 0) { if (this.numberOfImages < CaptureOptions.numberOfImages) { this.numberOfImages++ this.cameraEventListener?.onImageCaptured( "frame", this.numberOfImages, CaptureOptions.numberOfImages, imagePath, inferences, imageQuality.first, imageQuality.second, imageQuality.third ) return } this.cameraCallback.onStopAnalyzer() this.cameraEventListener?.onEndCapture() return } // process face unlimited. this.numberOfImages = (this.numberOfImages + 1) % NUMBER_OF_IMAGES_LIMIT this.cameraEventListener?.onImageCaptured( "frame", this.numberOfImages, CaptureOptions.numberOfImages, imagePath, inferences, imageQuality.first, imageQuality.second, imageQuality.third ) } /** * Handle save file image. * * @param mediaBitmap the original image bitmap. * @param rotationDegrees the rotation degrees to turn the image to portrait. * @return the image file path created. */ private fun handleSaveImage( mediaBitmap: Bitmap, rotationDegrees: Float ): String { val path = this.context.externalCacheDir.toString() val file = File(path, "yoonit-frame-".plus(this.numberOfImages).plus(".jpg")) val fileOutputStream = FileOutputStream(file) mediaBitmap .rotate(rotationDegrees) .mirror() .compress( Bitmap.CompressFormat.JPEG, 100, fileOutputStream ) fileOutputStream.close() return file.absolutePath } companion object { private const val TAG = "FrameAnalyzer" private const val NUMBER_OF_IMAGES_LIMIT = 25 } }
2
Kotlin
3
57
f1e1ca65726a4ae26c712ad0e60d131910856f8d
7,253
android-yoonit-camera
MIT License
src/main/kotlin/io/github/thebroccolibob/soulorigins/Util.kt
thebroccolibob
789,243,779
false
{"Kotlin": 230619, "Java": 22001, "mcfunction": 289}
package io.github.thebroccolibob.soulorigins import io.github.apace100.apoli.component.PowerHolderComponent import io.github.apace100.apoli.power.Power import io.github.apace100.calio.data.SerializableData import net.fabricmc.fabric.api.item.v1.FabricItemSettings import net.fabricmc.fabric.api.itemgroup.v1.FabricItemGroup import net.fabricmc.fabric.api.`object`.builder.v1.block.FabricBlockSettings import net.minecraft.block.Block import net.minecraft.data.client.Model import net.minecraft.data.client.TextureKey import net.minecraft.entity.Entity import net.minecraft.entity.data.TrackedData import net.minecraft.entity.player.PlayerEntity import net.minecraft.inventory.Inventory import net.minecraft.item.* import net.minecraft.nbt.NbtCompound import net.minecraft.nbt.NbtElement import net.minecraft.nbt.NbtList import net.minecraft.screen.PropertyDelegate import net.minecraft.registry.Registries import net.minecraft.util.Hand import net.minecraft.util.Identifier import net.minecraft.util.collection.DefaultedList import net.minecraft.util.hit.BlockHitResult import net.minecraft.util.math.BlockPos import net.minecraft.util.math.Direction import net.minecraft.util.math.Vec3d import net.minecraft.util.math.Vec3i import net.minecraft.world.World import java.util.* import kotlin.reflect.KMutableProperty0 import kotlin.reflect.KProperty import net.minecraft.util.Pair as McPair inline fun FabricItemSettings(init: FabricItemSettings.() -> Unit) = FabricItemSettings().apply(init) inline fun FabricBlockSettings(init: FabricBlockSettings.() -> Unit): FabricBlockSettings = FabricBlockSettings.create().apply(init) operator fun ItemUsageContext.component1(): ItemStack = stack operator fun ItemUsageContext.component2(): PlayerEntity? = player operator fun ItemUsageContext.component3(): BlockPos = blockPos operator fun ItemUsageContext.component4(): World = world operator fun ItemUsageContext.component5(): Hand = hand operator fun ItemUsageContext.component6(): Direction = side operator fun BlockHitResult.component1(): Vec3d = this.pos operator fun BlockHitResult.component2(): Direction = this.side operator fun BlockHitResult.component3(): BlockPos = this.blockPos fun NbtCompound.getOrCreateCompound(key: String): NbtCompound { if (key in this) return getCompound(key) return NbtCompound().also { put(key, it) } } fun NbtCompound.getOrCreateList(key: String, type: Byte): NbtList { if (key in this) return getList(key, type) return NbtList().also { put(key, it) } } fun NbtList.setIfEmpty(index: Int, element: NbtElement) : Boolean { if (!getCompound(index).isEmpty) return false set(index, element) return true } fun NbtCompound.getList(key: String, type: Byte): NbtList = getList(key, type.toInt()) fun <T: Any> Optional<T>.toNullable(): T? = orElse(null) fun <T: Any> T?.toOptional() = Optional.ofNullable(this) fun <T, R> Iterable<T>.mapWithNext(transform: (current: T, next: T?) -> R): List<R> { return toList().let { it.mapIndexed { index, item -> transform(item, it.getOrNull(index + 1)) } } } operator fun <T> McPair<T, *>.component1(): T = left operator fun <T> McPair<*, T>.component2(): T = right fun <T> Iterable<T>.forEachWithNext(transform: (current: T, next: T?) -> Unit) { toList().let { it.forEachIndexed { index, item -> transform(item, it.getOrNull(index + 1)) } } } fun SerializableData(init: SerializableData.() -> Unit) = SerializableData().apply(init) operator fun Item.plus(suffix: String) = "$translationKey.$suffix" inline fun <reified T : Power> Entity.hasPower() = PowerHolderComponent.hasPower(this, T::class.java) inline fun <reified T : Power> Entity.getPowers(): List<T> = PowerHolderComponent.getPowers(this, T::class.java) fun ItemGroup(init: ItemGroup.Builder.() -> Unit): ItemGroup { return FabricItemGroup.builder().apply(init).build() } fun ItemGroup.Builder.entries(vararg items: ItemConvertible) { entries { _, entries -> entries.addAll(items.map { it.asItem().defaultStack }) } } fun ItemGroup.Builder.entries(vararg items: ItemStack) { entries { _, entries -> entries.addAll(items.toList()) } } fun Model(parent: Identifier? = null, variant: String? = null, vararg requiredTextureKeys: TextureKey): Model { return Model(parent.toOptional(), variant.toOptional(), *requiredTextureKeys) } operator fun Vec3i.plus(other: Vec3i): Vec3i = this.add(other) operator fun BlockPos.plus(other: Vec3i): BlockPos = this.add(other) operator fun Vec3i.minus(other: Vec3i): Vec3i = this.subtract(other) operator fun BlockPos.minus(other: Vec3i): BlockPos = this.subtract(other) operator fun Vec3d.plus(other: Vec3d): Vec3d = this.add(other) operator fun Vec3d.minus(other: Vec3d): Vec3d = this.subtract(other) operator fun Vec3d.times(scalar: Double): Vec3d = this.multiply(scalar) val Block.id get() = Registries.BLOCK.getId(this) fun BlockPos.copy() = BlockPos(x, y, z) operator fun <T> TrackedData<T>.getValue(thisRef: Entity, property: KProperty<*>): T { return thisRef.dataTracker.get(this) } operator fun <T> TrackedData<T>.setValue(thisRef: Entity, property: KProperty<*>, value: T) { thisRef.dataTracker.set(this, value) } @JvmName("getValueOptional") operator fun <T: Any> TrackedData<Optional<T>>.getValue(thisRef: Entity, property: KProperty<*>): T? { return thisRef.dataTracker.get(this).toNullable() } @JvmName("setValueOptional") operator fun <T : Any> TrackedData<Optional<T>>.setValue(thisRef: Entity, property: KProperty<*>, value: T?) { thisRef.dataTracker.set(this, value.toOptional()) } infix fun Double.floorMod(other: Double) = (this % other + other) % other fun PropertyDelegate(vararg properties: KMutableProperty0<Int>) = object : PropertyDelegate { override fun get(index: Int) = properties[index].get() override fun set(index: Int, value: Int) { properties[index].set(value) } override fun size() = properties.size } fun DefaultedList<ItemStack>.toInventory(): Inventory { val list = this return object : Inventory { override fun clear() { list.clear() } override fun size() = list.size override fun isEmpty() = list.isEmpty() override fun getStack(slot: Int) = list[slot] override fun removeStack(slot: Int, amount: Int) = list[slot].split(amount) override fun removeStack(slot: Int) = list[slot].also { setStack(slot, ItemStack.EMPTY) } override fun setStack(slot: Int, stack: ItemStack) { list[slot] = stack } override fun markDirty() {} override fun canPlayerUse(player: PlayerEntity) = true } } operator fun <T> List<T>.get(range: IntRange): List<T> = range.map(this::get)
0
Kotlin
0
1
97812bd356fd1ce00666d8dab61bd3afc05468d9
6,820
SoulOrigins
MIT License
cufyorg-PED-core/src/commonMain/kotlin/NullableCodecCore.kt
cufyorg
723,726,145
false
{"Kotlin": 291403}
/* * Copyright 2023 cufy.org and meemer.com * * 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. */ @file:Suppress("NOTHING_TO_INLINE") package org.cufy.ped import kotlin.js.JsName import kotlin.jvm.JvmName /* ============= ------------------ ============= */ /** * Decode the given [value] to [O] using the given [codec]. * * @param value the value to decode. * @param codec the codec to be used. * @return the decoding result. * @since 2.0.0 */ @JvmName("tryDecodeNullish") @JsName("tryDecodeNullish") @PEDMarker2 inline fun <I, O> tryDecode(value: O?, codec: NullableCodec<I, O>): Result<I?> { return tryDecodeAny(value, codec) } /** * Decode the given [value] to [O] using the given [codec]. * * @param value the value to decode. * @param codec the codec to be used. * @return the decoding result. * @since 2.0.0 */ @JvmName("tryDecodeNullable") @JsName("tryDecodeNullable") @PEDMarker2 inline fun <I, O> tryDecode(value: O, codec: NullableCodec<I, O>): Result<I?> { return tryDecodeAny(value, codec) } /** * Decode the given [value] to [O] using the given [codec]. * * @param value the value to decode. * @param codec the codec to be used. * @return the decoded value. * @throws CodecException if decoding failed. * @since 2.0.0 */ @JvmName("decodeNullish") @JsName("decodeNullish") @PEDMarker2 inline fun <I, O> decode(value: O?, codec: NullableCodec<I, O>): I? { return decodeAny(value, codec) } /** * Decode the given [value] to [O] using the given [codec]. * * @param value the value to decode. * @param codec the codec to be used. * @return the decoded value. * @throws CodecException if decoding failed. * @since 2.0.0 */ @JvmName("decodeNullable") @JsName("decodeNullable") @PEDMarker2 inline fun <I, O> decode(value: O, codec: NullableCodec<I, O>): I? { return decodeAny(value, codec) } /** * Decode [this] value to [I] using the given [codec]. * * @receiver the value to decode. * @param codec the codec to be used. * @return the decoded value. * @throws CodecException if decoding failed. * @since 2.0.0 */ @JvmName("decodeInfixNullish") @JsName("decodeInfixNullish") @PEDMarker3 inline infix fun <I, O> O?.decode(codec: NullableCodec<I, O>): I? { return decode(this, codec) } /** * Decode [this] value to [I] using the given [codec]. * * @receiver the value to decode. * @param codec the codec to be used. * @return the decoded value. * @throws CodecException if decoding failed. * @since 2.0.0 */ @JvmName("decodeInfixNullable") @JsName("decodeInfixNullable") @PEDMarker3 inline infix fun <I, O> O.decode(codec: NullableCodec<I, O>): I? { return decode(this, codec) } /* ============= ------------------ ============= */
0
Kotlin
0
0
c47b1c0f25c397ce1d1bb070781cc0d6bf0ea510
3,225
serialization
Apache License 2.0
compose/src/androidMain/kotlin/com/camackenzie/exvi/client/components/AlertDialog.kt
CallumMackenzie
450,286,341
false
null
package com.camackenzie.exvi.client.components import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier @Composable actual fun AlertDialog( onDismissRequest: () -> Unit, buttons: @Composable (() -> Unit), modifier: Modifier, title: @Composable (() -> Unit)?, text: @Composable (() -> Unit)? ) = androidx.compose.material.AlertDialog( onDismissRequest = onDismissRequest, buttons = buttons, modifier = modifier, title = title, text = text, )
1
Kotlin
0
0
85c0bde76ab0bf4a8ee2a2ad0ea3bd249bc7422b
504
exvi-client
Apache License 2.0
core-common/src/main/java/de/niklasbednarczyk/nbweather/core/common/nullsafe/NBNullSafeUtils.kt
NiklasBednarczyk
529,683,941
false
{"Kotlin": 1235016}
package de.niklasbednarczyk.nbweather.core.common.nullsafe inline fun <T1, R> nbNullSafe( value1: T1?, transform: (value1: T1) -> R? ): R? { return if (value1 != null) { transform(value1) } else { null } } inline fun <T1, T2, R> nbNullSafe( value1: T1?, value2: T2?, transform: (value1: T1, value2: T2) -> R? ): R? { return if (value1 != null && value2 != null) { transform(value1, value2) } else { null } } inline fun <T1, T2, T3, R> nbNullSafe( value1: T1?, value2: T2?, value3: T3?, transform: (value1: T1, value2: T2, value3: T3) -> R? ): R? { return if (value1 != null && value2 != null && value3 != null) { transform(value1, value2, value3) } else { null } } inline fun <T1, T2, T3, T4, R> nbNullSafe( value1: T1?, value2: T2?, value3: T3?, value4: T4?, transform: (value1: T1, value2: T2, value3: T3, value4: T4) -> R? ): R? { return if (value1 != null && value2 != null && value3 != null && value4 != null) { transform(value1, value2, value3, value4) } else { null } } inline fun <T1, T2, T3, T4, T5, R> nbNullSafe( value1: T1?, value2: T2?, value3: T3?, value4: T4?, value5: T5?, transform: (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5) -> R? ): R? { return if (value1 != null && value2 != null && value3 != null && value4 != null && value5 != null) { transform(value1, value2, value3, value4, value5) } else { null } } inline fun <T1, T2, T3, T4, T5, T6, R> nbNullSafe( value1: T1?, value2: T2?, value3: T3?, value4: T4?, value5: T5?, value6: T6?, transform: (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5, value6: T6) -> R? ): R? { return if (value1 != null && value2 != null && value3 != null && value4 != null && value5 != null && value6 != null) { transform(value1, value2, value3, value4, value5, value6) } else { null } } inline fun <T1, T2, T3, T4, T5, T6, T7, R> nbNullSafe( value1: T1?, value2: T2?, value3: T3?, value4: T4?, value5: T5?, value6: T6?, value7: T7?, transform: (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5, value6: T6, value7: T7) -> R? ): R? { return if (value1 != null && value2 != null && value3 != null && value4 != null && value5 != null && value6 != null && value7 != null) { transform(value1, value2, value3, value4, value5, value6, value7) } else { null } } inline fun <T1, T2, T3, T4, T5, T6, T7, T8, R> nbNullSafe( value1: T1?, value2: T2?, value3: T3?, value4: T4?, value5: T5?, value6: T6?, value7: T7?, value8: T8?, transform: (value1: T1, value2: T2, value3: T3, value4: T4, value5: T5, value6: T6, value7: T7, value8: T8) -> R? ): R? { return if (value1 != null && value2 != null && value3 != null && value4 != null && value5 != null && value6 != null && value7 != null && value8 != null) { transform(value1, value2, value3, value4, value5, value6, value7, value8) } else { null } } inline fun <T1, R> nbNullSafeList( value1: List<T1>?, transform: (value1: List<T1>) -> R? ): R? { return nbNullSafe(value1) { v1 -> if (v1.isNotEmpty()) { transform(v1) } else { null } } } inline fun <T1, T2, R> nbNullSafeList( value1: List<T1>?, value2: List<T2>?, transform: (value1: List<T1>, value2: List<T2>) -> R? ): R? { return nbNullSafe(value1, value2) { v1, v2 -> if (v1.isNotEmpty() && v2.isNotEmpty()) { transform(v1, v2) } else { null } } }
12
Kotlin
0
1
3e3a93a177eda96ed158d7c2d842945737c4796a
3,770
NBWeather
MIT License
src/main/kotlin/algorithm/operator/MutateAddNode.kt
MikeDepies
776,556,570
false
{"Kotlin": 232231}
package algorithm.operator import algorithm.activation.ActivationFunctionSelection import algorithm.InnovationTracker import algorithm.weight.RandomWeight import genome.ConnectionGenome import genome.NetworkGenome import genome.NodeGenome import genome.NodeType import kotlin.random.Random interface MutateAddNodeOperator : GeneticOperator { val random: Random val innovationTracker: InnovationTracker val connectionInnovationTracker: InnovationTracker val activationFunctionSelection: ActivationFunctionSelection } class MutateAddNodeOperatorImpl( override val random: Random, override val innovationTracker: InnovationTracker, override val connectionInnovationTracker: InnovationTracker, override val activationFunctionSelection: ActivationFunctionSelection, val randomWeight: RandomWeight ) : MutateAddNodeOperator { override fun apply(genome: NetworkGenome): NetworkGenome { val enabledConnections = genome.connectionGenes.filter { it.enabled } if (enabledConnections.isEmpty()) return genome val randomConnectionIndex = random.nextInt(enabledConnections.size) val connectionToSplit = genome.connectionGenes[randomConnectionIndex] // Disable the old connection val disabledConnection = connectionToSplit.copy(enabled = false) // Create a new node val newNodeId = innovationTracker.getNextInnovationNumber() val newNode = NodeGenome(newNodeId, NodeType.HIDDEN, activationFunctionSelection.select(), randomWeight()) // Create two new connections val newConnection1 = ConnectionGenome( id = connectionInnovationTracker.getNextInnovationNumber(), inputNode = connectionToSplit.inputNode, outputNode = newNode, weight = 1.0, enabled = true ) val newConnection2 = ConnectionGenome( id = connectionInnovationTracker.getNextInnovationNumber(), inputNode = newNode, outputNode = connectionToSplit.outputNode, weight = connectionToSplit.weight, enabled = true ) // Update the genome val updatedNodeGenomes = genome.nodeGenomes + newNode val updatedConnectionGenes = genome.connectionGenes.map { if (it.id == connectionToSplit.id) disabledConnection else it } + newConnection1 + newConnection2 return genome.copy( nodeGenomes = updatedNodeGenomes, connectionGenes = updatedConnectionGenes, fitness = null, sharedFitness = null, speciesId = null ) } }
0
Kotlin
0
0
d576526cccc24a9db85ec9685c8864e23cd2b010
2,739
hyperNeatKotlin
MIT License
common/src/main/kotlin/net/spaceeye/vsource/rendering/types/BaseRenderer.kt
SuperSpaceEye
751,999,893
false
{"Kotlin": 275574, "Java": 6101}
package net.spaceeye.vmod.rendering.types import com.mojang.blaze3d.vertex.PoseStack import net.minecraft.client.Camera import net.spaceeye.vmod.networking.dataSynchronization.DataUnit import net.spaceeye.vmod.rendering.SynchronisedRenderingData import net.spaceeye.vmod.utils.Vector3d interface BaseRenderer: DataUnit { fun renderData(poseStack: PoseStack, camera: Camera) override fun hash(): ByteArray = SynchronisedRenderingData.hasher.digest(serialize().accessByteBufWithCorrectSize()) } interface PositionDependentRenderer: BaseRenderer { // if client is farther than rendering area, then it will not render val renderingArea: Double // position that will be used in calculation of whenever or not to render the object // doesn't need to be an actual position val renderingPosition: Vector3d } interface TimedRenderer: BaseRenderer { // timestamp of when it was started // if -1, then do not take beginning time into account, and always execute it var timestampOfBeginning: Long // time for how long it should be active // if timestampOfBeginning + activeFor_mc > current time, then it will not render on client val activeFor_ms: Long // a flag for internal use that should be set to false at the beginning var wasActivated: Boolean }
1
Kotlin
6
3
e27661640502092052496929f844e4555afbdb7e
1,306
VSource
MIT License
collections/core/src/commonMain/kotlin/presenters/collections/Column.kt
picortex
529,690,175
false
null
@file:JsExport @file:Suppress("NON_EXPORTABLE_TYPE") package presenters.collections import kotlin.js.JsExport @Deprecated("use symphony instead") sealed class Column<in D> { abstract val name: String abstract val key: String abstract val index: Int val number get() = index + 1 class Select( override val name: String, override val key: String, override val index: Int, ) : Column<Any?>() class Data<in D>( override val name: String, override val key: String, override val index: Int, val default: String, val accessor: (Row<D>) -> Any? ) : Column<D>() { fun resolve(row: Row<D>): String = accessor(row)?.toString() ?: default } class Action( override val name: String, override val key: String, override val index: Int ) : Column<Any?>() val asSelect get() = this as? Select val asData get() = this as? Data val asAction get() = this as? Action internal fun copy( name: String = this.name, index: Int = this.index ): Column<D> = when (this) { is Action -> Action(name, key, index) is Data -> Data(name, key, index, default, accessor) is Select -> Select(name, key, index) } override fun toString() = name override fun equals(other: Any?): Boolean = other is Column<Nothing> && other.name == name && other.key == key }
0
null
0
1
1e8b2a56e6c6513bc787c24c5f1c25700c3d62af
1,439
presenters
MIT License
analysis/analysis-api-fe10/tests/org/jetbrains/kotlin/analysis/api/descriptors/test/AbstractKtFe10ReferenceResolveTest.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.analysis.api.descriptors.test import org.jetbrains.kotlin.analysis.api.impl.base.test.AbstractReferenceResolveTest abstract class AbstractKtFe10ReferenceResolveTest : AbstractReferenceResolveTest(KtFe10FrontendApiTestConfiguratorService)
118
null
4857
39,693
3fb1096c18f2f1be82823ab7c997c8e6e9a8393b
478
kotlin
Apache License 2.0
server/src/main/kotlin/io/github/alessandrojean/tankobon/interfaces/api/rest/dto/UserDto.kt
alessandrojean
609,405,137
false
null
package io.github.alessandrojean.tankobon.interfaces.api.rest.dto import io.github.alessandrojean.tankobon.domain.model.TankobonUser import io.github.alessandrojean.tankobon.infrastructure.jooq.toUtcTimeZone import io.github.alessandrojean.tankobon.infrastructure.security.TankobonPrincipal import io.swagger.v3.oas.annotations.media.Schema import jakarta.validation.constraints.Email import jakarta.validation.constraints.NotBlank import jakarta.validation.constraints.NotNull import java.time.LocalDateTime data class UserEntityDto( override val id: String, override val attributes: UserAttributesDto, override var relationships: List<RelationDto>? = null, ) : EntityDto { @Schema(type = "string", allowableValues = ["USER"]) override val type = EntityType.USER } data class UserAttributesDto( val name: String, val biography: String = "", val email: String, val roles: Set<RoleDto> = emptySet(), val createdAt: LocalDateTime, ) : EntityAttributesDto() enum class RoleDto { ROLE_USER, ROLE_ADMIN } fun TankobonUser.toDto(avatarRelationship: RelationDto? = null) = UserEntityDto( id = id, attributes = toAttributesDto(), relationships = avatarRelationship?.let { listOf(it) }, ) fun TankobonUser.toAttributesDto() = UserAttributesDto( name = name, biography = biography, email = email, roles = roles.map { RoleDto.valueOf("ROLE_$it") }.toSet(), createdAt = createdAt.toUtcTimeZone(), ) fun TankobonPrincipal.toDto() = user.toDto() data class UserCreationDto( @get:NotBlank val name: String, @get:Email(regexp = ".+@.+\\..+") @get:Schema(format = "email") val email: String, @get:NotBlank @get:Schema(format = "password") val password: String, val roles: Set<RoleDto>, ) { fun toDomain(): TankobonUser = TankobonUser( email, password, isAdmin = roles.contains(RoleDto.ROLE_ADMIN), name, ) } data class PasswordUpdateDto( @get:NotBlank @Schema(format = "password") val password: String, ) data class UserUpdateDto( @get:NotBlank val name: String, @get:NotNull val biography: String = "", @get:Email(regexp = ".+@.+\\..+") @get:Schema(format = "email") val email: String, val roles: Set<RoleDto>, ) data class EmailAvailabilityDto(val isAvailable: Boolean)
0
Kotlin
0
1
cb28b68c0b6f3b1de7f77450122a609295396c28
2,255
tankobon
MIT License
generator/src/main/kotlin/ch/bailu/gtk/builder/AliasBuilder.kt
bailuk
404,475,468
false
null
package ch.bailu.gtk.builder import ch.bailu.gtk.NamespaceConfig import ch.bailu.gtk.converter.NamespaceType import ch.bailu.gtk.parser.tag.* import ch.bailu.gtk.table.AliasTable.add import ch.bailu.gtk.table.AliasTable.convert import ch.bailu.gtk.table.CallbackTable.add import ch.bailu.gtk.table.EnumTable.add import ch.bailu.gtk.table.NamespaceTable.add import ch.bailu.gtk.table.StructureTable.add class AliasBuilder : BuilderInterface{ private var namespace = "" override fun buildStructure(structure: StructureTag) { add(namespace, convert(namespace, structure.getName())) } private fun convert(namespace: String, name: String): String { return convert(NamespaceType(namespace, name)).name } override fun buildNamespaceStart(namespace: NamespaceTag, namespaceConfig: NamespaceConfig) { this.namespace = namespace.getName().lowercase() add(this.namespace, namespaceConfig) } override fun buildNamespaceEnd() {} override fun buildAlias(aliasTag: AliasTag) { add(namespace, aliasTag.getName(), aliasTag.getTypeName()) } override fun buildEnumeration(enumeration: EnumerationTag) { add(NamespaceType(namespace, enumeration.getName())) add(NamespaceType(namespace, enumeration.type)) } override fun buildCallback(callbackTag: CallbackTag) { add(namespace, callbackTag) } }
0
Kotlin
3
59
cb688585b79c9e401b32f5b8bfabb2e3717f517e
1,403
java-gtk
MIT License
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/auto/ForAndrew.kt
WHHSFTC
298,673,129
false
null
package org.firstinspires.ftc.teamcode.auto import android.transition.TransitionManager.go import com.acmerobotics.dashboard.config.Config import com.acmerobotics.roadrunner.geometry.Pose2d import com.acmerobotics.roadrunner.geometry.Vector2d import com.acmerobotics.roadrunner.trajectory.Trajectory import com.qualcomm.robotcore.eventloop.opmode.Autonomous import com.qualcomm.robotcore.eventloop.opmode.Disabled import kotlinx.coroutines.runBlocking import org.firstinspires.ftc.teamcode.cmd.* import org.firstinspires.ftc.teamcode.dsl.* import org.firstinspires.ftc.teamcode.module.* import org.firstinspires.ftc.teamcode.module.vision.PipelineRunner import org.firstinspires.ftc.teamcode.module.vision.RingPipeline import org.firstinspires.ftc.teamcode.module.vision.StackPipeline import kotlin.math.* @Disabled @Config @Autonomous(name = "Blue - High Goal 6 rings :((((") class ForAndrew: DslOpMode(mode = Mode.AUTO) { init { runBlocking {dsl { val start: Pose2d = Pose2d(Vector2d(-62.0, 15.5), 0.0) onInit { seq { +autoInit +cmd {dt.poseEstimate = start; StackPipeline.StackConstants.MIN_WIDTH = StackPipeline.StackConstants.FAR_MIN_WIDTH} } } val prepFull = CommandContext.seq {+setState(bot.out) { Shooter.State.FULL }} suspend fun autoBurst(t: Long): Command = CommandContext.seq { +cmd { telemetry.addData("aim", aim.motor.currentPosition) telemetry.update() } +cmd {feed.shoot()} +delayC(t) +cmd {feed.shoot()} +delayC(t) +cmd {feed.shoot()} +delayC(150) +setState(bot.feed.height) {Indexer.Height.IN} +delayC(500) +setState(bot.out) {Shooter.State.OFF} } val lineBurst = autoBurst(150) val slowBurst = autoBurst(750) val singleShot = CommandContext.seq { +cmd {feed.shoot()} +delayC(750) +setState(bot.feed.height) {Indexer.Height.IN} +delayC(500) +setState(bot.out) {Shooter.State.OFF} } val stackSet = CommandContext.seq { +setState(bot.feed.height) {Indexer.Height.POWER} +setState(bot.aim.height) {HeightController.Height.STACK} } val lineSet = CommandContext.seq { +setState(bot.feed.height) {Indexer.Height.HIGH} +setState(bot.aim.height) {HeightController.Height.HIGH} } val dropWob = CommandContext.seq { +setState(bot.wob.claw) { Wobble.ClawState.OPEN } +delayC(500) +setState(bot.wob.elbow) { Wobble.ElbowState.STORE } } val takeWob = CommandContext.seq { +setState(bot.wob.claw) { Wobble.ClawState.CLOSED } +delayC(500) } val linePose = Pose2d(0.0, 24.0, 0.0) val psPose = Pose2d(0.0, PS_Y, 0.0) val psBetween = 7.5 val psEndPose = psPose + Pose2d(0.0, 2 * psBetween, 0.0) val powerShots = CommandContext.seq { +cmd { feed.shoot() } +delayC(500) +go(psPose) { strafeLeft(psBetween) } +cmd { feed.shoot() } +delayC(500) +go(psPose + Pose2d(0.0, psBetween, 0.0)) { strafeLeft(psBetween) } +cmd { feed.shoot() } +delayC(500) } onRun { seq { //+cmd { vis!!.halt() } +switch({ vis!!.stack.height }, listOf( case({ StackPipeline.Height.ZERO }, CommandContext.seq { // shoot from line +prepFull +lineSet +go(start) { lineToConstantHeading(linePose.vec() + Vector2d(0.0, 4.0)) } +slowBurst // drop wobble at A +setState(bot.wob.elbow) { Wobble.ElbowState.DROP } +go(linePose + Pose2d(0.0, 4.0)) { splineTo(Vector2d(18.0, 50.0), PI/2.0) } +dropWob +go(Pose2d(18.0, 50.0, PI/2.0)) { lineToConstantHeading(Vector2d(18.0, 24.0)) } //+cmd {dt.turn(PI/2.0)} // intake wobble +go(Pose2d(18.0, 24.0, PI)) { addDisplacementMarker { bot.wob.elbow(Wobble.ElbowState.INTAKE) } splineToConstantHeading(Vector2d(-24.0, 52.0), Math.toRadians(180.0), constraintsOverride = DriveConstants.SLOW_CONSTRAINTS) splineToConstantHeading(Vector2d(-37.0, 54.0), Math.toRadians(90.0), constraintsOverride = DriveConstants.SLOW_CONSTRAINTS) } +takeWob // drop wobble 2 at A +go(Pose2d(-36.0, 59.0, PI)) { lineToLinearHeading(Pose2d(12.0, 44.0, PI/2.0)) } +dropWob +go(Pose2d(12.0, 44.0, PI/2.0)) { lineToLinearHeading(Pose2d(12.0, 24.0, 0.0)) } }), case({ StackPipeline.Height.ONE }, CommandContext.seq { // shoot from line +prepFull +lineSet +go(start) { lineToConstantHeading(linePose.vec()+Vector2d(0.0, 4.0) ) } +slowBurst // drop wobble at B +setState(bot.wob.elbow) { Wobble.ElbowState.DROP } +go(linePose + Pose2d(0.0, 4.0)) { lineToConstantHeading(Vector2d(26.0, 32.0)) } +dropWob +go(Pose2d(26.0, 32.0, )) { lineToConstantHeading(Vector2d(10.0, 36.0)) } //+cmd {dt.turn(PI)} +go(Pose2d(10.0, 36.0, 0.0)) { lineToLinearHeading(Pose2d(0.0, 12.0, PI/2.0)) } // intake +setState(bot.ink) { Intake.Power.IN } +go(Pose2d(0.0, 12.0, PI/2.0)) { splineTo(Vector2d(-24.0, 36.0), PI, constraintsOverride = DriveConstants.SLOW_CONSTRAINTS) addDisplacementMarker { bot.wob.elbow(Wobble.ElbowState.INTAKE) } splineToConstantHeading(Vector2d(-34.0, 48.0), Math.toRadians(180.0), constraintsOverride = DriveConstants.SLOW_CONSTRAINTS) splineToConstantHeading(Vector2d(-37.0, 59.0), Math.toRadians(90.0), constraintsOverride = DriveConstants.SLOW_CONSTRAINTS) } +setState(bot.ink) { Intake.Power.OFF } +setState(bot.feed.height) { Indexer.Height.HIGH } +takeWob // drop wobble 2 at B +go(Pose2d(-37.0, 59.0, 3.0 * PI / 2.0)) { lineToLinearHeading(Pose2d(18.0, 32.0, 0.0), constraintsOverride = DriveConstants.SLOW_CONSTRAINTS) } +dropWob +setState(bot.wob.elbow) {Wobble.ElbowState.DROP} +prepFull +lineSet +go(Pose2d(18.0, 32.0, 0.0)) { lineToConstantHeading(linePose.vec() - Vector2d(8.0)) } +slowBurst +setState(bot.wob.elbow) {Wobble.ElbowState.STORE} +go(linePose - Pose2d(8.0)) { //lineToConstantHeading(Vector2d(12.0, 24.0)) forward(18.0) } }), case({ StackPipeline.Height.FOUR }, CommandContext.seq { // shoot from line +prepFull +lineSet +go(start) { lineToConstantHeading(linePose.vec()+Vector2d(0.0, 4.0) ) } +slowBurst // drop wobble at C +setState(bot.wob.elbow) { Wobble.ElbowState.DROP } +go(linePose + Pose2d(0.0, 4.0)) { strafeTo(Vector2d(46.0, 44.0)) } +dropWob +go(Pose2d(46.0, 44.0)) { lineToConstantHeading(Vector2d(10.0, 36.0)) } //+cmd {dt.turn(PI)} +go(Pose2d(10.0, 36.0, 0.0)) { lineToLinearHeading(Pose2d(0.0, 12.0, PI/2.0)) } // intake +setState(bot.ink) { Intake.Power.IN } +go(Pose2d(0.0, 12.0, PI/2.0)) { splineTo(Vector2d(-24.0, 36.0), PI, constraintsOverride = DriveConstants.SLOW_CONSTRAINTS) addDisplacementMarker { bot.wob.elbow(Wobble.ElbowState.INTAKE) } splineToConstantHeading(Vector2d(-34.0, 48.0), Math.toRadians(180.0), constraintsOverride = DriveConstants.SLOW_CONSTRAINTS) splineToConstantHeading(Vector2d(-37.0, 59.0), Math.toRadians(90.0), constraintsOverride = DriveConstants.SLOW_CONSTRAINTS) } +setState(bot.ink) { Intake.Power.OFF } +setState(bot.feed.height) { Indexer.Height.HIGH } +takeWob // drop wobble 2 at C +go(Pose2d(-37.0, 59.0, 3.0 * PI / 2.0)) { lineToLinearHeading(Pose2d(18.0, 32.0, 0.0), constraintsOverride = DriveConstants.SLOW_CONSTRAINTS) } +go(Pose2d(-37.0, 58.0, 3.0*PI/2.0)) { splineTo(Vector2d(42.0, 36.0), PI/4.0) addDisplacementMarker { bot.wob.claw(Wobble.ClawState.OPEN) bot.wob.elbow(Wobble.ElbowState.CARRY) } splineToConstantHeading(Vector2d(12.0, 36.0), -PI/2.0) } +dropWob +setState(bot.wob.elbow) {Wobble.ElbowState.DROP} +prepFull +lineSet +go(Pose2d(18.0, 32.0, 0.0)) { lineToConstantHeading(linePose.vec() - Vector2d(8.0)) } +slowBurst +setState(bot.wob.elbow) {Wobble.ElbowState.STORE} +go(linePose - Pose2d(8.0)) { //lineToConstantHeading(Vector2d(12.0, 24.0)) forward(18.0) } }) )) } } onStop { seq { //+setState(bot.aim.height) { HeightController.Height.ZERO } +cmd { dt.powers = CustomMecanumDrive.Powers() //if (DEBUG) //dt.followTrajectory(dt.trajectoryBuilder(dt.poseEstimate).lineToSplineHeading(start).build()) } } } }} } companion object { @JvmField var PS_Y = -5.0 } }
1
Kotlin
1
5
e2297d983c7267ce6e5c30f330393ba2d47288bf
12,954
20-21_season
MIT License
lovebird-api/src/main/kotlin/com/lovebird/api/controller/couple/CoupleController.kt
wooda-ege
722,352,043
false
null
package com.lovebird.api.controller.couple import com.lovebird.api.dto.response.couple.CoupleCheckResponse import com.lovebird.api.service.couple.CoupleService import com.lovebird.common.annotation.AuthorizedUser import com.lovebird.common.response.ApiResponse import com.lovebird.domain.entity.User import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @RestController @RequestMapping("/api/v1/couple") class CoupleController( private val coupleService: CoupleService ) { @GetMapping("/check") fun checkCouple(@AuthorizedUser user: User): ApiResponse<CoupleCheckResponse> { return ApiResponse.success(CoupleCheckResponse(coupleService.existByUser(user))) } }
6
null
0
9
f35a7febafc19d34b8aa57063efe930bf0d162ab
797
lovebird-server
MIT License
ktor-core/src/org/jetbrains/ktor/host/CommandLine.kt
yiweig
54,407,957
true
{"Kotlin": 507115}
package org.jetbrains.ktor.host import com.typesafe.config.* import org.jetbrains.ktor.application.* import org.jetbrains.ktor.logging.* import java.io.* import java.net.* fun commandLineConfig(args: Array<String>): Pair<ApplicationHostConfig, ApplicationConfig> { val argsMap = args.mapNotNull { it.splitPair('=') }.toMap() val jar = argsMap["-jar"]?.let { File(it).toURI().toURL() } val argConfig = ConfigFactory.parseMap(argsMap.filterKeys { it.startsWith("-P:") }.mapKeys { it.key.removePrefix("-P:") }, "Command-line options") val combinedConfig = argConfig.withFallback(ConfigFactory.load()) val applicationIdPath = "ktor.application.id" val hostConfigPath = "ktor.deployment.host" val hostPortPath = "ktor.deployment.port" val applicationId = combinedConfig.tryGetString(applicationIdPath) ?: "Application" val log = SLF4JApplicationLog(applicationId) val classLoader = jar?.let { URLClassLoader(arrayOf(jar), ApplicationConfig::class.java.classLoader) } ?: ApplicationConfig::class.java.classLoader val appConfig = HoconApplicationConfig(combinedConfig, classLoader, log) log.info(combinedConfig.getObject("ktor").render()) val hostConfig = applicationHostConfig { (argsMap["-host"] ?: combinedConfig.tryGetString(hostConfigPath))?.let { host = it } (argsMap["-port"] ?: combinedConfig.tryGetString(hostPortPath))?.let { port = it.toInt() } } return hostConfig to appConfig } private fun String.splitPair(ch: Char): Pair<String, String>? = indexOf(ch).let { idx -> when (idx) { -1 -> null else -> Pair(take(idx), drop(idx + 1)) } }
0
Kotlin
0
0
9c6f99860b567d33ccc4984e7e5932d10f10872a
1,701
ktor
Apache License 2.0
idea/tests/test/org/jetbrains/kotlin/idea/structuralsearch/replace/KotlinSSRPropertyReplaceTest.kt
JetBrains
278,369,660
false
null
/* * Copyright 2000-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.idea.structuralsearch.replace import org.jetbrains.kotlin.idea.structuralsearch.KotlinSSRReplaceTest class KotlinSSRPropertyReplaceTest : KotlinSSRReplaceTest() { fun testPropertyValueReplaceExplicitType() { doTest( searchPattern = "val '_ID : String = '_INIT", replacePattern = "val '_ID = \"foo\"", match = "val foo: String = \"bar\"", result = "val foo: String = \"foo\"" ) } fun testPropertyValueReplaceExplicitTypeFormatCopy() { doTest( searchPattern = "val '_ID : String = '_INIT", replacePattern = "val '_ID = \"foo\"", match = "val foo : String = \"bar\"", result = "val foo : String = \"foo\"" ) } fun testPropertyNoInitializer() { doTest( searchPattern = "var '_ID : '_TYPE = '_INIT{0,1}", replacePattern = "var '_ID : '_TYPE = '_INIT", match = "var foo: String", result = "var foo : String" ) } fun testPropertyInitializer() { doTest( searchPattern = "'_ID()", replacePattern = "'_ID()", match = """ class Foo val foo = Foo() """.trimIndent(), result = """ class Foo val foo = Foo() """.trimIndent() ) } }
0
Kotlin
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
1,682
intellij-kotlin
Apache License 2.0
manifestk_xxpermissions/src/main/java/com/mozhimen/manifestk/xxpermissions/XXPermissionsNavHostUtil.kt
Sangan0
761,219,723
true
{"Java Properties": 2, "Gradle": 6, "Shell": 1, "Markdown": 4, "Batchfile": 1, "Text": 1, "Ignore List": 3, "Proguard": 4, "Kotlin": 8, "XML": 23, "YAML": 9, "INI": 2, "Java": 39}
package com.mozhimen.manifestk.xxpermissions import android.annotation.SuppressLint import android.content.Context import androidx.annotation.RequiresPermission import com.mozhimen.basick.lintk.optins.permission.OPermission_MANAGE_EXTERNAL_STORAGE import com.mozhimen.basick.manifestk.cons.CPermission import com.mozhimen.basick.utilk.android.app.UtilKLaunchActivity /** * @ClassName XXPermissionNavHostUtil * @Description TODO * @Author Mozhimen & <NAME> * @Date 2024/1/22 * @Version 1.0 */ object XXPermissionsNavHostUtil { //去设置页面详情页 @OPermission_MANAGE_EXTERNAL_STORAGE @RequiresPermission(CPermission.MANAGE_EXTERNAL_STORAGE) @JvmStatic fun startSettingManageStorage(context: Context) { UtilKLaunchActivity.startManageAllFilesAccess(context) } //去设置未知源页 @JvmStatic fun startSettingInstall(context: Context) { UtilKLaunchActivity.startManageUnknownInstallSource(context) } @JvmStatic fun startSettingNotification(context: Context) { UtilKLaunchActivity.startAppNotificationSettings(context) } }
0
null
0
0
a6b287370f6e9080f20365028a0fc6886c708d3c
1,086
AManifestKit_XXPermissions
Apache License 2.0
packages/SystemUI/src/com/android/systemui/media/controls/models/player/MediaData.kt
liu-wanshun
595,904,109
true
null
/* * Copyright (C) 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License */ package com.android.systemui.media.controls.models.player import android.app.PendingIntent import android.graphics.drawable.Drawable import android.graphics.drawable.Icon import android.media.session.MediaSession import com.android.internal.logging.InstanceId import com.android.systemui.R /** State of a media view. */ data class MediaData( val userId: Int, val initialized: Boolean = false, /** App name that will be displayed on the player. */ val app: String?, /** App icon shown on player. */ val appIcon: Icon?, /** Artist name. */ val artist: CharSequence?, /** Song name. */ val song: CharSequence?, /** Album artwork. */ val artwork: Icon?, /** List of generic action buttons for the media player, based on notification actions */ val actions: List<MediaAction>, /** Same as above, but shown on smaller versions of the player, like in QQS or keyguard. */ val actionsToShowInCompact: List<Int>, /** * Semantic actions buttons, based on the PlaybackState of the media session. If present, these * actions will be preferred in the UI over [actions] */ val semanticActions: MediaButton? = null, /** Package name of the app that's posting the media. */ val packageName: String, /** Unique media session identifier. */ val token: MediaSession.Token?, /** Action to perform when the player is tapped. This is unrelated to {@link #actions}. */ val clickIntent: PendingIntent?, /** Where the media is playing: phone, headphones, ear buds, remote session. */ val device: MediaDeviceData?, /** * When active, a player will be displayed on keyguard and quick-quick settings. This is * unrelated to the stream being playing or not, a player will not be active if timed out, or in * resumption mode. */ var active: Boolean, /** Action that should be performed to restart a non active session. */ var resumeAction: Runnable?, /** Playback location: one of PLAYBACK_LOCAL, PLAYBACK_CAST_LOCAL, or PLAYBACK_CAST_REMOTE */ var playbackLocation: Int = PLAYBACK_LOCAL, /** * Indicates that this player is a resumption player (ie. It only shows a play actions which * will start the app and start playing). */ var resumption: Boolean = false, /** * Notification key for cancelling a media player after a timeout (when not using resumption.) */ val notificationKey: String? = null, var hasCheckedForResume: Boolean = false, /** If apps do not report PlaybackState, set as null to imply 'undetermined' */ val isPlaying: Boolean? = null, /** Set from the notification and used as fallback when PlaybackState cannot be determined */ val isClearable: Boolean = true, /** Timestamp when this player was last active. */ var lastActive: Long = 0L, /** Instance ID for logging purposes */ val instanceId: InstanceId, /** The UID of the app, used for logging */ val appUid: Int ) { companion object { /** Media is playing on the local device */ const val PLAYBACK_LOCAL = 0 /** Media is cast but originated on the local device */ const val PLAYBACK_CAST_LOCAL = 1 /** Media is from a remote cast notification */ const val PLAYBACK_CAST_REMOTE = 2 } fun isLocalSession(): Boolean { return playbackLocation == PLAYBACK_LOCAL } } /** Contains [MediaAction] objects which represent specific buttons in the UI */ data class MediaButton( /** Play/pause button */ val playOrPause: MediaAction? = null, /** Next button, or custom action */ val nextOrCustom: MediaAction? = null, /** Previous button, or custom action */ val prevOrCustom: MediaAction? = null, /** First custom action space */ val custom0: MediaAction? = null, /** Second custom action space */ val custom1: MediaAction? = null, /** Whether to reserve the empty space when the nextOrCustom is null */ val reserveNext: Boolean = false, /** Whether to reserve the empty space when the prevOrCustom is null */ val reservePrev: Boolean = false ) { fun getActionById(id: Int): MediaAction? { return when (id) { R.id.actionPlayPause -> playOrPause R.id.actionNext -> nextOrCustom R.id.actionPrev -> prevOrCustom R.id.action0 -> custom0 R.id.action1 -> custom1 else -> null } } } /** State of a media action. */ data class MediaAction( val icon: Drawable?, val action: Runnable?, val contentDescription: CharSequence?, val background: Drawable?, // Rebind Id is used to detect identical rebinds and ignore them. It is intended // to prevent continuously looping animations from restarting due to the arrival // of repeated media notifications that are visually identical. val rebindId: Int? = null ) /** State of the media device. */ data class MediaDeviceData @JvmOverloads constructor( /** Whether or not to enable the chip */ val enabled: Boolean, /** Device icon to show in the chip */ val icon: Drawable?, /** Device display name */ val name: CharSequence?, /** Optional intent to override the default output switcher for this control */ val intent: PendingIntent? = null, /** Unique id for this device */ val id: String? = null, /** Whether or not to show the broadcast button */ val showBroadcastButton: Boolean ) { /** * Check whether [MediaDeviceData] objects are equal in all fields except the icon. The icon is * ignored because it can change by reference frequently depending on the device type's * implementation, but this is not usually relevant unless other info has changed */ fun equalsWithoutIcon(other: MediaDeviceData?): Boolean { if (other == null) { return false } return enabled == other.enabled && name == other.name && intent == other.intent && id == other.id && showBroadcastButton == other.showBroadcastButton } }
0
Java
1
2
e99201cd9b6a123b16c30cce427a2dc31bb2f501
6,775
platform_frameworks_base
Apache License 2.0
kokain-core-lib/src/main/java/com/schwarz/kokain/corelib/scope/Lockable.kt
SchwarzIT
247,762,834
false
{"Gradle": 11, "INI": 3, "Shell": 1, "Text": 1, "Ignore List": 10, "Batchfile": 1, "YAML": 2, "Markdown": 1, "Kotlin": 65, "Java Properties": 1, "Proguard": 4, "XML": 15, "CODEOWNERS": 1, "Java": 6}
package com.schwarz.kokain.corelib.scope interface Lockable { fun lock() fun unlock() }
1
null
1
1
fb7ffd27d33c7535fa60da0a3a1e64b0eb90dc00
97
kokain
MIT License
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/broken/Shieldsearch.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.broken import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import moe.tlaster.icons.vuesax.vuesaxicons.BrokenGroup public val BrokenGroup.Shieldsearch: ImageVector get() { if (_shieldsearch != null) { return _shieldsearch!! } _shieldsearch = Builder(name = "Shieldsearch", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(3.4102f, 11.02f) verticalLineTo(14.56f) curveTo(3.4102f, 15.74f, 4.1902f, 17.29f, 5.1402f, 18.0f) lineTo(9.4402f, 21.21f) curveTo(10.1402f, 21.74f, 11.0702f, 22.0f, 12.0002f, 22.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.5902f, 10.5501f) verticalLineTo(7.1201f) curveTo(20.5902f, 5.8901f, 19.6502f, 4.5301f, 18.5002f, 4.1001f) lineTo(13.5102f, 2.2301f) curveTo(12.6802f, 1.9201f, 11.3202f, 1.9201f, 10.4902f, 2.2301f) lineTo(5.5002f, 4.1101f) curveTo(4.3502f, 4.5401f, 3.4102f, 5.9001f, 3.4102f, 7.1201f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.0f, 16.0f) curveTo(20.0f, 18.21f, 18.21f, 20.0f, 16.0f, 20.0f) curveTo(13.79f, 20.0f, 12.0f, 18.21f, 12.0f, 16.0f) curveTo(12.0f, 15.27f, 12.19f, 14.59f, 12.53f, 14.01f) curveTo(13.22f, 12.81f, 14.51f, 12.01f, 15.99f, 12.01f) curveTo(16.6f, 12.01f, 17.17f, 12.15f, 17.69f, 12.39f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(20.9955f, 21.0f) horizontalLineTo(21.0045f) } } .build() return _shieldsearch!! } private var _shieldsearch: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
3,410
VuesaxIcons
MIT License
src/jsMain/kotlin/io/github/aerialist7/showcase/ShowcaseMaterial.kt
aerialist7
388,885,791
false
{"Kotlin": 85864, "JavaScript": 1111, "HTML": 515, "CSS": 160}
package io.github.aerialist7.showcase import react.FC import react.Props import react.router.useLoaderData val ShowcaseMaterial = FC<Props> { val ShowcaseComponent = useLoaderData() .unsafeCast<Showcase>() .Component ShowcaseComponent() }
0
Kotlin
13
88
5a56f30a72f0ea700f9485972c0ebebbdded3ebc
266
kotlin-mui-showcase
Apache License 2.0
backend/src/test/kotlin/app/ehrenamtskarte/backend/helper/TestAdministrators.kt
digitalfabrik
310,244,313
false
{"TypeScript": 580721, "Kotlin": 477234, "Dart": 326932, "Ruby": 17252, "Swift": 17185, "PLpgSQL": 4734, "Shell": 4442, "HTML": 4050, "JavaScript": 2376, "Java": 1039, "CSS": 433, "Objective-C": 38}
package app.ehrenamtskarte.backend.helper import app.ehrenamtskarte.backend.auth.database.repos.AdministratorsRepository import app.ehrenamtskarte.backend.auth.webservice.JwtService import app.ehrenamtskarte.backend.auth.webservice.schema.types.Administrator import app.ehrenamtskarte.backend.auth.webservice.schema.types.Role import org.jetbrains.exposed.sql.transactions.transaction enum class TestAdministrators( val project: String, val email: String, val password: String = "<PASSWORD>!", val role: Role, val regionId: Int? = null ) { EAK_REGION_ADMIN( project = "bayern.ehrenamtskarte.app", email = "<EMAIL>", role = Role.REGION_ADMIN, regionId = 16 ), EAK_PROJECT_ADMIN( project = "bayern.ehrenamtskarte.app", email = "<EMAIL>", role = Role.PROJECT_ADMIN ); fun getJwtToken(): String { val adminEntity = transaction { AdministratorsRepository.findByAuthData(project, email, password) ?: AdministratorsRepository.insert(project, email, password, role, regionId) } val admin = Administrator.fromDbEntity(adminEntity) return JwtService.createToken(admin) } }
125
TypeScript
3
36
f752386204f4a3f93c1c2aa08a0012ddb40120df
1,226
entitlementcard
MIT License
remotedatasource/src/main/java/io/melih/android/currencyconverter/remotedatasource/retrofit/CurrencyRetrofitDataSource.kt
melomg
282,532,575
false
null
/* * Copyright 2019 CurrencyConverter * * 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.melih.android.currencyconverter.remotedatasource.retrofit import io.melih.android.currencyconverter.core.model.Currency import io.melih.android.currencyconverter.core.model.Result import io.melih.android.currencyconverter.remotedatasource.CurrencyRemoteDataSource import io.melih.android.currencyconverter.remotedatasource.safeApiCall import java.io.IOException import java.math.BigDecimal import javax.inject.Inject import javax.inject.Singleton private const val UNKNOWN_ERROR = "Error fetching latest currency rates" @Singleton class CurrencyRetrofitDataSource @Inject constructor(private val api: CurrencyApi) : CurrencyRemoteDataSource { override suspend fun getLatestCurrencyRateList(): Result<List<Currency>> = safeApiCall( call = { requestLatestCurrencyRateList() }, errorMessage = UNKNOWN_ERROR ) private suspend fun requestLatestCurrencyRateList(): Result<List<Currency>> { val response = api.getLatestCurrencyRateListAsync().await() val ratesMap = response.ratesMap if (ratesMap.isNotEmpty()) { val currencyList = arrayListOf<Currency>() currencyList.add(Currency(response.baseCurrency, BigDecimal.ONE)) currencyList.addAll(ratesMap.map { Currency(it.key, it.value) }) return Result.Success(currencyList) } return Result.Error(IOException(UNKNOWN_ERROR)) } }
1
Kotlin
0
0
5d94b9ce0a141403082a9157b4df19787f455bf2
2,011
currency-converter-android
Apache License 2.0
app/src/main/java/com/onoffrice/marvel_comics/ui/characterDetail/CharacterDetailViewModel.kt
LucasOnofre
246,949,422
false
null
package com.onoffrice.marvel_comics.ui.characterDetail import android.os.Bundle import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.onoffrice.marvel_comics.Constants import com.onoffrice.marvel_comics.data.remote.model.Character import com.onoffrice.marvel_comics.data.remote.model.ComicModel import com.onoffrice.marvel_comics.data.remote.model.Price import com.onoffrice.marvel_comics.data.repositories.CharactersRepository import com.onoffrice.marvel_comics.utils.SingleLiveEvent import com.onoffrice.marvel_comics.utils.extensions.singleSubscribe import io.reactivex.disposables.CompositeDisposable class CharacterDetailViewModel(private val repository: CharactersRepository) : ViewModel() { private val comicPrices: MutableList<ComicModel> = mutableListOf() val comic = SingleLiveEvent<ComicModel>() val character = SingleLiveEvent<Character>() val errorEvent = SingleLiveEvent<String>() val loadingEvent = SingleLiveEvent<Boolean>() private val disposable = CompositeDisposable() fun getExtras(extras: Bundle?){ character.value = extras?.getSerializable(Constants.EXTRA_CHARACTER_DETAIL) as Character } fun getCharacterComics() { character.value?.id?.let { characterId -> disposable.add(repository.getCharacterComics(characterId).singleSubscribe( onLoading = { loadingEvent.value = it }, onSuccess = { handleCharacterComicsResponse(it.characterComicsData.comics) }, onError = { errorEvent.value = it.message } )) } } private fun handleCharacterComicsResponse(comics: List<ComicModel>) { comic.value = comics[0] } override fun onCleared() { disposable.dispose() super.onCleared() } }
0
Kotlin
0
2
48a352905df791baddd7d2c0313409b948502e98
1,933
Marvel-Comics
MIT License
window/window/src/main/java/androidx/window/WindowProperties.kt
DSteve595
344,295,851
true
{"Kotlin": 60951265, "Java": 55056375, "C++": 9010832, "Python": 277595, "AIDL": 252157, "Shell": 168504, "ANTLR": 19860, "HTML": 19215, "CMake": 12007, "TypeScript": 7599, "C": 4764, "Swift": 3159, "JavaScript": 1343}
/* * Copyright 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.window /** * Window related [android.content.pm.PackageManager.Property] tags for developers to define in app * AndroidManifest. */ object WindowProperties { /** * Application level [android.content.pm.PackageManager.Property] tag for developers to * provide consent for their app to allow OEMs to manually provide ActivityEmbedding split * rule configuration on behalf of the app. * <p>If `true`, the system can override the windowing behaviors for the app, such as * showing some activities side-by-side. In this case, it will report that ActivityEmbedding * APIs are disabled for the app to avoid conflict. * <p>If `false`, the system can't override the window behavior for the app. It should * be used if the app wants to provide their own ActivityEmbedding split rules, or if the * app wants to opt-out of system overrides for any other reason. * <p>Default is `false`. * <p>The system enforcement is added in Android 14, but some devices may start following the * requirement before that. The best practice for apps is to always explicitly set this * property in AndroidManifest instead of relying on the default value. * <p>Example usage: * <pre> * &lt;application&gt; * &lt;property * android:name="android.window.PROPERTY_ACTIVITY_EMBEDDING_ALLOW_SYSTEM_OVERRIDE" * android:value="true|false"/&gt; * &lt;/application&gt; * </pre> */ const val PROPERTY_ACTIVITY_EMBEDDING_ALLOW_SYSTEM_OVERRIDE = "android.window.PROPERTY_ACTIVITY_EMBEDDING_ALLOW_SYSTEM_OVERRIDE" }
0
Kotlin
0
0
289d7e347f7734afe27751f9fa2abf723c488200
2,246
androidx
Apache License 2.0
chat-deploy-redis/src/main/kotlin/com/demo/chat/deploy/redis/App.kt
marios-code-path
181,180,043
false
{"Kotlin": 924762, "Shell": 36602, "C": 3160, "HTML": 2714, "Starlark": 278}
package com.demo.chat.deploy.redis class App { }
2
Kotlin
1
9
2ae59375cd44e8fb58093b0f24596fc3111fd447
50
demo-chat
MIT License
app/src/main/java/com/brentpanther/newsapi/sample/article/ArticleFragment.kt
revinur
193,823,184
true
{"Kotlin": 30856}
package com.brentpanther.newsapi.sample.article import android.arch.lifecycle.ViewModelProviders import android.os.Bundle /** * Fragment to show a list of articles from a list of sources */ class ArticleFragment : BaseArticleFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) viewModel = ViewModelProviders.of(this).get(ArticleListViewModel::class.java) arguments?.apply { viewModel?.initializeTop(getString("section", ""), sources = getString("sources")) } } companion object { fun newInstance(section: String, sources: String? = null) : ArticleFragment { val articleFragment = ArticleFragment() with (Bundle()) { putString("sources", sources) putString("section", section) articleFragment.arguments = this } return articleFragment } } }
0
Kotlin
0
0
775643b262e8de65858e53ec6d6a4bf3b3946d73
968
NewsAPISample
MIT License
ERMSEmployee/src/main/java/com/kust/ermsemployee/ui/employee/EmployeeListingFragment.kt
sabghat90
591,653,827
false
{"Kotlin": 583902, "HTML": 87217}
package com.kust.ermsemployee.ui.employee import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.lifecycleScope import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import com.kust.ermsemployee.R import com.kust.ermsemployee.databinding.FragmentEmployeeListingBinding import com.kust.ermslibrary.utils.UiState import com.kust.ermslibrary.utils.hide import com.kust.ermslibrary.utils.toast import dagger.hilt.android.AndroidEntryPoint import kotlinx.coroutines.launch @AndroidEntryPoint class EmployeeListingFragment : Fragment() { private var _binding: FragmentEmployeeListingBinding? = null private val binding get() = _binding!! private val employeeViewModel: EmployeeViewModel by viewModels() private val adapter by lazy { EmployeeListingAdapter( requireContext(), onItemClicked = { _, employee -> val bundle = Bundle() bundle.putParcelable("employee", employee) findNavController().navigate( R.id.action_employeeListingFragment_to_employeeProfileFragment, bundle ) } ) } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment _binding = FragmentEmployeeListingBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) observer() lifecycleScope.launch { employeeViewModel.getEmployeeList() } binding.rvEmployeeList.layoutManager = LinearLayoutManager(requireContext()) binding.rvEmployeeList.adapter = adapter } private fun observer() { employeeViewModel.getEmployeeList.observe(viewLifecycleOwner) { when (it) { is UiState.Loading -> { binding.shimmerLayout.startShimmer() } is UiState.Success -> { binding.shimmerLayout.stopShimmer() binding.shimmerLayout.visibility = View.GONE binding.rvEmployeeList.visibility = View.VISIBLE adapter.submitList(it.data) } is UiState.Error -> { binding.shimmerLayout.stopShimmer() binding.shimmerLayout.hide() binding.rvEmployeeList.hide() toast(it.error) } } } } override fun onDestroyView() { super.onDestroyView() _binding = null } }
1
Kotlin
0
2
56497f553ddcbbe2bdbafb987caa40cb44d552e8
2,975
ERMS
MIT License
kueski/data/movie/src/androidUnitTest/kotlin/MovieRepositoryTest.kt
kiquenet85
849,346,240
false
{"Kotlin": 183158, "Swift": 621}
import app.cash.turbine.test import co.nestor.coroutine.dispatcher.IDispatcherProvider import co.nestor.database.dao.movie.FavoriteDao import co.nestor.database.dao.movie.NowPlayingDao import co.nestor.database.dao.movie.PopularDao import co.nestor.database.dao.movie.gender.GenreDao import co.nestor.database.entity.movie.FavoriteMovie import co.nestor.error.Result import co.nestor.movie.dto.gender.GenreDto import co.nestor.movie.dto.gender.GenreResponseDto import co.nestor.movie.dto.movies.MovieDto import co.nestor.movie.dto.movies.MovieResponseDto import co.nestor.movie.dto.movies.SortBy import co.nestor.movie.repositories.MovieRepository import co.nestor.movie.services.gender.IGenreService import co.nestor.movie.services.movies.IMoviesService import io.mockk.coEvery import io.mockk.every import io.mockk.mockk import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.TestResult import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import kotlinx.datetime.LocalDate import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertTrue class MovieRepositoryTest { private val moviesService: IMoviesService = mockk() private val genreService: IGenreService = mockk() private val popularDao: PopularDao = mockk() private val favoriteDao: FavoriteDao = mockk() private val nowPlayingDao: NowPlayingDao = mockk() private val dispatcherProvider: IDispatcherProvider = mockk() private val genreDao: GenreDao = mockk() private lateinit var repository: MovieRepository @OptIn(ExperimentalCoroutinesApi::class) @BeforeTest fun setUp() { repository = MovieRepository( moviesService = moviesService, genreService = genreService, popularDao = popularDao, favoriteDao = favoriteDao, nowPlayingDao = nowPlayingDao, genreDao = genreDao, dispatcherProvider = dispatcherProvider ) every { dispatcherProvider.getIO() } returns UnconfinedTestDispatcher() } @Test fun `getPopularMovies returns a Flow of PagingData of PopularMovie`() = runTest { // Given val sortBy = SortBy.TITLE_ASC val moviesDto = MovieResponseDto( results = listOf( MovieDto( id = 1, title = "Popular Movie", overview = "Overview", releaseDate ="2021-01-01", voteAverage = 5f, popularity = 5f, genreIds = listOf(1, 2), isForAdult = false, backdropPath = "https://image.com", originalLanguage = "en", originalTitle = "Popular Movie", posterPath = "https://image.com", video = false, voteCount = 5 ) ) ) coEvery { moviesService.getMovies( page = any(), sortBy = sortBy.value ) } returns flowOf(Result.Success(moviesDto)) coEvery { popularDao.deleteAll() } returns Unit coEvery { popularDao.insertPopular(any()) } returns Unit // When // Then } @Test fun `getFavoriteMovies should return favorite movies`(): TestResult = runTest { // Given val favoriteMovies = listOf( FAVORITE_MOVIE ) coEvery { favoriteDao.getFavoriteMovies() } returns favoriteMovies // When val resultFlow = repository.getFavoriteMovies() // Then resultFlow.test { val movies = awaitItem() assertTrue { movies.size == 1 } assertTrue { movies[0].title == FAVORITE_MOVIE.title } awaitComplete() } } @Test fun `getFavoriteMovies should return a list of favorite movies`() = runTest { // Given val favoriteMovies = listOf( FAVORITE_MOVIE ) coEvery { favoriteDao.getFavoriteMovies() } returns favoriteMovies // When val resultFlow = repository.getFavoriteMovies() // Then resultFlow.test { val result = awaitItem() assertTrue { result.size == 1 } assertTrue { result[0].title == FAVORITE_MOVIE.title } awaitComplete() } } @Test fun `addFavoriteMovie should insert a favorite movie into the database`() = runTest { // Given coEvery { favoriteDao.insertFavorite(FAVORITE_MOVIE) } returns Unit // When repository.addFavoriteMovie(FAVORITE_MOVIE) // Then coEvery { favoriteDao.insertFavorite(FAVORITE_MOVIE) } } @Test fun `removeFavoriteMovie should delete a favorite movie from the database`() = runTest { // Given coEvery { favoriteDao.deleteFavorite(FAVORITE_MOVIE) } returns Unit // When repository.removeFavoriteMovie(FAVORITE_MOVIE) // Then coEvery { favoriteDao.deleteFavorite(FAVORITE_MOVIE) } } @Test fun `getGenre should return a list of genres`() = runTest { // Given val genres = GenreResponseDto( genres = listOf( GenreDto( id = 1, name = "Action" ) ) ) coEvery { genreService.getGenre() } returns flowOf(Result.Success(genres)) coEvery { genreDao.getGenre() } returns listOf() coEvery { genreDao.insertGenre(any()) } returns Unit // When val resultFlow = repository.getGenre() // Then resultFlow.test { awaitItem() val result = awaitItem() assertTrue { result.size == 1 } assertTrue { result[0].name == "Action" } awaitComplete() } } companion object { val FAVORITE_MOVIE = FavoriteMovie( id = 1, title = "Favorite Movie", genresIds = listOf(1, 2), overview = "Overview", releaseDate = LocalDate(2021, 1, 1), voteAverage = 5f, popularity = 5f, backdropImageUrl = "https://image.com", posterImageUrl = "https://image.com", language = "en", ) } }
0
Kotlin
0
0
2f000a653ddbb56f7439df4185e944fd76df6061
6,705
kueski
Apache License 2.0
app/src/main/java/dev/borisochieng/gitrack/data/models/AccessTokenResponse.kt
slowburn-404
777,819,284
false
{"Kotlin": 71653}
package dev.borisochieng.gitrack.data.models import com.google.gson.annotations.SerializedName data class AccessTokenResponse( @SerializedName("access_token") val accessToken: String )
0
Kotlin
0
1
2681b07ced3b0383e1cd94ca61ec723fd624f4e2
191
GiTrack
MIT License
src/main/kotlin/org/overrun/ktgl/model/IMesh.kt
Over-Run
518,871,751
false
null
package org.overrun.ktgl.model import org.overrun.ktgl.gl.GLDrawMode /** * @author squid233 * @since 0.1.0 */ data class Vector2( val x: Float = 0f, val y: Float = 0f ) /** * @author squid233 * @since 0.1.0 */ data class Vector3( val x: Float = 0f, val y: Float = 0f, val z: Float = 0f ) /** * @author squid233 * @since 0.1.0 */ data class Vector4( val x: Float = 0f, val y: Float = 0f, val z: Float = 0f, val w: Float = 0f ) /** * @author squid233 * @since 0.1.0 */ data class Vertex( val vertex: Vector3 = Vector3(), val color0: Vector4? = null, val texCoord0: Vector3? = null, val normal: Vector3? = null ) /** * Similar to [Vertex] but mutable. * * @author squid233 * @since 0.1.0 */ data class MutableVertex( var vertex: Vector3 = Vector3(), var color0: Vector4? = null, var texCoord0: Vector3? = null, var normal: Vector3? = null ) { fun toImmutable() = Vertex(vertex, color0, texCoord0, normal) } /** * @author squid233 * @since 0.1.0 */ interface IMesh { fun render(mode: GLDrawMode) fun getVertices(): List<Vertex> fun getLayout(): VertexLayout }
0
Kotlin
0
1
f434cd5d0e9cf428621be88b93d55cef78c26b95
1,167
ktgl
MIT License
okpermission/src/main/java/com/kelin/okpermission/applicant/PermissionsApplicant.kt
kelinZhou
196,686,266
false
null
package com.kelin.okpermission.applicant import android.app.Activity import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.os.Bundle import android.util.SparseArray import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentActivity import androidx.fragment.app.FragmentManager import com.kelin.okpermission.OkActivityResult import com.kelin.okpermission.OkPermission import com.kelin.okpermission.Renewable import com.kelin.okpermission.applicant.intentgenerator.AppDetailIntentGenerator import com.kelin.okpermission.applicant.intentgenerator.SettingIntentGenerator import com.kelin.okpermission.permission.Permission import com.kelin.okpermission.router.BasicRouter import com.kelin.okpermission.router.PermissionRequestRouter import com.kelin.okpermission.router.SupportBasicRouter /** * **描述:** 权限申请器。 * * **创建人:** kelin * * **创建时间:** 2019-08-15 15:12 * * **版本:** v 1.0.0 */ abstract class PermissionsApplicant(private val target: Any) { private val permissionList: MutableList<Permission> = ArrayList() protected val activity: Activity get() = OkPermission.getActivityByTarget(target) protected val applicationContext: Context get() = activity.applicationContext internal lateinit var intentGenerator: SettingIntentGenerator internal var isGranted: Boolean = true internal val deniedPermissions = ArrayList<Permission>() internal var missingPermissionDialogInterceptor: ((renewable: Renewable) -> Unit)? = null private val permissions: Array<out Permission> get() = permissionList.toTypedArray() internal val checkDeniedPermissions: List<Permission> get() = permissionList.filter { !checkSelfPermission(it) } /** * 检测是否已经拥有权限。 */ protected abstract fun checkSelfPermission(permission: Permission): Boolean /** * 判断用户是否勾选了禁止后不再询问。 */ protected abstract fun shouldShowRequestPermissionRationale( router: PermissionRequestRouter, permission: Permission ): Boolean protected abstract fun requestPermissions( router: PermissionRequestRouter, permissions: Array<out Permission>, onResult: (permissions: Array<out Permission>) -> Unit ) internal fun addPermission(permission: Permission) { permissionList.add(permission) } internal fun applyPermission( applyPermissions: Array<out Permission> = permissions, finished: () -> Unit ) { if (applyPermissions.all { checkSelfPermission(it) }) { finished() } else { onRequestPermissions(applyPermissions, finished) } } private fun applyPermissionAgain( applyPermissions: Array<out Permission> = permissions, finished: () -> Unit ) { var needCheck = true val router = getRouter(activity) val deniedPermissions = ArrayList<Permission>() val canRequestPermissions = ArrayList<Permission>() for (permission in applyPermissions) { val granted = checkSelfPermission(permission) if (!granted) { isGranted = false if (!permission.isWeak) { if (shouldShowRequestPermissionRationale(router, permission)) { canRequestPermissions.add(permission) } else { deniedPermissions.add(permission) } } } } if (canRequestPermissions.isEmpty() && deniedPermissions.isNotEmpty()) { needCheck = false showMissingPermissionDialog(applyPermissions, finished) } if (needCheck) { if (isGranted) { isGranted = true finished() } else { onRequestPermissions(applyPermissions, finished) } } } private fun onRequestPermissions( applyPermissions: Array<out Permission>, finished: () -> Unit ) { val router = getRouter(activity) requestPermissions(router, applyPermissions) { deniedPermissions -> when { //如果用户已经同意了全部权限 deniedPermissions.isEmpty() -> { isGranted = true finished() } //如果全部都是弱申请 deniedPermissions.all { it.isWeak } -> continueRequest( false, deniedPermissions, finished ) //如果有可继续申请的权限 deniedPermissions.any { !it.isWeak && shouldShowRequestPermissionRationale(router, it) } -> { val haveNecessary = deniedPermissions.any { it.necessary } continueRequest( haveNecessary, if (haveNecessary) filterWeak(deniedPermissions) else deniedPermissions, finished ) } //显示设置引导页面。 else -> showMissingPermissionDialog(deniedPermissions, finished) } } } private fun continueRequest( isContinue: Boolean, deniedPermissions: Array<out Permission>, finished: () -> Unit ) { if (isContinue) { applyPermissionAgain(deniedPermissions, finished) } else { isGranted = if (permissionList.any { it.necessary }) !deniedPermissions.any { it.necessary } else deniedPermissions.isEmpty() this.deniedPermissions.addAll(deniedPermissions) finished() } } private fun showMissingPermissionDialog( deniedPermissions: Array<out Permission>, finished: () -> Unit ) { if (missingPermissionDialogInterceptor != null) { missingPermissionDialogInterceptor!!.invoke(object : Renewable { override fun continueWorking(isContinue: Boolean) { onContinueWorking(isContinue, deniedPermissions, finished) } }) } else { AlertDialog.Builder(activity) .setCancelable(false) .setTitle("帮助") .setMessage("当前操作缺少必要权限。\n请点击\"设置\"-\"权限\"-打开所需权限。\n最后点击两次后退按钮,即可返回。") .setNegativeButton("退出") { _, _ -> onContinueWorking(false, deniedPermissions, finished) } .setPositiveButton("设置") { _, _ -> onContinueWorking(true, deniedPermissions, finished) }.show() } } private fun onContinueWorking( isContinue: Boolean, deniedPermissions: Array<out Permission>, finished: () -> Unit ) { if (isContinue) { OkActivityResult.startActivityOrException( activity, intentGenerator.generatorIntent(activity) ) { _, e -> if (e == null) { applyPermissionAgain( filterWeak(deniedPermissions), finished ) } else { OkActivityResult.startActivityOrException( activity, AppDetailIntentGenerator(null).generatorIntent(activity) ) { _, exception -> if (exception == null) { applyPermissionAgain( filterWeak(deniedPermissions), finished ) } else { isGranted = false this.deniedPermissions.clear() this.deniedPermissions.addAll(deniedPermissions) } } } } } else { isGranted = false this.deniedPermissions.addAll(deniedPermissions) finished() } } protected fun filterWeak(permissions: Array<out Permission>): Array<out Permission> { val list = ArrayList<Permission>(permissions.size) permissions.forEach { if (it.isWeak) { deniedPermissions.add(it) } else { list.add(it) } } return list.toTypedArray() } private fun getRouter(context: Activity): PermissionRequestRouter { return findRouter(context) ?: createRouter() } private fun createRouter(): PermissionRequestRouter { return when (target) { is FragmentActivity -> SupportPermissionRouter().also { addRouter(target.supportFragmentManager, it) } is Activity -> PermissionRouter().also { val fm = target.fragmentManager fm.beginTransaction() .add(it, ROUTER_TAG) .commitAllowingStateLoss() fm.executePendingTransactions() } is Fragment -> SupportPermissionRouter().also { addRouter(target.childFragmentManager, it) } is android.app.Fragment -> PermissionRouter().also { addRouter(target.fragmentManager, it) } else -> { throw NullPointerException("The target must be Activity or Fragment!!!") } } } private fun addRouter(fm: FragmentManager, router: SupportBasicRouter) { fm.beginTransaction() .add(router, ROUTER_TAG) .commitAllowingStateLoss() fm.executePendingTransactions() } private fun addRouter(fm: android.app.FragmentManager, router: BasicRouter) { fm.beginTransaction() .add(router, ROUTER_TAG) .commitAllowingStateLoss() fm.executePendingTransactions() } private fun findRouter(activity: Activity): PermissionRequestRouter? { return if (activity is FragmentActivity) { activity.supportFragmentManager.findFragmentByTag(ROUTER_TAG) as? PermissionRequestRouter } else { activity.fragmentManager.findFragmentByTag(ROUTER_TAG) as? PermissionRequestRouter } } companion object { private const val ROUTER_TAG = "ok_permission_apply_permissions_router_tag" } internal class PermissionRouter : BasicRouter(), PermissionRequestRouter { private val permissionCallbackCache = SparseArray<CallbackWrapper>() override fun requestPermissions( permissions: Array<out Permission>, onResult: (permissions: Array<out Permission>) -> Unit ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val requestCode = makeRequestCode() permissionCallbackCache.put(requestCode, CallbackWrapper(permissions, onResult)) requestPermissions(permissions.map { it.permission }.toTypedArray(), requestCode) } else { onResult(emptyArray()) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { val callback = permissionCallbackCache[requestCode] permissionCallbackCache.remove(requestCode) callback?.onResult(permissions, grantResults) } override fun onDestroy() { super.onDestroy() permissionCallbackCache.clear() } /** * 生成一个code。 */ private fun makeRequestCode(): Int { val code = randomGenerator.nextInt(0, 0x0001_0000) return if (permissionCallbackCache.indexOfKey(code) < 0) { code } else { makeRequestCode() } } } internal class SupportPermissionRouter : SupportBasicRouter(), PermissionRequestRouter { private val permissionCallbackCache = SparseArray<CallbackWrapper>() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) retainInstance = true } override fun requestPermissions( permissions: Array<out Permission>, onResult: (permissions: Array<out Permission>) -> Unit ) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { val requestCode = makeRequestCode() permissionCallbackCache.put(requestCode, CallbackWrapper(permissions, onResult)) requestPermissions(permissions.map { it.permission }.toTypedArray(), requestCode) } else { onResult(emptyArray()) } } override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { val callback = permissionCallbackCache[requestCode] permissionCallbackCache.remove(requestCode) callback?.onResult(permissions, grantResults) } override fun onDestroy() { super.onDestroy() permissionCallbackCache.clear() } /** * 生成一个code。 */ private fun makeRequestCode(): Int { val code = randomGenerator.nextInt(0, 0x0001_0000) return if (permissionCallbackCache.indexOfKey(code) < 0) { code } else { makeRequestCode() } } } private class CallbackWrapper( val permissions: Array<out Permission>, val callback: (permissions: Array<out Permission>) -> Unit ) { fun onResult(permissionArray: Array<String>, grantResults: IntArray) { grantResults.forEachIndexed { index, i -> if (i == PackageManager.PERMISSION_GRANTED) { permissionArray[index] = "" } } callback(permissions.filter { permissionArray.contains(it.permission) }.toTypedArray()) } } }
0
Kotlin
0
6
1c98fff6ba007b87ea4ef9c0d087d7f184e45ec6
14,213
OkPermission
Apache License 2.0
app/src/main/java/com/virginiaprivacy/raydos/InfoItemFragment.kt
virginiaprivacycoalition
288,048,093
false
null
package com.virginiaprivacy.raydos import android.Manifest import android.app.AlertDialog import android.content.Intent import android.content.pm.PackageManager import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.Button import android.widget.TextView import androidx.core.app.ActivityCompat import androidx.fragment.app.Fragment import androidx.fragment.app.commit import androidx.preference.PreferenceManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.LinearSnapHelper import androidx.recyclerview.widget.RecyclerView import com.virginiaprivacy.raydos.infoitem.InfoItem import com.virginiaprivacy.raydos.settings.SettingsActivity import jp.wasabeef.recyclerview.animators.LandingAnimator import kotlinx.coroutines.ExperimentalCoroutinesApi import ru.tinkoff.scrollingpagerindicator.ScrollingPagerIndicator import splitties.views.onClick /** * A fragment representing a list of Items. */ @ExperimentalCoroutinesApi class InfoItemFragment : Fragment() { private var columnCount = 1 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { columnCount = it.getInt(ARG_COLUMN_COUNT) } } private val firstInfoItem by lazy { InfoItem(getString(R.string.info_item_1_title), listOf(getString(R.string.info_item_details_1), getString(R.string.info_item_details_2), getString(R.string.info_item_details_3), getString(R.string.info_item_details_4))) } private val secondInfoItem by lazy { InfoItem(getString(R.string.info_item_2_title), listOf(getString(R.string.info_item_details_5), getString(R.string.info_item_details_6), getString(R.string.info_item_details_7), getString(R.string.info_item_details_8))) } private val thirdInfoItem by lazy { InfoItem(getString(R.string.info_item_3_title), listOf(getString(R.string.info_item_details_9), getString(R.string.info_item_details_10), getString(R.string.info_item_details_11))) } private val fourthInfoItem by lazy { InfoItem(getString(R.string.info_item_4_title), listOf(getString(R.string.info_item_details_12))) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.info_fragment_item_list, container, false) val infoItems = ArrayList<InfoItem>() infoItems += firstInfoItem infoItems += secondInfoItem infoItems += thirdInfoItem infoItems += fourthInfoItem val rv = view.findViewById<RecyclerView>(R.id.info_item_rv) rv.layoutManager = LinearLayoutManager(view.context, LinearLayoutManager.HORIZONTAL, false) rv.adapter = InfoItemAdapter(infoItems) rv.setHasFixedSize(true) LinearSnapHelper().attachToRecyclerView(rv) rv.itemAnimator = LandingAnimator() //rv.addItemDecoration(DividerItemDecoration(context, DividerItemDecoration.VERTICAL)) val recyclerIndicator: ScrollingPagerIndicator = view.findViewById(R.id.indicator) recyclerIndicator.attachToRecyclerView(rv) val useRandomTarget = PreferenceManager.getDefaultSharedPreferences(context).getBoolean(SettingsActivity.KEY_PREF_RANDOM_TARGET_SWITCH, false) val targetText = MainActivity.prefs.pull(SettingsActivity.KEY_PREF_TARGET_NUMBER_TEXT, "") val continueButton = view.findViewById<Button>(R.id.continue_button) val configureButton = view.findViewById<Button>(R.id.configure_button) val errorText = view.findViewById<TextView>(R.id.info_error_message) if (!useRandomTarget && targetText.length <= 1) { errorText.text = getString(R.string.destination_number_error_message) errorText.visibility = TextView.VISIBLE continueButton.isEnabled = false } configureButton.onClick { val intent = Intent(context, SettingsActivity::class.java) startActivity(intent) } continueButton.onClick { parentFragmentManager.commit { replace(R.id.fragment_container_view, (activity as MainActivity).readyFragment!!) } } return view } override fun onRequestPermissionsResult( requestCode: Int, permissions: Array<out String>, grantResults: IntArray) { println(grantResults.asList()) if (!permissions.contentEquals(arrayOf(Manifest.permission.SEND_SMS))) { return } view?.let { if (grantResults[0] == -1) { AlertDialog.Builder(context).run { setMessage(getString(R.string.sms_permission_dialog_message)) setPositiveButton(getString(R.string.sms_permission_dialog_retry_button)) { dialog, _ -> dialog.dismiss() requestSmsPermission() } setNegativeButton(getString(R.string.sms_permission_dialog_exit_button)) { dialogInterface, _ -> dialogInterface.cancel() (activity as MainActivity).finish() } show() } return@onRequestPermissionsResult } } } private fun requestSmsPermission() = requestPermissions(arrayOf(Manifest.permission.SEND_SMS, Manifest.permission.READ_SMS), 1) private fun hasSendPermission(): Boolean = context.let { it?.let { it1 -> ActivityCompat.checkSelfPermission(it1, Manifest.permission.SEND_SMS) .and(ActivityCompat.checkSelfPermission(it1, Manifest.permission.READ_SMS)) } == PackageManager.PERMISSION_GRANTED } companion object { // TODO: Customize parameter argument names const val ARG_COLUMN_COUNT = "column-count" } }
0
Kotlin
1
1
7c1d4588f51f24986976305c722459cfe1c00fb2
6,242
RayDos
MIT License
kotlin-typescript/src/main/generated/typescript/SignatureHelpRetriggerCharacter.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! package typescript sealed external interface SignatureHelpRetriggerCharacter /* SignatureHelpTriggerCharacter | ")" */
12
Kotlin
145
983
a99345a0160a80a7a90bf1adfbfdc83a31a18dd6
165
kotlin-wrappers
Apache License 2.0
relive-simulator-core/src/commonMain/kotlin/xyz/qwewqa/relive/simulator/core/presets/dress/generated/dress2030008.kt
qwewqa
390,928,568
false
null
package xyz.qwewqa.relive.simulator.core.presets.dress.generated import xyz.qwewqa.relive.simulator.core.stage.actor.ActType import xyz.qwewqa.relive.simulator.core.stage.actor.Attribute import xyz.qwewqa.relive.simulator.core.stage.actor.StatData import xyz.qwewqa.relive.simulator.core.stage.dress.ActParameters import xyz.qwewqa.relive.simulator.core.stage.dress.ActBlueprint import xyz.qwewqa.relive.simulator.core.stage.dress.PartialDressBlueprint import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoost import xyz.qwewqa.relive.simulator.core.stage.dress.StatBoostType import xyz.qwewqa.relive.simulator.stage.character.Character import xyz.qwewqa.relive.simulator.stage.character.DamageType import xyz.qwewqa.relive.simulator.stage.character.Position /* import xyz.qwewqa.relive.simulator.core.presets.condition.* import xyz.qwewqa.relive.simulator.core.presets.dress.generated.dress2030008 import xyz.qwewqa.relive.simulator.core.stage.Act import xyz.qwewqa.relive.simulator.core.stage.actor.ActType import xyz.qwewqa.relive.simulator.core.stage.actor.CountableBuff import xyz.qwewqa.relive.simulator.core.stage.dress.DressCategory import xyz.qwewqa.relive.simulator.core.stage.autoskill.new import xyz.qwewqa.relive.simulator.core.stage.dress.blueprint import xyz.qwewqa.relive.simulator.core.stage.buff.* import xyz.qwewqa.relive.simulator.core.stage.passive.* import xyz.qwewqa.relive.simulator.core.stage.stageeffect.* val dress = dress2030008( name = "凛明館女学校", acts = listOf( ActType.Act1.blueprint("斬撃") { Act { /* %attr%属性攻撃(威力%value%) target: 前から1番目の敵役 hit_rate1: 100 values1: [88, 92, 96, 101, 105] times1: 1 */ } }, ActType.Act2.blueprint("渾身の斬撃") { Act { /* %attr%属性攻撃(威力%value%) target: 前から1番目の敵役 hit_rate1: 100 values1: [129, 136, 142, 149, 155] times1: 1 */ } }, ActType.Act3.blueprint("奮起の喝采") { Act { /* %attr%属性攻撃(威力%value%) target: ACTパワーが1番高い敵役 hit_rate1: 100 values1: [132, 138, 145, 151, 158] times1: 1 ACTパワーアップ(%value%) target: 自身 hit_rate2: 100 values2: [7, 8, 9, 9, 10] times2: [3, 3, 3, 3, 3] */ } }, ActType.ClimaxAct.blueprint("川蝉") { Act { /* %attr%属性攻撃(威力%value%) target: ACTパワーが1番高い敵役 hit_rate1: 100 values1: [286, 300, 314, 328, 343] times1: 6 */ } } ), autoSkills = listOf( listOf( /* auto skill 1: 与ダメージアップ(%value%) target: 自身 values: [2, 3, 3, 3, 4] */ ), listOf( /* auto skill 2: フェンサー特攻(%value%) target: 自身 values: [50, 75, 75, 75, 100] */ ), listOf( /* auto skill 3: 与ダメージアップ(%value%) target: 自身 values: [5, 6, 6, 7, 8] */ ), ), unitSkill = null /* None */, multipleCA = false, categories = setOf(), ) */ val dress2030008 = PartialDressBlueprint( id = 2030008, name = "凛明館女学校", baseRarity = 3, cost = 9, character = Character.Fumi, attribute = Attribute.Cloud, damageType = DamageType.Normal, position = Position.Front, positionValue = 14050, stats = StatData( hp = 936, actPower = 122, normalDefense = 72, specialDefense = 53, agility = 141, dexterity = 5, critical = 50, accuracy = 0, evasion = 0, ), growthStats = StatData( hp = 30850, actPower = 2020, normalDefense = 1220, specialDefense = 900, agility = 2340, ), actParameters = mapOf( ActType.Act1 to ActBlueprint( name = "斬撃", type = ActType.Act1, apCost = 1, icon = 1, parameters = listOf( actParameters0, actParameters1, actParameters1, actParameters1, actParameters1, ), ), ActType.Act2 to ActBlueprint( name = "渾身の斬撃", type = ActType.Act2, apCost = 2, icon = 1, parameters = listOf( actParameters10, actParameters1, actParameters1, actParameters1, actParameters1, ), ), ActType.Act3 to ActBlueprint( name = "奮起の喝采", type = ActType.Act3, apCost = 3, icon = 8, parameters = listOf( actParameters7, actParameters151, actParameters1, actParameters1, actParameters1, ), ), ActType.ClimaxAct to ActBlueprint( name = "川蝉", type = ActType.ClimaxAct, apCost = 2, icon = 1, parameters = listOf( actParameters280, actParameters1, actParameters1, actParameters1, actParameters1, ), ), ), autoSkillRanks = listOf(1, 4, 9, null), autoSkillPanels = listOf(0, 0, 5, 0), rankPanels = growthBoard1, friendshipPanels = friendshipPattern0, remakeParameters = listOf( ), )
0
Kotlin
11
7
70e1cfaee4c2b5ab4deff33b0e4fd5001c016b74
5,486
relight
MIT License
app/src/main/java/com/islamelmrabet/cookconnect/ui/screens/commonScreens/WelcomeScreen.kt
IslamReact
787,626,098
false
{"Kotlin": 310386}
package com.islamelmrabet.cookconnect.ui.screens.commonScreens import android.content.ContentValues.TAG import android.util.Log import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize 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.ButtonDefaults import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.ExposedDropdownMenuBox import androidx.compose.material3.ExposedDropdownMenuDefaults import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.navigation.NavController import com.airbnb.lottie.compose.LottieAnimation import com.airbnb.lottie.compose.LottieCompositionSpec import com.airbnb.lottie.compose.LottieConstants import com.airbnb.lottie.compose.rememberLottieComposition import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import com.islamelmrabet.cookconnect.R import com.islamelmrabet.cookconnect.navigation.Routes import com.islamelmrabet.cookconnect.tools.BasicButton /** * Composable screen WelcomeScreen * * @param navController */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun WelcomeScreen(navController: NavController) { val lessRoundedShape = RoundedCornerShape(8.dp) val primaryColor = MaterialTheme.colorScheme.primary val buttonColors = ButtonDefaults.buttonColors( containerColor = primaryColor ) val composition by rememberLottieComposition( spec = LottieCompositionSpec.Url("https://lottie.host/22030422-d085-49d7-9886-4a48803576e6/HJkT0Z7bVp.json") ) var expandedState by remember { mutableStateOf(false) } val options = remember { mutableStateListOf<String>() } var selectedItem by remember { mutableStateOf<String?>(null) } var loading by remember { mutableStateOf(true) } LaunchedEffect(Unit) { val workersRef = Firebase.firestore.collection("workers") workersRef.get().addOnCompleteListener { task -> if (task.isSuccessful) { val namesAndRolesAndEmail = mutableListOf<String>() for (document in task.result) { val name = document.getString("name") val userRole = document.getString("userRole") val email = document.getString("email") if (name != null && userRole != null && email != null) { namesAndRolesAndEmail.add("$name - $userRole - $email") } } options.addAll(namesAndRolesAndEmail) if (options.isNotEmpty()) { selectedItem = options[0] } loading = false } else { Log.d(TAG, "Error getting documents: ${task.exception?.message}") } } } Column( modifier = Modifier.padding(start = 25.dp, top = 60.dp, end = 25.dp, bottom = 10.dp), horizontalAlignment = Alignment.Start ) { Text( text = stringResource(id = R.string.welcome), fontWeight = FontWeight.Bold, fontSize = 25.sp, lineHeight = 32.sp, letterSpacing = 0.5.sp ) Text( modifier = Modifier.padding(top = 15.dp), text = stringResource(id = R.string.welcome_text), fontSize = 20.sp, lineHeight = 22.sp, letterSpacing = 0.5.sp, textAlign = TextAlign.Justify ) Row( modifier = Modifier .padding(vertical = 30.dp) .fillMaxWidth(), ) { if (loading) { Box( modifier = Modifier .fillMaxWidth(), contentAlignment = Alignment.Center ) { LottieAnimation( composition = composition, iterations = LottieConstants.IterateForever ) } } else { ExposedDropdownMenuBox( expanded = expandedState, onExpandedChange = { expandedState = !expandedState }, modifier = Modifier.fillMaxWidth(), ) { selectedItem?.let { OutlinedTextField( value = it, modifier = Modifier.menuAnchor(), onValueChange = {}, readOnly = true, trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expandedState) } ) } ExposedDropdownMenu( expanded = expandedState, onDismissRequest = { expandedState = false }, modifier = Modifier.fillMaxWidth() ) { options.forEachIndexed { index, option -> DropdownMenuItem( text = { Text(text = option) }, onClick = { selectedItem = options[index] expandedState = false }, modifier = Modifier.fillMaxWidth() ) } } } } } Column( modifier = Modifier .fillMaxWidth() .padding(vertical = 20.dp), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Image( painter = painterResource(id = R.drawable.welcome_logo), contentDescription = "Welcome Logo", modifier = Modifier.size(240.dp) ) } Spacer(modifier = Modifier.weight(0.5f)) Row ( modifier = Modifier .fillMaxWidth(), horizontalArrangement = Arrangement.Center, verticalAlignment = Alignment.CenterVertically ){ BasicButton( buttonText = stringResource(id = R.string.register), lessRoundedShape = lessRoundedShape, buttonColors = buttonColors, onClick = { navController.navigate(Routes.CreateAccountScreen.route) } ) Spacer(modifier = Modifier.fillMaxWidth(0.2f)) BasicButton( buttonText = stringResource(id = R.string.login), lessRoundedShape = lessRoundedShape, buttonColors = buttonColors, onClick = { selectedItem?.let { selected -> val email = selected.split(" - ")[2] navController.navigate("${Routes.LogInScreen.route}/$email") } } ) } } }
0
Kotlin
0
0
bf95d715964f7a222dec41b07ac565dcdf761276
8,407
CookConnectTPV
MIT License
src/test/kotlin/days/Day9Test.kt
sicruse
315,469,617
false
null
package days import org.hamcrest.MatcherAssert.assertThat import org.hamcrest.core.Is.`is` import org.junit.Test class Day9Test { private val day = Day9() @Test fun testPartOne() { assertThat(day.findWeakness(5), `is`(127L)) } @Test fun testPartTwo() { assertThat(day.findExploit(127L), `is`(62)) } }
0
Kotlin
0
0
9a07af4879a6eca534c5dd7eb9fc60b71bfa2f0f
350
aoc-kotlin-2020
Creative Commons Zero v1.0 Universal
app/src/main/java/com/anshdeep/kotlinmessenger/messages/NewMessageActivity.kt
pranaypatel512
155,750,341
true
{"Kotlin": 30570}
package com.anshdeep.kotlinmessenger.messages import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log import com.anshdeep.kotlinmessenger.R import com.anshdeep.kotlinmessenger.models.User import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.google.firebase.auth.FirebaseAuth import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.xwray.groupie.GroupAdapter import com.xwray.groupie.Item import com.xwray.groupie.ViewHolder import kotlinx.android.synthetic.main.activity_new_message.* import kotlinx.android.synthetic.main.user_row_new_message.view.* class NewMessageActivity : AppCompatActivity() { companion object { const val USER_KEY = "USER_KEY" } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_new_message) swiperefresh.setColorSchemeColors(resources.getColor(R.color.colorAccent)) supportActionBar?.title = "Select User" fetchUsers() //Todo - Add more users and messages for screenshots swiperefresh.setOnRefreshListener { fetchUsers() } } private fun fetchUsers() { swiperefresh.isRefreshing = true val ref = FirebaseDatabase.getInstance().getReference("/users") ref.addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { } override fun onDataChange(p0: DataSnapshot) { val adapter = GroupAdapter<ViewHolder>() p0.children.forEach { Log.d("NewMessage", it.toString()) val user = it.getValue(User::class.java) if (user != null) { if(user.uid != FirebaseAuth.getInstance().uid){ adapter.add(UserItem(user)) } } } adapter.setOnItemClickListener { item, view -> val userItem = item as UserItem val intent = Intent(view.context, ChatLogActivity::class.java) intent.putExtra(USER_KEY, userItem.user) startActivity(intent) finish() } recyclerview_newmessage.adapter = adapter swiperefresh.isRefreshing = false } }) } } class UserItem(val user: User) : Item<ViewHolder>() { override fun bind(viewHolder: ViewHolder, position: Int) { viewHolder.itemView.username_textview_new_message.text = user.name if (!user.profileImageUrl!!.isEmpty()) { val requestOptions = RequestOptions().placeholder(R.drawable.no_image2) Glide.with(viewHolder.itemView.imageview_new_message.context) .load(user.profileImageUrl) .thumbnail(0.1f) .apply(requestOptions) .into(viewHolder.itemView.imageview_new_message) } } override fun getLayout(): Int { return R.layout.user_row_new_message } }
0
Kotlin
0
2
e331158010722609acda029efb0fbf254852a745
3,403
KotlinMessenger
Apache License 2.0
src/main/kotlin/com/example/coreweb/domains/locations/controllers/LocationPublicController.kt
teambankrupt
292,072,114
false
{"Kotlin": 286623, "Java": 61650, "HTML": 22230}
package com.example.coreweb.domains.locations.controllers import com.example.coreweb.domains.locations.models.dtos.LocationDto import com.example.coreweb.domains.locations.models.mappers.LocationMapper import com.example.coreweb.domains.locations.services.LocationService import com.example.common.utils.ExceptionUtil import com.example.coreweb.domains.base.controllers.CrudControllerV2 import com.example.coreweb.domains.base.models.enums.SortByFields import com.example.coreweb.routing.Route import io.swagger.annotations.Api import org.springframework.beans.factory.annotation.Autowired import org.springframework.data.domain.Page import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.* import javax.validation.Valid import org.springframework.data.domain.Sort @RestController @Api(tags = ["Locations"], description = "Description about Locations") class LocationPublicController @Autowired constructor( private val locationService: LocationService, private val locationMapper: LocationMapper ) { @GetMapping(Route.V1.SEARCH_CHILD_LOCATIONS_PUBLIC) fun searchChildLocations(@RequestParam("parent_id", required = false) parentId: Long?, @RequestParam("q", defaultValue = "") query: String, @RequestParam("page", defaultValue = "0") page: Int, @RequestParam("size", defaultValue = "10") size: Int, @RequestParam("sort_by", defaultValue = "ID") sortBy: SortByFields, @RequestParam("sort_direction", defaultValue = "DESC") direction: Sort.Direction): ResponseEntity<Page<LocationDto>> { val entities = this.locationService.searchByParent(parentId, query, page, size, sortBy, direction) return ResponseEntity.ok(entities.map { this.locationMapper.map(it) }) } }
3
Kotlin
0
2
fed50aeef2ac3b2553a76941d2d2c08c9c84e61d
1,894
coreweb
Apache License 2.0
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonerfromnomismigration/casenotes/CaseNotesMappingApiService.kt
ministryofjustice
452,734,022
false
{"Kotlin": 2884389, "Shell": 2955, "Mustache": 1803, "Dockerfile": 1377}
package uk.gov.justice.digital.hmpps.prisonerfromnomismigration.casenotes import kotlinx.coroutines.reactive.awaitFirstOrDefault import org.springframework.beans.factory.annotation.Qualifier import org.springframework.core.ParameterizedTypeReference import org.springframework.stereotype.Service import org.springframework.web.reactive.function.client.WebClient import org.springframework.web.reactive.function.client.WebClientResponseException import org.springframework.web.reactive.function.client.awaitBodilessEntity import org.springframework.web.reactive.function.client.awaitBody import reactor.core.publisher.Mono import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.helpers.awaitBodyOrNullWhenNotFound import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.integration.history.CreateMappingResult import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.integration.history.DuplicateErrorResponse import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.integration.history.MigrationMapping import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomismappings.model.CaseNoteMappingDto @Service class CaseNotesMappingApiService(@Qualifier("mappingApiWebClient") webClient: WebClient) : MigrationMapping<CaseNoteMappingDto>(domainUrl = "/mapping/casenotes", webClient) { suspend fun createMappings( mappings: List<CaseNoteMappingDto>, errorJavaClass: ParameterizedTypeReference<DuplicateErrorResponse<CaseNoteMappingDto>>, ): CreateMappingResult<CaseNoteMappingDto> = webClient.post() .uri("/mapping/casenotes/batch") .bodyValue(mappings) .retrieve() .bodyToMono(Unit::class.java) .map { CreateMappingResult<CaseNoteMappingDto>() } .onErrorResume(WebClientResponseException.Conflict::class.java) { Mono.just(CreateMappingResult(it.getResponseBodyAs(errorJavaClass))) } .awaitFirstOrDefault(CreateMappingResult()) suspend fun deleteMappingGivenDpsId(dpsCaseNoteId: String) { webClient.delete() .uri("/mapping/casenotes/dps-casenote-id/{dpsCaseNoteId}", dpsCaseNoteId) .retrieve() .awaitBodilessEntity() } suspend fun getMappingGivenNomisId(caseNoteId: Long): CaseNoteMappingDto = webClient.get() .uri("/mapping/casenotes/nomis-casenote-id/$caseNoteId") .retrieve() .awaitBody() suspend fun getMappingGivenNomisIdOrNull(caseNoteId: Long): CaseNoteMappingDto? = webClient.get() .uri("/mapping/casenotes/nomis-casenote-id/$caseNoteId") .retrieve() .awaitBodyOrNullWhenNotFound() }
2
Kotlin
1
2
5e5379936e8766cda30c1f499a5d375dcc6e48f7
2,575
hmpps-prisoner-from-nomis-migration
MIT License
src/main/kotlin/br/com/jiratorio/service/chart/impl/HistogramServiceImpl.kt
andrelugomes
230,294,644
false
null
package br.com.jiratorio.service.chart.impl import br.com.jiratorio.domain.entity.Issue import br.com.jiratorio.domain.entity.embedded.Chart import br.com.jiratorio.domain.entity.embedded.Histogram import br.com.jiratorio.extension.log import br.com.jiratorio.service.PercentileService import br.com.jiratorio.service.chart.HistogramService import org.springframework.stereotype.Service @Service class HistogramServiceImpl( private val percentileService: PercentileService ) : HistogramService { override fun issueHistogram(issues: List<Issue>): Histogram { log.info("Method=issueHistogram, issues={}", issues) val leadTimeList = issues.map { it.leadTime } val percentile = percentileService.calculatePercentile(leadTimeList) val chart = histogramChart(issues) return Histogram( chart = chart, median = percentile.median, percentile75 = percentile.percentile75, percentile90 = percentile.percentile90 ) } private fun histogramChart(issues: List<Issue>): Chart<Long, Int> { log.info("Method=histogramChart, issues={}", issues) val collect: MutableMap<Long, Int> = issues .groupingBy { it.leadTime } .eachCount() .toMutableMap() val max = collect.keys.max() ?: 1L for (i in 1 until max) { collect.putIfAbsent(i, 0) } return Chart(collect) } }
0
null
0
1
168de10e5e53f31734937816811ac9dae6940202
1,461
jirareport
MIT License
src/main/kotlin/br/com/jiratorio/service/chart/impl/HistogramServiceImpl.kt
andrelugomes
230,294,644
false
null
package br.com.jiratorio.service.chart.impl import br.com.jiratorio.domain.entity.Issue import br.com.jiratorio.domain.entity.embedded.Chart import br.com.jiratorio.domain.entity.embedded.Histogram import br.com.jiratorio.extension.log import br.com.jiratorio.service.PercentileService import br.com.jiratorio.service.chart.HistogramService import org.springframework.stereotype.Service @Service class HistogramServiceImpl( private val percentileService: PercentileService ) : HistogramService { override fun issueHistogram(issues: List<Issue>): Histogram { log.info("Method=issueHistogram, issues={}", issues) val leadTimeList = issues.map { it.leadTime } val percentile = percentileService.calculatePercentile(leadTimeList) val chart = histogramChart(issues) return Histogram( chart = chart, median = percentile.median, percentile75 = percentile.percentile75, percentile90 = percentile.percentile90 ) } private fun histogramChart(issues: List<Issue>): Chart<Long, Int> { log.info("Method=histogramChart, issues={}", issues) val collect: MutableMap<Long, Int> = issues .groupingBy { it.leadTime } .eachCount() .toMutableMap() val max = collect.keys.max() ?: 1L for (i in 1 until max) { collect.putIfAbsent(i, 0) } return Chart(collect) } }
0
null
0
1
168de10e5e53f31734937816811ac9dae6940202
1,461
jirareport
MIT License
app/src/main/java/am2/hu/ezshop/ui/main/NavigationAdapter.kt
AliElDerawi
117,346,602
true
{"Kotlin": 43785}
package am2.hu.ezshop.ui.main import am2.hu.ezshop.R import am2.hu.ezshop.persistance.entity.ListName import android.content.Context import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import kotlinx.android.synthetic.main.nav_item.view.* class NavigationAdapter(context: Context, private val menuClick: (ListName) -> Unit) : RecyclerView.Adapter<NavigationAdapter.NavViewHolder>() { private var layoutInflater: LayoutInflater = LayoutInflater.from(context) var menuItems: List<ListName> = emptyList() set(value) { field = value notifyDataSetChanged() } var selectedShop = "" set(value) { field = value notifyDataSetChanged() } override fun onBindViewHolder(holder: NavViewHolder, position: Int) { holder.onBindMenu(menuItems[position]) } override fun getItemCount(): Int = menuItems.size override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): NavViewHolder { val view = layoutInflater.inflate(R.layout.nav_item, parent, false) return NavViewHolder(view) } inner class NavViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), View.OnClickListener { init { itemView.menuName.setOnClickListener(this) } override fun onClick(v: View?) { menuClick(menuItems[adapterPosition]) } fun onBindMenu(menu: ListName) { itemView.menuName.text = menu.listName itemView.menuName.setCompoundDrawablesWithIntrinsicBounds(0, 0, if (menu.listName == selectedShop) R.drawable.ic_done_24dp else 0, 0) } } }
0
Kotlin
0
0
ca5aabf41d7a36ef413b1b8f7c3e6cd5f238eef7
1,745
EzShop
The Unlicense
src/main/kotlin/counters/minter/grpc/client/LimitOrderRequestKt.kt
counters
424,713,046
false
{"Kotlin": 940649, "Java": 183428}
//Generated by the protocol buffer compiler. DO NOT EDIT! // source: resources.proto package counters.minter.grpc.client; @kotlin.jvm.JvmName("-initializelimitOrderRequest") public inline fun limitOrderRequest(block: counters.minter.grpc.client.LimitOrderRequestKt.Dsl.() -> kotlin.Unit): counters.minter.grpc.client.LimitOrderRequest = counters.minter.grpc.client.LimitOrderRequestKt.Dsl._create(counters.minter.grpc.client.LimitOrderRequest.newBuilder()).apply { block() }._build() public object LimitOrderRequestKt { @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) @com.google.protobuf.kotlin.ProtoDslMarker public class Dsl private constructor( private val _builder: counters.minter.grpc.client.LimitOrderRequest.Builder ) { public companion object { @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _create(builder: counters.minter.grpc.client.LimitOrderRequest.Builder): Dsl = Dsl(builder) } @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _build(): counters.minter.grpc.client.LimitOrderRequest = _builder.build() /** * <code>uint64 order_id = 1;</code> */ public var orderId: kotlin.Long @JvmName("getOrderId") get() = _builder.getOrderId() @JvmName("setOrderId") set(value) { _builder.setOrderId(value) } /** * <code>uint64 order_id = 1;</code> */ public fun clearOrderId() { _builder.clearOrderId() } /** * <code>uint64 height = 2;</code> */ public var height: kotlin.Long @JvmName("getHeight") get() = _builder.getHeight() @JvmName("setHeight") set(value) { _builder.setHeight(value) } /** * <code>uint64 height = 2;</code> */ public fun clearHeight() { _builder.clearHeight() } } } @kotlin.jvm.JvmSynthetic public inline fun counters.minter.grpc.client.LimitOrderRequest.copy(block: counters.minter.grpc.client.LimitOrderRequestKt.Dsl.() -> kotlin.Unit): counters.minter.grpc.client.LimitOrderRequest = counters.minter.grpc.client.LimitOrderRequestKt.Dsl._create(this.toBuilder()).apply { block() }._build()
0
Kotlin
0
2
7f431b1551732cad28b471ad667cd18691e2e209
2,203
jvm-minter-grpc-class
Apache License 2.0
test-harness/sdks/web5-kt/src/main/kotlin/com/web5/models/PresentationDefinitionSubmissionRequirement.kt
TBD54566975
704,146,876
false
{"Kotlin": 19912, "Go": 18418, "JavaScript": 6578, "TypeScript": 6317, "HTML": 2431, "Dockerfile": 983, "Makefile": 197}
/** * web5 SDK test server * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 0.2.0 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.web5.models /** * * @param rule * @param name * @param purpose * @param count * @param min * @param max * @param from * @param fromNested */ data class PresentationDefinitionSubmissionRequirement( val rule: PresentationDefinitionSubmissionRequirement.Rule, val name: kotlin.String? = null, val purpose: kotlin.String? = null, val count: java.math.BigDecimal? = null, val min: java.math.BigDecimal? = null, val max: java.math.BigDecimal? = null, val from: kotlin.String? = null, val fromNested: kotlin.collections.List<PresentationDefinitionSubmissionRequirement>? = null ) { /** * * Values: all,pick */ enum class Rule(val value: kotlin.String){ all("all"), pick("pick"); } }
24
Kotlin
1
1
c7c1f353a6d7781cf3a5a16a484ba85ed0016f01
1,134
sdk-development
Apache License 2.0
apps/shared/shared/src/commonMain/kotlin/com/keygenqt/mb/shared/requests/CityRequest.kt
keygenqt
815,799,361
false
{"JavaScript": 609518, "Kotlin": 431821, "SCSS": 15489, "PHP": 5404, "HTML": 3459, "CSS": 2509, "Dockerfile": 104}
/* * Copyright 2024 Vitaliy Zarubin * * 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.keygenqt.mb.shared.requests import kotlinx.serialization.Serializable import kotlin.js.ExperimentalJsExport import kotlin.js.JsExport /** * Request city */ @OptIn(ExperimentalJsExport::class) @JsExport @Serializable @Suppress("ArrayInDataClass") data class CityRequest( val countryID: Int, val image: String, val link: String, val name: String, val locales: Array<ColumnLocaleRequest>, val organizers: Array<Int>, val uploads: Array<Int>, )
0
JavaScript
0
11
cac59e138d47d232a349613686af6bad727028bd
1,084
kmp-mb
Apache License 2.0
app/src/main/java/com/zobaer53/zedmovies/domain/model/CastModel.kt
zobaer53
661,586,013
false
{"Kotlin": 498107, "JavaScript": 344099, "C++": 10825, "CMake": 2160}
package com.zobaer53.zedmovies.domain.model data class CastModel( val id: Int, val name: String, val adult: Boolean, val castId: Int?, val character: String, val creditId: String, val gender: Int?, val knownForDepartment: String, val order: Int, val originalName: String, val popularity: Double, val profilePath: String? )
11
Kotlin
3
6
1e70d46924b711942b573364745fa74ef1f8493f
374
NoFlix
Apache License 2.0
backend/src/main/kotlin/app/vatov/idserver/model/serializers/RefreshTokenInfo.kt
IvanVatov
758,566,955
false
{"Kotlin": 184109, "Dart": 124070, "C++": 19208, "HTML": 17737, "CMake": 10220, "C": 734, "JavaScript": 489}
package app.vatov.idserver.model.serializers import java.time.Instant data class RefreshTokenInfo( val tenantId: Int, val userId: String, val refreshToken: String, val clientId: String, val scope: List<String>, val createdAt: Instant = Instant.now(), val refreshedAt: Instant = Instant.now(), val userAgent: String )
0
Kotlin
0
0
dc9ea65b320ce6a162eed6f2954b182c0c0aa1b3
351
IdServer
MIT License
Sui/sgx-components/src/main/java/com/bestswlkh0310/sgx_components/component/organization/calendar/Calendar.kt
HNW-DevON
674,124,124
false
null
package com.bestswlkh0310.sgx_components.component.organization.calendar import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import com.bestswlkh0310.sgx_components.component.basic.Divider import com.bestswlkh0310.sgx_components.component.organization.calendar.schedule.SgxScheduleItem import com.bestswlkh0310.sgx_components.component.organization.calendar.schedule.Schedule import com.bestswlkh0310.sgx_components.foundation.Text import com.bestswlkh0310.sgx_components.modifier.sgxClickable import com.bestswlkh0310.sgx_components.theme.SgxColor import com.bestswlkh0310.sgx_components.theme.SgxTheme import com.bestswlkh0310.sgx_components.theme.IcCalendar import com.bestswlkh0310.sgx_components.theme.IcLeftArrow import com.bestswlkh0310.sgx_components.theme.IcRightArrow import com.bestswlkh0310.sgx_components.utlis.SgxDimen import java.time.LocalDate /** * Dodam Calendar, for schedule * * @param schedules schedules(events) list type * @param modifier modifier * @param categories use SgxBasicCalendarCategory, list type * @param showCategories visible state category * @param onDayChange callback when day state changed, (currentDate, daySchedules) */ @Composable fun SgxCalendar( schedules: List<Schedule>, modifier: Modifier = Modifier, categories: List<SgxBasicCalendarCategory> = sgxBasicCalendarCategories, showCategories: Boolean = true, onDayChange: (date: LocalDate, daySchedules: List<DaySchedule>) -> Unit = { _, _ -> Unit }, ) { var selectedDay by remember { mutableStateOf(LocalDate.now()) } onDayChange(selectedDay, selectedDay.hasSchedules(schedules)) Column( modifier = modifier .fillMaxWidth() ) { // Category Bar if (showCategories) { Spacer(modifier = Modifier.height(16.dp)) CategoryBar(categories = categories) } Spacer(modifier = Modifier.height(16.dp)) // Top Bar CalendarTopBar( dayTitle = "${selectedDay.year}년 ${selectedDay.monthValue}월", onClickMinus = { selectedDay = selectedDay.minusMonths(1) }, onClickPlus = { selectedDay = selectedDay.plusMonths(1) } ) Spacer(modifier = Modifier.height(19.dp)) DayOfWeekBar() Spacer(modifier = Modifier.height(5.dp)) LazyVerticalGrid( columns = GridCells.Fixed(7), modifier = Modifier .fillMaxWidth() .padding(horizontal = SgxDimen.ScreenSidePadding), userScrollEnabled = false, contentPadding = PaddingValues(all = 1.dp), ) { items(selectedDay.getMonthDays()) { monthDay -> DayItem(selectedDay = selectedDay, monthDay = monthDay, schedules = schedules) { val selected = LocalDate.of(selectedDay.year, selectedDay.monthValue, it) if (selectedDay.isEqual(selected).not()) { selectedDay = selected } } } } } } @Composable private fun DayItem( selectedDay: LocalDate, monthDay: MonthDay, schedules: List<Schedule>, onClickItem: (day: Int) -> Unit, ) { Box( Modifier .fillMaxSize() .aspectRatio(1f) .border( width = 1.dp, color = if (selectedDay.dayOfMonth == monthDay.day) SgxTheme.color.Gray100 else SgxTheme.color.Transparent, shape = SgxTheme.shape.small, ) .sgxClickable { if (monthDay.day != -1) onClickItem(monthDay.day) } ) { var textColor = SgxTheme.color.Black if (monthDay.day != -1) if (LocalDate.now().isEqual(LocalDate.of(selectedDay.year, selectedDay.monthValue, monthDay.day))) { TodayIndicationBox() textColor = SgxTheme.color.White } Column( modifier = Modifier.fillMaxSize() ) { if (monthDay.day != -1) { Spacer(modifier = Modifier.height(3.dp)) BasicDayText(textColor = textColor, monthDay = monthDay) Spacer(modifier = Modifier.height(6.dp)) val daySchedules = LocalDate.of(selectedDay.year, selectedDay.monthValue, monthDay.day) .hasSchedules(schedules) if (daySchedules.isNotEmpty()) { daySchedules.forEach { when (it.type) { DayScheduleType.START -> ScheduleStartHorizontalBar(color = it.schedule.category.color) DayScheduleType.MIDDLE -> ScheduleMiddleHorizontalBar(color = it.schedule.category.color) DayScheduleType.END -> ScheduleEndHorizontalBar(color = it.schedule.category.color) } Spacer(modifier = Modifier.height(3.dp)) } } } } } } @Composable private fun BoxScope.TodayIndicationBox() { Column( modifier = Modifier.align(Alignment.TopCenter) ) { Spacer(modifier = Modifier.height(3.dp)) Box( modifier = Modifier .background(SgxTheme.color.Black, shape = SgxTheme.shape.small) .size(15.dp) ) } } @Composable private fun ColumnScope.BasicDayText(textColor: Color, monthDay: MonthDay) { Text( text = monthDay.day.toString(), color = if ((monthDay.dayOfWeek == 0) || (monthDay.dayOfWeek == 6)) SgxColor.MainColor400 else textColor, style = SgxTheme.typography.body3.copy( fontSize = 10.sp, fontWeight = FontWeight.SemiBold, lineHeight = 10.sp, ), modifier = Modifier.align(Alignment.CenterHorizontally) ) } @Composable private fun ScheduleEndHorizontalBar(color: Color) { Box( modifier = Modifier .fillMaxWidth() .height(4.dp) .background(color, shape = RoundedCornerShape(topEnd = 20.dp, bottomEnd = 20.dp)) .padding(end = 2.dp) ) } @Composable private fun ScheduleStartHorizontalBar(color: Color) { Box( modifier = Modifier .fillMaxWidth() .height(4.dp) .background(color, shape = RoundedCornerShape(topStart = 20.dp, bottomStart = 20.dp)) .padding(start = 2.dp) ) } @Composable private fun ScheduleMiddleHorizontalBar(color: Color) { Box( modifier = Modifier .fillMaxWidth() .height(4.dp) .background(color) ) } @Composable private fun CategoryBar( categories: List<SgxBasicCalendarCategory> ) { LazyRow( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(16.dp), contentPadding = PaddingValues(horizontal = 16.dp), ) { items(categories) { category -> CategoryItem(category = category) } } } @Composable private fun CategoryItem(category: SgxBasicCalendarCategory) { Row { Box( modifier = Modifier .background( color = category.color, shape = SgxTheme.shape.small, ) .size(12.dp) .align(Alignment.CenterVertically) ) Spacer(modifier = Modifier.width(5.dp)) Text( text = category.name, style = SgxTheme.typography.body3.copy( color = Color.Black, fontSize = 10.sp, lineHeight = 12.sp, ), modifier = Modifier .align(Alignment.CenterVertically) ) } } @Composable private fun CalendarTopBar( dayTitle: String, onClickPlus: () -> Unit, onClickMinus: () -> Unit, ) { Row( modifier = Modifier .padding(horizontal = SgxDimen.ScreenSidePadding) .fillMaxWidth() ) { Text( text = dayTitle, style = SgxTheme.typography.label1.copy( color = SgxTheme.color.Black, fontWeight = FontWeight.Bold ), modifier = Modifier .weight(1f) .align(Alignment.CenterVertically) ) Row(modifier = Modifier.align(Alignment.CenterVertically)) { IcLeftArrow( modifier = Modifier .size(15.dp) .sgxClickable { onClickMinus() }, contentDescription = null, ) Spacer(modifier = Modifier.width(12.dp)) IcRightArrow( modifier = Modifier .size(15.dp) .sgxClickable { onClickPlus() }, contentDescription = null, ) } } } private val dayOfWeeks = listOf("일", "월", "화", "수", "목", "금", "토") @Composable private fun DayOfWeekBar() { LazyRow( modifier = Modifier .fillMaxWidth() .padding(horizontal = SgxDimen.ScreenSidePadding), userScrollEnabled = false, horizontalArrangement = Arrangement.SpaceAround, ) { items(dayOfWeeks) { dayOfWeek -> Text( text = dayOfWeek, style = SgxTheme.typography.body3.copy( color = if (dayOfWeek == "일" || dayOfWeek == "토") SgxColor.MainColor400 else SgxTheme.color.Black, fontSize = 10.sp, lineHeight = 10.sp, ), ) } } } @Preview @Composable private fun PreviewCalendar() { var selectedDay by remember { mutableStateOf(LocalDate.now()) } var selectedSchedules by remember { mutableStateOf(emptyList<DaySchedule>()) } Column(Modifier.fillMaxSize()) { SgxCalendar( schedules = sampleSchedules, ) { date, schedules -> selectedDay = date selectedSchedules = schedules } Spacer(modifier = Modifier.height(10.dp)) Divider(thickness = 1.dp, color = SgxTheme.color.Gray100) Spacer(modifier = Modifier.height(10.dp)) Text( text = "${selectedDay.monthValue}월 ${selectedDay.dayOfMonth}일", color = SgxTheme.color.Gray500, style = SgxTheme.typography.body3.copy( fontSize = 10.sp, lineHeight = 12.sp, ), modifier = Modifier.padding(start = 16.dp) ) Spacer(modifier = Modifier.height(16.dp)) Row { Spacer(modifier = Modifier.width(24.dp)) IcCalendar(contentDescription = null, tint = SgxTheme.color.Gray500, modifier = Modifier.size(16.dp)) Spacer(modifier = Modifier.width(11.dp)) LazyColumn { items(selectedSchedules) { daySchedule -> SgxScheduleItem(schedule = daySchedule.schedule) Spacer(modifier = Modifier.height(24.dp)) } } } } } @Preview @Composable private fun PreviewCategoryItem() { CategoryItem(category = SgxBasicCalendarCategory.FirstGrade()) } private val sampleSchedules = listOf( Schedule( title = "비포스쿨", category = SgxBasicCalendarCategory.FirstGrade(), startDateTime = LocalDate.of(2023, 2, 12).getLocalDateTime(), endDateTime = LocalDate.of(2023, 2, 15).getLocalDateTime(), ), Schedule( title = "겨울방학", category = SgxBasicCalendarCategory.AllGrade(), startDateTime = LocalDate.of(2023, 2, 10).getLocalDateTime(), endDateTime = LocalDate.of(2023, 3, 7).getLocalDateTime(), ), )
0
Kotlin
0
1
3f16377f1cb71aee2bbe4115b6fe8e7734c8b32b
13,597
HNW-Android
MIT License
app/src/main/java/m/derakhshan/done/main/TimeModel.kt
m-derakhshan
361,720,327
false
null
package m.derakhshan.done.main data class TimeModel( val second: Int, val minute: Int, val hour: Int )
0
Kotlin
0
0
45ad53392d31b6b2ee98379179dbcd40663ff812
127
done
MIT License
app/src/main/java/me/naoti/panelapp/navigation/NavigationHost.kt
noaione
496,111,768
false
null
package me.naoti.panelapp.navigation import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.padding import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.navigation.NavController import androidx.navigation.NavHostController import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import androidx.navigation.navArgument import me.naoti.panelapp.state.AppState import me.naoti.panelapp.ui.preferences.UserSettings import me.naoti.panelapp.ui.screens.DashboardScreen import me.naoti.panelapp.ui.screens.ProjectsScreen import me.naoti.panelapp.ui.screens.SettingsScreen import me.naoti.panelapp.utils.getLogger @Composable fun NavigationHost( appState: AppState, navController: NavController, paddingValues: PaddingValues, userSettings: UserSettings, onRouteChange: (String) -> Unit, ) { val log = getLogger("NavigationMain") log.i("Creating navigation host") NavHost( navController = navController as NavHostController, startDestination = NavigationItem.Dashboard.route, Modifier.padding(paddingValues) ) { // Main screen composable( NavigationItem.Dashboard.route, arguments = listOf(navArgument("refresh") {defaultValue = "false"}) ) { log.i("Entering route: ${NavigationItem.Dashboard.route}") onRouteChange(NavigationItem.Dashboard.route) DashboardScreen(appState, userSettings) } composable( NavigationItem.Projects.route, arguments = listOf(navArgument("refresh") {defaultValue = "false"}) ) { log.i("Entering route: ${NavigationItem.Projects.route}") onRouteChange(NavigationItem.Projects.route) ProjectsScreen(appState, userSettings) } composable(NavigationItem.Settings.route) { log.i("Entering route: ${NavigationItem.Settings.route}") onRouteChange(NavigationItem.Settings.route) SettingsScreen(appState, userSettings) } } }
0
Kotlin
0
0
32ae54e9581aa88a6fafef20e559d12b2ab7c6a0
2,144
naoTimesApp
MIT License
kotlin-electron/src/jsMain/generated/electron/common/ShortcutDetails.kt
JetBrains
93,250,841
false
{"Kotlin": 11400167, "JavaScript": 146545}
package electron.common typealias ShortcutDetails = electron.core.ShortcutDetails
28
Kotlin
173
1,250
d1f8f5d805ffa18431dfefb7a1aa2f67f48915f6
84
kotlin-wrappers
Apache License 2.0
IndoorNavAndroid/nav-core/src/main/java/com/izhxx/navcore/domain/model/SearchRequest.kt
ZhevlakovII
507,916,442
false
null
package com.izhxx.navcore.domain.model /** * Модель для запросов пользователя. Поиск состоит из двух параметров и строго зависит от ID локаций, * так как идёт привязка к ID из-за дешевезны поиска * @param requestId ID запроса, для сортировки * @param locationId ID локации, которую искали */ data class SearchRequest( val requestId: Int, val locationId: Int )
2
Kotlin
0
1
c59bbb793ee28057f49392eab36206a05909265b
373
IndoorNavigation
MIT License
src/main/kotlin/org/grakovne/template/telegram/user/repository/UserRepository.kt
GrakovNe
704,967,060
false
{"Kotlin": 28494}
package org.grakovne.template.telegram.user.repository import org.grakovne.template.telegram.user.domain.Type import org.grakovne.template.telegram.user.domain.User import org.springframework.data.jpa.repository.JpaRepository interface UserRepository : JpaRepository<User, String> { fun findByType(type: Type): List<User> }
0
Kotlin
0
1
e2dc9252ddd50c8bdabf021be72b8957b10c0c2d
330
telegram_bot_template
MIT License
build_logic/plugin/checker/src/main/kotlin/AndroidProjectChecker.kt
VegetableChicken-Group
497,243,579
false
{"Kotlin": 315359, "Shell": 8775}
package check import check.rule.ModuleNamespaceCheckRule import org.gradle.api.Project /** * 用于检查 Android 项目是否规范 * * @author 985892345 * 2022/12/20 17:37 */ object AndroidProjectChecker { // TODO 在这里进行注册 private val checkRules = arrayOf( ModuleNamespaceCheckRule ) /** * 配置插件前触发 */ fun configBefore(project: Project) { try { checkRules.forEach { it.onConfigBefore(project) } } catch (e: RuntimeException) { println("项目检查工具发现问题:${e.message}") throw RuntimeException(e.message + hint) } } /** * 配置插件后触发 */ fun configAfter(project: Project) { try { checkRules.forEach { it.onConfigAfter(project) } } catch (e: RuntimeException) { println("项目检查工具发现问题:${e.message}") throw RuntimeException(e.message + hint) } } // gradle 默然字符集会导致中文乱码,所以这里单独写了个英文提示 private val hint = """ ===================================================================================================== = NOTE: If you have garbled Chinese characters, such as: 一二三 = = place click "Help - Edit Custom VM Options" and then add "-Dfile.encoding=UTF-8" and restart AS = ===================================================================================================== """.trimIndent() }
0
Kotlin
14
30
3455309ef00ecbe61dbc2c80b8871f8981b412e2
1,365
WanAndroid_Multi
MIT License
app/src/main/kotlin/com/thesomeshkumar/flixplorer/ui/screens/movie/MoviesViewModel.kt
TheSomeshKumar
620,466,665
false
null
package com.thesomeshkumar.flixplorer.ui.screens.movie import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.paging.cachedIn import com.thesomeshkumar.flixplorer.data.repository.FlixplorerRepository import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.stateIn @HiltViewModel class MoviesViewModel @Inject constructor(private val flixRepository: FlixplorerRepository) : ViewModel() { val moviesState: StateFlow<MovieScreenUIState> = flow { emit( MovieScreenUIState( upcoming = flixRepository.getUpcomingMovies().cachedIn(viewModelScope), nowPlaying = flixRepository.getNowPlayingMovies().cachedIn(viewModelScope), popular = flixRepository.getPopularMovies().cachedIn(viewModelScope), topRated = flixRepository.getTopMovies().cachedIn(viewModelScope) ) ) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), MovieScreenUIState.default) }
0
Kotlin
2
21
8b19412b41f256691cbd478c0f96fdf310d60f7b
1,185
Flixplorer
MIT License
daimbria/src/test/kotlin/de/daimpl/daimbria/transformation/PlungeTransformationTest.kt
stg-tud
856,831,530
false
{"Kotlin": 54177}
package de.daimpl.daimbria.transformation import de.cmdjulian.jdsl.JacksonArrayNodeBuilder.Companion.arr import de.cmdjulian.jdsl.JacksonObjectNodeBuilder.Companion.obj import de.daimpl.daimbria.InvalidJsonNodeTypeException import de.daimpl.daimbria.TransformationEngine import de.daimpl.daimbria.lensOps import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.nulls.shouldBeNull import io.kotest.matchers.nulls.shouldNotBeNull import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test class PlungeTransformationTest { private val json = obj { put("field", "value") put("object", obj { }) put("array", arr {}) } @Test fun plungeOnlyInObject() { val plungeLens = lensOps { plunge("field", "object") } shouldThrow<InvalidJsonNodeTypeException> { TransformationEngine.applyMigrations(arr {}, plungeLens) } } @Test fun simplePlunge() { val plungeLens = lensOps { plunge("field", "object") } val result = TransformationEngine.applyMigrations(json, plungeLens).shouldNotBeNull() result["field"].shouldBeNull() result["object"].shouldNotBeNull()["field"].shouldNotBeNull().textValue() shouldBe "value" } @Test fun plungeInArrayThrows() { val plungeLens = lensOps { plunge("field", "array") } shouldThrow<InvalidJsonNodeTypeException> { TransformationEngine.applyMigrations(json, plungeLens) } } }
0
Kotlin
0
0
21060d87a68c2964e62c25d2698065b34eae46b3
1,462
daimpl-2024-DAIMBRIA
MIT License
krefty-core/src/commonMain/kotlin/dev/ustits/krefty/predicate/Equal.kt
ustitc
410,678,793
false
{"Kotlin": 49157}
package dev.ustits.krefty.predicate import dev.ustits.krefty.core.Predicate class Equal<in T>(private val toCompare: T) : Predicate<T> { override fun isRefined(value: T): Boolean { return toCompare == value } }
0
Kotlin
1
8
a0c6301bcf28154b59afcd14f32563ba40dd2993
230
krefty
MIT License
payment-library/src/main/java/ru/modulkassa/payment/library/network/BigDecimalFormatter.kt
modulkassa
647,749,589
false
null
package ru.modulkassa.payment.library.network import java.math.BigDecimal import java.math.RoundingMode internal object BigDecimalFormatter { fun format(source: BigDecimal, scale: Int = 2): String { return source.setScale(scale, RoundingMode.HALF_UP) .stripTrailingZeros() .toPlainString() } }
0
Kotlin
0
1
66f0543e53bb38275157f882aac94f161bf54ab9
336
payment-android-sdk
MIT License