path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/org/mightyfrog/android/s4fd/details/DetailsContract.kt
mightyfrog
84,848,729
false
null
package org.mightyfrog.android.s4fd.details import org.mightyfrog.android.s4fd.BaseView import org.mightyfrog.android.s4fd.data.KHCharacter /** * @author <NAME> */ interface DetailsContract { interface View : BaseView<DetailsPresenter> { fun showActivityCircle() fun hideActivityCircle() fun showCompareDialog(list: List<KHCharacter>, displayNames: List<String>, scrollPosition: Int) fun setSubtitle(resId: Int, vararg args: String?) fun clearSubtitle() fun showVsThumbnail(charToCompare: KHCharacter?) fun hideVsThumbnail() fun setCharToCompare(charToCompare: KHCharacter?) } interface Presenter { infix fun compareTo(id: Int) fun setCharToCompare(ownerId: Int, charToCompare: KHCharacter?) fun setCharToCompareIfAny(ownerId: Int) } }
1
null
1
2
21f2f158a85ce4229d284dab507b3578d5aecff7
854
S4FD
Apache License 2.0
src/main/kotlin/jp/nephy/hypixelin/model/stats/SmashHeroes.kt
SlashNephy
112,994,308
false
null
package jp.nephy.hypixelin.model.stats import com.github.salomonbrys.kotson.byNullableFloat import com.github.salomonbrys.kotson.byNullableInt import com.github.salomonbrys.kotson.byNullableObject import com.google.gson.JsonElement class SmashHeroes(val json: JsonElement) { val classStats by json.byNullableObject("class_stats") val coins by json.byNullableInt val damageDealt by json.byNullableInt("damage_dealt") val damageDealt2V2 by json.byNullableInt("damage_dealt_2v2") val deaths by json.byNullableInt val deaths2V2 by json.byNullableInt("deaths_2v2") val games by json.byNullableInt val games2V2 by json.byNullableInt("games_2v2") val gamesMonthlyB by json.byNullableInt("games_monthly_b") val gamesWeeklyB by json.byNullableInt("games_weekly_b") val kills by json.byNullableInt val kills2V2 by json.byNullableInt("kills_2v2") val killsMonthlyB by json.byNullableInt("kills_monthly_b") val killsWeeklyB by json.byNullableInt("kills_weekly_b") val lastLevelTheBulk by json.byNullableInt("lastLevel_THE_BULK") val losses by json.byNullableInt val losses2V2 by json.byNullableInt("losses_2v2") val lossesMonthlyB by json.byNullableInt("losses_monthly_b") val lossesWeeklyB by json.byNullableInt("losses_weekly_b") val smashLevel by json.byNullableInt val smashLevelTotal by json.byNullableInt("smash_level_total") val smashed by json.byNullableInt val smashed2V2 by json.byNullableInt("smashed_2v2") val smasher by json.byNullableInt val smasher2V2 by json.byNullableInt("smasher_2v2") val winStreak by json.byNullableInt("win_streak") val wins by json.byNullableInt val wins2V2 by json.byNullableInt("wins_2v2") val winsMonthlyB by json.byNullableInt("wins_monthly_b") val winsWeeklyB by json.byNullableInt("wins_weekly_b") val xpTheBulk by json.byNullableFloat("xp_THE_BULK") }
0
Kotlin
0
0
17573678a2e46cae714eb04d75930288e552afb8
1,912
Hypixelin
MIT License
app/src/main/java/com/qingmei2/sample/ui/main/profile/ProfileModule.kt
msdgwzhy6
157,537,516
true
{"Kotlin": 112168}
package com.qingmei2.sample.ui.main.profile import android.support.v4.app.Fragment import com.qingmei2.rhine.ext.viewmodel.addLifecycle import org.kodein.di.Kodein import org.kodein.di.android.AndroidComponentsWeakScope import org.kodein.di.android.support.AndroidLifecycleScope import org.kodein.di.generic.* const val PROFILE_MODULE_TAG = "PROFILE_MODULE_TAG" val profileKodeinModule = Kodein.Module(PROFILE_MODULE_TAG) { bind<ProfileViewDelegate>() with scoped(AndroidLifecycleScope<Fragment>()).singleton { ProfileViewDelegate(instance()) } bind<ProfileViewModel>() with scoped(AndroidLifecycleScope<Fragment>()).singleton { ProfileViewModel(instance()).apply { addLifecycle(context) } } bind<ProfileRemoteDataSource>() with scoped(AndroidLifecycleScope<Fragment>()).singleton { ProfileRemoteDataSource(instance()) } bind<ProfileRepository>() with scoped(AndroidLifecycleScope<Fragment>()).singleton { ProfileRepository(instance()) } }
0
Kotlin
0
1
ac829cbef19a105ce34589cda89c6c397386b60d
1,030
MVVM-Rhine
Apache License 2.0
src/main/kotlin/io/emeraldpay/dshackle/config/RequestLogConfig.kt
emeraldpay
191,297,773
false
null
/** * Copyright (c) 2022 EmeraldPay, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * 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.emeraldpay.dshackle.config /** * Config for logging of the request made from Dshackle to an upstream */ class RequestLogConfig( val enabled: Boolean = false, val includeParams: Boolean = false ) { var filename: String = "./request_log.jsonl" companion object { fun default(): RequestLogConfig { return disabled() } fun disabled(): RequestLogConfig { return RequestLogConfig( enabled = false ) } } }
69
Kotlin
47
192
ed4fcf253f2f488b57e651fb8d9a5f03c2639c73
1,128
dshackle
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/cognito/UserPoolSESOptionsDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.cognito import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.Unit import software.amazon.awscdk.services.cognito.UserPoolSESOptions @Generated public fun buildUserPoolSESOptions(initializer: @AwsCdkDsl UserPoolSESOptions.Builder.() -> Unit): UserPoolSESOptions = UserPoolSESOptions.Builder().apply(initializer).build()
1
Kotlin
0
0
b22e397ff37c5fce365a5430790e5d83f0dd5a64
408
aws-cdk-kt
Apache License 2.0
AdventOfCodeDay05/src/nativeMain/kotlin/Main.kt
bdlepla
451,510,571
false
{"Kotlin": 165771}
import kotlin.system.measureTimeMicros fun main() { val lines = readAllLinesFromStdInput() val count = lines.count() println("$count lines") val day05 = Day05(lines) val time1 = measureTimeMicros { val result1 = day05.solvePart1() println("Result #1 = $result1") } println("Results #1 in $time1 ms") val time2 = measureTimeMicros { val result2 = day05.solvePart2() println("Result #2 = $result2") } println("Results #2 in $time2 ms") } fun readAllLinesFromStdInput():List<String> = buildString() { while (true) { val line = readLine() ?: break append(line) } }.split("\n")
0
Kotlin
0
0
1d60a1b3d0d60e0b3565263ca8d3bd5c229e2871
702
AdventOfCode2021
The Unlicense
feature/auth/domain/src/test/java/app/tasky/auth/domain/usecase/auth/SignInUseCaseTest.kt
usdaves
611,128,186
false
null
/* * Copyright 2023 usdaves(Usmon Abdurakhmanov) * * 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 app.tasky.auth.domain.usecase.auth import app.cash.turbine.test import app.tasky.auth.domain.fake.FakeAuthRepository import app.tasky.auth.domain.fake.FakeSignInValidationUseCase import app.tasky.auth.domain.repository.SignInResult import app.tasky.auth.domain.usecase.validation.SignInValidationResult import app.tasky.test.domain.fake.FakeLogger import com.google.common.truth.Truth.assertThat import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import org.junit.Before import org.junit.Test // Created by usdaves(Usmon Abdurakhmanov) on 3/8/2023 @OptIn(ExperimentalCoroutinesApi::class) class SignInUseCaseTest { private lateinit var fakeAuthRepository: FakeAuthRepository private lateinit var fakeSignInValidationUseCase: FakeSignInValidationUseCase private val fakeLogger: FakeLogger = FakeLogger() private lateinit var signInUseCase: SignInUseCase private val defaultEmail = "email@mail.com" private val defaultPassword = "12345678" @Before fun setUp() { fakeAuthRepository = FakeAuthRepository() fakeSignInValidationUseCase = FakeSignInValidationUseCase() signInUseCase = SignInUseCase( repository = fakeAuthRepository.mock, signInValidationUseCase = fakeSignInValidationUseCase.mock, logger = fakeLogger.mock, ) } @Test fun `flow emits Authenticating result as a initial emission`() = runTest { val expectedResults = arrayOf( SignInResult.Authenticating, ) val signInFlow = signInUseCase.invoke(defaultEmail, defaultPassword) signInFlow.test { expectedResults.forEach { result -> assertThat(awaitItem()).isEqualTo(result) } cancelAndConsumeRemainingEvents() } } @Test fun `emits retrieved result from SignInValidationUseCase`() = runTest { val expectedResults = arrayOf( SignInResult.Authenticating, SignInResult.Failure.InvalidCredentials(SignInValidationResult.EmptyEmail), ) fakeSignInValidationUseCase.mockValidationResult( SignInValidationResult.EmptyEmail, ) val signInFlow = signInUseCase.invoke("", defaultPassword) signInFlow.test { expectedResults.forEach { result -> assertThat(awaitItem()).isEqualTo(result) } expectNoEvents() } } @Test fun `emits retrieved result from AuthRepository`() = runTest { val expectedResults = arrayOf( SignInResult.Authenticating, SignInResult.Authenticated, ) fakeSignInValidationUseCase.mockValidationResult(null) fakeAuthRepository.mockForSignInResult( defaultEmail, defaultPassword, SignInResult.Authenticated, ) val signInFlow = signInUseCase.invoke(defaultEmail, defaultPassword) signInFlow.test { expectedResults.forEach { result -> assertThat(awaitItem()).isEqualTo(result) } expectNoEvents() } } }
0
Kotlin
0
0
d9e25bfeb91dbe759dba229dd319bbe86dbcf98d
3,516
Tasky
Apache License 2.0
app/src/main/java/com/binlly/gankee/business/home/HomePresenter.kt
binlly
110,812,581
false
{"Gradle": 3, "YAML": 1, "Gradle Kotlin DSL": 1, "Text": 1, "Ignore List": 2, "Markdown": 1, "Proguard": 1, "Kotlin": 129, "XML": 48, "FreeMarker": 30, "Fluent": 53, "Java": 4}
package com.binlly.gankee.business.home import android.content.Context import com.binlly.gankee.base.mvp.BaseFragmentPresenterImpl import com.binlly.gankee.base.rx.RxObserver import com.binlly.gankee.repo.HomeRepo class HomePresenter( context: Context?, mView: HomeContract.View ): BaseFragmentPresenterImpl<HomeContract.View>(context, mView), HomeContract.Presenter { private var page = 1 override fun requestFeedAll(page: Int, observer: RxObserver<List<FeedAll>?>) { HomeRepo.requestFeedAll(page, observer) } override fun refresh() { page = 1 requestFeedAll(1, object: RxObserver<List<FeedAll>?>() { override fun onNext(list: List<FeedAll>?) { if (list == null || list.isEmpty()) { V().setPageEmpty() return } V().setPageSuccess() V().refresh(list) } override fun onError(e: Throwable) { super.onError(e) V().loadFail() } }) } override fun loadmore() { ++page requestFeedAll(page, object: RxObserver<List<FeedAll>?>() { override fun onNext(list: List<FeedAll>?) { if (list == null || list.isEmpty()) { V().loadEnd() return } V().loadMore(list) V().loadComplete() } override fun onError(e: Throwable) { super.onError(e) V().loadFail() } }) } }
1
null
1
1
5735cd793b186a75a8defeb9c2ccb9513cc656e2
1,613
Gankee
MIT License
app/src/main/java/com/jiwenjie/cocomusic/ui/adapter/BottomMusicAdapter.kt
jiwenjie
179,411,368
false
null
package com.jiwenjie.cocomusic.ui.adapter import android.content.Context import android.view.View import com.jiwenjie.basepart.adapters.BaseRecyclerAdapter import com.jiwenjie.cocomusic.R import com.jiwenjie.cocomusic.aidl.Music import com.jiwenjie.cocomusic.utils.CommonUtils import com.jiwenjie.cocomusic.utils.CoverLoader import kotlinx.android.synthetic.main.fragment_bottom_music_item.view.* /** * author:Jiwenjie * email:<EMAIL> * time:2019/05/09 * desc:本地歌曲item * version:1.0 */ class BottomMusicAdapter(context: Context, beanList: ArrayList<Music>) : BaseRecyclerAdapter<Music>(context, beanList) { override fun getAdapterLayoutId(viewType: Int): Int = R.layout.fragment_bottom_music_item override fun convertView(itemView: View, data: Music, position: Int) { CoverLoader.loadImageView(mContext, data.coverUri!!, itemView.iv_cover) itemView.tv_title.text = CommonUtils.getTitle(data.title) // 设置歌手专辑名称 itemView.tv_artist.text = CommonUtils.getArtistAndAlbum(data.artist!!, data.album!!) if (data.coverUri != null) { CoverLoader.loadImageView(mContext, data.coverUri!!, R.drawable.default_cover, itemView.iv_cover) } if (data.coverUri.isNullOrEmpty()) { // 加载歌曲专辑图 data.title?.let { // 加载网络歌曲的专辑图 // MusicApi.getMusicAlbumPic(item.title.toString(), success = { // item.coverUri = it // CoverLoader.loadImageView(mContext, it, R.drawable.default_cover, holder.getView(R.id.iv_cover)) // }) } } } }
1
null
1
9
314940ee717562b2a943c14bd659a52ba8214fbd
1,628
CocoMusic
Apache License 2.0
Series/Building_DRAG_forAndroid/project/app/src/main/java/edu/sempreacodar/drag/ui/theme/Color.kt
palbp
249,798,469
false
null
package edu.sempreacodar.drag.ui.theme import androidx.compose.ui.graphics.Color val purple200 = Color(0xFFBB86FC) val purple500 = Color(0xFF6200EE) val purple700 = Color(0xFF3700B3) val teal200 = Color(0xFF03DAC5) val red = Color(0xFFE41212) val lightOrange = Color(0xFFFF9800)
2
Kotlin
7
44
a13802274b32e90b20c15ffe8d38629b0c84dbd4
282
sempre_a_codar
MIT License
app/src/main/java/com/codepath/apps/restclienttemplate/models/LinkifyTextview.kt
sureshritika
546,851,253
false
{"Kotlin": 67166}
package com.codepath.apps.restclienttemplate.models import android.content.Context import android.text.Layout import android.text.Selection import android.text.Spannable import android.text.style.ClickableSpan import android.text.util.Linkify import android.util.AttributeSet import android.view.MotionEvent import android.widget.TextView class LinkifyTextView : androidx.appcompat.widget.AppCompatTextView { constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super( context, attrs, defStyle ) { init() } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { init() } constructor(context: Context) : super(context) { init() } private fun init() { this.autoLinkMask = Linkify.ALL } /** * @Linkify applies to a movementMethod to the textView @LinkMovementMethod. That movement method thought it * implements a scrolling vertically method it overrides any other scrolling method the parent has. * * Although touchEvent can be dispached to the parent, the specific parent ScrollView needed the whole sequence * ACTION_DOWN , ACTION_MOVE, ACTION_UP to perform (sweep detection). So the solution to this problem is after * applying @Linkify we need to remove the textView's scrolling method and handle the @LinkMovementMethod link * detection action in onTouchEvent of the textView. */ override fun onTouchEvent(event: MotionEvent): Boolean { val widget = this as TextView val text: Any = widget.text if (text is Spannable) { val buffer = text val action = event.action if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) { var x = event.x.toInt() var y = event.y.toInt() x -= widget.totalPaddingLeft y -= widget.totalPaddingTop x += widget.scrollX y += widget.scrollY val layout: Layout = widget.layout val line: Int = layout.getLineForVertical(y) val off: Int = layout.getOffsetForHorizontal(line, x.toFloat()) val link = buffer.getSpans( off, off, ClickableSpan::class.java ) if (link.size != 0) { if (action == MotionEvent.ACTION_UP) { link[0].onClick(widget) } else if (action == MotionEvent.ACTION_DOWN) { Selection.setSelection( buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd( link[0] ) ) } return true } } } return false } override fun setText(text: CharSequence, type: BufferType) { super.setText(text, type) this.movementMethod = null } }
2
Kotlin
0
0
70a6a4e1dc59e89b1b07f27e8b4e167dc9bc0fd2
3,067
SimpleTweet
Apache License 2.0
android_kmp/craftd-compose/src/androidMain/kotlin/com/github/codandotv/craftd/compose/ui/text/CraftDText.kt
CodandoTV
788,958,834
false
{"Kotlin": 56933, "C++": 20938, "CMake": 18713, "HTML": 17445, "Swift": 16229, "Dart": 15344, "C": 1425, "Ruby": 638, "Objective-C": 38}
package com.github.codandotv.craftd.compose.ui.text import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.TextUnit import androidx.compose.ui.unit.sp import androidx.core.text.HtmlCompat import com.github.codandotv.craftd.androidcore.data.model.text.TextProperties import com.github.codandotv.craftd.androidcore.extensions.empty import com.github.codandotv.craftd.compose.extensions.parseColorCompose import com.github.codandotv.craftd.compose.extensions.toAlignCompose import com.github.codandotv.craftd.compose.extensions.toTextStyle @Composable fun CraftDText( textProperties: TextProperties, modifier: Modifier = Modifier, clickable: (() -> Unit)? = null, ) { val modifierCustom = clickable?.let { Modifier.clickable { clickable.invoke() } } ?: modifier Surface( modifier = Modifier.fillMaxSize(), color = textProperties.backgroundHex.parseColorCompose() ) { Text( modifier = modifierCustom, style = textProperties.textStyle.toTextStyle().copy( fontSize = textProperties.textSize?.toFloat()?.sp ?: TextUnit.Unspecified, ), text = textProperties.textHtml?.let { html -> HtmlCompat.fromHtml( html, HtmlCompat.FROM_HTML_MODE_COMPACT ).toString() } ?: textProperties.textWithRightCaps(), color = textProperties.textColorHex?.parseColorCompose() ?: Color.Unspecified, textAlign = textProperties.align.toAlignCompose(), ) } } private fun TextProperties.textWithRightCaps(): String = when (textAllCaps) { true -> text?.uppercase() false -> text?.lowercase() else -> text } ?: String.empty()
1
Kotlin
0
9
b05b8575537f426048a4a63d4c7b48f9396a48be
2,027
CraftD
MIT License
examples/src/main/kotlin/org/dashevo/examples/RegisterNames.kt
bspanda98
265,215,725
true
{"Kotlin": 64281}
/** * Copyright (c) 2020-present, Dash Core Group * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ package org.dashevo.examples import org.bitcoinj.core.ECKey import org.bitcoinj.core.Sha256Hash import org.bitcoinj.core.Utils import org.bitcoinj.evolution.CreditFundingTransaction import org.dashevo.Client import org.json.JSONObject /** * This is an example that will register all the names from the command line * using an example identity on mobile devnet */ class RegisterNames { companion object { val sdk = Client("mobile") @JvmStatic fun main(args: Array<String>) { for (i in 1 until args.size) registerName(args[i]) } fun registerName(name: String) { val platform = sdk.platform sdk.isReady(); val cftx = CreditFundingTransaction(platform.params, DefaultIdentity.creditBurnTx) cftx.setCreditBurnPublicKeyAndIndex(DefaultIdentity.identityPrivateKey, 0) try { val identityPrivateKey = DefaultIdentity.identityPrivateKey var identity = platform.identities.get(cftx.creditBurnIdentityIdentifier.toStringBase58()) if (platform.names.get(name) == null) { var nameDocument = platform.names.register(name, identity!!, identityPrivateKey) // display information println("Name Created: ${name}") println(JSONObject(nameDocument!!.toJSON()).toString(2)) } else { println("ERROR: username $name already exists") } } catch (e: Exception) { println(e.localizedMessage) } } } }
0
null
0
0
882e6f9ee9aff67271c70a8ba8f276e6e58d2efe
1,833
android-dashpay
MIT License
src/main/kotlin/de/olk90/filechooser/actions/FileChooserButtons.kt
olk90
506,712,307
false
{"Kotlin": 22422}
package de.olk90.filechooser.actions import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Home import androidx.compose.runtime.Composable import androidx.compose.runtime.MutableState import androidx.compose.ui.graphics.vector.ImageVector @Composable fun FileChooserButton(isDialogOpen: MutableState<Boolean>, icon: ImageVector = Icons.Filled.Home) { IconButton( onClick = { isDialogOpen.value = true }) { Icon( icon, contentDescription = "Add new directory" ) } }
0
Kotlin
0
7
3c2a4964dd0e09b348c8be6743e48ea2bb112998
662
compose-fileChooser
Apache License 2.0
core/core/src/jvmMain/kotlin/zakadabar/core/alarm/LogAlarmSupport.kt
spxbhuhb
290,390,793
false
{"Kotlin": 2348240, "HTML": 2835, "JavaScript": 1021, "Dockerfile": 269, "Shell": 253}
/* * Copyright © 2020-2021, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license. */ package zakadabar.core.alarm import org.slf4j.LoggerFactory import zakadabar.core.business.BusinessLogicCommon /** * Uses an sfl4j logger to write out the alarms as errors. */ class LogAlarmSupport( val businessLogic: BusinessLogicCommon<*> ) : AlarmSupport { val logger by lazy { LoggerFactory.getLogger(businessLogic.namespace) } override fun create(ex: Exception) { logger.error(ex.message, ex) } }
12
Kotlin
3
24
61ac92ff04eb53bff5b9a9b2649bd4866f469942
554
zakadabar-stack
Apache License 2.0
core/core/src/jvmMain/kotlin/zakadabar/core/alarm/LogAlarmSupport.kt
spxbhuhb
290,390,793
false
{"Kotlin": 2348240, "HTML": 2835, "JavaScript": 1021, "Dockerfile": 269, "Shell": 253}
/* * Copyright © 2020-2021, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license. */ package zakadabar.core.alarm import org.slf4j.LoggerFactory import zakadabar.core.business.BusinessLogicCommon /** * Uses an sfl4j logger to write out the alarms as errors. */ class LogAlarmSupport( val businessLogic: BusinessLogicCommon<*> ) : AlarmSupport { val logger by lazy { LoggerFactory.getLogger(businessLogic.namespace) } override fun create(ex: Exception) { logger.error(ex.message, ex) } }
12
Kotlin
3
24
61ac92ff04eb53bff5b9a9b2649bd4866f469942
554
zakadabar-stack
Apache License 2.0
src/main/kotlin/backtobasicsoop/domain/data/CartRepository.kt
joaofbantunes
226,717,208
false
null
package backtobasicsoop.domain.data import backtobasicsoop.domain.entities.Cart import backtobasicsoop.domain.entities.CartId interface CartRepository { fun get(id: CartId): Cart? fun save(cart: Cart): Cart fun delete(id: CartId) }
0
Kotlin
0
0
7a9c5d4d2911f5073f58bb8daaa2b3347f08f479
248
BackToBasicsTheMessWereMakingOutOfOOPKT
MIT License
src/main/java/io/github/alexiscomete/lapinousecond/entity/xp/Level.kt
Alexiscomete
377,132,555
false
{"Kotlin": 502869}
package io.github.alexiscomete.lapinousecond.entity.xp import io.github.alexiscomete.lapinousecond.data.dataclass.ProgressionBar import io.github.alexiscomete.lapinousecond.data.managesave.CacheGetSet import kotlin.math.roundToInt const val ROUND_PRECISION_D = 1000.0 const val PROGRESSION_STRING_SIZE = 15 open class Level( val entity: CacheGetSet, private val field: String, accumulation: Double = 2.5, start: Double = 2.5 ) : ComputeLevel(accumulation, start) { val level get() = levelForXp(if (entity[field] == "") 0.0 else entity[field].toDouble()) val xpForNextLevel get() = xpForNextLevel(if (entity[field] == "") 0.0 else entity[field].toDouble()) val totalXpForNextLevel get() = totalXpForNextLevel(if (entity[field] == "") 0.0 else entity[field].toDouble()) val xpForLastLevel get() = totalXpForCurrentLevel(if (entity[field] == "") 0.0 else entity[field].toDouble()) val xpInCurrentLevel get() = xpInCurrentLevel(if (entity[field] == "") 0.0 else entity[field].toDouble()) open fun addXp(xp: Double): Pair<Int, Int>? { val currentLevel = level entity[field] = ((if (entity[field] == "") 0.0 else entity[field].toDouble()) + xp).toString() val newLevel = level if (currentLevel != newLevel) { return Pair(currentLevel, newLevel) } return null } fun removeXp(xp: Double) { entity[field] = ((if (entity[field] == "") 0.0 else entity[field].toDouble()) - xp).toString() if (entity[field].toDouble() < 0) entity[field] = "0" } fun setXp(xp: Double) { entity[field] = xp.toString() } fun setLevel(level: Int) { entity[field] = xpForLevel(level).toString() } fun addLevel(level: Int) { entity[field] = (xpForLevel(level) + (if (entity[field] == "") 0.0 else entity[field].toDouble())).toString() } override fun toString(): String { return ProgressionBar( "🟡", "🟨", "⬜", totalXpForNextLevel, xpInCurrentLevel, PROGRESSION_STRING_SIZE ).bar + " **$level** (${(xpInCurrentLevel * ROUND_PRECISION_D).roundToInt() / ROUND_PRECISION_D}/${(totalXpForNextLevel * ROUND_PRECISION_D).roundToInt() / ROUND_PRECISION_D})" } }
65
Kotlin
0
9
50f39fa386cbd141c81896184b3648850343684d
2,344
A-Discord-Adventure
MIT License
bbfgradle/tmp/results/diffCompile/kmregol.kt
DaniilStepanov
346,008,310
false
null
// Different compile happens on:JVM ,JVM -Xnew-inference val z: Int = TODO() fun box() { (z ?: true === 1L) .not() }
1
null
1
1
e772ef1f8f951873ebe7d8f6d73cf19aead480fa
123
kotlinWithFuzzer
Apache License 2.0
src/main/kotlin/com/example/springbootrestapikt/pojo/Cell.kt
SultanICQ
347,057,414
false
null
package com.example.springbootrestapikt.pojo class Cell(val fighter: Fighter, val position: Position) { } fun List<Cell>.rowOf(cell: Cell) = this.filter { it.position.vertical == cell.position.vertical } fun List<Cell>.columnOf(cell: Cell) = this.filter { it.position.horizontal == cell.position.horizontal }
0
Kotlin
0
1
a34021e667a5148ac21aded0962d2235ff5655cf
312
street-fighter-kata-kotlin
Apache License 2.0
processor-steps/src/main/java/boringyuri/processor/common/steps/type/CommonTypeName.kt
anton-novikau
252,574,617
false
{"Kotlin": 210266, "Java": 63079, "Shell": 2935}
/* * Copyright 2020 Anton Novikau * * 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 boringyuri.processor.common.steps.type import androidx.annotation.NonNull import androidx.annotation.Nullable import boringyuri.api.adapter.BoringTypeAdapter import com.squareup.javapoet.ClassName import com.squareup.javapoet.ParameterizedTypeName import com.squareup.javapoet.TypeName import com.squareup.javapoet.WildcardTypeName import org.jetbrains.annotations.NotNull as JBNonNull import org.jetbrains.annotations.Nullable as JBNullable object CommonTypeName { val NON_NULL: ClassName = ClassName.get(NonNull::class.java) val NULLABLE: ClassName = ClassName.get(Nullable::class.java) val JB_NON_NULL: ClassName = ClassName.get(JBNonNull::class.java) val JB_NULLABLE: ClassName = ClassName.get(JBNullable::class.java) val STRING: ClassName = ClassName.get(String::class.java) val OVERRIDE: ClassName = ClassName.get(Override::class.java) var UNSUPPORTED_OPERATION: ClassName = ClassName.get(UnsupportedOperationException::class.java) val MAP: ClassName = ClassName.get(MutableMap::class.java) val HASH_MAP: ClassName = ClassName.get(HashMap::class.java) val CLASS: ClassName = ClassName.get(Class::class.java) val ANDROID_URI: ClassName = ClassName.get("android.net", "Uri") var ANDROID_URI_MATCHER: ClassName = ClassName.get("android.content", "UriMatcher") val ANDROID_URI_BUILDER: ClassName = ANDROID_URI.nestedClass("Builder") private var TYPE_ADAPTER: ClassName = ClassName.get(BoringTypeAdapter::class.java) val ANY_TYPE_ADAPTER: ParameterizedTypeName = ParameterizedTypeName.get( TYPE_ADAPTER, WildcardTypeName.subtypeOf(TypeName.OBJECT) ) val STRING_LIST: ParameterizedTypeName = ParameterizedTypeName.get( ClassName.get(MutableList::class.java), STRING ) }
2
Kotlin
2
12
ff4e4e1436cf0913207271ed0f777aeba810fdc5
2,401
boringYURI
Apache License 2.0
src/main/kotlin/io/projectenv/intellijplugin/services/impl/ProjectEnvConfigFileResolverServiceImpl.kt
Project-Env
324,322,609
false
{"Kotlin": 50785}
package io.projectenv.intellijplugin.services.impl import com.intellij.openapi.project.Project import io.projectenv.intellijplugin.services.ProjectEnvConfigFileResolverService import java.io.File class ProjectEnvConfigFileResolverServiceImpl(val project: Project) : ProjectEnvConfigFileResolverService { override fun resolveConfig(): File? { val configFile = File(project.basePath, "project-env.toml") if (!configFile.exists()) { return null } return configFile } override fun dispose() { // noop } }
3
Kotlin
1
7
5fcaf74f76f3605481cadd7455fc8bb65446d17a
574
project-env-intellij-plugin
MIT License
app/src/main/java/com/sunnyweather/android/SunnyWeatherApplication.kt
maxwellcatoo
471,893,716
false
{"Kotlin": 32058}
package com.sunnyweather.android import android.annotation.SuppressLint import android.app.Application import android.content.Context /** * 全局提供获取context * 也可以子啊object中定义全局变量,方便之后的获取 */ class SunnyWeatherApplication: Application() { companion object { // 该注解用于忽略警告: Do not place Android context classes in static fields; this is a memory leak @SuppressLint("StaticFieldLeak") lateinit var context: Context const val isGApi = true // 彩云天气api的key值 const val TOKEN = "TOKEN值" // 高德地图 天气查询api申请到的key const val G_TOKEN = "<PASSWORD>" } override fun onCreate() { super.onCreate() context = applicationContext } }
0
Kotlin
0
1
93012abe323a819a9e81132139590f71de7240f0
709
SunnyWeather
MIT License
app/src/main/java/com/example/emojigarden/MainActivity.kt
ssoni-wish
368,323,011
true
{"Kotlin": 14665}
package com.example.emojigarden import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.GridCells import androidx.compose.foundation.lazy.LazyVerticalGrid import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.setContent import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.viewinterop.viewModel import com.example.emojigarden.ui.EmojiGardenTheme @ExperimentalFoundationApi @ExperimentalLayout class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { val loginVm : LoginVm = viewModel() if(loginVm.showGarden){ val model : EmojiVmRealm = viewModel() MainActivityUi(model.emojiState) } else { LoginView(loginVm::login) } } } } @ExperimentalFoundationApi @ExperimentalLayout @Composable fun EmojiGrid(emojiList: List<EmojiTile>) { LazyVerticalGrid(cells = GridCells.Adaptive(20.dp)) { items(emojiList) { emojiTile -> EmojiHolder(emojiTile) } } } @Composable fun EmojiHolder(emoji: EmojiTile) { Text(emoji.emoji) } @Preview @Composable fun EmojiPreview() { EmojiHolder(EmojiTile().apply { emoji = "😼" }) } @ExperimentalFoundationApi @ExperimentalLayout @Composable fun MainActivityUi(emojiList: List<EmojiTile>) { EmojiGardenTheme { Box( Modifier.fillMaxSize().padding(16.dp) ) { EmojiGrid(emojiList) } } } @Composable fun LoginView(login : () -> Unit) { Column(modifier = Modifier.fillMaxWidth().padding(16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally){ Button(login){ Text("Login") } } } @Composable @Preview(showBackground = true) fun LoginPreview() { LoginView{} } @ExperimentalFoundationApi @ExperimentalLayout @Preview(showBackground = true) @Composable fun DefaultPreview() { val emojis = listOf("🐤","🐦","🐔","🦤","🕊","️","🦆","🦅","🪶","🦩","🐥","-","🐣","🦉","🦜","🦚","🐧","🐓","🦢","🦃","🦡","🦇","🐻","🦫","🦬","🐈","‍","⬛","🐗","🐪","🐈","🐱","🐿","️","🐄","🐮","🦌","🐕","🐶","🐘","🐑","🦊","🦒","🐐","🦍","🦮","🐹","🦔","🦛","🐎","🐴","🦘","🐨","🐆","🦁","🦙","🦣","🐒","🐵","🐁","🐭","🦧","🦦","🐂","🐼","🐾","🐖","🐷","🐽","🐻","‍","❄","️","🐩","🐇","🐰","🦝","🐏","🐀","🦏","🐕","‍","🦺","🦨","🦥","🐅","🐯","🐫","-","🦄","🐃","🐺","🦓","🐳","🐡","🐬","🐟","🐙","🦭","🦈","🐚","🐳","🐠","🐋","🌱","🌵","🌳","🌲","🍂","🍀","🌿","🍃","🍁","🌴","🪴","🌱","☘","️","🌾","🐊","🐊","🐉","🐲","🦎","🦕","🐍","🦖","-","🐢") MainActivityUi(List(102){ i -> EmojiTile().apply { emoji = emojis[i] }}) }
0
null
0
0
53021077c7f4b99b39a1c95b19cca266b2d48f01
3,005
EmojiGarden
Apache License 2.0
src/main/kotlin/com/beust/kobalt/plugin/publish/JCenterApi.kt
benignbala
43,803,632
true
{"Kotlin": 226043, "Java": 10604, "HTML": 1021, "Shell": 17}
package com.beust.kobalt.plugin.publish import com.beust.klaxon.* import com.beust.kobalt.api.Project import com.beust.kobalt.internal.TaskResult import com.beust.kobalt.maven.Gpg import com.beust.kobalt.maven.Http import com.beust.kobalt.maven.KobaltException import com.beust.kobalt.maven.Md5 import com.beust.kobalt.misc.* import com.google.inject.assistedinject.Assisted import com.squareup.okhttp.Response import org.jetbrains.annotations.Nullable import java.io.ByteArrayInputStream import java.io.File import java.nio.charset.Charset import javax.inject.Inject data class JCenterPackage(val jo: JsonObject) { @Suppress("UNCHECKED_CAST") val latestPublishedVersion = (jo.get("versions") as JsonArray<String>).get(0) } open public class UnauthenticatedJCenterApi @Inject constructor(open val http: Http){ companion object { const val BINTRAY_URL_API = "https://api.bintray.com" const val BINTRAY_URL_API_CONTENT = BINTRAY_URL_API + "/content" } fun parseResponse(response: String) : JsonObject { return Parser().parse(ByteArrayInputStream(response.toByteArray(Charset.defaultCharset()))) as JsonObject } fun getPackage(name: String) : JCenterPackage { val url = arrayListOf(BINTRAY_URL_API, "packages", "cbeust", "maven", "kobalt").join("/") val response = http.get(url).getAsString() val result = parseResponse(response) return JCenterPackage(result) } val kobaltPackage : JCenterPackage get() = getPackage("kobalt") } public class JCenterApi @Inject constructor (@Nullable @Assisted("username") val username: String?, @Nullable @Assisted("password") val password: String?, override val http: Http, val gpg: Gpg, val executors: KobaltExecutors) : UnauthenticatedJCenterApi(http) { interface IFactory { fun create(@Nullable @Assisted("username") username: String?, @Nullable @Assisted("password") password: String?) : JCenterApi } fun packageExists(packageName: String) : Boolean { val url = arrayListOf(UnauthenticatedJCenterApi.BINTRAY_URL_API, "packages", username!!, "maven", packageName) .join("/") val response = http.get(username, password, url).getAsString() val jo = parseResponse(response) return jo.string("name") == packageName } fun createPackage(packageName: String) : String { val url = arrayListOf(UnauthenticatedJCenterApi.BINTRAY_URL_API, "packages", username!!, "maven").join("/") val jo = json { obj("name" to packageName) obj("license" to array("Apache 2.0")) } return http.post(username, password, url, jo.toJsonString()) } fun uploadMaven(project: Project, files: List<File>, configuration : JCenterConfiguration?) : TaskResult { if (! packageExists(project.name!!)) { throw KobaltException("Couldn't find a package called ${project.name} on bintray, please create one first" + " as explained at https://bintray.com/docs/usermanual/uploads/uploads_creatinganewpackage.html") } val fileToPath: (File) -> String = { f: File -> arrayListOf( UnauthenticatedJCenterApi.BINTRAY_URL_API_CONTENT, username!!, "maven", project.name!!, project.version!!, project.group!!.replace(".", "/"), project.artifactId!!, project.version!!, f.name) .join("/") } return upload(files, configuration, fileToPath, generateMd5 = true, generateAsc = true) } fun uploadFile(file: File, url: String, configuration: JCenterConfiguration, generateMd5: Boolean = false, generateAsc: Boolean = false) = upload(arrayListOf(file), configuration, { f: File -> "${UnauthenticatedJCenterApi.BINTRAY_URL_API_CONTENT}/$username/generic/$url"}, generateMd5, generateAsc) private fun upload(files: List<File>, configuration : JCenterConfiguration?, fileToPath: (File) -> String, generateMd5: Boolean = false, generateAsc: Boolean) : TaskResult { val filesToUpload = arrayListOf<File>() if (generateAsc) { // Create the .asc files filesToUpload.addAll(gpg.runGpg(files)) } files.forEach { filesToUpload.add(it) if (generateMd5) { // Create and upload the md5 for this file with(File(it.absolutePath)) { val md5: String = Md5.toMd5(this) val md5File = File(absolutePath + ".md5") md5File.writeText(md5) filesToUpload.add(md5File) } } } // // If any configuration was given, apply them so the URL reflects them, e.g. ?publish=1 // val options = arrayListOf<String>() if (configuration?.publish == true) options.add("publish=1") val optionPath = StringBuffer() if (options.size() > 0) { optionPath.append("?" + options.join("&")) } // // Uploads can'be done in parallel or JCenter rejects them // val fileCount = filesToUpload.size() if (fileCount > 0) { log(1, " Found $fileCount artifacts to upload: " + filesToUpload.get(0) + if (fileCount > 1) "..." else "") var i = 1 val errorMessages = arrayListOf<String>() fun dots(total: Int, list: List<Boolean>) : String { val spaces : String = Array(total - list.size(), { " " }).join("") return "|" + list.map { if (it) "." else "X" }.join("") + spaces + "|" } val results = arrayListOf<Boolean>() filesToUpload.forEach { file -> http.uploadFile(username, password, fileToPath(file) + optionPath, file, { r: Response -> results.add(true)}, { r: Response -> results.add(false) val jo = parseResponse(r.body().string()) errorMessages.add(jo.string("message") ?: "No message found") }) val end = if (i >= fileCount) "\n" else "" log(1, " Uploading " + (i++) + " / $fileCount " + dots(fileCount, results) + end, false) } if (errorMessages.isEmpty()) { return TaskResult() } else { error("Errors while uploading:\n" + errorMessages.map { " $it" }.join("\n")) return TaskResult(false, errorMessages.join("\n")) } } else { warn("Found no artifacts to upload") return TaskResult() } } }
0
Kotlin
0
0
8fe1dd10b076d5363455875b8422f929dc924fa6
6,991
kobalt
Apache License 2.0
View-common/src/main/kotlin/view/core/loaders/Ids.kt
mzaart
160,253,085
false
null
package view.core.loaders /** * This class keeps track of used view Ids. */ class Ids { private val ids: MutableList<Int> = mutableListOf() private var idCounter = 0 /** * Returns a new unique id * * @return The generated Id */ fun newId(): Int { val newId = idCounter++ ids += newId return newId } /** * Marks the id as "used" * * @param id The used Id */ fun addId(id: Int): Boolean { if (containsId(id)) { return false } ids += id return true } /** * Checks if the passed id is already used. * * @param The id to check. * @return True if the id is used before, false otherwise */ fun containsId(id: Int) = ids.contains(id) /** * Mark all previously used Ids as "unused" */ fun clear() = ids.clear() }
0
Kotlin
1
2
b374346a2a17dca51ecbabc00e058eaeb286ae6f
902
View
Apache License 2.0
app/src/main/java/com/creepersan/switchhost/manager/FileManager.kt
CreeperSan
216,014,973
false
null
package com.creepersan.switchhost.manager import android.os.Environment import com.creepersan.switchhost.bean.HostFile import java.io.File import java.util.* object FileManager { private val NAME_DIRECTORY_ROOT = "SwitchHost" private val NAME_DIRECTORY_HOST = "host" private val NAME_DIRECTORY_UPDATE = "update" private val NAME_DIRECTORY_BACKUP = "backup" fun getApplicationDirectory(): File { return File("${Environment.getExternalStorageDirectory().path}/$NAME_DIRECTORY_ROOT") } fun getHostDirectory():File{ return File("${getApplicationDirectory().path}/$NAME_DIRECTORY_HOST") } fun getUpdateDirectory():File{ return File("${getApplicationDirectory().path}/$NAME_DIRECTORY_UPDATE") } fun getBackupDirectory():File{ return File("${getApplicationDirectory().path}/$NAME_DIRECTORY_BACKUP") } fun getSystemHostFile():File{ // return File("/system/etc/${System.currentTimeMillis()}.host") return File("/system/etc/hosts") // return File("/storage/emulated/0/${System.currentTimeMillis()}.host") } fun initApplicationDirectory():Boolean{ arrayListOf( getApplicationDirectory(), getHostDirectory(), getUpdateDirectory(), getBackupDirectory() ).forEach { directory -> if (!initDirectory(directory)){ return false } } return true } fun getAllHostFile(): ArrayList<HostFile> { val list = ArrayList<HostFile>() getHostDirectory().listFiles()?.forEach { val hostFile = HostFile.new(it.path) if (hostFile != null){ list.add(hostFile) } } list.sortBy { hostFile -> hostFile.name.toLowerCase(Locale.getDefault()) } return list } fun getAllBackupHostFile(): ArrayList<HostFile>{ val list = ArrayList<HostFile>() getBackupDirectory().listFiles()?.forEach { val hostFile = HostFile.new(it.path) if (hostFile != null){ list.add(hostFile) } } list.sortBy { hostFile -> hostFile.name.toLowerCase(Locale.getDefault()) } return list } fun deleteHostFile(hostFile:HostFile):Boolean{ val file = File(hostFile.path) if (!file.exists()) { return true } return file.delete() } fun hasBackupHostFile():Boolean{ return getBackupDirectory().list()?.isNotEmpty() ?: false } /** * 初始化文件夹,有则使用,无则创建 */ private fun initDirectory(directory:File):Boolean{ if (directory.exists()){ return directory.isDirectory }else{ return directory.mkdirs() } } }
0
Kotlin
0
4
103fee3880a9544d46c460fa0312b9cefd32e349
2,807
SwitchHost-Android
Apache License 2.0
src/test/kotlin/fundamental/StackDequeOptTest.kt
xmmmmmovo
280,634,710
false
null
/* * Copyright (c) 2020. xmmmmmovo */ package fundamental import ds.StackDequeOpt import org.junit.jupiter.api.* import org.junit.jupiter.api.Assertions.* import org.junit.platform.commons.logging.LoggerFactory internal class StackDequeOptTest { private val sdo = StackDequeOpt<Int>() companion object { private val log = LoggerFactory.getLogger(StackDequeOptTest::class.java) @BeforeAll @JvmStatic fun before() { log.info { "StackDequeOptTest start" } } @AfterAll @JvmStatic fun after() { log.info { "StackDequeOptTest end" } } } @Test fun isEmpty() { log.info { "isEmpty testing" } assertEquals(true, sdo.isEmpty()) sdo.pushRight(1) assertEquals(false, sdo.isEmpty()) sdo.popLeft() assertEquals(true, sdo.isEmpty()) } @Test fun pushRight() { log.info { "pushRight testing" } sdo.pushRight(1) sdo.pushRight(2) sdo.pushRight(3) assertEquals(1, sdo.popLeft()) assertEquals(2, sdo.popLeft()) assertEquals(3, sdo.popLeft()) } @Test fun peekLeft() { log.info { "peekLeft testing" } sdo.pushRight(1) sdo.pushRight(2) sdo.pushRight(3) assertEquals(1, sdo.peekLeft()) sdo.popLeft() assertEquals(2, sdo.peekLeft()) } @Test fun getSize() { log.info { "getSize testing" } assertEquals(0, sdo.size) sdo.pushRight(1) assertEquals(1, sdo.size) sdo.popLeft() assertEquals(0, sdo.size) sdo.pushRight(1) sdo.pushRight(2) sdo.pushRight(3) assertEquals(3, sdo.size) } }
0
Kotlin
0
0
94da0519cf2b8d8a9b42b4aea09caf50d9732599
1,764
Algorithms4thEditionKotlinSolutions
Apache License 2.0
src/main/kotlin/no/nav/syfo/client/pdl/PdlClient.kt
navikt
257,523,904
false
null
package no.nav.syfo.client.pdl import io.ktor.client.call.* import io.ktor.client.request.* import io.ktor.client.statement.* import io.ktor.http.* import no.nav.syfo.client.azuread.v2.AzureAdV2Client import no.nav.syfo.client.azuread.v2.AzureAdV2Token import no.nav.syfo.client.httpClient import no.nav.syfo.domain.PersonIdent import no.nav.syfo.util.* import org.slf4j.LoggerFactory class PdlClient( private val azureAdV2Client: AzureAdV2Client, private val pdlClientId: String, private val pdlUrl: String, ) { suspend fun personEksisterer( personIdent: PersonIdent, ): Boolean { val token = azureAdV2Client.getSystemToken(pdlClientId) ?: throw RuntimeException("Failed to send request to PDL: No token was found") return identer( ident = personIdent.value, token = token, )?.hentIdenter?.identer?.isNotEmpty() ?: false } private suspend fun identer( ident: String, token: AzureAdV2Token, ): PdlHentIdenter? { val request = PdlHentIdenterRequest( query = getPdlQuery("/pdl/hentIdenter.graphql"), variables = PdlHentIdenterRequestVariables( ident = ident, historikk = false, grupper = listOf( IdentType.AKTORID.name, IdentType.FOLKEREGISTERIDENT.name ) ) ) val response: HttpResponse = httpClient.post(pdlUrl) { body = request header(HttpHeaders.ContentType, "application/json") header(HttpHeaders.Authorization, bearerHeader(token.accessToken)) header(TEMA_HEADER, ALLE_TEMA_HEADERVERDI) header(IDENTER_HEADER, IDENTER_HEADER) } return when (response.status) { HttpStatusCode.OK -> { val pdlPersonReponse = response.receive<PdlIdenterResponse>() if (pdlPersonReponse.errors.isNullOrEmpty()) { COUNT_CALL_PDL_IDENTER_SUCCESS.inc() pdlPersonReponse.data } else { COUNT_CALL_PDL_IDENTER_FAIL.inc() pdlPersonReponse.errors.forEach { logger.error("Error while requesting Identer from PersonDataLosningen: ${it.message}") } null } } else -> { COUNT_CALL_PDL_IDENTER_FAIL.inc() throw RuntimeException("Request with url: $pdlUrl failed with response code ${response.status.value}") } } } private fun getPdlQuery(queryFilePath: String): String { return this::class.java.getResource(queryFilePath) .readText() .replace("[\n\r]", "") } companion object { private val logger = LoggerFactory.getLogger(PdlClient::class.java) const val IDENTER_HEADER = "identer" } }
1
null
0
1
eff4595eb477829a9d7241466039c564a0a16bdf
2,983
padm2
MIT License
app/src/main/java/com/sharkaboi/mediahub/modules/anime_search/repository/AnimeSearchRepositoryImpl.kt
1999FordFocus
379,613,392
true
{"Kotlin": 432335}
package com.sharkaboi.mediahub.modules.anime_search.repository import android.content.SharedPreferences import android.util.Log import androidx.paging.Pager import androidx.paging.PagingConfig import androidx.paging.PagingData import com.sharkaboi.mediahub.data.api.ApiConstants import com.sharkaboi.mediahub.data.api.models.anime.AnimeSearchResponse import com.sharkaboi.mediahub.data.api.retrofit.AnimeService import com.sharkaboi.mediahub.data.datastore.DataStoreRepository import com.sharkaboi.mediahub.data.paging.AnimeSearchDataSource import com.sharkaboi.mediahub.data.sharedpref.SharedPreferencesKeys import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.firstOrNull class AnimeSearchRepositoryImpl( private val animeService: AnimeService, private val dataStoreRepository: DataStoreRepository, private val sharedPreferences: SharedPreferences ) : AnimeSearchRepository { override suspend fun getAnimeByQuery(query: String): Flow<PagingData<AnimeSearchResponse.Data>> { val showNsfw = sharedPreferences.getBoolean(SharedPreferencesKeys.NSFW_OPTION, false) val accessToken: String? = dataStoreRepository.accessTokenFlow.firstOrNull() Log.d(TAG, "accessToken: $accessToken") return Pager( config = PagingConfig( pageSize = ApiConstants.API_PAGE_LIMIT, enablePlaceholders = false ), pagingSourceFactory = { AnimeSearchDataSource( animeService = animeService, accessToken = accessToken, query = query, showNsfw = showNsfw ) } ).flow } companion object { private const val TAG = "AnimeSearchRepository" } }
0
null
0
0
5200b21912d2816ac6d992f95ce4e206971590e4
1,793
MediaHub
MIT License
app/src/main/java/com/puntogris/neonmaze/data/DocumentSnapshotDeserializer.kt
puntogris
268,299,359
false
null
package com.puntogris.neonmaze.data import com.google.firebase.firestore.DocumentSnapshot internal interface DocumentSnapshotDeserializer<T> : Deserializer<DocumentSnapshot, T>
0
Kotlin
0
0
cc862c0c9512e1cf43e701331322252b97ca3e5b
183
neon-maze
MIT License
app/src/main/java/com/test/project/ui/home_events/full_event/FullEventFragment.kt
Petrov-Daniil
568,047,081
false
null
package com.test.project.ui.home_events.full_event import android.content.Context import android.os.Bundle import android.text.method.ScrollingMovementMethod import android.view.* import android.viewbinding.library.fragment.viewBinding import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.fragment.app.Fragment import androidx.lifecycle.Lifecycle import androidx.lifecycle.lifecycleScope import androidx.lifecycle.repeatOnLifecycle import androidx.navigation.fragment.findNavController import coil.load import com.google.firebase.database.DatabaseReference import com.google.firebase.database.FirebaseDatabase import com.test.project.R import com.test.project.databinding.FullEventFragmentBinding import com.test.project.domain.entity.Event import com.test.project.ui.home_events.HomeEventViewModel import kotlinx.coroutines.launch import org.koin.androidx.viewmodel.ext.android.viewModel class FullEventFragment : Fragment(R.layout.full_event_fragment) { private val binding: FullEventFragmentBinding by viewBinding() private val model: HomeEventViewModel by viewModel() private val adapterEventList: FullEventListAdapter = FullEventListAdapter() private val dataBase: DatabaseReference = FirebaseDatabase.getInstance().getReference("events") override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val eventIndex = arguments?.getInt("position") ?: 0 viewLifecycleOwner.lifecycleScope.launch { model.eventStateFlow.collect { bindUi(it[eventIndex]) } } viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { launch { model.eventStateFlow.collect { adapterEventList.setUpdatedData(it) } } } } } private fun bindUi(event: Event) { with(binding) { with(event) { toolBar.inflateMenu(R.menu.full_event_menu) toolBar.setNavigationOnClickListener { findNavController().navigateUp() } toolBar.setOnMenuItemClickListener { item -> when (item.itemId) { R.id.delete_event -> { AlertDialog.Builder(requireContext()) .setMessage("Удалить мероприятие?") .setPositiveButton("Удалить") { _, _ -> model.delete(event.id) val dbEvent = dataBase.child(event.firebaseId) val deleteEvent = dbEvent.removeValue() deleteEvent.addOnSuccessListener { findNavController().navigateUp() Toast.makeText( requireContext(), "Мероприятие удалено", Toast.LENGTH_LONG ).show() }.addOnFailureListener { Toast.makeText( requireContext(), "Мероприятие не удалено, ошибка: $it", Toast.LENGTH_LONG ).show() } } .setNegativeButton("Отменить", null) .create() .show() true } else -> false } } textviewItemTitle.text = title textviewItemTitle.typeface = android.graphics.Typeface.DEFAULT_BOLD textviewItemDate.text = date textviewItemDescription.text = description textviewItemDescription.movementMethod = ScrollingMovementMethod() imageviewItemImage.load(imageUrl) } } } }
0
Kotlin
0
0
f5d994d4082da014021d6c4923d84b0eb0321907
4,408
Events
MIT License
app/src/main/java/reach52/marketplace/community/persistence/medication_mapper/SuppliersMapper.kt
reach52
422,514,975
false
{"Kotlin": 1436380, "Java": 18303}
package reach52.marketplace.community.persistence.medication_mapper import reach52.marketplace.community.models.medication.Suppliers import reach52.marketplace.community.persistence.Marshaler import reach52.marketplace.community.persistence.Unmarshaler class SuppliersMapper: Marshaler<Suppliers>, Unmarshaler<Suppliers> { companion object{ const val KEY_ID = "_id" const val KEY_IDENTIFIER = "identifier" const val KEY_SUPPLIER_NAME = "supplierName" const val KEY_TYPE = "type" const val TYPE_SUPPLIER = "medicationSupplier" } override fun marshal(t: Suppliers): Map<String, Any> { return mapOf( KEY_ID to t.id, KEY_IDENTIFIER to t.identifier, KEY_SUPPLIER_NAME to t.supplierName, KEY_TYPE to t.type ) } override fun unmarshal(properties: Map<String, Any>): Suppliers { return Suppliers( id = properties[KEY_ID] as String, identifier = properties[KEY_IDENTIFIER] as String, supplierName = properties[KEY_SUPPLIER_NAME] as String, type = properties[KEY_TYPE] as String ) } }
0
Kotlin
0
0
629c52368d06f978f19238d0bd865f4ef84c23d8
1,186
Marketplace-Community-Edition
MIT License
src/main/kotlin/io/data2viz/kotlinx/htmlplugin/ide/ConvertHTMLToKotlinxAction.kt
data2viz
178,198,023
false
null
package io.data2viz.kotlinx.htmlplugin.ide import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.command.WriteCommandAction import com.intellij.psi.PsiFile import com.intellij.psi.impl.source.html.HtmlFileImpl import io.data2viz.kotlinx.htmlplugin.conversion.HtmlPsiToHtmlDataConverter import io.data2viz.kotlinx.htmlplugin.conversion.converToHtmlElements import io.data2viz.kotlinx.htmlplugin.conversion.toKotlinx class ConvertHTMLToKotlinxAction : AnAction("Convert HTML To Kotlinx.html") { override fun actionPerformed(e: AnActionEvent) { logger.debug { "actionPerformed" } val editor = e.getRequiredData(CommonDataKeys.EDITOR) val project = e.project ?: return val document = editor.document val selectionModel = editor.selectionModel val start = selectionModel.selectionStart val end = selectionModel.selectionEnd val text = selectionModel.selectedText if (text.isNullOrEmpty()) { return } val sourcePsiFileFromText: PsiFile = HtmlPsiToHtmlDataConverter.createHtmlFileFromText(project, text!!) if (sourcePsiFileFromText !is HtmlFileImpl) { return } val convertedToKotlinText = sourcePsiFileFromText .converToHtmlElements() .toKotlinx() if (convertedToKotlinText.isEmpty()) { return } //Making the replacement WriteCommandAction.runWriteCommandAction(project) { document.replaceString(start, end, convertedToKotlinText) } selectionModel.removeSelection() } }
2
Kotlin
4
9
8268654f8195890a1a5dcd7080581541406e2435
1,761
kotlinx.html-plugin
Apache License 2.0
updater-mapper-standard/src/main/java/org/runestar/client/updater/mapper/std/classes/NetCache.kt
ittwit
163,532,582
true
{"Kotlin": 1295734, "Java": 982488}
package org.runestar.client.updater.mapper.std.classes import org.runestar.client.updater.mapper.IdentityMapper import org.runestar.client.updater.mapper.annotations.DependsOn import org.runestar.client.updater.mapper.extensions.Predicate import org.runestar.client.updater.mapper.extensions.predicateOf import org.runestar.client.updater.mapper.tree.Class2 @DependsOn(Client.NetCache_indexCaches::class) class NetCache : IdentityMapper.Class() { override val predicate = predicateOf<Class2> { field<Client.NetCache_indexCaches>().klass == it } }
0
Kotlin
0
0
0a3ff702877b63cbe71d710c24af2c98ba90a9ec
552
client
MIT License
src/main/kotlin/org/jitsi/jibri/service/JibriService.kt
tes5884
120,510,452
false
null
/* * Copyright @ 2018 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.jitsi.jibri.service import org.jitsi.jibri.util.StatusPublisher enum class JibriServiceStatus { FINISHED, ERROR } /** * Parameters needed for starting any [JibriService] */ data class ServiceParams( val usageTimeoutMinutes: Int ) typealias JibriServiceStatusHandler = (JibriServiceStatus) -> Unit /** * Interface implemented by all implemented [JibriService]s. A [JibriService] * is responsible for an entire feature of Jibri, such as recording a call * to a file or streaming a call to a url. */ abstract class JibriService : StatusPublisher<JibriServiceStatus>() { /** * Starts this [JibriService] */ abstract fun start(): Boolean /** * Stops this [JibriService] */ abstract fun stop() }
1
null
1
1
302282309812b5413b9397c5b49567dbc2770cbd
1,370
jibri
Apache License 2.0
app/src/main/java/com/mbobiosio/currencyconverter/App.kt
mbobiosio
494,454,639
false
null
package com.mbobiosio.currencyconverter import android.app.Application import dagger.hilt.android.HiltAndroidApp import timber.log.Timber /** * @Author <NAME> * https://linktr.ee/mbobiosio */ @HiltAndroidApp class App : Application() { override fun onCreate() { super.onCreate() initTimber() } private fun initTimber() { if (BuildConfig.DEBUG) Timber.plant(Timber.DebugTree()) } }
0
null
0
6
29a404cfa3def7bf0dea50e0ff4bc8e95001a5a6
429
CurrencyConverter
MIT License
celsius/src/main/java/com/moyuruaizawa/celsius/Temperature.kt
MoyuruAizawa
144,808,492
false
null
package com.moyuruaizawa.celsius data class Temperature(val type: String, val temperature: Float)
0
Kotlin
0
1
cf2bf11183dde8b39ceedc67a3041ab14d8c52a5
98
Celsius
Apache License 2.0
src/main/kotlin/com/github/shatteredsuite/core/math/vector/MutableVector2.kt
ShatteredSoftware
263,221,103
false
null
package com.github.shatteredsuite.core.math.vector import com.github.shatteredsuite.core.math.context.NumericContext open class MutableVector2<T : Number>(context: NumericContext<T>, x: T, y: T) : Vector2<T>(context, x, y) { fun translate(dx: Number, dy: Number) { with(context) { _x += dx _y += dy } } fun scale(scale: Number) { with(context) { _x *= scale _y *= scale } } fun scale(sx: Number, sy: Number) { with(context) { _x *= sx _y *= sy } } operator fun plus(other: MutableVector2<out Number>): MutableVector2<T> { return with(context) { MutableVector2(context, x + other.x, y + other.y) } } operator fun timesAssign(other: Number) { scale(other) } operator fun times(other: MutableVector2<out Number>): MutableVector2<T> { return with(context) { MutableVector2(context, x * other.x, y * other.y) } } operator fun timesAssign(other: MutableVector2<out Number>) { this.scale(other.x, other.y) } infix fun dot(other: MutableVector2<out Number>): T { return with(context) { x * other.x + y * other.y } } fun normalize() { with(context) { val inverseMagnitude = 1 / magnitude() _x /= inverseMagnitude _y /= inverseMagnitude } } fun asImmutable(): Vector2<T> { return this } }
5
null
3
1
13a5bd2ff37028281eb9fcb16f8418ee5e1508ed
1,549
ShatteredCore
MIT License
lang/src/main/kotlin/com/uchuhimo/extension/Extension.kt
uchuhimo
90,075,694
false
null
package com.uchuhimo.extension class HasExtensionFunction { fun Int.test() { println(this) } } fun main(args: Array<String>) { val hasExtensionFunction = HasExtensionFunction() hasExtensionFunction.apply { 1.test() } }
0
Kotlin
0
1
cbd4b6fbdc6c9af595369a4d7389044792cd20c0
257
kotlin-playground
Apache License 2.0
app/src/main/java/tool/xfy9326/schedule/ui/fragment/TableFragment.kt
XFY9326
325,915,275
false
null
package tool.xfy9326.schedule.ui.fragment import android.animation.LayoutTransition import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import androidx.core.os.bundleOf import androidx.core.view.children import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.Observer import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import tool.xfy9326.schedule.beans.CourseCell import tool.xfy9326.schedule.beans.ScheduleBuildBundle import tool.xfy9326.schedule.ui.vm.ScheduleViewModel import tool.xfy9326.schedule.utils.schedule.CourseUtils import tool.xfy9326.schedule.utils.view.ScheduleViewHelper import kotlin.properties.Delegates class TableFragment : Fragment(), Observer<ScheduleBuildBundle> { companion object { private const val ARGUMENT_WEEK_NUM = "ARGUMENT_WEEK_NUM" fun create(weekNum: Int) = TableFragment().apply { arguments = bundleOf( ARGUMENT_WEEK_NUM to weekNum ) } } private val viewModel by activityViewModels<ScheduleViewModel>() private var weekNum by Delegates.notNull<Int>() override fun onAttach(context: Context) { super.onAttach(context) weekNum = requireArguments().getInt(ARGUMENT_WEEK_NUM) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { return view ?: FrameLayout(requireContext()).apply { layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT) layoutTransition = LayoutTransition().apply { setAnimateParentHierarchy(false) } } } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) viewModel.scheduleBuildData.observeForever(this) } override fun onChanged(value: ScheduleBuildBundle) { lifecycleScope.launch(Dispatchers.Default) { val viewData = CourseUtils.getScheduleViewDataByWeek(weekNum, value) val scheduleView = ScheduleViewHelper.buildScheduleView(requireContext(), viewData, ::onCourseCellClick) updateScheduleView(scheduleView) } } override fun onDestroyView() { viewModel.scheduleBuildData.removeObserver(this) super.onDestroyView() } private suspend fun updateScheduleView(view: View) = withContext(Dispatchers.Main.immediate) { (requireView() as? ViewGroup)?.apply { if (view != children.firstOrNull()) { removeAllViewsInLayout() addView(view) } } } private fun onCourseCellClick(courseCell: CourseCell) { viewModel.showCourseDetailDialog(courseCell.courseId, courseCell.timeId) } }
0
null
0
5
8e1fdbf481f19f7c57262d008fd0e550c58bf99f
3,052
Schedule
Apache License 2.0
src/main/kotlin/settingdust/kinecraft/serialization/MinecraftSerializers.kt
SettingDust
659,706,798
false
{"Kotlin": 173880, "Java": 5893}
package settingdust.kinecraft.serialization import kotlinx.serialization.ExperimentalSerializationApi import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import net.minecraft.nbt.CompoundTag import net.minecraft.resources.ResourceLocation import net.minecraft.world.item.ItemStack @ExperimentalSerializationApi object ResourceLocationStringSerializer : KSerializer<ResourceLocation> { override val descriptor = PrimitiveSerialDescriptor(ResourceLocation::class.simpleName!!, PrimitiveKind.STRING) override fun deserialize(decoder: Decoder) = ResourceLocation(decoder.decodeString()) override fun serialize(encoder: Encoder, value: ResourceLocation) = encoder.encodeString(value.toString()) } @ExperimentalSerializationApi object ItemStackSerializer : KSerializer<ItemStack> { override val descriptor = SerialDescriptor(ItemStack::class.simpleName!!, CompoundTagSerializer.descriptor) override fun deserialize(decoder: Decoder) = ItemStack.of(decoder.decodeSerializableValue(CompoundTagSerializer)) override fun serialize(encoder: Encoder, value: ItemStack) = encoder.encodeSerializableValue(CompoundTagSerializer, CompoundTag().also(value::save)) }
0
Kotlin
0
0
f8da1290a858127e70ed1911bf4ee7a8e1281b77
1,481
kinecraft-serialization
MIT License
app/src/androidTest/java/com/foreverrafs/superdiary/di/TestPersistenceModule.kt
rafsanjani
315,355,130
false
null
package com.foreverrafs.superdiary.di import android.app.Application import android.content.SharedPreferences import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.createDataStore import androidx.preference.PreferenceManager import androidx.room.Room import com.foreverrafs.superdiary.business.repository.DataSource import com.foreverrafs.superdiary.business.repository.DiaryRepository import com.foreverrafs.superdiary.data.MockDataSource import com.foreverrafs.superdiary.framework.datasource.local.database.DiaryDao import com.foreverrafs.superdiary.framework.datasource.local.database.DiaryDatabase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object TestPersistenceModule { @Singleton @Provides fun provideDiaryDatabase(appContext: Application): DiaryDatabase { return Room .inMemoryDatabaseBuilder(appContext, DiaryDatabase::class.java) .fallbackToDestructiveMigration() .build() } @Singleton @Provides fun provideDataStore(appContext: Application): DataStore<Preferences> { return appContext.createDataStore(name = "settings") } @Singleton @Provides fun provideSharedPreferences(appContext: Application): SharedPreferences { return PreferenceManager.getDefaultSharedPreferences(appContext) } @Singleton @Provides fun provideRoomDataSource( ): DataSource { return MockDataSource() } @Singleton @Provides fun provideDiaryRepository(dataSource: DataSource): DiaryRepository { return DiaryRepository(dataSource = dataSource) } @Singleton @Provides fun provideDiaryDao(database: DiaryDatabase): DiaryDao { return database.diaryDao() } }
7
Kotlin
2
7
cc4e67f8946a10f89eb299359ce62b05779c51a8
1,963
superdiary
MIT License
game/src/main/kotlin/com/runt9/heroDynasty/character/item/weapon/HandCrossbow.kt
runt9
130,910,358
false
null
package com.runt9.heroDynasty.character.item.weapon class HandCrossbow : Weapon() { override val damageRangeRoll = 0.6 to 1.0 override val damageClampRoll = 0.04 to 0.12 override val accuracyRoll = 0.9 to 1.15 override val critChanceRoll = 1.1 to 1.3 override val critDamageRoll = 0.9 to 1.0 override val offHandPenaltyRoll = -0.5 to -0.3 override val range = 4 override val hands = 1 }
0
Kotlin
0
0
87be0aa7394a2980145768ee315797a3e1655ff0
420
hero-dynasty
MIT License
src/main/java/io/github/bloodnighttw/whateverBot/utils/command/CommandRegister.kt
bloodnighttw
441,596,457
false
{"Kotlin": 46130, "Procfile": 61}
package io.github.bloodnighttw.whateverBot.utils.command import net.dv8tion.jda.api.JDA import net.dv8tion.jda.api.interactions.commands.build.CommandData import net.dv8tion.jda.api.interactions.commands.build.Commands import org.slf4j.LoggerFactory class CommandRegister(private val bot: JDA) { private val logger = LoggerFactory.getLogger(CommandRegister::class.java) private val commandDataLocalList: ArrayList<CommandData> = ArrayList() private val commandDataGlobalList: ArrayList<CommandData> = ArrayList() private fun register(iCommand: ICommand) { var tempCommandData = iCommand.command val tempDataList: ArrayList<CommandData> = if (iCommand.isGlobal) commandDataGlobalList else commandDataLocalList tempCommandData = tempCommandData.addSubcommands(iCommand.subCommandMap.values.map { it.subCommand }) logger.debug("add ${if(tempDataList === commandDataGlobalList) "GLOBAL" else "LOCAL"} command for ${iCommand.command.name}") tempDataList.add(tempCommandData) for (alias in iCommand.alias) { tempCommandData = Commands.slash(alias, tempCommandData.description).addSubcommands(tempCommandData.subcommands) tempDataList.add(tempCommandData) logger.debug("add ${if(tempDataList === commandDataGlobalList) "GLOBAL" else "LOCAL"} command for ${iCommand.command.name}") } } fun registerCommand(iCommand: ICommand) { register(iCommand) bot.addEventListener(CommandHandler(iCommand)) } fun registerPrivateCommand(iCommand: ICommand) { register(iCommand) bot.addEventListener(CommandHandler(iCommand, true)) } fun addToAllServer() { bot.updateCommands().addCommands(commandDataGlobalList).queue() for (guild in bot.guilds) { logger.debug("Guild Found Name:" + guild.name) logger.debug("Add command to server: " + guild.name) guild.updateCommands() .addCommands(commandDataLocalList) //.addCommands(commandDataGlobalList) .queue() } } }
12
Kotlin
0
1
54abbc11db2b4604e1c3a71493b027f2f850c114
1,925
WhateverBot
Apache License 2.0
app/src/main/java/com/pandacorp/knowui/presentation/ui/screens/SettingsScreen.kt
MrRuslanYT
664,626,789
false
{"Kotlin": 107994}
package com.pandacorp.knowui.presentation.ui.screens import android.content.Context import android.content.res.Configuration import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row 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.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.ArrowBack import androidx.compose.material.icons.filled.Logout import androidx.compose.material.ripple.LocalRippleTheme import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.livedata.observeAsState import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable 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.graphics.vector.ImageVector import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalInspectionMode import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.PlatformTextStyle import androidx.compose.ui.text.TextStyle 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 androidx.navigation.NavController import com.pandacorp.knowui.R import com.pandacorp.knowui.data.repository.CustomSharedPreferencesImpl import com.pandacorp.knowui.presentation.ui.dialogs.SettingsDialog import com.pandacorp.knowui.presentation.ui.theme.GrayBorder import com.pandacorp.knowui.presentation.ui.theme.KnowUITheme import com.pandacorp.knowui.presentation.ui.theme.WhiteRippleTheme import com.pandacorp.knowui.presentation.viewmodel.LoginViewModel import com.pandacorp.knowui.presentation.viewmodel.PreferencesViewModel import com.pandacorp.knowui.utils.Constants import com.pandacorp.knowui.utils.getAppVersion import com.pandacorp.knowui.utils.topappbar.FixedTopAppBar import com.pandacorp.knowui.utils.topappbar.TopAppBarDefaults import org.koin.androidx.compose.koinViewModel @OptIn(ExperimentalMaterial3Api::class) @Composable fun SettingsScreen( navController: NavController? = null, preferencesViewModel: PreferencesViewModel = koinViewModel(), loginViewModel: LoginViewModel = koinViewModel(), ) { val defaultTheme = Constants.Preferences.THEME_DEFAULT val defaultLanguage = stringResource(id = R.string.default_language) val theme = preferencesViewModel.themeLiveData.observeAsState().value?.ifEmpty { defaultTheme } ?: defaultTheme val language = preferencesViewModel.languageLiveData.observeAsState().value?.ifEmpty { defaultLanguage } ?: defaultLanguage val context = LocalContext.current var openedDialog: String? by rememberSaveable { mutableStateOf(null) } when (openedDialog) { Constants.Preferences.THEME_KEY -> SettingsDialog( key = Constants.Preferences.THEME_KEY, onValueAppliedListener = { openedDialog = null preferencesViewModel.changeTheme(it) }, onDismiss = { openedDialog = null }, ) Constants.Preferences.LANGUAGE_KEY -> SettingsDialog( key = Constants.Preferences.LANGUAGE_KEY, onValueAppliedListener = { openedDialog = null preferencesViewModel.changeLanguage(it) }, onDismiss = { openedDialog = null }, ) null -> Unit } Scaffold(topBar = { BackButtonTopAppBar(title = R.string.settings) { navController?.popBackStack() } }) { padding -> // Use inside of a Box to apply the padding right Box(modifier = Modifier.padding(padding)) { Column( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colorScheme.background) .verticalScroll(rememberScrollState()) .padding(bottom = 60.dp), ) { Text( text = stringResource(R.string.appearance), modifier = Modifier.padding(start = 24.dp, top = 20.dp), style = TextStyle(fontWeight = FontWeight.Bold), ) Card( modifier = Modifier .fillMaxWidth() .padding(horizontal = 20.dp) .padding(top = 8.dp), border = GrayBorder, colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.primary, ), ) { Column { CardComponent( drawable = R.drawable.ic_theme, text = stringResource(R.string.theme), value = getThemeTitle(context, theme), onClick = { openedDialog = Constants.Preferences.THEME_KEY }, ) CardComponent( drawable = R.drawable.ic_language, text = stringResource(R.string.language), value = getLanguageTitle(context, language), onClick = { openedDialog = Constants.Preferences.LANGUAGE_KEY }, ) } } Text( text = stringResource(R.string.another), modifier = Modifier .fillMaxSize() .padding(start = 24.dp, top = 20.dp), style = TextStyle(fontWeight = FontWeight.Bold), ) Card( modifier = Modifier .padding(horizontal = 20.dp) .fillMaxWidth() .padding(top = 8.dp), border = GrayBorder, colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.primary, ), ) { val isSignedAnonymously = loginViewModel.isSignedAnonymously() CardComponent( imageVector = Icons.Default.Logout, // Sign In if skipped and Sign Out if the user got account text = if (isSignedAnonymously) stringResource(R.string.signIn) else stringResource(R.string.signOut), ) { loginViewModel.signOut() } } Card( modifier = Modifier .padding(top = 8.dp) .padding(horizontal = 20.dp) .fillMaxWidth() .padding(top = 8.dp), border = GrayBorder, colors = CardDefaults.cardColors( containerColor = MaterialTheme.colorScheme.primary, ), ) { // Retrieve the version from build.gradle val version = if (LocalInspectionMode.current) { "1.0.0-preview" // Placeholder for preview } else { LocalContext.current.getAppVersion() } CardComponent( drawable = R.drawable.ic_version, text = stringResource(R.string.version, version), ) } } } } } @Composable private fun CardComponent( modifier: Modifier = Modifier, drawable: Int? = null, imageVector: ImageVector? = null, text: String = "", value: String? = null, onClick: () -> Unit = {}, ) { CompositionLocalProvider(LocalRippleTheme provides WhiteRippleTheme()) { Row( modifier = modifier .clickable(onClick = onClick) .fillMaxSize() .padding(horizontal = 12.dp, vertical = 8.dp) .padding(start = 4.dp, end = 4.dp, bottom = 8.dp, top = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { if (drawable != null) { Icon( painter = painterResource(id = drawable), contentDescription = null, modifier = Modifier .padding(end = 8.dp) .size(24.dp), tint = Color.White, ) } else if (imageVector != null) { Icon( imageVector = imageVector, contentDescription = null, modifier = Modifier .padding(end = 8.dp) .size(24.dp), tint = Color.White, ) } @Suppress("DEPRECATION") // includeFontPadding is set to true by default, ignore deprecation as the value is true by default Column { Text( text = text, style = TextStyle( fontSize = 16.sp, platformStyle = PlatformTextStyle(includeFontPadding = false), ), color = Color.White, ) if (value != null) { Text( modifier = Modifier.padding(top = 4.dp), text = value, style = TextStyle( fontSize = 14.sp, platformStyle = PlatformTextStyle(includeFontPadding = false), color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.8f), ), ) } } } } } @ExperimentalMaterial3Api @Composable fun BackButtonTopAppBar( title: Int = 0, onClick: () -> Unit = {} ) { FixedTopAppBar( title = { Text(text = stringResource(id = title)) }, colors = TopAppBarDefaults.smallTopAppBarColors(containerColor = MaterialTheme.colorScheme.primary), navigationIcon = { IconButton(onClick = onClick) { Icon(Icons.Default.ArrowBack, contentDescription = stringResource(id = R.string.back_button)) } }, ) } @Preview(showSystemUi = true, showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES) @Composable private fun SettingsScreenPreview() { KnowUITheme { SettingsScreen() } } private fun getThemeTitle( context: Context, key: String ): String = context.resources.getStringArray(R.array.Themes) .toList()[ CustomSharedPreferencesImpl.getThemesKeys(context) .indexOf(key), ] private fun getLanguageTitle( context: Context, key: String ): String = context.resources.getStringArray(R.array.Languages) .toList()[ CustomSharedPreferencesImpl.getLanguagesKeys(context) .indexOf(key), ]
0
Kotlin
0
0
2534f0208793afc06e74ac95bbed97f8bd904fc0
13,018
KnowUI
Apache License 2.0
core/deserialization/src/org/jetbrains/kotlin/serialization/deserialization/suspendFunctionTypeUtil.kt
arrow-kt
109,678,056
true
null
/* * Copyright 2010-2018 JetBrains s.r.o. 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.serialization.deserialization import org.jetbrains.kotlin.name.FqName @JvmField val KOTLIN_SUSPEND_BUILT_IN_FUNCTION_FQ_NAME = FqName("kotlin.suspend")
12
Kotlin
2
43
d2a24985b602e5f708e199aa58ece652a4b0ea48
347
kotlin
Apache License 2.0
test-utils/testData/api/objCacheB.kt
google
297,744,725
false
{"Kotlin": 2173589, "Shell": 5321, "Java": 3893}
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * 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. */ // WITH_RUNTIME // TEST PROCESSOR: ObjCacheBProcessor // EXPECTED: // value(true) // END // MODULE: lib // FILE: Test.kt open class BaseClass( open val value : List<Int> ) class SubClass( override val value : MutableList<Int> ) : BaseClass(value) // MODULE: main(lib) // FILE: Main.kt class Main
370
Kotlin
268
2,854
a977fb96b05ec9c3e15b5a0cf32e8e7ea73ab3b3
981
ksp
Apache License 2.0
src/main/kotlin/dev/teogor/pixel/harvest/database/DatabaseManager.kt
teogor
643,945,038
false
null
package dev.teogor.pixel.harvest.database object DatabaseManager { private val databaseHandler: DatabaseHandler = DatabaseHandler("src/main/resources/pixel-harvest.db").apply { initializeDatabase() } fun addUser(discordId: Long, username: String) { databaseHandler.addUser( discordId = discordId, username = username ) } fun addDownload(discordId: Long, url: String) { databaseHandler.addDownload( discordId = discordId, url = url ) } fun getTotalDownloadCountByDiscordUser(discordId: Long): Long { return databaseHandler.getTotalDownloadCountByDiscordUser( discordId = discordId, ) } }
0
Kotlin
0
0
c28d0e319ad59a4bf38f8309a80c47f66fccd6d8
738
pixel-harvest
Apache License 2.0
app/src/main/java/com/example/connectnodejs/adapter/HomeGenreAdapter.kt
Tuh11343
782,797,769
false
{"Kotlin": 270952}
package com.example.connectnodejs.adapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.example.connectnodejs.model.Genre import com.example.connectnodejs.R import com.example.connectnodejs.databinding.GenreViewHomeBinding class HomeGenreAdapter(var genreList: MutableList<Genre>) : RecyclerView.Adapter<HomeGenreAdapter.ViewHolder>() { inner class ViewHolder(val binding: GenreViewHomeBinding) : RecyclerView.ViewHolder(binding.root) override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder( GenreViewHomeBinding.inflate( LayoutInflater.from(parent.context), parent, false ) ) } override fun getItemCount(): Int { return genreList.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val genre = genreList[holder.absoluteAdapterPosition] if (genre != null) { Glide.with(holder.itemView.context) .load(genre.image) .placeholder(R.drawable.song_circle) .error(R.drawable.icon_shake_hand) .into(holder.binding.genreImg) holder.binding.genreName.text = genre.name } } }
0
Kotlin
0
0
80e1833793bd0bacdd68a6bf9d83da60a28f9bcb
1,396
Ebook_Kotlin
Open Market License
app/src/main/java/com/sumit/assistant/util/AppUtil.kt
sumitsahoo
263,283,011
false
null
package com.sumit.assistant.util import android.content.SharedPreferences import android.graphics.Color import android.graphics.drawable.AnimationDrawable import android.view.View import android.view.WindowManager import androidx.appcompat.app.AppCompatActivity import org.koin.core.KoinComponent import org.koin.core.inject class AppUtil { companion object : KoinComponent { private val sharedPreferences: SharedPreferences by inject() fun makeStatusbarTransparent(activity: AppCompatActivity) { activity.window.apply { clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN statusBarColor = Color.TRANSPARENT } } fun toggleAnimationBackground(view: View, isStart: Boolean) { if (isStart) { //window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN val animDrawable = view.background as AnimationDrawable animDrawable.setEnterFadeDuration(10) animDrawable.setExitFadeDuration(5000) animDrawable.start() } else { val animDrawable = view.background as AnimationDrawable animDrawable.stop() } } fun isSharedPrefKeyPresent(key: String): Boolean { return sharedPreferences.contains(key) } fun saveIntToSharedPref(key: String, value: Int) { with(sharedPreferences.edit()) { putInt(key, value) commit() } } fun getIntFromSharedPref(key: String): Int { return sharedPreferences.getInt(key, 0) } fun saveStringToSharedPref(key: String, value: String) { with(sharedPreferences.edit()) { putString(key, value) commit() } } fun getStringFromSharedPref(key: String): String? { return sharedPreferences.getString(key, "") } } }
1
Kotlin
5
4
a05c02fbf0e4c0877f1dfeeb8df01de193bbed19
2,215
RASA-With-Aimybox
MIT License
src/main/java/com/store/config/DummySecurityConfig.kt
znsio
690,364,752
false
{"Kotlin": 16669, "Java": 890}
package com.store.config import com.store.security.DummySecurityFilter import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration import org.springframework.context.annotation.Profile import org.springframework.http.HttpMethod import org.springframework.security.config.Customizer import org.springframework.security.config.annotation.web.builders.HttpSecurity import org.springframework.security.web.SecurityFilterChain import org.springframework.security.web.authentication.preauth.AbstractPreAuthenticatedProcessingFilter @Configuration @Profile("test") open class DummySecurityConfig { @Bean open fun dummyFilterChain(http: HttpSecurity): SecurityFilterChain? { http .authorizeRequests(Customizer { auth -> auth.anyRequest().permitAll() }) .addFilterBefore(DummySecurityFilter(), AbstractPreAuthenticatedProcessingFilter::class.java) .csrf().disable() return http.build() } }
10
Kotlin
0
1
e0403de82340fd572c3815d7ab77d057a8b335b7
1,026
specmatic-order-api-java-with-oauth
MIT License
os/src/main/kotlin/me/jraynor/os/Os.kt
MrManiacc
643,736,834
false
null
package me.jraynor.os import me.jraynor.vfs.VFS import me.jraynor.vfs.VPath import me.jraynor.vfs.impl.SystemVFS import java.io.File class Os(val workingDirectory: File) { private val vfs: VFS = SystemVFS(workingDirectory) }
0
Kotlin
0
0
dc555eb18a9272570d5f89a8a1f8a8a8cfd0d95d
233
jsedit
MIT License
app/src/main/java/konrad/tercjak/flickr/model/FlickrSize.kt
tercjak
233,453,745
false
null
package konrad.tercjak.flickr.model import com.squareup.moshi.Json data class FlickrSizesResponse( @field:Json(name = "sizes") val data: FlickrPhotoSizeList ) data class FlickrPhotoSizeList( @field:Json(name = "size") val items:List<FlickrImage> ) data class FlickrImage( @field:Json(name = "label") val label:String, @field:Json(name = "width") val width:Int, @field:Json(name = "height") val height:Int, @field:Json(name = "source") val url:String )
0
Kotlin
0
0
14d9a1407dc5cde8d89d271c54f3c97ef8609c72
500
flickr
Apache License 2.0
app/src/main/java/com/longitivityintime/test/di/NetworkModule.kt
youcefboukandoura
518,784,282
false
{"Kotlin": 16024}
package com.longitivityintime.test.di import com.longitivityintime.test.BuildConfig import com.longitivityintime.test.network.CoinsApi import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Singleton @Provides fun provideOkHttpClient() = if (BuildConfig.DEBUG) { val loggingInterceptor = HttpLoggingInterceptor() loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY) OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build() } else { OkHttpClient .Builder() .build() } @Singleton @Provides fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit = Retrofit.Builder() .addConverterFactory(MoshiConverterFactory.create()) .baseUrl("https://api.coingecko.com/") .client(okHttpClient) .build() @Provides @Singleton fun provideApiService(retrofit: Retrofit): CoinsApi = retrofit.create(CoinsApi::class.java) }
0
Kotlin
0
0
d8e1c1c0a95df3b711330cba21700868c202b932
1,317
LongtivityInTime
MIT License
app/src/main/java/com/example/mvvmavengers/features/avengerslist/koin/ListAvengerViewModelModule.kt
rmiguel1985
371,660,123
false
null
package com.example.mvvmavengers.features.avengerslist.koin import com.example.mvvmavengers.features.avengerslist.ui.AvengersListViewModel import kotlinx.coroutines.InternalCoroutinesApi import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.dsl.module @InternalCoroutinesApi @kotlinx.coroutines.ExperimentalCoroutinesApi val ListAvengerViewModelModule = module { viewModel { AvengersListViewModel(get()) } }
0
Kotlin
0
0
bdb596310d03bb819d5c74bc62087bef8185a760
425
andriod-mvvm-avengers
The Unlicense
core/designsystem/src/main/java/com/githukudenis/comlib/core/designsystem/ui/components/SectionSeparator.kt
DenisGithuku
707,847,935
false
{"Kotlin": 576276, "Java": 95753, "Roff": 12367}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.githukudenis.comlib.core.designsystem.ui.components import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.remember 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.unit.dp import com.githukudenis.comlib.core.designsystem.R @Composable fun SectionSeparator(modifier: Modifier = Modifier, title: String, onViewAll: () -> Unit) { val interactionSource = remember { MutableInteractionSource() } Row( modifier = modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically ) { Text( text = title, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.8f) ) Row( modifier = Modifier.clickable( interactionSource = interactionSource, enabled = true, indication = null, onClick = { onViewAll() } ), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(4.dp) ) { Text( text = stringResource(id = R.string.view_all), style = MaterialTheme.typography.labelSmall ) Icon( painter = painterResource(id = R.drawable.ic_chevron_right), contentDescription = stringResource(R.string.view_all), tint = MaterialTheme.colorScheme.onBackground.copy(alpha = 0.6f) ) } } }
5
Kotlin
1
0
f7cac6483c4d847fafd2777946798f683cf29533
2,747
comlib-android-client
Apache License 2.0
kwiet-actions-sdk/src/test/kotlin/au/com/louth/kwiet/actionssdk/ValuesTest.kt
louth
131,220,695
false
null
package au.com.louth.kwiet.actionssdk import org.hamcrest.CoreMatchers.* import org.hamcrest.MatcherAssert.assertThat import org.junit.Test class ValuesTest() { @Test fun verifyStandardIntents() { assertThat(StandardIntent.MAIN, `is`("actions.intent.MAIN")) assertThat(StandardIntent.TEXT, `is`("actions.intent.TEXT")) assertThat(StandardIntent.PERMISSION, `is`("actions.intent.PERMISSION")) assertThat(StandardIntent.OPTION, `is`("actions.intent.OPTION")) assertThat(StandardIntent.TRANSACTION_REQUIREMENTS_CHECK, `is`("actions.intent.TRANSACTION_REQUIREMENTS_CHECK")) assertThat(StandardIntent.DELIVERY_ADDRESS, `is`("actions.intent.DELIVERY_ADDRESS")) assertThat(StandardIntent.TRANSACTION_DECISION, `is`("actions.intent.TRANSACTION_DECISION")) assertThat(StandardIntent.CONFIRMATION, `is`("actions.intent.CONFIRMATION")) assertThat(StandardIntent.DATETIME, `is`("actions.intent.DATETIME")) assertThat(StandardIntent.SIGN_IN, `is`("actions.intent.SIGN_IN")) assertThat(StandardIntent.NO_INPUT, `is`("actions.intent.NO_INPUT")) assertThat(StandardIntent.CANCEL, `is`("actions.intent.CANCEL")) assertThat(StandardIntent.NEW_SURFACE, `is`("actions.intent.NEW_SURFACE")) assertThat(StandardIntent.REGISTER_UPDATE, `is`("actions.intent.REGISTER_UPDATE")) assertThat(StandardIntent.CONFIGURE_UPDATES, `is`("actions.intent.CONFIGURE_UPDATES")) } @Test fun verifyStandardArguments() { assertThat(StandardArgument.PERMISSION_GRANTED,`is`("PERMISSION")) assertThat(StandardArgument.OPTION,`is`("OPTION")) assertThat(StandardArgument.TRANSACTION_REQ_CHECK_RESULT,`is`("TRANSACTION_REQUIREMENTS_CHECK_RESULT")) assertThat(StandardArgument.DELIVERY_ADDRESS_VALUE,`is`("DELIVERY_ADDRESS_VALUE")) assertThat(StandardArgument.TRANSACTION_DECISION_VALUE,`is`("TRANSACTION_DECISION_VALUE")) assertThat(StandardArgument.CONFIRMATION,`is`("CONFIRMATION")) assertThat(StandardArgument.DATETIME,`is`("DATETIME")) assertThat(StandardArgument.SIGN_IN,`is`("SIGN_IN")) assertThat(StandardArgument.REPROMPT_COUNT,`is`("REPROMPT_COUNT")) assertThat(StandardArgument.IS_FINAL_REPROMPT,`is`("IS_FINAL_REPROMPT")) assertThat(StandardArgument.NEW_SURFACE,`is`("NEW_SURFACE")) assertThat(StandardArgument.REGISTER_UPDATE,`is`("REGISTER_UPDATE")) } }
0
Kotlin
0
0
5c75236dd3acefc2af8e5902344e510884ac71d5
2,466
kwiet
Apache License 2.0
source/app/src/main/java/com/apion/apionhome/data/model/local/LocationName.kt
viet06061999
471,421,323
true
{"Kotlin": 161735, "Java": 51216}
package com.apion.apionhome.data.model.local import com.apion.apionhome.data.model.GeneraEntity import com.apion.apionhome.utils.removeSpecific import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedName data class LocationName( @SerializedName("id") val id: Int = -1, @SerializedName("name") val name: String = "", var district: District, @SerializedName("prefix") val prefix: String = "" ) : ILocation { override fun getTitle(): String = district.getTitle() override fun getContent(): String = "$prefix $name, ${district.getContent()}" override fun areItemsTheSame(newItem: GeneraEntity): Boolean = newItem is District && this.id == newItem.id override fun areContentsTheSame(newItem: GeneraEntity): Boolean = newItem is District && this == newItem override fun toString(): String { return "${getContent()}${getTitle()}".removeSpecific() } fun getNameLocation() = "$prefix $name" }
0
null
0
0
24ddb088ffd985dcd34e3e8deeb5edcc1d717558
1,004
apion_home
Apache License 2.0
core/src/main/java/com/exozet/android/core/extensions/ByteArray+Extensions.kt
exozet
133,497,547
false
null
@file:JvmName("ByteArrayExtensions") package com.exozet.android.core.extensions import net.kibotu.logger.Logger import java.io.File import java.io.FileOutputStream /** * Created by [<NAME>](https://about.me/janrabe). */ fun ByteArray.saveAt(pathName: String): Boolean = try { FileOutputStream(File(pathName)).use { it.write(this) } true } catch (e: Exception) { Logger.e(e) false }
1
null
2
11
72cbb02bc262b1c26450b570e41842ab65406c3e
404
AndroidCore
MIT License
frontend/modules/core/src/jsMain/kotlin/io/github/andrewk2112/kjsbox/frontend/core/dinjection/DefaultDependencyInjectionInitializer.kt
andrew-k-21-12
497,585,003
false
{"Kotlin": 338265, "JavaScript": 7404, "HTML": 726}
package io.github.andrewk2112.kjsbox.frontend.core.dinjection import io.github.andrewk2112.kjsbox.frontend.core.dinjection.modules.designTokensModule import io.github.andrewk2112.kjsbox.frontend.core.dinjection.modules.hooksModule import io.github.andrewk2112.kjsbox.frontend.core.dinjection.modules.localizationModule import io.github.andrewk2112.kjsbox.frontend.core.dinjection.modules.reduxModule import org.kodein.di.DI /** * Includes default modules to provide injectable dependencies. */ internal class DefaultDependencyInjectionInitializer : DependencyInjectionInitializer { override fun initialize(builder: DI.MainBuilder) = with(builder) { import(hooksModule) import(reduxModule) import(designTokensModule) import(localizationModule) } }
0
Kotlin
0
2
6522756774ded07a335d29d6dd67204e5cfe0f23
793
kjs-box
MIT License
app/src/main/java/com/kennyc/dashweather/api/WeatherResult.kt
nguyenngan
193,031,765
true
{"Kotlin": 35770}
package com.kennyc.dashweather.api import com.kennyc.dashweather.models.DailyWeatherModel import com.kennyc.dashweather.models.WeatherModel /** * Created by Kenny-PC on 9/22/2017. */ open class WeatherResult { open var latitude: Float = 0.0F open var longitude: Float = 0.0F open var currently: WeatherModel? = null open var daily: DailyWeatherModel? = null }
0
Kotlin
0
0
a34f8c3f28aec9b16675ef0bcadc6d2b8ed816b4
382
DashWeatherExtension
Apache License 2.0
ychat/src/commonMain/kotlin/co/yml/ychat/domain/model/AudioParams.kt
codeandtheory
590,561,356
false
{"Objective-C": 147180, "Kotlin": 138808, "Swift": 395, "Shell": 355}
package co.yml.ychat.domain.model internal data class AudioParams( var model: String = "whisper-1", var prompt: String = "", var responseFormat: String = "json", var temperature: Double = 0.0, var language: String = "en" )
9
Objective-C
10
139
7f08e78844a779d615cd56b046744e8980e763ab
244
ychat
Apache License 2.0
src/main/kotlin/dev/adirelle/adicrate/client/renderer/CrateRenderer.kt
Adirelle
454,710,946
false
{"Kotlin": 74806}
@file:Suppress("UnstableApiUsage") package dev.adirelle.adicrate.client.renderer import dev.adirelle.adicrate.block.entity.CrateBlockEntity import net.fabricmc.api.EnvType.CLIENT import net.fabricmc.api.Environment import net.minecraft.client.MinecraftClient import net.minecraft.client.render.VertexConsumerProvider import net.minecraft.client.render.WorldRenderer import net.minecraft.client.render.block.entity.BlockEntityRenderer import net.minecraft.client.render.block.entity.BlockEntityRendererFactory.Context import net.minecraft.client.render.model.json.ModelTransformation import net.minecraft.client.util.math.MatrixStack import net.minecraft.item.ItemStack import net.minecraft.util.math.Quaternion import net.minecraft.util.math.Vec3f @Environment(CLIENT) class CrateRenderer(private val ctx: Context) : BlockEntityRenderer<CrateBlockEntity> { override fun render( crate: CrateBlockEntity, tickDelta: Float, matrices: MatrixStack, vertexConsumers: VertexConsumerProvider, light: Int, overlay: Int ) { val frontLight = WorldRenderer.getLightmapCoordinates(crate.world, crate.pos.offset(crate.facing)) matrices.withNested { matrices.translate(0.5, 0.5, 0.5) matrices.multiply(Vec3f.NEGATIVE_Y.getDegreesQuaternion(crate.facing.opposite.asRotation())) val resource = crate.storage.resource if (!resource.isBlank) { matrices.withNested { renderItem(resource.toStack(), matrices, vertexConsumers, frontLight, overlay) } } matrices.withNested { renderAmount(crate.storage.amount, matrices, vertexConsumers, frontLight) } } } private fun renderItem( stack: ItemStack, matrices: MatrixStack, vertexConsumers: VertexConsumerProvider, light: Int, overlay: Int ) { val itemRenderer = MinecraftClient.getInstance().itemRenderer val model = itemRenderer.getModel(stack, null, null, 0) if (model.hasDepth()) { matrices.translate(0.0, 0.0, -0.51) matrices.scale(0.37f, 0.37f, 0.01f) matrices.multiply(Quaternion(-30f, 45f, 0f, true)) } else { matrices.translate(0.0, 0.0, -0.5) matrices.scale(0.5f, 0.5f, 0.5f) } itemRenderer.renderItem( stack, ModelTransformation.Mode.NONE, light, overlay, matrices, vertexConsumers, 0 ) } private fun renderAmount( amount: Long, matrices: MatrixStack, vertexConsumers: VertexConsumerProvider, light: Int ) { matrices.translate(0.0, -0.45, -0.505) matrices.scale(-0.02f, -0.02f, -0.02f) val text = String.format("% 4d", amount) val xPosition = -ctx.textRenderer.getWidth(text).toFloat() / 2 ctx.textRenderer.draw( text, xPosition, -9f, 0, false, matrices.peek().positionMatrix, vertexConsumers, false, 0, light ) } private inline fun MatrixStack.withNested(block: () -> Unit) { push() try { block() } finally { pop() } } }
0
Kotlin
0
1
3d34c36e0c649c8e394a03c4a67c141fba16cb07
3,433
AdiCrate
MIT License
src/main/kotlin/dev/adirelle/adicrate/client/renderer/CrateRenderer.kt
Adirelle
454,710,946
false
{"Kotlin": 74806}
@file:Suppress("UnstableApiUsage") package dev.adirelle.adicrate.client.renderer import dev.adirelle.adicrate.block.entity.CrateBlockEntity import net.fabricmc.api.EnvType.CLIENT import net.fabricmc.api.Environment import net.minecraft.client.MinecraftClient import net.minecraft.client.render.VertexConsumerProvider import net.minecraft.client.render.WorldRenderer import net.minecraft.client.render.block.entity.BlockEntityRenderer import net.minecraft.client.render.block.entity.BlockEntityRendererFactory.Context import net.minecraft.client.render.model.json.ModelTransformation import net.minecraft.client.util.math.MatrixStack import net.minecraft.item.ItemStack import net.minecraft.util.math.Quaternion import net.minecraft.util.math.Vec3f @Environment(CLIENT) class CrateRenderer(private val ctx: Context) : BlockEntityRenderer<CrateBlockEntity> { override fun render( crate: CrateBlockEntity, tickDelta: Float, matrices: MatrixStack, vertexConsumers: VertexConsumerProvider, light: Int, overlay: Int ) { val frontLight = WorldRenderer.getLightmapCoordinates(crate.world, crate.pos.offset(crate.facing)) matrices.withNested { matrices.translate(0.5, 0.5, 0.5) matrices.multiply(Vec3f.NEGATIVE_Y.getDegreesQuaternion(crate.facing.opposite.asRotation())) val resource = crate.storage.resource if (!resource.isBlank) { matrices.withNested { renderItem(resource.toStack(), matrices, vertexConsumers, frontLight, overlay) } } matrices.withNested { renderAmount(crate.storage.amount, matrices, vertexConsumers, frontLight) } } } private fun renderItem( stack: ItemStack, matrices: MatrixStack, vertexConsumers: VertexConsumerProvider, light: Int, overlay: Int ) { val itemRenderer = MinecraftClient.getInstance().itemRenderer val model = itemRenderer.getModel(stack, null, null, 0) if (model.hasDepth()) { matrices.translate(0.0, 0.0, -0.51) matrices.scale(0.37f, 0.37f, 0.01f) matrices.multiply(Quaternion(-30f, 45f, 0f, true)) } else { matrices.translate(0.0, 0.0, -0.5) matrices.scale(0.5f, 0.5f, 0.5f) } itemRenderer.renderItem( stack, ModelTransformation.Mode.NONE, light, overlay, matrices, vertexConsumers, 0 ) } private fun renderAmount( amount: Long, matrices: MatrixStack, vertexConsumers: VertexConsumerProvider, light: Int ) { matrices.translate(0.0, -0.45, -0.505) matrices.scale(-0.02f, -0.02f, -0.02f) val text = String.format("% 4d", amount) val xPosition = -ctx.textRenderer.getWidth(text).toFloat() / 2 ctx.textRenderer.draw( text, xPosition, -9f, 0, false, matrices.peek().positionMatrix, vertexConsumers, false, 0, light ) } private inline fun MatrixStack.withNested(block: () -> Unit) { push() try { block() } finally { pop() } } }
0
Kotlin
0
1
3d34c36e0c649c8e394a03c4a67c141fba16cb07
3,433
AdiCrate
MIT License
app/src/main/java/com/example/winner/tebakgambar3.kt
laser123495
591,175,591
false
{"Kotlin": 105375}
package com.example.winner import android.app.Dialog import android.content.Intent import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.media.MediaPlayer import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.widget.Button import android.widget.Toast import com.example.winner.databinding.ActivityTebakgambar2Binding import com.example.winner.databinding.ActivityTebakgambar3Binding import kotlinx.android.synthetic.main.activity_perhitungan1.* import kotlinx.android.synthetic.main.activity_tebakgambar2.* import kotlinx.android.synthetic.main.activity_tebakgambar2.kucing import kotlinx.android.synthetic.main.activity_tebakgambar2.kucing2 import kotlinx.android.synthetic.main.activity_tebakgambar2.kucing3 import kotlinx.android.synthetic.main.activity_tebakgambar3.* import kotlinx.coroutines.delay class tebakgambar3 : AppCompatActivity() { private lateinit var binding: ActivityTebakgambar3Binding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityTebakgambar3Binding.inflate(layoutInflater) setContentView(binding.root) Handler().postDelayed({ var mediaPlayer2 = MediaPlayer.create(this,R.raw.kucing) mediaPlayer2.start() kucing.animate().apply { duration = 500 rotationYBy(360f) }.start() },500) Handler().postDelayed({ var mediaPlayer2 = MediaPlayer.create(this,R.raw.dog) mediaPlayer2.start() kucing2.animate().apply { duration = 500 rotationYBy(360f) }.start() },1500) Handler().postDelayed({ var mediaPlayer2 = MediaPlayer.create(this,R.raw.chicken) mediaPlayer2.start() kucing3.animate().apply { duration = 500 rotationYBy(360f) }.start() },2500) binding.back2.setOnClickListener { var mediaPlayer = MediaPlayer.create(this,R.raw.click) mediaPlayer.start() val dilaogBinding = layoutInflater.inflate(R.layout.activity_quit,null) val myDialog = Dialog(this) myDialog.setContentView(dilaogBinding) myDialog.setCancelable(true) myDialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) myDialog.show() val yesbtn = dilaogBinding.findViewById<Button>(R.id.alert_yes) yesbtn.setOnClickListener{ var mediaPlayer = MediaPlayer.create(this,R.raw.click) mediaPlayer.start() val intent = Intent(this,tebakgambar::class.java) startActivity(intent) } val nobtn = dilaogBinding.findViewById<Button>(R.id.alert_no) nobtn.setOnClickListener{ var mediaPlayer = MediaPlayer.create(this,R.raw.click) mediaPlayer.start() myDialog.dismiss() } } binding.kucing.setOnClickListener { var mediaPlayer = MediaPlayer.create(this,R.raw.kucing) mediaPlayer.start() Toast.makeText(applicationContext," yee benar, kamu hebat!!",Toast.LENGTH_SHORT).show() kucing.animate().apply { duration = 500 rotationYBy(360f) }.start() Handler().postDelayed({val intent = Intent(this,tebakgambar4::class.java) startActivity(intent) },600) } binding.kucing2.setOnClickListener { var mediaPlayer = MediaPlayer.create(this,R.raw.dog) mediaPlayer.start() Toast.makeText(applicationContext," yah salah, itu kaki anjing",Toast.LENGTH_SHORT).show() kucing2.animate().apply { duration = 500 rotationYBy(360f) }.start() } binding.kucing3.setOnClickListener { var mediaPlayer = MediaPlayer.create(this,R.raw.chicken) mediaPlayer.start() Toast.makeText(applicationContext," yah salah, itu kaki ayam",Toast.LENGTH_SHORT).show() kucing3.animate().apply { duration = 500 rotationYBy(360f) }.start() } binding.tb3help.setOnClickListener { tb3help.animate().apply { duration = 2000 rotationYBy(720f) }.start() var mediaPlayer = MediaPlayer.create(this,R.raw.click) mediaPlayer.start() Toast.makeText(applicationContext,"coba pilih yang paling kiri ya.", Toast.LENGTH_SHORT).show() } } }
0
Kotlin
0
0
4ca08dd0f2268aca296da39b9a685d181170b62a
4,813
winner_app
Apache License 2.0
app/src/main/java/com/brins/riceweather/data/network/api/WeatherService.kt
BrinsLee
219,101,877
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 46, "XML": 34, "Java": 1}
package com.brins.riceweather.data.network.api import com.brins.riceweather.data.model.weather.HeWeather import com.brins.riceweather.data.model.weather.WeatherDetail import com.brins.riceweather.utils.weatherAppId import com.brins.riceweather.utils.weatherAppSecret import retrofit2.Call import retrofit2.http.GET import retrofit2.http.Query interface WeatherService { @GET("api/") fun getWeather(@Query("appid") appId: String = weatherAppId, @Query("appsecret") appSecret: String = weatherAppSecret, @Query("version") version: String = "v1", @Query("city") city: String): Call<HeWeather> @GET("api/") fun getWeatherDetail(@Query("appid") appId: String = weatherAppId, @Query("appsecret") appSecret: String = weatherAppSecret, @Query("version") version: String = "v6", @Query("city") city: String): Call<WeatherDetail> }
0
Kotlin
0
0
9b2e4b7782c3ad82a4871c2e16ca2bf9f27acec4
973
RiceWeather
Apache License 2.0
app/src/main/java/com/payback/demo/database/Room.kt
SairaNawaz
478,181,198
false
{"Kotlin": 21925}
package com.payback.demo.database import androidx.lifecycle.LiveData import androidx.room.* @Dao interface ImagesDao { // Image List @Query("select * from DatabaseImageListItem WHERE tags LIKE '%' || :search_query || '%' order by id asc") fun getDatabaseImages(search_query:String): LiveData<List<DatabaseImageListItem>> @Query("select * from DatabaseImageListItem order by id asc") fun getDatabaseImages(): LiveData<List<DatabaseImageListItem>> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertAll(images: List<DatabaseImageListItem>) // single Image @Query("select * from DatabaseImageListItem WHERE id = :id") fun getImageDetails(id: Int): LiveData<DatabaseImageListItem> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertImageDetails(databaseImageDetails: DatabaseImageListItem) } @Database(entities = [DatabaseImageListItem::class], version = 1) abstract class ImagesDatabase : RoomDatabase() { abstract val imagesDao: ImagesDao }
0
Kotlin
0
0
5153a371c27a1b6a5ab19c9284bb72c4ba040820
1,013
mvvm_clean_demo
MIT License
app/src/main/java/com/n0stalgiaultra/head2head/domain/team/TeamRepository.kt
N0stalgiaUltra
684,244,140
false
{"Kotlin": 37181}
package com.n0stalgiaultra.head2head.domain.team import androidx.lifecycle.LiveData import com.n0stalgiaultra.head2head.data.local.model.TeamLocal interface TeamRepository { fun getLocalTeams(): LiveData<List<TeamLocal>> suspend fun getRemoteTeams(): LiveData<List<TeamLocal>> }
0
Kotlin
0
0
2f1ac3cacb6518906116a724767b07884b2ad69b
288
Head2HeadApp
Apache License 2.0
android/src/com/android/tools/idea/diagnostics/hprof/visitors/DebugVisitor.kt
JetBrains
60,701,247
false
null
/* * Copyright (C) 2019 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.tools.idea.diagnostics.hprof.visitors import com.android.tools.idea.diagnostics.hprof.parser.ConstantPoolEntry import com.android.tools.idea.diagnostics.hprof.parser.HProfVisitor import com.android.tools.idea.diagnostics.hprof.parser.InstanceFieldEntry import com.android.tools.idea.diagnostics.hprof.parser.StaticFieldEntry import com.android.tools.idea.diagnostics.hprof.parser.Type import java.nio.ByteBuffer class DebugVisitor(private val printer: (String) -> Unit) : HProfVisitor() { override fun visitStringInUTF8(id: Long, s: String) { printer.invoke("StringInUTF8: id=$id value=$s") } override fun visitLoadClass(classSerialNumber: Long, classObjectId: Long, stackSerialNumber: Long, classNameStringId: Long) { printer.invoke("LoadClass: " + "classSerialNumber=$classSerialNumber, " + "classObjectId=$classObjectId, " + "stackSerialNumber=$stackSerialNumber, " + "classNameStringId=$classNameStringId") } override fun visitStackFrame(stackFrameId: Long, methodNameStringId: Long, methodSignatureStringId: Long, sourceFilenameStringId: Long, classSerialNumber: Long, lineNumber: Int) { printer.invoke("StackFrame: " + "stackFrameId=$stackFrameId, " + "methodNameStringId=$methodNameStringId, " + "methodSignatureStringId=$methodSignatureStringId, " + "sourceFilenameStringId=$sourceFilenameStringId, " + "classSerialNumber=$classSerialNumber, " + "lineNumber=$lineNumber") } override fun visitStackTrace(stackTraceSerialNumber: Long, threadSerialNumber: Long, numberOfFrames: Int, stackFrameIds: LongArray) { printer.invoke("StackTrace: " + "stackTraceSerialNumber: $stackTraceSerialNumber, " + "threadSerialNumber: $threadSerialNumber, " + "numberOfFrames: $numberOfFrames, " + "stackFrameIds: ${stackFrameIds.arrayToString()}") } override fun visitAllocSites() { printer.invoke("AllocSites") } override fun visitHeapSummary(totalLiveBytes: Long, totalLiveInstances: Long, totalBytesAllocated: Long, totalInstancesAllocated: Long) { printer.invoke("HeapSummary: " + "totalLiveBytes: $totalLiveBytes, " + "totalLiveInstances: $totalLiveInstances, " + "totalBytesAllocated: $totalBytesAllocated, " + "totalInstancesAllocated: $totalInstancesAllocated") } override fun visitStartThread() { printer.invoke("StartThread") } override fun visitEndThread(threadSerialNumber: Long) { printer.invoke("EndThread") } override fun visitHeapDump() { printer.invoke("HeapDump") } override fun visitHeapDumpEnd() { printer.invoke("HeapDumpEnd") } override fun visitCPUSamples() { printer.invoke("CPUSamples") } override fun visitControlSettings() { printer.invoke("ControlSettings") } override fun visitRootUnknown(objectId: Long) { printer.invoke("RootUnknown: objectId=$objectId") } override fun visitRootGlobalJNI(objectId: Long, jniGlobalRefId: Long) { printer.invoke("RootGlobalJNI: objectId=$objectId, jniGlobalRefId=$jniGlobalRefId") } override fun visitRootLocalJNI(objectId: Long, threadSerialNumber: Long, frameNumber: Long) { printer.invoke("RootLocalJNI: objectId=$objectId, threadSerialNumber=$threadSerialNumber, frameNumber=$frameNumber") } override fun visitRootJavaFrame(objectId: Long, threadSerialNumber: Long, frameNumber: Long) { printer.invoke("RootJavaFrame: objectId=$objectId, threadSerialNumber=$threadSerialNumber, frameNumber=$frameNumber") } override fun visitRootNativeStack(objectId: Long, threadSerialNumber: Long) { printer.invoke("RootNativeStack: objectId=$objectId, threadSerialNumber=$threadSerialNumber") } override fun visitRootStickyClass(objectId: Long) { printer.invoke("RootStickyClass: objectId=$objectId") } override fun visitRootThreadBlock(objectId: Long, threadSerialNumber: Long) { printer.invoke("RootThreadBlock: objectId=$objectId, threadSerialNumber=$threadSerialNumber") } override fun visitRootMonitorUsed(objectId: Long) { printer.invoke("RootMonitorUsed: objectId=$objectId") } override fun visitRootThreadObject(objectId: Long, threadSerialNumber: Long, stackTraceSerialNumber: Long) { printer.invoke("RootThreadObject: " + "objectId=$objectId, " + "threadSerialNumber=$threadSerialNumber, " + "stackTraceSerialNumber=$stackTraceSerialNumber") } override fun visitPrimitiveArrayDump(arrayObjectId: Long, stackTraceSerialNumber: Long, numberOfElements: Long, elementType: Type) { printer.invoke("PrimitiveArrayDump: " + "arrayObjectId=$arrayObjectId, " + "stackTraceSerialNumber=$stackTraceSerialNumber, " + "numberOfElements=$numberOfElements, " + "elementType=${elementType.name}") } override fun visitClassDump(classId: Long, stackTraceSerialNumber: Long, superClassId: Long, classloaderClassId: Long, instanceSize: Long, constants: Array<ConstantPoolEntry>, staticFields: Array<StaticFieldEntry>, instanceFields: Array<InstanceFieldEntry>) { printer.invoke("ClassDump: " + "classId=$classId, " + "stackTraceSerialNumber=$stackTraceSerialNumber, " + "superClassId=$superClassId, " + "classloaderClassId=$classloaderClassId, " + "instanceSize=$instanceSize") } override fun visitObjectArrayDump(arrayObjectId: Long, stackTraceSerialNumber: Long, arrayClassObjectId: Long, objects: LongArray) { printer.invoke("ObjectArrayDump: arrayObjectId=$arrayObjectId, " + "stackTraceSerialNumber=$stackTraceSerialNumber, " + "arrayClassObjectId=$arrayClassObjectId, " + "objects=id[${objects.size}") } override fun visitInstanceDump(objectId: Long, stackTraceSerialNumber: Long, classObjectId: Long, bytes: ByteBuffer) { printer.invoke("InstanceDump: " + "objectId=$objectId, " + "stackTraceSerialNumber: $stackTraceSerialNumber, " + "classObjectId=$classObjectId," + "bytes=byte[${bytes.limit()}]") } override fun visitUnloadClass(classSerialNumber: Long) { printer.invoke("UnloadClass: classSerialNumber=$classSerialNumber") } private fun LongArray.arrayToString(): String = buildString { append('[') for (i in this@arrayToString.indices) { if (i > 0) append(", ") append(this@arrayToString[i]) } append(']') } }
5
null
227
948
10110983c7e784122d94c7467e9d243aba943bf4
7,839
android
Apache License 2.0
server/src/main/kotlin/com/salastroya/bgserver/infrastructure/plant/mapper/PlantMappers.kt
adrisalas
780,369,375
false
{"Kotlin": 387465, "TypeScript": 104856, "HTML": 49103, "CSS": 6424}
package com.salastroya.bgserver.infrastructure.plant.mapper import com.salastroya.bgserver.core.plant.model.Plant import com.salastroya.bgserver.core.plant.model.PlantDetails import com.salastroya.bgserver.infrastructure.plant.dto.PlantDto fun Plant.toDto() = PlantDto( id = this.id, commonName = this.commonName, scientificName = this.scientificName, description = this.description, image = this.image, plantType = this.type, season = this.details.season, leafType = this.details.leafType, water = this.details.water, floweringBegin = this.details.flowering?.first, floweringEnd = this.details.flowering?.second ) fun PlantDto.toModel(): Plant { val flowering = if (this.floweringBegin != null && this.floweringEnd != null) Pair( this.floweringBegin, this.floweringEnd ) else null val details = PlantDetails( season = this.season, leafType = this.leafType, water = this.water, flowering = flowering ) return Plant( id = this.id ?: -1, commonName = this.commonName, scientificName = this.scientificName, description = this.description, image = this.image, type = this.plantType, details = details ) }
0
Kotlin
0
0
d84cb29909f133a64f2cd5b43622d4ce45d56048
1,342
botanic-garden
MIT License
shared/src/commonMain/kotlin/hr/dtakac/prognoza/shared/domain/GetPrecipitationUnit.kt
davidtakac
387,038,134
false
null
package hr.dtakac.prognoza.shared.domain import hr.dtakac.prognoza.shared.domain.data.SettingsRepository import hr.dtakac.prognoza.shared.entity.LengthUnit class GetPrecipitationUnit internal constructor( private val settingsRepository: SettingsRepository ) { suspend operator fun invoke(): LengthUnit = settingsRepository.getPrecipitationUnit() }
24
Kotlin
11
194
2ff651b1b6470441fc81066f84271feacc855195
357
prognoza
MIT License
quickstart-kotlin/src/main/kotlin/com/bookislife/jgsk/kotlin/_26_xml_json/App.kt
youngzil
140,260,338
false
{"Java": 5366579, "Shell": 82397, "Scala": 72073, "Kotlin": 54790, "Groovy": 51919, "Python": 6361, "HTML": 2249, "Clojure": 1900, "JavaScript": 1727, "Lua": 1301, "XSLT": 964, "AspectJ": 359, "Batchfile": 52}
package com.bookislife.jgsk.kotlin._26_xml_json import java.io.ByteArrayInputStream import javax.xml.parsers.DocumentBuilderFactory /** * Created by SidneyXu on 2015/10/13. */ fun main(args: Array<String>) { // Create Xml val xml = """ <langs type='current' count='4' mainstream='true'> <language flavor='static' version='1.8.0_25'>Java</language> <language flavor='dynamic' version='2.4.4'>Groovy</language> <language flavor='static' version='2.11.5'>Scala</language> <language flavor='static' version='0.12.613'>Kotlin</language> </langs> """ val builder = DocumentBuilderFactory.newInstance().newDocumentBuilder() val doc = builder.parse(ByteArrayInputStream(xml.toByteArray())) //TODO // println(doc.toXmlString()) // Parse Xml val langs = doc.getElementsByTagName("langs").item(0) println(langs.getAttributes().getNamedItem("count").getNodeValue()) // 4 }
24
Java
4
3
4c0d48b576ad3230c026fb2cd323e80755fe415e
912
quickstart-framework
Apache License 2.0
compiler/testData/diagnostics/tests/warningsForBreakingChanges/capturedTypes/noWarningAfterSmartcast.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// SKIP_TXT interface Comp<T> { fun foo(t: T) } fun <E : Any> foo(c: Comp<in E>, e: E?) { if (e == null) return c.foo(<!DEBUG_INFO_SMARTCAST!>e<!>) }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
163
kotlin
Apache License 2.0
compiler/testData/diagnostics/tests/multimodule/LambdaReceiversOfInaccessibleTypes.fir.kt
JetBrains
3,432,266
false
{"Kotlin": 79248651, "Java": 6821839, "Swift": 4063506, "C": 2609288, "C++": 1969323, "Objective-C++": 171723, "JavaScript": 138329, "Python": 59488, "Shell": 32251, "TypeScript": 22800, "Objective-C": 22132, "Lex": 21352, "Groovy": 17400, "Batchfile": 11695, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9857, "EJS": 5241, "HTML": 4877, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
// MODULE: start // FILE: start.kt interface InaccessibleConcreteType interface InaccessibleGenericType<T> // MODULE: middle(start) // FILE: middle.kt fun withConcreteReceiver(arg: InaccessibleConcreteType.() -> Unit) {} fun withGenericReceiver(arg: InaccessibleGenericType<*>.() -> Unit) {} // MODULE: end(middle) // FILE: end.kt fun test() { withConcreteReceiver <!MISSING_DEPENDENCY_CLASS_IN_LAMBDA_RECEIVER!>{}<!> withGenericReceiver <!MISSING_DEPENDENCY_CLASS!>{}<!> }
182
Kotlin
5646
48,182
bc1ddd8205f6107c7aec87a9fb3bd7713e68902d
487
kotlin
Apache License 2.0
idea/testData/intentions/specifyExplicitLambdaSignature/emptyParamListWithWhiteSpace.kt
JakeWharton
99,388,807
false
null
fun main() { val oom: (Int)->Int = {<caret> it * 2 } }
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
70
kotlin
Apache License 2.0
java/kotlin/src/main/kotlin/cosmos/base/reflection/v2alpha1/AuthnDescriptorKt.kt
iqdevelop
474,485,760
true
{"Git Config": 1, "Text": 1, "Ignore List": 3, "Makefile": 3, "Markdown": 3, "Gradle Kotlin DSL": 5, "INI": 2, "Shell": 3, "Batchfile": 1, "Java": 181, "Kotlin": 917, "JSON with Comments": 1, "JSON": 3, "Git Attributes": 1, "EditorConfig": 1}
//Generated by the protocol buffer compiler. DO NOT EDIT! // source: cosmos/base/reflection/v2alpha1/reflection.proto package cosmos.base.reflection.v2alpha1; @kotlin.jvm.JvmSynthetic inline fun authnDescriptor(block: cosmos.base.reflection.v2alpha1.AuthnDescriptorKt.Dsl.() -> Unit): cosmos.base.reflection.v2alpha1.Reflection.AuthnDescriptor = cosmos.base.reflection.v2alpha1.AuthnDescriptorKt.Dsl._create(cosmos.base.reflection.v2alpha1.Reflection.AuthnDescriptor.newBuilder()).apply { block() }._build() object AuthnDescriptorKt { @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) @com.google.protobuf.kotlin.ProtoDslMarker class Dsl private constructor( @kotlin.jvm.JvmField private val _builder: cosmos.base.reflection.v2alpha1.Reflection.AuthnDescriptor.Builder ) { companion object { @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _create(builder: cosmos.base.reflection.v2alpha1.Reflection.AuthnDescriptor.Builder): Dsl = Dsl(builder) } @kotlin.jvm.JvmSynthetic @kotlin.PublishedApi internal fun _build(): cosmos.base.reflection.v2alpha1.Reflection.AuthnDescriptor = _builder.build() /** * An uninstantiable, behaviorless type to represent the field in * generics. */ @kotlin.OptIn(com.google.protobuf.kotlin.OnlyForUseByGeneratedProtoCode::class) class SignModesProxy private constructor() : com.google.protobuf.kotlin.DslProxy() /** * <pre> * sign_modes defines the supported signature algorithm * </pre> * * <code>repeated .cosmos.base.reflection.v2alpha1.SigningModeDescriptor sign_modes = 1;</code> */ val signModes: com.google.protobuf.kotlin.DslList<cosmos.base.reflection.v2alpha1.Reflection.SigningModeDescriptor, SignModesProxy> @kotlin.jvm.JvmSynthetic get() = com.google.protobuf.kotlin.DslList( _builder.getSignModesList() ) /** * <pre> * sign_modes defines the supported signature algorithm * </pre> * * <code>repeated .cosmos.base.reflection.v2alpha1.SigningModeDescriptor sign_modes = 1;</code> * @param value The signModes to add. */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("addSignModes") fun com.google.protobuf.kotlin.DslList<cosmos.base.reflection.v2alpha1.Reflection.SigningModeDescriptor, SignModesProxy>.add(value: cosmos.base.reflection.v2alpha1.Reflection.SigningModeDescriptor) { _builder.addSignModes(value) }/** * <pre> * sign_modes defines the supported signature algorithm * </pre> * * <code>repeated .cosmos.base.reflection.v2alpha1.SigningModeDescriptor sign_modes = 1;</code> * @param value The signModes to add. */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("plusAssignSignModes") inline operator fun com.google.protobuf.kotlin.DslList<cosmos.base.reflection.v2alpha1.Reflection.SigningModeDescriptor, SignModesProxy>.plusAssign(value: cosmos.base.reflection.v2alpha1.Reflection.SigningModeDescriptor) { add(value) }/** * <pre> * sign_modes defines the supported signature algorithm * </pre> * * <code>repeated .cosmos.base.reflection.v2alpha1.SigningModeDescriptor sign_modes = 1;</code> * @param values The signModes to add. */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("addAllSignModes") fun com.google.protobuf.kotlin.DslList<cosmos.base.reflection.v2alpha1.Reflection.SigningModeDescriptor, SignModesProxy>.addAll(values: kotlin.collections.Iterable<cosmos.base.reflection.v2alpha1.Reflection.SigningModeDescriptor>) { _builder.addAllSignModes(values) }/** * <pre> * sign_modes defines the supported signature algorithm * </pre> * * <code>repeated .cosmos.base.reflection.v2alpha1.SigningModeDescriptor sign_modes = 1;</code> * @param values The signModes to add. */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("plusAssignAllSignModes") inline operator fun com.google.protobuf.kotlin.DslList<cosmos.base.reflection.v2alpha1.Reflection.SigningModeDescriptor, SignModesProxy>.plusAssign(values: kotlin.collections.Iterable<cosmos.base.reflection.v2alpha1.Reflection.SigningModeDescriptor>) { addAll(values) }/** * <pre> * sign_modes defines the supported signature algorithm * </pre> * * <code>repeated .cosmos.base.reflection.v2alpha1.SigningModeDescriptor sign_modes = 1;</code> * @param index The index to set the value at. * @param value The signModes to set. */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("setSignModes") operator fun com.google.protobuf.kotlin.DslList<cosmos.base.reflection.v2alpha1.Reflection.SigningModeDescriptor, SignModesProxy>.set(index: kotlin.Int, value: cosmos.base.reflection.v2alpha1.Reflection.SigningModeDescriptor) { _builder.setSignModes(index, value) }/** * <pre> * sign_modes defines the supported signature algorithm * </pre> * * <code>repeated .cosmos.base.reflection.v2alpha1.SigningModeDescriptor sign_modes = 1;</code> */ @kotlin.jvm.JvmSynthetic @kotlin.jvm.JvmName("clearSignModes") fun com.google.protobuf.kotlin.DslList<cosmos.base.reflection.v2alpha1.Reflection.SigningModeDescriptor, SignModesProxy>.clear() { _builder.clearSignModes() }} } @kotlin.jvm.JvmSynthetic inline fun cosmos.base.reflection.v2alpha1.Reflection.AuthnDescriptor.copy(block: cosmos.base.reflection.v2alpha1.AuthnDescriptorKt.Dsl.() -> Unit): cosmos.base.reflection.v2alpha1.Reflection.AuthnDescriptor = cosmos.base.reflection.v2alpha1.AuthnDescriptorKt.Dsl._create(this.toBuilder()).apply { block() }._build()
0
null
0
0
06fcb6a1e57962a46af0aebb90b5b110e0b42435
5,732
terra.proto
Apache License 2.0
compiler/testData/codegen/box/escapeAnalysis/test4.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE file. */ // TODO: check mentioned debug output of escape analyser class A(val s: String) class B { var f: A = A("qzz") } class C { var g: B = B() } // ----- Agressive ----- // PointsTo: // P0.g.f -> P1.g.f // RET.v@lue -> D0 // Escapes: D0 // ----- Passive ----- // PointsTo: // P0.g.f -> P1.g.f // RET.v@lue -> D0 // Escapes: D0 fun foo(c1: C, c2: C) { c1.g.f = c2.g.f } fun box(): String { foo(C(), C()) return "OK" }
181
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
601
kotlin
Apache License 2.0
app/src/prod/java/com/github/vase4kin/teamcityapp/dagger/modules/buildlog/BuildLogUrlProviderModule.kt
vase4kin
68,111,887
false
null
/* * Copyright 2020 <NAME> * * 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.vase4kin.teamcityapp.dagger.modules.buildlog import com.github.vase4kin.teamcityapp.buildlog.data.BuildLogInteractor import com.github.vase4kin.teamcityapp.buildlog.urlprovider.BuildLogUrlProvider import com.github.vase4kin.teamcityapp.buildlog.urlprovider.BuildLogUrlProviderImpl import dagger.Module import dagger.Provides @Module object BuildLogUrlProviderModule { @JvmStatic @Provides fun providesUrlProvider( buildLogInteractor: BuildLogInteractor ): BuildLogUrlProvider { return BuildLogUrlProviderImpl(buildLogInteractor) } }
0
null
11
52
9abb1ed56c127d64679124c38d30b0014ec024de
1,181
TeamCityApp
Apache License 2.0
src/main/java/il/co/codeguru/corewars8086/runner/GroupsRunner.kt
yoavst
51,307,921
true
{"Maven POM": 1, "Markdown": 1, "Text": 1, "Ignore List": 1, "Kotlin": 11, "Java": 43}
package il.co.codeguru.corewars8086.runner import com.yoavst.codeguru.runner.BaseRunner import il.co.codeguru.corewars8086.runner.util.Params import il.co.codeguru.corewars8086.runner.util.Runner import il.co.codeguru.corewars8086.runner.util.print import java.io.File class GroupsRunner(val wars: Int, val warriorsPerGroup: Int, val baseFolder: String) : Runner() { override fun run() { //FIXME gui val newDir = Directory.knockoutOf(16).toFile() if (newDir.exists()) newDir.deleteRecursively() newDir.mkdirs() Directory.TopGroup.toFile().listFiles().forEach { it.copyTo(File(newDir, it.name)) } createGroupRunner(1, newDir).run() } protected fun String.toFile() = File(baseFolder, this) var position = 1 private fun createGroupRunner(groupNumber: Int, newDir: File): Runner { return object : BaseRunner(wars, warriorsPerGroup, baseFolder, Params.Groups, groupNumber) { override fun onEndWars() { val groups = competition.warriorRepository.warriorGroups.sortedByDescending { it.groupScore } println("Group $groupNumber:") groups.forEachIndexed { i, warriorGroup -> warriorGroup.print(i + 1) } groups[0].warriors.forEach { warrior -> File(dir, warrior.name).copyTo(File(newDir, warrior.name)) } position++ if (position < 9) createGroupRunner(groupNumber + 1, newDir).run() } } } }
0
Java
0
0
10f4831e074ccf3b828a27546438c8febd1249eb
1,528
corewars8086
Apache License 2.0
app/src/main/java/com/mumu/filebrowser/eventbus/events/BackEvent.kt
mumumusuc
110,905,313
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "JSON": 2, "Java": 21, "XML": 75, "Kotlin": 28}
package com.mumu.filebrowser.eventbus.events /** * Created by leonardo on 17-12-2. */ class BackEvent
0
Kotlin
0
0
b1825807d04feda74c15711b85cb95dc548c6eab
104
FileManager
Apache License 2.0
app/src/main/java/com/kamontat/checkidnumber/view/MainView.kt
kamontat
91,566,835
false
{"Gradle": 3, "Java Properties": 2, "Shell": 4, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 7, "YAML": 2, "PlantUML": 5, "JSON": 1, "Proguard": 1, "XML": 23, "Java": 5, "Kotlin": 23}
package com.kamontat.checkidnumber.view import android.content.Context import com.kamontat.checkidnumber.model.IDNumber import java.io.Serializable /** * @author kamontat * * * @version 1.0 * * * @since Mon 15/May/2017 - 1:23 AM */ interface MainView : Serializable { val inputText: String fun checkAndInsert() fun updateInput(id: IDNumber) fun hideKeyBoard() fun showKeyBoard() val isStorageWritable: Boolean val idNumbers: Array<IDNumber> val context: Context fun checkPermission(): Boolean /** * @return * * 0 - already have permission * * 1 - on requesting permission * * 2 - deny before */ fun requestPermission(): Boolean }
1
null
1
1
f75a59d72e1567b3bafd16160b756ee6cd9fa1bb
715
CheckIDNumberA
MIT License
src/org/ice1000/tt/psi/minitt/semantics.kt
owo-lang
174,763,486
false
null
package org.ice1000.tt.psi.minitt import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import com.intellij.psi.ResolveState import com.intellij.psi.impl.source.resolve.ResolveCache import com.intellij.psi.scope.PsiScopeProcessor import com.intellij.psi.util.PsiTreeUtil import com.intellij.util.IncorrectOperationException import icons.TTIcons import org.ice1000.tt.orTrue import org.ice1000.tt.psi.* import org.ice1000.tt.psi.minitt.impl.MiniTTExpressionImpl import org.ice1000.tt.psi.minitt.impl.MiniTTPatternImpl val miniTTResolver = ResolveCache.PolyVariantResolver<MiniTTVariableGeneratedMixin> { ref, _ -> val name = ref.canonicalText resolveWith(PatternResolveProcessor(name) { if ((it as? IPattern<*>)?.parent !is MiniTTTypedPatternGeneratedMixin) it.text == name else it.text == name && PsiTreeUtil.isAncestor(PsiTreeUtil.getParentOfType(it, GeneralDeclaration::class.java), ref, true) }, ref) } abstract class MiniTTAtomPatternMixin(node: ASTNode) : MiniTTPatternImpl(node), MiniTTAtomPattern { override fun visit(visitor: (MiniTTVariable) -> Boolean) = variable?.let(visitor).orTrue() && pattern?.visit(visitor).orTrue() } abstract class MiniTTPairPatternMixin(node: ASTNode) : MiniTTPatternImpl(node), MiniTTPairPattern { override fun visit(visitor: (MiniTTVariable) -> Boolean) = patternList.all { it.visit(visitor) } } abstract class MiniTTDeclarationExpressionMixin(node: ASTNode) : ASTWrapperPsiElement(node), MiniTTDeclarationExpression { override fun processDeclarations(processor: PsiScopeProcessor, state: ResolveState, lastParent: PsiElement?, place: PsiElement) = declaration.processDeclarations(processor, state, lastParent, place) } abstract class MiniTTConstExpressionMixin(node: ASTNode) : ASTWrapperPsiElement(node), MiniTTConstExpression { override fun processDeclarations(processor: PsiScopeProcessor, state: ResolveState, lastParent: PsiElement?, place: PsiElement) = constDeclaration.processDeclarations(processor, state, lastParent, place) } abstract class MiniTTGeneralPattern(node: ASTNode) : GeneralNameIdentifier(node) { override fun getIcon(flags: Int) = TTIcons.MINI_TT @Throws(IncorrectOperationException::class) override fun setName(newName: String) = replace(MiniTTTokenType.createPattern(newName, project) ?: invalidName(newName)) } abstract class MiniTTTypedAbstractionMixin(node: ASTNode) : MiniTTExpressionImpl(node), MiniTTTypedAbstraction { override fun processDeclarations(processor: PsiScopeProcessor, state: ResolveState, lastParent: PsiElement?, place: PsiElement) = typedPattern.processDeclarations(processor, state, lastParent, place) } abstract class MiniTTDeclarationMixin(node: ASTNode) : MiniTTDeclarationGeneratedMixin(node), MiniTTDeclaration { override fun processDeclarations(processor: PsiScopeProcessor, state: ResolveState, lastParent: PsiElement?, place: PsiElement) = childrenRevWithLeaves.filterIsInstance<MiniTTPrefixParameter>().all { it.typedPattern.processDeclarations(processor, state, lastParent, place) } && super.processDeclarations(processor, state, lastParent, place) }
5
Kotlin
5
35
7e601041978a0497db7d4cf3bcf4971f532235cd
3,155
intellij-dtlc
Apache License 2.0
app/src/test/java/com/example/android/testing/notes/data/InMemoryNotesRepositoryTest.kt
develodroid
63,719,774
false
null
/* * Copyright 2015, 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.example.android.testing.notes.data import com.example.android.testing.notes.alias._is import com.example.android.testing.notes.data.NotesServiceApi.NotesServiceCallback import org.hamcrest.Matchers.nullValue import org.junit.Assert.assertThat import org.junit.Before import org.junit.Test import org.mockito.ArgumentCaptor import org.mockito.Captor import org.mockito.Matchers.any import org.mockito.Matchers.eq import org.mockito.Mock import org.mockito.Mockito.times import org.mockito.Mockito.verify import org.mockito.MockitoAnnotations /** * Unit tests for the implementation of the in-memory repository with cache. */ class InMemoryNotesRepositoryTest { private val NOTE_TITLE = "title" private val NOTES = arrayListOf(Note("Title1", "Description1"), Note("Title2", "Description2")) lateinit private var mNotesRepository: InMemoryNotesRepository @Mock lateinit private var mServiceApi: NotesServiceApiImpl @Mock lateinit private var mGetNoteCallback: NotesRepository.GetNoteCallback @Mock lateinit private var mLoadNotesCallback : NotesRepository.LoadNotesCallback /** * [ArgumentCaptor] is a powerful Mockito API to capture argument values and use them to * perform further actions or assertions on them. */ @Captor lateinit var mNotesServiceCallbackCaptor: ArgumentCaptor<NotesServiceCallback<List<Note>>> @Before fun setupNotesRepository() { // Mockito has a very convenient way to inject mocks by using the @Mock annotation. To // inject the mocks in the test the initMocks method needs to be called. MockitoAnnotations.initMocks(this) // Get a reference to the class under test mNotesRepository = InMemoryNotesRepository(mServiceApi) } @Test fun getNotes_repositoryCachesAfterFirstApiCall() { // Given a setup Captor to capture callbacks // When two calls are issued to the notes repository twoLoadCallsToRepository(mLoadNotesCallback) // Then notes where only requested once from Service API verify(mServiceApi).getAllNotes(any(NotesServiceCallback::class.java)) } @Test fun invalidateCache_DoesNotCallTheServiceApi() { // Given a setup Captor to capture callbacks twoLoadCallsToRepository(mLoadNotesCallback) // When data refresh is requested mNotesRepository.refreshData() mNotesRepository.getNotes(mLoadNotesCallback) // Third call to API // The notes where requested twice from the Service API (Caching on first and third call) verify(mServiceApi, times(2)).getAllNotes(any(NotesServiceCallback::class.java)) } @Test fun getNotes_requestsAllNotesFromServiceApi() { // When notes are requested from the notes repository mNotesRepository.getNotes(mLoadNotesCallback) // Then notes are loaded from the service API verify(mServiceApi).getAllNotes(any(NotesServiceCallback::class.java)) } @Test fun saveNote_savesNoteToServiceAPIAndInvalidatesCache() { // Given a stub note with title and description val newNote = Note(NOTE_TITLE, "Some Note Description") // When a note is saved to the notes repository mNotesRepository.saveNote(newNote) // Then the notes cache is cleared assertThat(mNotesRepository.mCachedNotes, _is(nullValue())) } @Test fun getNote_requestsSingleNoteFromServiceApi() { // When a note is requested from the notes repository mNotesRepository.getNote(NOTE_TITLE, mGetNoteCallback) // Then the note is loaded from the service API verify(mServiceApi).getNote(eq(NOTE_TITLE), any(NotesServiceCallback::class.java)) } /** * Convenience method that issues two calls to the notes repository */ private fun twoLoadCallsToRepository(callback: NotesRepository.LoadNotesCallback) { // When notes are requested from repository mNotesRepository.getNotes(callback) // First call to API // Use the Mockito Captor to capture the callback verify(mServiceApi).getAllNotes(mNotesServiceCallbackCaptor.capture()) // Trigger callback so notes are cached mNotesServiceCallbackCaptor.value.onLoaded(NOTES) mNotesRepository.getNotes(callback) // Second call to API } }
1
null
1
1
25fb0f60ebbfd3847c9112015e3035e627a7dca2
5,009
kotlin-testing
Apache License 2.0
RPCBusSample/rpcbus/src/main/kotlin/me/tomalka/rpcbus/engines/ConnectionEngine.kt
ritave
55,894,401
false
{"Text": 1, "Ignore List": 6, "Gradle": 6, "Java Properties": 2, "Shell": 1, "Batchfile": 1, "Kotlin": 22, "Proguard": 3, "Java": 6, "XML": 19}
package me.tomalka.rpcbus.engines import me.tomalka.rpcbus.LocalDispatcher interface ConnectionEngine { fun install(localDispatcher: LocalDispatcher) fun destroy() fun onPost(event: Any) }
1
null
1
1
410104008bab5a4d5c14f16147d12c30245b24e5
203
RPCBus
MIT License
subprojects/test-runner/service/src/test/kotlin/com/avito/runner/service/worker/device/adb/request/shell/RunTestsAdbShellRequestTest.kt
avito-tech
230,265,582
false
{"Kotlin": 3752627, "Java": 67252, "Shell": 27892, "Dockerfile": 12799, "Makefile": 8086}
package com.avito.runner.service.worker.device.adb.request.shell import com.avito.runner.service.worker.device.adb.request.AdbRequestSerializer import com.google.common.truth.Truth.assertThat import org.junit.jupiter.api.Test class RunTestsAdbShellRequestTest { private val serializer = AdbRequestSerializer("stub") @Test fun `am instrument command - serialized correctly`() { val request = RunTestsAdbShellRequest( testPackageName = "com.avito.android", testRunnerClass = "com.avito.android.InstrumentationRunner", instrumentationArguments = mapOf( "plainValue" to "value", "emptyValue" to "", "blankValue" to " ", "jsonValue" to "{\"foo\" : {\"bar\" : 5 } }", "spaces in key" to "value" ), enableDeviceDebug = true, ) val serialized = serializer.serialize(request) @Suppress("MaxLineLength") assertThat(serialized).isEqualTo("adb -s stub shell am instrument -w -r -e debug true -e 'plainValue' 'value' -e 'emptyValue' '' -e 'blankValue' ' ' -e 'jsonValue' '{\"foo\" : {\"bar\" : 5 } }' -e 'spaces in key' 'value' com.avito.android/com.avito.android.InstrumentationRunner") } }
10
Kotlin
50
414
4dc43d73134301c36793e49289305768e68e645b
1,282
avito-android
MIT License
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/panels/management/packages/PackagesHeaderData.kt
zhoumin03
128,005,393
false
{"Text": 6391, "XML": 6476, "YAML": 417, "Ant Build System": 12, "Shell": 563, "Markdown": 577, "Ignore List": 97, "Git Attributes": 10, "EditorConfig": 233, "Batchfile": 27, "SVG": 2415, "Java": 76791, "Kotlin": 42750, "Java Properties": 199, "HTML": 2907, "INI": 428, "JFlex": 31, "CSS": 59, "Groovy": 3467, "XSLT": 112, "JavaScript": 211, "JSON": 1033, "desktop": 1, "Python": 13170, "Maven POM": 76, "JAR Manifest": 16, "PHP": 47, "Gradle Kotlin DSL": 273, "Protocol Buffer": 3, "Microsoft Visual Studio Solution": 5, "C#": 37, "Smalltalk": 17, "Diff": 131, "Erlang": 1, "Rich Text Format": 2, "AspectJ": 2, "Perl": 6, "HLSL": 2, "Objective-C": 21, "CoffeeScript": 3, "HTTP": 2, "JSON with Comments": 59, "GraphQL": 49, "OpenStep Property List": 46, "Tcl": 1, "fish": 1, "Gradle": 433, "Dockerfile": 3, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 4, "XML Property List": 86, "Vim Script": 7, "Vim Snippet": 3, "Vim Help File": 2, "Starlark": 2, "E-mail": 18, "Roff": 249, "Roff Manpage": 39, "Swift": 3, "C": 47, "TOML": 103, "Proguard": 2, "Checksums": 58, "Java Server Pages": 8, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 2, "CMake": 15, "C++": 32, "VBScript": 1, "NSIS": 5, "PlantUML": 5, "Thrift": 3, "Cython": 14, "reStructuredText": 56, "Regular Expression": 3, "JSON5": 4}
package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.packages import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.operations.PackageSearchOperation import org.jetbrains.annotations.Nls internal data class PackagesHeaderData( @Nls val labelText: String, val count: Int, val availableUpdatesCount: Int, val updateOperations: List<PackageSearchOperation<*>> ) { companion object { val EMPTY = PackagesHeaderData("", 0, 0, emptyList()) } }
1
null
1
1
85e5e3f22943744eaf80e844fdf195ca1130b14b
523
intellij-community
Apache License 2.0
app/src/main/java/com/vishnu/junitexample/coroutines/MyUseCase.kt
making-code-easy
260,397,962
false
null
package com.vishnu.junitexample.coroutines import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.withContext import kotlin.math.sqrt class MyUseCase(private val repository: MyRepository) { suspend fun getData(): DummyData { repository.doSomething() return DummyData() } /**********************************************************************************************/ suspend fun heavyOperation(): Long { return withContext(Dispatchers.Default) { return@withContext doHardMaths() } } suspend fun heavyOperationWithDelay(): Long { return withContext(Dispatchers.Default) { delay(15_000) return@withContext doHardMaths() } } private fun doHardMaths(): Long { var count = 0.0 for (i in 1..100_000_000) { count += sqrt(i.toDouble()) } return count.toLong() } }
1
Kotlin
1
2
e628c7db26b4358bde17d531315e73b44f6a89d2
970
unit-test-in-kotlin-using-mockk-library
Apache License 2.0
Final/presentation/src/main/java/ubb/thesis/david/monumental/common/BaseViewModel.kt
davidleiti
163,836,279
false
null
package ubb.thesis.david.monumental.common import androidx.lifecycle.ViewModel import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable open class BaseViewModel: ViewModel() { private val compositeDisposable = CompositeDisposable() protected fun addDisposable(d: Disposable) = compositeDisposable.add(d) override fun onCleared() { compositeDisposable.clear() super.onCleared() } }
0
Kotlin
0
2
59ca0edd6bf8f004c0a712ce532fcc107f58d147
455
Monumental
MIT License
src/integTest/kotlin/dev3/blockchainapiservice/repository/JooqAssetSendRequestRepositoryIntegTest.kt
0xDev3
539,904,697
false
null
package dev3.blockchainapiservice.repository import dev3.blockchainapiservice.TestBase import dev3.blockchainapiservice.TestData import dev3.blockchainapiservice.features.asset.send.model.params.StoreAssetSendRequestParams import dev3.blockchainapiservice.features.asset.send.model.result.AssetSendRequest import dev3.blockchainapiservice.features.asset.send.repository.JooqAssetSendRequestRepository import dev3.blockchainapiservice.generated.jooq.enums.UserIdentifierType import dev3.blockchainapiservice.generated.jooq.id.AssetSendRequestId import dev3.blockchainapiservice.generated.jooq.id.ProjectId import dev3.blockchainapiservice.generated.jooq.id.UserId import dev3.blockchainapiservice.generated.jooq.tables.records.AssetSendRequestRecord import dev3.blockchainapiservice.generated.jooq.tables.records.ProjectRecord import dev3.blockchainapiservice.generated.jooq.tables.records.UserIdentifierRecord import dev3.blockchainapiservice.model.ScreenConfig import dev3.blockchainapiservice.testcontainers.SharedTestContainers import dev3.blockchainapiservice.util.Balance import dev3.blockchainapiservice.util.BaseUrl import dev3.blockchainapiservice.util.ChainId import dev3.blockchainapiservice.util.ContractAddress import dev3.blockchainapiservice.util.TransactionHash import dev3.blockchainapiservice.util.WalletAddress import org.jooq.DSLContext import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.jooq.JooqTest import org.springframework.context.annotation.Import import org.springframework.test.annotation.DirtiesContext import java.math.BigInteger import java.util.UUID @JooqTest @Import(JooqAssetSendRequestRepository::class) @DirtiesContext @TestInstance(TestInstance.Lifecycle.PER_CLASS) class JooqAssetSendRequestRepositoryIntegTest : TestBase() { companion object { private val CHAIN_ID = ChainId(1337L) private const val REDIRECT_URL = "redirect-url" private val TOKEN_ADDRESS = ContractAddress("a") private val ASSET_AMOUNT = Balance(BigInteger.valueOf(123456L)) private val ASSET_SENDER_ADDRESS = WalletAddress("b") private val ASSET_RECIPIENT_ADDRESS = WalletAddress("c") private val ARBITRARY_DATA = TestData.EMPTY_JSON_OBJECT private const val SEND_SCREEN_BEFORE_ACTION_MESSAGE = "send-screen-before-action-message" private const val SEND_SCREEN_AFTER_ACTION_MESSAGE = "send-screen-after-action-message" private val TX_HASH = TransactionHash("tx-hash") private val PROJECT_ID = ProjectId(UUID.randomUUID()) private val OWNER_ID = UserId(UUID.randomUUID()) } @Suppress("unused") private val postgresContainer = SharedTestContainers.postgresContainer @Autowired private lateinit var repository: JooqAssetSendRequestRepository @Autowired private lateinit var dslContext: DSLContext @BeforeEach fun beforeEach() { postgresContainer.cleanAllDatabaseTables(dslContext) dslContext.executeInsert( UserIdentifierRecord( id = OWNER_ID, userIdentifier = "user-identifier", identifierType = UserIdentifierType.ETH_WALLET_ADDRESS, stripeClientId = null ) ) dslContext.executeInsert( ProjectRecord( id = PROJECT_ID, ownerId = OWNER_ID, issuerContractAddress = ContractAddress("0"), baseRedirectUrl = BaseUrl("base-redirect-url"), chainId = ChainId(1337L), customRpcUrl = "custom-rpc-url", createdAt = TestData.TIMESTAMP ) ) } @Test fun mustCorrectlyFetchAssetSendRequestById() { val id = AssetSendRequestId(UUID.randomUUID()) suppose("some asset send request exists in database") { dslContext.executeInsert( AssetSendRequestRecord( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ) ) } verify("asset send request is correctly fetched by ID") { val result = repository.getById(id) expectThat(result) .isEqualTo( AssetSendRequest( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, txHash = TX_HASH, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) ) } } @Test fun mustReturnNullWhenFetchingNonExistentAssetSendRequestById() { verify("null is returned when fetching non-existent asset send request") { val result = repository.getById(AssetSendRequestId(UUID.randomUUID())) expectThat(result) .isNull() } } @Test fun mustCorrectlyFetchAssetSendRequestsByProject() { val otherProjectId = ProjectId(UUID.randomUUID()) suppose("some other project is in database") { dslContext.executeInsert( ProjectRecord( id = otherProjectId, ownerId = OWNER_ID, issuerContractAddress = ContractAddress("1"), baseRedirectUrl = BaseUrl("base-redirect-url"), chainId = ChainId(1337L), customRpcUrl = "custom-rpc-url", createdAt = TestData.TIMESTAMP ) ) } val projectRequests = listOf( AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ), AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ) ) val otherRequests = listOf( AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = otherProjectId, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = WalletAddress("dead"), assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ), AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = otherProjectId, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = null, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ) ) suppose("some asset send requests exist in database") { dslContext.batchInsert(projectRequests + otherRequests).execute() } verify("asset send requests are correctly fetched by project") { val result = repository.getAllByProjectId(PROJECT_ID) expectThat(result) .containsExactlyInAnyOrderElementsOf( projectRequests.map { AssetSendRequest( id = it.id, projectId = it.projectId, chainId = it.chainId, redirectUrl = it.redirectUrl, tokenAddress = it.tokenAddress, assetAmount = it.assetAmount, assetSenderAddress = it.assetSenderAddress, assetRecipientAddress = it.assetRecipientAddress, txHash = it.txHash, arbitraryData = it.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = it.screenBeforeActionMessage, afterActionMessage = it.screenAfterActionMessage ), createdAt = it.createdAt ) } ) } } @Test fun mustCorrectlyFetchAssetSendRequestsBySender() { val senderRequests = listOf( AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ), AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ) ) val otherRequests = listOf( AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = WalletAddress("dead"), assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ), AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = null, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ) ) suppose("some asset send requests exist in database") { dslContext.batchInsert(senderRequests + otherRequests).execute() } verify("asset send requests are correctly fetched by sender") { val result = repository.getBySender(ASSET_SENDER_ADDRESS) expectThat(result) .containsExactlyInAnyOrderElementsOf( senderRequests.map { AssetSendRequest( id = it.id, projectId = it.projectId, chainId = it.chainId, redirectUrl = it.redirectUrl, tokenAddress = it.tokenAddress, assetAmount = it.assetAmount, assetSenderAddress = it.assetSenderAddress, assetRecipientAddress = it.assetRecipientAddress, txHash = it.txHash, arbitraryData = it.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = it.screenBeforeActionMessage, afterActionMessage = it.screenAfterActionMessage ), createdAt = it.createdAt ) } ) } } @Test fun mustCorrectlyFetchAssetSendRequestsByRecipient() { val recipientRequests = listOf( AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ), AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ) ) val otherRequests = listOf( AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = WalletAddress("dead"), arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ) ) suppose("some asset send requests exist in database") { dslContext.batchInsert(recipientRequests + otherRequests).execute() } verify("asset send requests are correctly fetched by recipient") { val result = repository.getByRecipient(ASSET_RECIPIENT_ADDRESS) expectThat(result) .containsExactlyInAnyOrderElementsOf( recipientRequests.map { AssetSendRequest( id = it.id, projectId = it.projectId, chainId = it.chainId, redirectUrl = it.redirectUrl, tokenAddress = it.tokenAddress, assetAmount = it.assetAmount, assetSenderAddress = it.assetSenderAddress, assetRecipientAddress = it.assetRecipientAddress, txHash = it.txHash, arbitraryData = it.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = it.screenBeforeActionMessage, afterActionMessage = it.screenAfterActionMessage ), createdAt = it.createdAt ) } ) } } @Test fun mustCorrectlyStoreAssetSendRequest() { val id = AssetSendRequestId(UUID.randomUUID()) val params = StoreAssetSendRequestParams( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) val storedAssetSendRequest = suppose("asset send request is stored in database") { repository.store(params) } val expectedAssetSendRequest = AssetSendRequest( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, txHash = null, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) verify("storing asset send request returns correct result") { expectThat(storedAssetSendRequest) .isEqualTo(expectedAssetSendRequest) } verify("asset send request was stored in database") { val result = repository.getById(id) expectThat(result) .isEqualTo(expectedAssetSendRequest) } } @Test fun mustCorrectlySetTxInfoForAssetSendRequestWithNullTxHash() { val id = AssetSendRequestId(UUID.randomUUID()) val params = StoreAssetSendRequestParams( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) suppose("asset send request is stored in database") { repository.store(params) } verify("setting txInfo will succeed") { expectThat(repository.setTxInfo(id, TX_HASH, ASSET_SENDER_ADDRESS)) .isTrue() } verify("txInfo was correctly set in database") { val result = repository.getById(id) expectThat(result) .isEqualTo( AssetSendRequest( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, txHash = TX_HASH, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) ) } } @Test fun mustNotUpdateTokenSenderAddressForAssetSendRequestWhenTokenSenderIsAlreadySet() { val id = AssetSendRequestId(UUID.randomUUID()) val params = StoreAssetSendRequestParams( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) suppose("asset send request is stored in database") { repository.store(params) } verify("setting txInfo will succeed") { val ignoredTokenSender = WalletAddress("f") expectThat(repository.setTxInfo(id, TX_HASH, ignoredTokenSender)) .isTrue() } verify("txHash was correctly set while token sender was not updated") { val result = repository.getById(id) expectThat(result) .isEqualTo( AssetSendRequest( id = id, chainId = CHAIN_ID, projectId = PROJECT_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, txHash = TX_HASH, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) ) } } @Test fun mustNotSetTxHashForAssetSendRequestWhenTxHashIsAlreadySet() { val id = AssetSendRequestId(UUID.randomUUID()) val params = StoreAssetSendRequestParams( id = id, chainId = CHAIN_ID, projectId = PROJECT_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) suppose("asset send request is stored in database") { repository.store(params) } verify("setting txInfo will succeed") { expectThat(repository.setTxInfo(id, TX_HASH, ASSET_SENDER_ADDRESS)) .isTrue() } verify("setting another txInfo will not succeed") { expectThat( repository.setTxInfo( id, TransactionHash("different-tx-hash"), ASSET_SENDER_ADDRESS ) ).isFalse() } verify("first txHash remains in database") { val result = repository.getById(id) expectThat(result) .isEqualTo( AssetSendRequest( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, txHash = TX_HASH, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) ) } } }
0
Kotlin
0
0
d9aa8802cf140e0cdd3b701fa2a9c30764b4ad5f
28,544
blockchain-api-service
MIT License
src/integTest/kotlin/dev3/blockchainapiservice/repository/JooqAssetSendRequestRepositoryIntegTest.kt
0xDev3
539,904,697
false
null
package dev3.blockchainapiservice.repository import dev3.blockchainapiservice.TestBase import dev3.blockchainapiservice.TestData import dev3.blockchainapiservice.features.asset.send.model.params.StoreAssetSendRequestParams import dev3.blockchainapiservice.features.asset.send.model.result.AssetSendRequest import dev3.blockchainapiservice.features.asset.send.repository.JooqAssetSendRequestRepository import dev3.blockchainapiservice.generated.jooq.enums.UserIdentifierType import dev3.blockchainapiservice.generated.jooq.id.AssetSendRequestId import dev3.blockchainapiservice.generated.jooq.id.ProjectId import dev3.blockchainapiservice.generated.jooq.id.UserId import dev3.blockchainapiservice.generated.jooq.tables.records.AssetSendRequestRecord import dev3.blockchainapiservice.generated.jooq.tables.records.ProjectRecord import dev3.blockchainapiservice.generated.jooq.tables.records.UserIdentifierRecord import dev3.blockchainapiservice.model.ScreenConfig import dev3.blockchainapiservice.testcontainers.SharedTestContainers import dev3.blockchainapiservice.util.Balance import dev3.blockchainapiservice.util.BaseUrl import dev3.blockchainapiservice.util.ChainId import dev3.blockchainapiservice.util.ContractAddress import dev3.blockchainapiservice.util.TransactionHash import dev3.blockchainapiservice.util.WalletAddress import org.jooq.DSLContext import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.jooq.JooqTest import org.springframework.context.annotation.Import import org.springframework.test.annotation.DirtiesContext import java.math.BigInteger import java.util.UUID @JooqTest @Import(JooqAssetSendRequestRepository::class) @DirtiesContext @TestInstance(TestInstance.Lifecycle.PER_CLASS) class JooqAssetSendRequestRepositoryIntegTest : TestBase() { companion object { private val CHAIN_ID = ChainId(1337L) private const val REDIRECT_URL = "redirect-url" private val TOKEN_ADDRESS = ContractAddress("a") private val ASSET_AMOUNT = Balance(BigInteger.valueOf(123456L)) private val ASSET_SENDER_ADDRESS = WalletAddress("b") private val ASSET_RECIPIENT_ADDRESS = WalletAddress("c") private val ARBITRARY_DATA = TestData.EMPTY_JSON_OBJECT private const val SEND_SCREEN_BEFORE_ACTION_MESSAGE = "send-screen-before-action-message" private const val SEND_SCREEN_AFTER_ACTION_MESSAGE = "send-screen-after-action-message" private val TX_HASH = TransactionHash("tx-hash") private val PROJECT_ID = ProjectId(UUID.randomUUID()) private val OWNER_ID = UserId(UUID.randomUUID()) } @Suppress("unused") private val postgresContainer = SharedTestContainers.postgresContainer @Autowired private lateinit var repository: JooqAssetSendRequestRepository @Autowired private lateinit var dslContext: DSLContext @BeforeEach fun beforeEach() { postgresContainer.cleanAllDatabaseTables(dslContext) dslContext.executeInsert( UserIdentifierRecord( id = OWNER_ID, userIdentifier = "user-identifier", identifierType = UserIdentifierType.ETH_WALLET_ADDRESS, stripeClientId = null ) ) dslContext.executeInsert( ProjectRecord( id = PROJECT_ID, ownerId = OWNER_ID, issuerContractAddress = ContractAddress("0"), baseRedirectUrl = BaseUrl("base-redirect-url"), chainId = ChainId(1337L), customRpcUrl = "custom-rpc-url", createdAt = TestData.TIMESTAMP ) ) } @Test fun mustCorrectlyFetchAssetSendRequestById() { val id = AssetSendRequestId(UUID.randomUUID()) suppose("some asset send request exists in database") { dslContext.executeInsert( AssetSendRequestRecord( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ) ) } verify("asset send request is correctly fetched by ID") { val result = repository.getById(id) expectThat(result) .isEqualTo( AssetSendRequest( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, txHash = TX_HASH, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) ) } } @Test fun mustReturnNullWhenFetchingNonExistentAssetSendRequestById() { verify("null is returned when fetching non-existent asset send request") { val result = repository.getById(AssetSendRequestId(UUID.randomUUID())) expectThat(result) .isNull() } } @Test fun mustCorrectlyFetchAssetSendRequestsByProject() { val otherProjectId = ProjectId(UUID.randomUUID()) suppose("some other project is in database") { dslContext.executeInsert( ProjectRecord( id = otherProjectId, ownerId = OWNER_ID, issuerContractAddress = ContractAddress("1"), baseRedirectUrl = BaseUrl("base-redirect-url"), chainId = ChainId(1337L), customRpcUrl = "custom-rpc-url", createdAt = TestData.TIMESTAMP ) ) } val projectRequests = listOf( AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ), AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ) ) val otherRequests = listOf( AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = otherProjectId, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = WalletAddress("dead"), assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ), AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = otherProjectId, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = null, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ) ) suppose("some asset send requests exist in database") { dslContext.batchInsert(projectRequests + otherRequests).execute() } verify("asset send requests are correctly fetched by project") { val result = repository.getAllByProjectId(PROJECT_ID) expectThat(result) .containsExactlyInAnyOrderElementsOf( projectRequests.map { AssetSendRequest( id = it.id, projectId = it.projectId, chainId = it.chainId, redirectUrl = it.redirectUrl, tokenAddress = it.tokenAddress, assetAmount = it.assetAmount, assetSenderAddress = it.assetSenderAddress, assetRecipientAddress = it.assetRecipientAddress, txHash = it.txHash, arbitraryData = it.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = it.screenBeforeActionMessage, afterActionMessage = it.screenAfterActionMessage ), createdAt = it.createdAt ) } ) } } @Test fun mustCorrectlyFetchAssetSendRequestsBySender() { val senderRequests = listOf( AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ), AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ) ) val otherRequests = listOf( AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = WalletAddress("dead"), assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ), AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = null, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ) ) suppose("some asset send requests exist in database") { dslContext.batchInsert(senderRequests + otherRequests).execute() } verify("asset send requests are correctly fetched by sender") { val result = repository.getBySender(ASSET_SENDER_ADDRESS) expectThat(result) .containsExactlyInAnyOrderElementsOf( senderRequests.map { AssetSendRequest( id = it.id, projectId = it.projectId, chainId = it.chainId, redirectUrl = it.redirectUrl, tokenAddress = it.tokenAddress, assetAmount = it.assetAmount, assetSenderAddress = it.assetSenderAddress, assetRecipientAddress = it.assetRecipientAddress, txHash = it.txHash, arbitraryData = it.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = it.screenBeforeActionMessage, afterActionMessage = it.screenAfterActionMessage ), createdAt = it.createdAt ) } ) } } @Test fun mustCorrectlyFetchAssetSendRequestsByRecipient() { val recipientRequests = listOf( AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ), AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ) ) val otherRequests = listOf( AssetSendRequestRecord( id = AssetSendRequestId(UUID.randomUUID()), projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = WalletAddress("dead"), arbitraryData = ARBITRARY_DATA, screenBeforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, screenAfterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE, txHash = TX_HASH, createdAt = TestData.TIMESTAMP ) ) suppose("some asset send requests exist in database") { dslContext.batchInsert(recipientRequests + otherRequests).execute() } verify("asset send requests are correctly fetched by recipient") { val result = repository.getByRecipient(ASSET_RECIPIENT_ADDRESS) expectThat(result) .containsExactlyInAnyOrderElementsOf( recipientRequests.map { AssetSendRequest( id = it.id, projectId = it.projectId, chainId = it.chainId, redirectUrl = it.redirectUrl, tokenAddress = it.tokenAddress, assetAmount = it.assetAmount, assetSenderAddress = it.assetSenderAddress, assetRecipientAddress = it.assetRecipientAddress, txHash = it.txHash, arbitraryData = it.arbitraryData, screenConfig = ScreenConfig( beforeActionMessage = it.screenBeforeActionMessage, afterActionMessage = it.screenAfterActionMessage ), createdAt = it.createdAt ) } ) } } @Test fun mustCorrectlyStoreAssetSendRequest() { val id = AssetSendRequestId(UUID.randomUUID()) val params = StoreAssetSendRequestParams( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) val storedAssetSendRequest = suppose("asset send request is stored in database") { repository.store(params) } val expectedAssetSendRequest = AssetSendRequest( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, txHash = null, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) verify("storing asset send request returns correct result") { expectThat(storedAssetSendRequest) .isEqualTo(expectedAssetSendRequest) } verify("asset send request was stored in database") { val result = repository.getById(id) expectThat(result) .isEqualTo(expectedAssetSendRequest) } } @Test fun mustCorrectlySetTxInfoForAssetSendRequestWithNullTxHash() { val id = AssetSendRequestId(UUID.randomUUID()) val params = StoreAssetSendRequestParams( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) suppose("asset send request is stored in database") { repository.store(params) } verify("setting txInfo will succeed") { expectThat(repository.setTxInfo(id, TX_HASH, ASSET_SENDER_ADDRESS)) .isTrue() } verify("txInfo was correctly set in database") { val result = repository.getById(id) expectThat(result) .isEqualTo( AssetSendRequest( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, txHash = TX_HASH, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) ) } } @Test fun mustNotUpdateTokenSenderAddressForAssetSendRequestWhenTokenSenderIsAlreadySet() { val id = AssetSendRequestId(UUID.randomUUID()) val params = StoreAssetSendRequestParams( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) suppose("asset send request is stored in database") { repository.store(params) } verify("setting txInfo will succeed") { val ignoredTokenSender = WalletAddress("f") expectThat(repository.setTxInfo(id, TX_HASH, ignoredTokenSender)) .isTrue() } verify("txHash was correctly set while token sender was not updated") { val result = repository.getById(id) expectThat(result) .isEqualTo( AssetSendRequest( id = id, chainId = CHAIN_ID, projectId = PROJECT_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, txHash = TX_HASH, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) ) } } @Test fun mustNotSetTxHashForAssetSendRequestWhenTxHashIsAlreadySet() { val id = AssetSendRequestId(UUID.randomUUID()) val params = StoreAssetSendRequestParams( id = id, chainId = CHAIN_ID, projectId = PROJECT_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) suppose("asset send request is stored in database") { repository.store(params) } verify("setting txInfo will succeed") { expectThat(repository.setTxInfo(id, TX_HASH, ASSET_SENDER_ADDRESS)) .isTrue() } verify("setting another txInfo will not succeed") { expectThat( repository.setTxInfo( id, TransactionHash("different-tx-hash"), ASSET_SENDER_ADDRESS ) ).isFalse() } verify("first txHash remains in database") { val result = repository.getById(id) expectThat(result) .isEqualTo( AssetSendRequest( id = id, projectId = PROJECT_ID, chainId = CHAIN_ID, redirectUrl = REDIRECT_URL, tokenAddress = TOKEN_ADDRESS, assetAmount = ASSET_AMOUNT, assetSenderAddress = ASSET_SENDER_ADDRESS, assetRecipientAddress = ASSET_RECIPIENT_ADDRESS, txHash = TX_HASH, arbitraryData = ARBITRARY_DATA, screenConfig = ScreenConfig( beforeActionMessage = SEND_SCREEN_BEFORE_ACTION_MESSAGE, afterActionMessage = SEND_SCREEN_AFTER_ACTION_MESSAGE ), createdAt = TestData.TIMESTAMP ) ) } } }
0
Kotlin
0
0
d9aa8802cf140e0cdd3b701fa2a9c30764b4ad5f
28,544
blockchain-api-service
MIT License
app/src/main/java/com/example/books/common/Ressource.kt
Moohaa
514,947,288
false
{"Kotlin": 68305}
package com.example.books.common sealed class Ressource<T>(val data: T? = null, val message: String? = null) { class Success<T>(data: T) : Ressource<T>(data) class Error<T>(message: String, data: T? = null) : Ressource<T>(data, message) class Loading<T>(data: T? = null) : Ressource<T>(data) }
0
Kotlin
0
0
941854481e722fcf060ea555782ba16c21e2f7ab
307
Bookest
MIT License
data/src/main/java/com/filipedrmorgado/data/di/RepositoryModule.kt
filipedrmorgado
729,274,421
false
{"Kotlin": 43642}
package com.filipedrmorgado.data.di import com.filipedrmorgado.data.repositories.FtuRepositoryImpl import com.filipedrmorgado.data.repositories.UserWalletDataRepositoryImpl import com.filipedrmorgado.domain.repository.FtuRepository import com.filipedrmorgado.domain.repository.UserWalletDataRepository import org.koin.dsl.module val repositoriesModule = module { single<UserWalletDataRepository> { UserWalletDataRepositoryImpl(get()) } single<FtuRepository> { FtuRepositoryImpl(get(),get()) } }
0
Kotlin
0
1
9ca066e222f4c9dcde746380087756ccb33bf40b
506
LightningMoney
Apache License 2.0
src/main/kotlin/pl/vemu/diamold/blocks/DiamoldBlock.kt
lospejos
427,424,341
true
{"Kotlin": 6360}
package pl.vemu.diamold.blocks import net.fabricmc.fabric.api.`object`.builder.v1.block.FabricBlockSettings import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags import net.minecraft.block.Block import net.minecraft.block.Material import net.minecraft.sound.BlockSoundGroup import pl.vemu.diamold.items.JsonName object DiamoldBlock : Block( FabricBlockSettings.of(Material.METAL).requiresTool().strength(5.0F, 6.0F) .sounds(BlockSoundGroup.METAL).breakByTool(FabricToolTags.PICKAXES, 2) ), JsonName { override val jsonName = "diamold_block" }
0
null
0
0
f9ba608d86c4c65ec51fe06ca33e6efaa16f25af
570
diamold
MIT License
src/main/kotlin/pl/vemu/diamold/blocks/DiamoldBlock.kt
lospejos
427,424,341
true
{"Kotlin": 6360}
package pl.vemu.diamold.blocks import net.fabricmc.fabric.api.`object`.builder.v1.block.FabricBlockSettings import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags import net.minecraft.block.Block import net.minecraft.block.Material import net.minecraft.sound.BlockSoundGroup import pl.vemu.diamold.items.JsonName object DiamoldBlock : Block( FabricBlockSettings.of(Material.METAL).requiresTool().strength(5.0F, 6.0F) .sounds(BlockSoundGroup.METAL).breakByTool(FabricToolTags.PICKAXES, 2) ), JsonName { override val jsonName = "diamold_block" }
0
null
0
0
f9ba608d86c4c65ec51fe06ca33e6efaa16f25af
570
diamold
MIT License
app/src/main/java/com/iti/tiempo/di/NetworkModule.kt
AbdElwahabZayed
489,923,791
false
null
package com.iti.tiempo.di import android.content.Context import com.iti.tiempo.local.AppSharedPreference import com.iti.tiempo.network.WeatherService import com.iti.tiempo.utils.NETWORK_TIMEOUT import com.iti.tiempo.utils.NETWORK_URL import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import okhttp3.Interceptor import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import java.util.concurrent.TimeUnit import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object NetworkModule { @Provides @Singleton fun provideHeadersInterceptor() = Interceptor { chain -> chain.proceed( chain.request().newBuilder() .build() ) } @Provides @Singleton fun provideHttpLoggingInterceptor(): HttpLoggingInterceptor { val logging = HttpLoggingInterceptor() logging.level = HttpLoggingInterceptor.Level.BODY return logging } @Provides @Singleton fun provideOkHttpClient( headersInterceptor: Interceptor, logging: HttpLoggingInterceptor, ): OkHttpClient { return OkHttpClient.Builder() .readTimeout(NETWORK_TIMEOUT, TimeUnit.SECONDS) .connectTimeout(NETWORK_TIMEOUT, TimeUnit.SECONDS) .addInterceptor(headersInterceptor) .addInterceptor(logging) .build() } @Provides @Singleton fun provideHomeServices(okHttpClient: OkHttpClient): WeatherService { return getDynamicRetrofitClient(okHttpClient, NETWORK_URL).create(WeatherService::class.java) } private fun getDynamicRetrofitClient( client: OkHttpClient, baseUrl: String, ): Retrofit { return Retrofit.Builder() .client(client) .baseUrl(baseUrl) .addConverterFactory(MoshiConverterFactory.create()) .build() } }
0
Kotlin
0
2
2b765bf9a5f869f02b71a12a399c30d5e4c5fe3b
2,153
Tiempo
University of Illinois/NCSA Open Source License
app/src/main/java/com/example/reactivearchitecture/core/dagger/ApplicationModule.kt
HIFILEO
160,580,982
false
null
/* Copyright 2017 LEO LLC Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.example.reactivearchitecture.core.dagger import android.app.Application import com.example.reactivearchitecture.R import com.example.reactivearchitecture.nowplaying.controller.ServiceController import com.example.reactivearchitecture.nowplaying.controller.ServiceControllerImpl import com.example.reactivearchitecture.nowplaying.service.ServiceApi import com.google.gson.Gson import com.google.gson.GsonBuilder import org.mockito.Mockito import javax.inject.Singleton import dagger.Module import dagger.Provides import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory /** * Dagger2 [Module] providing application-level dependency bindings for test. */ @Module(includes = arrayOf(ViewModelModule::class)) class TestApplicationModule { @Singleton @Provides fun providesGson(builder: GsonBuilder): Gson { return builder.create() } @Provides fun providesGsonBuilder(): GsonBuilder { return GsonBuilder() } @Singleton @Provides fun providesOkHttpBuilder(): OkHttpClient.Builder { return OkHttpClient.Builder() } @Singleton @Provides fun providesOkHttpClient(builder: OkHttpClient.Builder, level: HttpLoggingInterceptor.Level): OkHttpClient { // Log HTTP request and response data in debug mode val loggingInterceptor = HttpLoggingInterceptor() loggingInterceptor.level = level builder.addInterceptor(loggingInterceptor) return builder.build() } @Singleton @Provides fun providesRetrofitBuilder(client: OkHttpClient, gson: Gson): Retrofit.Builder { return Retrofit.Builder() .client(client) .addConverterFactory(GsonConverterFactory.create(gson)) } @Singleton @Provides fun providesHttpLoggingInterceptorLevel(): HttpLoggingInterceptor.Level { return HttpLoggingInterceptor.Level.NONE } @Provides @Singleton fun providesInfoServiceApi(retrofit: Retrofit.Builder): ServiceApi { // Note - mock the web calls. You test the in contract testing. return Mockito.mock(ServiceApi::class.java) } @Provides @Singleton fun providesGatewayInfo(serviceApi: ServiceApi, application: Application): ServiceController { return ServiceControllerImpl(serviceApi, application.getString(R.string.api_key), application.getString(R.string.image_url_path)) } }
0
Kotlin
1
1
bb9e3bb164fd6db47a776df2b823f72a46a2a8a9
3,616
ReactiveArchitectureKotlin
Apache License 2.0
src/main/kotlin/io/github/gilbertojrequena/bonsai_sns/api/action/ListEndpointsByPlatformApplication.kt
gilbertojrequena
225,954,375
false
null
package io.github.gilbertojrequena.bonsai_sns.api.action import io.github.gilbertojrequena.bonsai_sns.api.xml import io.ktor.application.ApplicationCall import io.ktor.http.Parameters import io.ktor.response.respondText internal class ListEndpointsByPlatformApplication : Action { override suspend fun execute(call: ApplicationCall, params: Parameters) { call.respondText { xml("ListEndpointsByPlatformApplicationResponse") { element("ListEndpointsByPlatformApplicationResult") { element("Endpoints") } } } } }
0
Kotlin
0
4
ec92bb2eb1abaf5204c85d7001a38cb117e5fa79
612
bonsai-sns
MIT License
src/main/kotlin/network/cere/ddc/crypto/v1/key/sign/spec.kt
Cerebellum-Network
344,519,038
false
null
package network.cere.ddc.crypto.v1.key.sign internal const val ALGORITHM = "Ed25519" internal const val FORMAT = "RAW"
0
Kotlin
1
0
dedeaaa58762b7d361f6c374fd5a2262a22df5f0
120
ddc-encryption-impl-kotlin
MIT License
android-common/src/main/java/com/caldremch/common/base/LifeCycleLogFragment.kt
android-module
424,496,469
false
{"Kotlin": 76902, "Java": 16616, "Shell": 514}
package com.caldremch.common.base import android.content.res.Configuration import android.os.Bundle import android.util.Log import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment /** * * @author Caldremch * * @date 2020-06-28 22:49 * * @email <EMAIL> * * @describe * **/ open class LifeCycleLogFragment : Fragment() { companion object{ private val DEFAULT_LOGGER = object : ILifeCycleLogger { override fun log(tag: String, msg: String) { Log.d(tag, msg) } } } open fun getLogger(): ILifeCycleLogger = DEFAULT_LOGGER object DebugUtils { fun buildShortClassTag(cls: Any?): String { val out = StringBuilder() if (cls == null) { out.append("null") } else { var simpleName = cls.javaClass.simpleName if (simpleName == null || simpleName.length <= 0) { simpleName = cls.javaClass.name val end = simpleName.lastIndexOf('.') if (end > 0) { simpleName = simpleName.substring(end + 1) } } out.append(simpleName) out.append('{') out.append(Integer.toHexString(System.identityHashCode(cls))) out.append('}') } return out.toString() } } private var shadowInstanceString: String? = null init { shadowInstanceString = DebugUtils.buildShortClassTag(this) } private val TAG = "LifeCycleLogFragment" protected fun isPrintLifeCycle(): Boolean { return true } override fun onDestroyView() { super.onDestroyView() d("onDestroyView: ") } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { d("onCreateView: ") return super.onCreateView(inflater, container, savedInstanceState) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { d("onViewCreated: ") super.onViewCreated(view, savedInstanceState) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) d("onActivityCreated: ") } private fun d(log: String) { if (isPrintLifeCycle()) { getLogger().log(TAG, "${shadowInstanceString}-->" + log) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) d("onCreate: ") } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) d("onConfigurationChanged: ") } override fun onStart() { super.onStart() d("onStart: ") } override fun onStop() { super.onStop() d("onStop: ") } override fun onDestroy() { super.onDestroy() d("onDestroy: ") } override fun onPause() { super.onPause() d("onPause: ") } override fun onResume() { super.onResume() d("onResume: ") } }
0
Kotlin
0
0
85037eb69d234970cd73cd44e91fb17403fe2700
3,309
android-common
Apache License 2.0