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
Compose/app/src/main/java/top/chilfish/compose/models/MessageViewModel.kt
Chilfish
610,771,353
false
null
package top.chilfish.compose.models import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.navigation.NavHostController import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.launch import top.chilfish.compose.data.Message import top.chilfish.compose.data.fake.Messages import top.chilfish.compose.navigation.NavigationActions import top.chilfish.compose.navigation.Routers class MessageViewModel(val chatUid: String) : ViewModel() { private val _messages = MutableStateFlow<List<Message>>(emptyList()) val messages: StateFlow<List<Message>> = _messages init { loadMessage() } private fun loadMessage() { viewModelScope.launch { _messages.value = Messages.chatHistory(chatUid) } } fun onAvatarClick(navController: NavHostController) { NavigationActions(navController).navigateTo(Routers.Profile, chatUid) } }
0
Kotlin
0
0
e5b88162f8d3d305a3b8c144653e0bf062e70ae1
987
Android-demo
MIT License
spring-pf4j-example/store-app/src/main/kotlin/tech/pf4j/store/config/Pf4jConfig.kt
vadimbublikov
710,930,704
false
{"Kotlin": 39973, "Shell": 1172, "Dockerfile": 694, "Java": 562}
package tech.pf4j.store.config import org.pf4j.spring.SpringPluginManager import org.springframework.context.annotation.Bean import org.springframework.context.annotation.Configuration @Configuration class Pf4jConfig { @Bean fun pluginManager(): SpringPluginManager { return SpringPluginManager() } }
0
Kotlin
0
0
8a06cc0a0c58fd726d341058a9d1270d982d7926
324
backend-modules
Apache License 2.0
server/src/main/kotlin/com/kazakago/cueue/model/WorkspaceId.kt
KazaKago
329,953,173
false
null
package com.kazakago.cueue.model import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable 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 @Serializable(with = WorkspaceId.Serializer::class) data class WorkspaceId(val value: Long) { object Serializer : KSerializer<WorkspaceId> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("workspace_id", PrimitiveKind.LONG) override fun serialize(encoder: Encoder, value: WorkspaceId) { encoder.encodeLong(value.value) } override fun deserialize(decoder: Decoder): WorkspaceId { return WorkspaceId(decoder.decodeLong()) } } }
2
Kotlin
0
3
122ae0c1386809033721a2bf0859d12bfbfe4758
915
cueue_server
Apache License 2.0
liveroom-uikit-core/src/main/java/com/qlive/uikitcore/CoroutineExt.kt
qiniu
538,322,435
false
{"Kotlin": 1143492, "Java": 484578}
package com.qlive.uikitcore import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.lifecycleScope import com.qlive.uikitcore.CoroutineExtSetting.canUseLifecycleScope import kotlinx.coroutines.* import java.lang.Exception object CoroutineExtSetting{ var canUseLifecycleScope = true } class CoroutineScopeWrap { var work: (suspend CoroutineScope.() -> Unit) = {} var error: (e: Throwable) -> Unit = {} var complete: () -> Unit = {} fun doWork(call: suspend CoroutineScope.() -> Unit) { this.work = call } fun catchError(error: (e: Throwable) -> Unit) { this.error = error } fun onFinally(call: () -> Unit) { this.complete = call } } fun backGround( dispatcher: MainCoroutineDispatcher = Dispatchers.Main, c: CoroutineScopeWrap.() -> Unit ) { GlobalScope .launch(dispatcher) { val block = CoroutineScopeWrap() c.invoke(block) try { block.work.invoke(this) } catch (e: Exception) { e.printStackTrace() block.error.invoke(e) } finally { block.complete.invoke() } } } fun LifecycleOwner.backGround( dispatcher: MainCoroutineDispatcher = Dispatchers.Main, c: CoroutineScopeWrap.() -> Unit ): Job { return if (canUseLifecycleScope) { lifecycleScope.launch(dispatcher) { val block = CoroutineScopeWrap() c.invoke(block) try { block.work.invoke(this) } catch (e: Exception) { e.printStackTrace() block.error.invoke(e) } finally { block.complete.invoke() } } } else { GlobalScope.launch(dispatcher) { val block = CoroutineScopeWrap() c.invoke(block) try { block.work.invoke(this) } catch (e: Exception) { e.printStackTrace() block.error.invoke(e) } finally { block.complete.invoke() } } } } //个别客户无法使用 lifecycleScope fun LifecycleOwner.tryBackGroundWithLifecycle( dispatcher: MainCoroutineDispatcher = Dispatchers.Main, work: (suspend CoroutineScope.() -> Unit) = {} ): Job { return if (canUseLifecycleScope) { lifecycleScope.launch(dispatcher) { work.invoke(this) } } else { GlobalScope.launch(dispatcher) { work.invoke(this) } } }
0
Kotlin
4
5
6a13f808c2c36d62944e7a206a1524dba07a9cec
2,573
QNLiveKit_Android
MIT License
portfolio/src/main/kotlin/info/saygindogu/hobby/portfolio/blog/Repositories.kt
saygindogu
321,132,939
false
null
package info.saygindogu.hobby.portfolio.blog import org.springframework.data.repository.PagingAndSortingRepository interface ArticleRepository : PagingAndSortingRepository<Article, Long> { fun findBySlug(slug: String): Article? fun findAllByOrderByAddedAtDesc(): Iterable<Article> }
0
Kotlin
0
0
58675859be1dd81f2dd63885dd69db7e1526dae5
292
kotlin-spring-play-portfolio
MIT License
data/src/main/java/com/anshtya/data/repository/impl/SearchRepositoryImpl.kt
anshtya
704,151,092
false
{"Kotlin": 252581}
package com.anshtya.data.repository.impl import com.anshtya.core.model.SearchItem import com.anshtya.core.network.model.search.asModel import com.anshtya.core.network.retrofit.TmdbApi import com.anshtya.data.model.NetworkResponse import com.anshtya.data.repository.SearchRepository import retrofit2.HttpException import java.io.IOException import javax.inject.Inject internal class SearchRepositoryImpl @Inject constructor( private val tmdbApi: TmdbApi ) : SearchRepository { override suspend fun getSearchSuggestions( query: String, includeAdult: Boolean ): NetworkResponse<List<SearchItem>> { return try { val result = tmdbApi.multiSearch( query = query, includeAdult = includeAdult ).results .map { suggestion -> suggestion.asModel() } NetworkResponse.Success(result) } catch (e: IOException) { NetworkResponse.Error() } catch (e: HttpException) { NetworkResponse.Error() } } }
1
Kotlin
0
1
2f44b6e36602ad1d0c2896e1c950aed50a989814
1,055
MovieInfo
MIT License
cuedes/app/src/main/java/com/kalai/cuedes/location/DistanceUnit.kt
Kalaiz
314,738,151
false
{"Kotlin": 112843}
package com.kalai.cuedes.location enum class DistanceUnit { KM,M,MI,FUR }
0
Kotlin
0
1
7359f399f2b946244461e0179e13740bf5e13017
74
cuedes
MIT License
cuedes/app/src/main/java/com/kalai/cuedes/location/DistanceUnit.kt
Kalaiz
314,738,151
false
{"Kotlin": 112843}
package com.kalai.cuedes.location enum class DistanceUnit { KM,M,MI,FUR }
0
Kotlin
0
1
7359f399f2b946244461e0179e13740bf5e13017
74
cuedes
MIT License
telegram/src/main/kotlin/me/ivmg/telegram/dispatcher/handlers/media/VideoNoteHandler.kt
seik
260,198,511
true
null
package me.ivmg.telegram.dispatcher.handlers.media import me.ivmg.telegram.HandleVideoNoteUpdate import me.ivmg.telegram.entities.Update import me.ivmg.telegram.entities.VideoNote class VideoNoteHandler( handleVideoNoteUpdate: HandleVideoNoteUpdate ) : MediaHandler<VideoNote>( handleVideoNoteUpdate, VideoNoteHandlerFunctions::toMedia, VideoNoteHandlerFunctions::predicate ) private object VideoNoteHandlerFunctions { fun toMedia(update: Update): VideoNote { val videoNote = update.message?.videoNote checkNotNull(videoNote) return videoNote } fun predicate(update: Update): Boolean = update.message?.videoNote != null }
0
null
0
1
6c33ea157af3001c8e75d860f6cdaa395a46945e
679
kotlin-telegram-bot
Apache License 2.0
composeApp/src/androidMain/kotlin/com/christophprenissl/hygienecompanion/util/PermissionHelper.kt
chris-prenissl
818,346,441
false
{"Kotlin": 270639}
package com.christophprenissl.hygienecompanion.util import android.Manifest import android.app.Activity import android.content.Context import android.content.pm.PackageManager import androidx.core.app.ActivityCompat fun requestWritePermission(context: Context) { ActivityCompat.requestPermissions( context as Activity, arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_FOREGROUND_ONLY_PERMISSIONS_REQUEST_CODE, ) } fun writePermissionApproved(context: Context): Boolean { return PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission( context, Manifest.permission.WRITE_EXTERNAL_STORAGE, ) }
0
Kotlin
0
0
ecf55c4fad348b4beabe75aeac2c7bbc6c3ddc72
671
hygiene-lab-companion
MIT License
diabutton/src/main/java/com/panax/diabutton/ui/RowDial.kt
panax11
795,119,666
false
{"Kotlin": 23331}
package com.panax.diabutton.ui import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.RowScope import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.boundsInWindow import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.panax.diabutton.component.DialItem import com.panax.diabutton.component.RowDialControl import com.panax.diabutton.rememberDialController /** * Horizontal dial * * @param modifier Modifier * @param itemSize items size, (0 <= itemSize) * @param controlIndex control position index, (0 <= index <= itemSize) * @param controlContent control composable * @param itemContent item composable * @param onItemSelect item select event, onDragEnd(true: touch up, false: touch move) */ @Composable fun RowDial( modifier: Modifier = Modifier, itemSize: Int = 0, controlIndex: Int = 0, controlContent: @Composable (RowScope.() -> Unit), itemContent: @Composable (BoxScope.(itemIndex: Int) -> Unit), onItemSelect: (itemIndex: Int?, onDragEnd: Boolean) -> Unit = { _, _ -> }, ) { // valid value val validItemSize = itemSize.coerceAtLeast(0) val validControlIndex = controlIndex.coerceIn(0, validItemSize) // controller state val controller = rememberDialController() Row( modifier = modifier .onGloballyPositioned { controller.setLimitArea(it.boundsInWindow()) }, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { for (index in 0 until validItemSize + 1) { // control position if (index == validControlIndex) { RowDialControl( onTargetSelect = onItemSelect, controller = controller, content = controlContent ) } // item position if (index < validItemSize) { DialItem( controller = controller, index = index, content = itemContent ) } } } } @Preview @Composable private fun RowDialPreview() { var selectIndex by remember { mutableIntStateOf(0) } RowDial( modifier = Modifier .size(100.dp, 50.dp) .background(color = Color.DarkGray) .border(width = 2.dp, color = Color.Green) .padding(2.dp), itemSize = 3, controlIndex = 1, onItemSelect = { index, onDragEnd -> if (index != null) { selectIndex = index } }, controlContent = { Box( modifier = Modifier .fillMaxHeight() .width(50.dp) .background(color = Color.Cyan) .border(width = 2.dp, color = Color.Black), contentAlignment = Alignment.Center, content = { Text(text = selectIndex.toString()) } ) }, itemContent = { item -> Box( modifier = Modifier .fillMaxHeight() .background(color = Color.LightGray) .border(width = 2.dp, color = Color.Gray), contentAlignment = Alignment.Center, content = { Text(text = item.toString()) } ) } ) }
0
Kotlin
0
0
f80cb4e171dfdfd918d7bd024bcc97cc3e3dbcad
4,349
DialButtons
Apache License 2.0
app/src/main/java/com/projectdelta/zoro/util/work/UpdateDatabaseWorker.kt
sarafanshul
437,651,086
false
{"Kotlin": 151913}
/* * Copyright (c) 2022. <NAME> */ package com.projectdelta.zoro.util.work import android.content.Context import androidx.hilt.work.HiltWorker import androidx.work.CoroutineWorker import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkRequest import androidx.work.WorkerParameters import com.projectdelta.zoro.data.model.Message import com.projectdelta.zoro.data.repository.MessageRepository import com.projectdelta.zoro.di.qualifiers.IODispatcher import dagger.assisted.Assisted import dagger.assisted.AssistedInject import kotlinx.coroutines.CoroutineDispatcher import kotlinx.coroutines.withContext /** * Removes the messages from Database where [Message.seen] == True * - Runs everytime on app_startup * - Uses [CoroutineWorker] for working in background thread */ @HiltWorker class UpdateDatabaseWorker @AssistedInject constructor( @Assisted private val appContext: Context, @Assisted workerParams: WorkerParameters, private val repository: MessageRepository, @IODispatcher private val dispatcher : CoroutineDispatcher, ) : CoroutineWorker(appContext, workerParams) { companion object{ val workerRequest : WorkRequest get() = OneTimeWorkRequestBuilder<UpdateDatabaseWorker>().build() } override suspend fun doWork(): Result { withContext(dispatcher){ repository.deleteAllMessagesFilteredBySeen(true) } return Result.success() } }
0
Kotlin
0
4
e24e20997f4f550adb6d24e1f093631b35464c82
1,453
Zoro
MIT License
src/main/kotlin/me/kvdpxne/dtm/command/BaseCommand.kt
kvdpxne
666,098,225
false
null
package me.kvdpxne.dtm.command import me.kvdpxne.dtm.command.restricted.WandCommand object BaseCommand : Command("dtm"), Executor<Performer> { private val nameSubCommandMap: Map<String, Executor<*>> init { nameSubCommandMap = buildMap { this["wand"] = WandCommand } } override fun execute(performer: Performer, parameter: Parameter) { val name = parameter.asText() val commandExecutor = nameSubCommandMap[name] ?: return commandExecutor.execute(performer, parameter) } }
0
Kotlin
0
0
6400b37e2638446a51d8912c64f19fee2212cec4
511
destroy-the-monument
Apache License 2.0
jetpack/src/main/java/com/laioffer/lesson1_lifecycle/demo4/Demo4Activity.kt
yuanuscfighton
632,030,844
false
{"Kotlin": 1005102, "Java": 675082}
package com.laioffer.lesson1_lifecycle.demo4 import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.laioffer.R /** * 类的描述: 版本5: 接口监听法 * * Created by 春夏秋冬在中南 on 2023/9/13 02:22 */ class Demo4Activity : AppCompatActivity() { private var myPresenter: IPresenter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.empty_layout) myPresenter = MyPresenter() // 用户端只需要面向接口编程,想用哪个实现类,直接new那个实现类 lifecycle.addObserver(myPresenter!!) } }
0
Kotlin
0
0
b03a297acdf094f56c5d43f99eb29afa35146109
556
SiberianHusky
Apache License 2.0
app/src/main/java/com/example/geolearnapp/ui/quiz/multiplechoices/MultipleChoicesViewModel.kt
Ahtar1
615,216,559
false
null
package com.example.geolearnapp.ui.quiz.multiplechoices import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.navigation.NavHostController import com.example.geolearnapp.data.database.entity.Country import com.example.geolearnapp.domain.repository.CountryRepository import com.example.geolearnapp.domain.use_case.CountryUseCases import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class MultipleChoicesViewModel @Inject constructor( val countryUseCases: CountryUseCases ): ViewModel() { private val _countriesState = MutableStateFlow(listOf<Country>()) val countriesState = _countriesState.asStateFlow() private val _chosenCapitalState = MutableStateFlow("") val chosenCapitalState = _chosenCapitalState.asStateFlow() private val _optionsState = MutableStateFlow(listOf<String>()) val optionsState = _optionsState.asStateFlow() private val _isAnswerCorrectState = MutableStateFlow<Boolean?>(null) val isAnswerCorrectState = _isAnswerCorrectState.asStateFlow() private val _scoreState = MutableStateFlow(0) val scoreState = _scoreState.asStateFlow() private val _highScoreState = MutableStateFlow(0) val highScoreState = _highScoreState.asStateFlow() private val _wrongAnswerState = MutableStateFlow(0) val wrongAnswerState = _wrongAnswerState.asStateFlow() private val _isGameFinishedState = MutableStateFlow(false) val isGameFinishedState = _isGameFinishedState.asStateFlow() private val _correctAnswerState = MutableStateFlow("") val correctAnswerState = _correctAnswerState.asStateFlow() private val _isButtonsActiveState = MutableStateFlow<Boolean>(true) val isButtonsActiveState = _isButtonsActiveState.asStateFlow() val _selectedAnswerState = MutableStateFlow(0) val selectedAnswerState = _selectedAnswerState.asStateFlow() init { getCountries() } fun getCountries(){ viewModelScope.launch(Dispatchers.IO) { _countriesState.value= countryUseCases.getCountriesFromDB() _highScoreState.value = countryUseCases.getHighScore("multiplechoices") getChosenCapitalAndOptions() } } fun getChosenCapitalAndOptions(){ var randomCountry = _countriesState.value.random() while (randomCountry.capital == ""){ randomCountry = _countriesState.value.random() } _chosenCapitalState.value = randomCountry.capital _correctAnswerState.value = randomCountry.name while (_optionsState.value.size < 3){ val country = _countriesState.value.random() if (country.capital != _chosenCapitalState.value && !_optionsState.value.contains(country.name)){ _optionsState.value = _optionsState.value + country.name } } _optionsState.value = _optionsState.value + randomCountry.name _optionsState.value = _optionsState.value.shuffled() } fun checkAnswer(answer: Int){ _isButtonsActiveState.value = false _selectedAnswerState.value = answer _isAnswerCorrectState.value = _optionsState.value[answer] == _correctAnswerState.value if (_isAnswerCorrectState.value == true){ _scoreState.value = _scoreState.value + 1 } else { _wrongAnswerState.value = _wrongAnswerState.value + 1 if (_wrongAnswerState.value == 3){ _isGameFinishedState.value = true viewModelScope.launch(Dispatchers.IO) { val highScore = countryUseCases.getHighScore("multiplechoices") if (_scoreState.value > highScore) { countryUseCases.insertHighScore("multiplechoices", _scoreState.value) _highScoreState.value = _scoreState.value } } } } } fun nextQuestion(){ _isAnswerCorrectState.value = null _isButtonsActiveState.value = true _optionsState.value = listOf() getChosenCapitalAndOptions() } fun onPlayAgain() { _scoreState.value = 0 _isButtonsActiveState.value = true _wrongAnswerState.value = 0 _isGameFinishedState.value = false nextQuestion() } fun onGoToMenu(navHostController: NavHostController) { _scoreState.value = 0 _wrongAnswerState.value = 0 _isGameFinishedState.value = false navHostController.navigate("quiz") } }
0
Kotlin
0
0
9c2b0f6902ac08debaa6e23e4d0a87673852c296
4,729
GeoLearnApp
MIT License
pageable2sources_ignite_cacheable/customer-nonpageable/src/main/kotlin/br/com/vagai/customer/entity/Address.kt
viniciustoni
251,750,270
false
{"Kotlin": 23504}
package br.com.vagai.customer.entity import br.com.vagai.customer.entity.enumerated.AddressType import javax.persistence.* import javax.persistence.EnumType.STRING import javax.persistence.FetchType.LAZY import javax.persistence.GenerationType.SEQUENCE @Entity @Table(name = "ADDRESS") @SequenceGenerator(name = "ADDRESS_SEQ", sequenceName = "ADDRESS_SEQ", allocationSize = 1) class Address( @Id @GeneratedValue(generator = "ADDRESS_SEQ", strategy = SEQUENCE) @Column(name = "ID", nullable = false) var id: Long, @Enumerated(STRING) @Column(name = "TYPE", nullable = false) var type: AddressType, var address: String?, var number: String?, var complement: String?, var city: String?, var zipCode: String?, @ManyToOne(fetch = LAZY) @JoinColumn(name = "COUNTRY_ID", referencedColumnName = "ID", updatable = false, insertable = false) var country: Country?, @ManyToOne(fetch = LAZY) @JoinColumn(name = "CLIENT_ID", referencedColumnName = "ID", updatable = false, insertable = false, nullable = false) var client: Client)
0
Kotlin
0
0
6af19202f7531436fa46081be2a5719a13ff3875
1,166
kotlin-samples
MIT License
Kotlin/problems/0039_n_repeated_element_in_size_2n_array.kt
oxone-999
243,366,951
true
{"C++": 961697, "Kotlin": 99948, "Java": 17927, "Python": 9476, "Shell": 999, "Makefile": 187}
//Problem Statement //In a array A of size 2N, there are N+1 unique elements, and exactly one of //these elements is repeated N times. /* Return the element repeated N times. Example : Input: [1,2,3,3] Output: 3 */ class Solution { fun repeatedNTimes(A: IntArray): Int { var unique:HashSet<Int> = HashSet<Int>(); for( value in A){ if(unique.contains(value)){ return value; } unique.add(value); } return 0; } } fun main(args:Array<String>){ val vec:IntArray = intArrayOf(1,2,3,3); val sol:Solution = Solution(); println(sol.repeatedNTimes(vec)); }
0
null
0
0
52dc527111e7422923a0e25684d8f4837e81a09b
650
algorithms
MIT License
src/main/java/com/ecwid/maleorang/method/v3_0/campaigns/DayOfWeek.kt
Ecwid
65,213,967
false
null
package com.ecwid.maleorang.method.v3_0.campaigns import com.google.gson.annotations.SerializedName enum class DayOfWeek { @SerializedName("sunday") SUNDAY, @SerializedName("monday") MONDAY, @SerializedName("tuesday") TUESDAY, @SerializedName("wednesday") WEDNESDAY, @SerializedName("thursday") THURSDAY, @SerializedName("friday") FRIDAY, @SerializedName("saturday") SATURDAY, }
3
Kotlin
34
84
e7f4acc50a7b5c383d8f3c1441e6d4b77b37989f
436
maleorang
Apache License 2.0
downloader/src/main/java/com/coopsrc/xandroid/downloader/core/service/DownloadService.kt
coopsrc
205,337,383
false
{"C": 3578156, "Java": 461908, "HTML": 357345, "Kotlin": 140323, "C++": 94835, "Makefile": 12567, "Roff": 5263, "CMake": 3217, "RenderScript": 3054, "CSS": 2721, "GLSL": 493, "Lua": 229}
package com.coopsrc.xandroid.downloader.core.service import android.app.Service import android.content.Intent import android.os.IBinder import com.coopsrc.xandroid.downloader.utils.Constants import com.coopsrc.xandroid.downloader.utils.Logger class DownloadService : Service() { private val tag = "DownloadService" private var binder: DownloadBinder = DownloadBinder() override fun onCreate() { super.onCreate() Logger.i(tag, "onCreate: ") } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { Logger.i(tag, "onStartCommand: $intent, $flags, $startId") return super.onStartCommand(intent, flags, startId) } override fun onBind(intent: Intent): IBinder { Logger.i(tag, "onBind: $intent") val maxTask = intent.getIntExtra("maxTask", Constants.Config.maxTask) Logger.i(tag, "createLocalTaskRepo: $maxTask") binder = DownloadBinder(maxTask) return binder } override fun onDestroy() { Logger.v(tag, "onDestroy: ") binder.stopAll().subscribe() super.onDestroy() } }
0
C
0
1
7e9aeeaa385e62f617abf3142a79818f0eab9aaf
1,131
xAndroid
Apache License 2.0
plugin/src/adapter/kotlin/org/jlleitschuh/gradle/ktlint/reporter/ReporterProviderWrapper.kt
JLLeitschuh
84,131,083
false
null
package org.jlleitschuh.gradle.ktlint.reporter class ReporterProviderWrapper<T>(val id: String, val reporterProvider: T)
82
null
157
1,385
d29b339587cc1eb0aebc48b9bb98e242dafdd7ff
122
ktlint-gradle
MIT License
Kazak-Android/core/src/main/kotlin/io/kazak/repository/FavoriteSessionsRepository.kt
frakbot
38,201,466
false
{"Java": 137822, "Kotlin": 29863, "XSLT": 6315, "Groovy": 5469}
package io.kazak.repository import io.kazak.model.FavoriteSessions import rx.Observable interface FavoriteSessionsRepository { fun store(favorites: FavoriteSessions): Observable<Unit> fun read(): Observable<FavoriteSessions> }
2
null
1
1
a33a0271ee8235fd23f90ad33b818ce4d3b7c856
240
kazak-android
MIT License
src/lib/kotlin/slatekit-entities/src/main/kotlin/slatekit/entities/core/EntityInfo.kt
ColleenKeegan
174,519,919
false
null
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: <NAME> * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package slatekit.entities.core import slatekit.common.newline import slatekit.db.DbType import slatekit.db.DbType.DbTypeMySql import slatekit.entities.databases.SqlBuilder import slatekit.meta.kClass import slatekit.meta.models.Model import kotlin.reflect.KClass /** * * @param entityType : the type of the entity * @param entityServiceType : the type of the service ( EntityService[T] or derivative ) * @param entityRepoType : the type of the repository ( EntityRepository[T] or derivative ) * @param entityMapperType : the type of the mapper ( EntityMapper[T] or derivative ) * @param entityServiceInstance : an instance of the service ( singleton usage ) * @param entityRepoInstance : an instance of the repo ( singleton usage ) * @param entityMapperInstance : an instance of the mapper ( singleton usage ) * @param dbType : the database provider type * @param dbKey : a key identifying the database connection * ( see DbLookup / Example_Database.scala ) * @param dbShard : a key identifying the database shard * ( see DbLookup / Example_Database.scala ) */ data class EntityInfo( val entityType: KClass<*>, val model: Model, val entityServiceType: KClass<*>? = null, val entityRepoType: KClass<*>? = null, val entityMapperType: KClass<*>? = null, val entityServiceInstance: IEntityService? = null, val entityRepoInstance: IEntityRepo? = null, val entityMapperInstance: EntityMapper? = null, val entityDDL: SqlBuilder? = null, val dbType: DbType = DbTypeMySql, val dbKey: String = "", val dbShard: String = "" ) { val entityTypeName = entityType.qualifiedName ?: "" fun toStringDetail(): String { val text = "entity type : " + entityTypeName + newline + "model : " + model.fullName "svc type : " + getTypeName(entityServiceType) + newline + "svc inst : " + getTypeNameFromInst(entityServiceInstance) + newline + "repo type : " + getTypeName(entityRepoType) + newline + "repo inst : " + getTypeNameFromInst(entityRepoInstance) + newline + "mapper type : " + getTypeName(entityMapperType) + newline + "mapper inst : " + getTypeNameFromInst(entityMapperInstance) + newline + "db type : " + dbType + newline + "db key : " + dbKey + newline + "db shard : " + dbShard + newline return text } fun getTypeName(tpe: KClass<*>?): String = tpe?.qualifiedName ?: "" fun getTypeNameFromInst(tpe: Any?): String = tpe?.kClass?.qualifiedName ?: "" }
1
null
1
1
bd1d55f2191f729149e901be102c22d7c719793d
3,096
slatekit
Apache License 2.0
app/src/main/java/com/zj/example/dagger2/example3/bean/Dog.kt
zhengjiong
106,264,089
false
null
package com.zj.example.dagger2.example3.bean /** * Created by zhengjiong * date: 2017/10/10 22:44 */ class Dog(val name: String)
0
Kotlin
0
0
3cfd16bbbd540a7f8f8b6bf7956d5db3d57a78c4
133
ZJ_Dagger2Example
MIT License
core/src/test/kotlin/kr/scripton/biz/core/config/TestWebSecurityInitializer.kt
archmagece-backyard
118,200,646
false
{"Gradle": 9, "Markdown": 5, "Java Properties": 1, "Text": 1, "Ignore List": 1, "YAML": 4, "Gherkin": 1, "Kotlin": 77, "Groovy": 3, "INI": 1, "Java": 1}
package kr.scripton.biz.core.config import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer class TestWebSecurityInitializer : AbstractSecurityWebApplicationInitializer()
0
Kotlin
0
0
633d8601742574fb1ae1cf153b15fa5731b8f814
206
spring-security-business
Apache License 2.0
Kotiln/client/src/test/kotlin/com/example/client/ClientApplicationTests.kt
bekurin
558,176,225
false
{"Git Config": 1, "Text": 12, "Ignore List": 96, "Markdown": 58, "YAML": 55, "JSON with Comments": 2, "JSON": 46, "HTML": 104, "robots.txt": 6, "SVG": 10, "TSX": 15, "CSS": 64, "Gradle Kotlin DSL": 107, "Shell": 72, "Batchfile": 71, "HTTP": 15, "INI": 112, "Kotlin": 682, "EditorConfig": 1, "Gradle": 40, "Java": 620, "JavaScript": 53, "Go": 8, "XML": 38, "Go Module": 1, "SQL": 7, "Dockerfile": 1, "Gherkin": 1, "Python": 153, "SCSS": 113, "Java Properties": 3, "AsciiDoc": 5, "Java Server Pages": 6, "Unity3D Asset": 451, "C#": 48, "Objective-C": 51, "C": 8, "Objective-C++": 1, "Smalltalk": 1, "OpenStep Property List": 12, "Dart": 17, "Swift": 8, "Ruby": 1}
package com.example.client import org.junit.jupiter.api.Test import org.springframework.boot.test.context.SpringBootTest @SpringBootTest class ClientApplicationTests { @Test fun contextLoads() { } }
0
Java
0
2
ede7cdb0e164ed1d3d2ee91c7770327b2ee71e4d
215
blog_and_study
MIT License
app/src/main/java/de/sharknoon/officesense/models/History.kt
Sharknoon
153,621,427
false
null
package de.sharknoon.officesense.models import org.threeten.bp.LocalDateTime data class History(val measurementValues: List<Value>) { data class Value(val id: LocalDateTime, val temperature: Double, val light: Double, val humidity: Double) }
0
Kotlin
0
0
8b66a7b4930d3782550087af78542ca76c1f5f96
249
OfficeSenseFrontend
Apache License 2.0
src/test/kotlin/hm/binkley/kotlin/sequences/SeekableSequenceTest.kt
binkley
231,763,068
false
null
package hm.binkley.kotlin.sequences import io.kotest.assertions.throwables.shouldThrow import io.kotest.matchers.shouldBe import org.junit.jupiter.api.Test internal class SeekableSequenceTest { @Test fun `should select first valid index`() { TestSeekableSequence[0] shouldBe "abc" } @Test fun `should select second valid index`() { TestSeekableSequence[1] shouldBe "def" } @Test fun `should reject negative indices`() { shouldThrow<IndexOutOfBoundsException> { TestSeekableSequence[-1] } } @Test fun `should reject excessive indices`() { shouldThrow<IndexOutOfBoundsException> { TestSeekableSequence[2] } } } private object TestSeekableSequence : SeekableSequence<String>, Sequence<String> by sequenceOf("abc", "def")
8
null
2
9
1f59d52f5d4c6af5b6b0180ea5f1fc297cec3eb4
852
kotlin-rational
The Unlicense
modules/core/src/main/java/de/deutschebahn/bahnhoflive/ui/station/info/PublicTrainStationService.kt
rish93
282,634,155
true
{"Java": 964898, "Kotlin": 357729, "HTML": 41940}
package de.deutschebahn.bahnhoflive.ui.station.info import de.deutschebahn.bahnhoflive.backend.db.publictrainstation.model.DetailedStopPlace import de.deutschebahn.bahnhoflive.backend.local.model.ChatbotStation import de.deutschebahn.bahnhoflive.backend.local.model.ServiceContent object PublicTrainStationService { val predicates = mapOf( ServiceContent.Type.DB_INFORMATION to { detailedStopPlace: DetailedStopPlace -> detailedStopPlace.hasDbInformation }, ServiceContent.Type.BAHNHOFSMISSION to { detailedStopPlace: DetailedStopPlace -> detailedStopPlace.hasRailwayMission }, ServiceContent.Type.TRAVELERS_SUPPLIES to { detailedStopPlace: DetailedStopPlace -> detailedStopPlace.hasTravelNecessities }, ServiceContent.Type.MOBILE_SERVICE to { detailedStopPlace: DetailedStopPlace -> detailedStopPlace.hasMobileService }, ServiceContent.Type.Local.TRAVEL_CENTER to { detailedStopPlace: DetailedStopPlace -> detailedStopPlace.hasTravelCenter }, ServiceContent.Type.Local.DB_LOUNGE to { detailedStopPlace: DetailedStopPlace -> detailedStopPlace.hasDbLounge }, ServiceContent.Type.MOBILITY_SERVICE to { detailedStopPlace: DetailedStopPlace -> detailedStopPlace.hasMobilityService }, ServiceContent.Type.Local.LOST_AND_FOUND to { detailedStopPlace: DetailedStopPlace -> detailedStopPlace.hasLostAndFound }, ServiceContent.Type.LOST_AND_FOUND to { detailedStopPlace: DetailedStopPlace -> detailedStopPlace.hasLostAndFound }, ServiceContent.Type.Local.CHATBOT to { detailedStopPlace: DetailedStopPlace -> ChatbotStation.isInTeaserPeriod && detailedStopPlace.stadaId.let { ChatbotStation.ids.contains(it) } == true } ) }
0
null
0
0
d0b3826c3955f8b30c8d81d2cfe404a0e94cc6f9
2,059
dbbahnhoflive-android
Apache License 2.0
json-plugin/src/main/kotlin/juuxel/adorn/json/kitchen/KitchenCupboardBlockState.kt
Juuxel
182,782,106
false
null
package juuxel.adorn.json.kitchen import io.github.cottonmc.jsonfactory.data.BlockStateProperty import io.github.cottonmc.jsonfactory.data.Identifier import io.github.cottonmc.jsonfactory.gens.AbstractContentGenerator import io.github.cottonmc.jsonfactory.output.model.ModelVariant import io.github.cottonmc.jsonfactory.output.model.MultipartBlockState import io.github.cottonmc.jsonfactory.output.model.MultipartBlockState.* import io.github.cottonmc.jsonfactory.output.suffixed import juuxel.adorn.json.AdornPlugin object KitchenCupboardBlockState : AbstractContentGenerator("kitchen_cupboard.block_state", "blockstates", AdornPlugin.KITCHEN ) { override fun generate(id: Identifier) = listOf( MultipartBlockState( multipart = BlockStateProperty.horizontalFacing.values.flatMap { listOf( Multipart( `when` = When("facing", it), apply = ModelVariant( model = id.wrapPath("block/", "_kitchen_counter"), y = getYRotation(it), uvlock = true ) ), Multipart( `when` = When("facing", it), apply = ModelVariant( model = id.wrapPath("block/", "_kitchen_cupboard_door"), y = getYRotation(it) ) ) ) } ).suffixed("kitchen_cupboard") ) private fun getYRotation(facing: String): Int = when (facing) { "east" -> 0 "south" -> 90 "west" -> 180 "north" -> 270 else -> 0 } }
41
null
24
44
2987c56d81b56e6de763b06fa385a4436a3e30a3
1,758
Adorn
MIT License
loader/src/main/java/com/xueqiu/image/loader/view/progress/BaseNetProgressBar.kt
snowman-team
200,222,108
false
{"Java": 53467, "Kotlin": 53009}
package com.xueqiu.image.loader.view.progress import android.graphics.* import android.graphics.drawable.Drawable abstract class BaseNetProgressBar : Drawable() { protected val mPaint = Paint(Paint.ANTI_ALIAS_FLAG) protected val mPath = Path() protected val mRect = RectF() protected var mLevel = 0 var hideWhenZero = false var color: Int = -0x7fff7f01 set(value) { field = value invalidateSelf() } var backgroundColor: Int = -0x80000000 set(value) { field = value invalidateSelf() } override fun onLevelChange(level: Int): Boolean { mLevel = level invalidateSelf() return true } override fun setAlpha(alpha: Int) { mPaint.alpha = alpha } override fun setColorFilter(cf: ColorFilter?) { mPaint.colorFilter = cf } override fun getOpacity(): Int { return when (color.ushr(24)) { 255 -> PixelFormat.OPAQUE 0 -> PixelFormat.TRANSPARENT else -> PixelFormat.TRANSLUCENT } } final override fun draw(canvas: Canvas) = drawProgressBar(canvas) abstract fun drawProgressBar(canvas: Canvas) }
1
Java
1
1
67b3480d57d21a41a78fc5a5f074b9deefaf2e26
1,234
ImageLoader
Apache License 2.0
glib-core/src/main/java/com/glib/core/logging/GLog.kt
hgani
223,511,724
false
{"Gradle": 5, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "Java Properties": 1, "Proguard": 3, "XML": 22, "Kotlin": 222, "Java": 19}
package com.glib.core.logging import android.util.Log import com.glib.core.GApp import com.glib.core.collection.SelfTruncatingSet import java.io.BufferedReader import java.io.IOException import java.io.InputStreamReader object GLog { // See http://stackoverflow.com/questions/4655861/displaying-more-string-on-logcat // private static int LOGCAT_CHAR_LIMIT = 4000; // Turn if off now because it makes debugging harder in normal circumstances. private val LOGCAT_CHAR_LIMIT = Integer.MAX_VALUE fun w(cls: Class<*>, msg: String, t: Throwable) { Log.w(cls.name, msg, t) } fun w(cls: Class<*>, msg: String) { Log.w(cls.name, msg) } fun i(cls: Class<*>, msg: String) { if (msg.length > LOGCAT_CHAR_LIMIT) { Log.i(cls.name, msg.substring(0, LOGCAT_CHAR_LIMIT)) i(cls, msg.substring(LOGCAT_CHAR_LIMIT)) } else { Log.i(cls.name, msg) } } fun d(cls: Class<*>, msg: String) { if (msg.length > LOGCAT_CHAR_LIMIT) { Log.d(cls.name, msg.substring(0, LOGCAT_CHAR_LIMIT)) d(cls, msg.substring(LOGCAT_CHAR_LIMIT)) } else { Log.d(cls.name, msg) } } fun v(cls: Class<*>, msg: String) { Log.v(cls.name, msg) } // Prominent logging to accomodate temporary testing. fun t(cls: Class<*>, msg: String) { i(cls, "********** $msg") } fun e(cls: Class<*>, msg: String) { Log.e(cls.name, msg) } fun e(cls: Class<*>, msg: String, t: Throwable) { Log.e(cls.name, msg, t) } // Adopted from http://stackoverflow.com/questions/27957300/read-logcat-programmatically-for-an-application object Reader { private val processIds = SelfTruncatingSet<String>(3) private val BLACKLISTED_STRINGS = arrayOf(" D/TextLayoutCache", " D/FlurryAgent", " D/dalvikvm") // See http://www.helloandroid.com/tutorials/reading-logs-programatically // See http://developer.android.com/tools/debugging/debugging-log.html#outputFormat val log: String get() { try { val process = Runtime.getRuntime().exec("logcat -d -v time") val log = StringBuilder("App version: " + GApp.INSTANCE.version) BufferedReader(InputStreamReader(process.inputStream)).use { r -> r.lineSequence().forEach { println(it) } } // var line: String // while ((line = bufferedReader.readLine()) != null) { // if (shouldLog(line)) { // log.append(line + "\n\n") // } // } return log.toString() } catch (ex: IOException) { throw RuntimeException(ex) } } fun registerProcessId() { processIds.add(Integer.toString(android.os.Process.myPid())) } // private static final String TAG = Reader.class.getCanonicalName(); // private static final String processId = Integer.toString(android.os.Process.myPid()); private fun belongsToApp(line: String): Boolean { for (processId in processIds) { if (line.contains(processId)) { return true } } return false } private fun shouldLog(line: String): Boolean { if (belongsToApp(line)) { for (blacklistedString in BLACKLISTED_STRINGS) { if (line.contains(blacklistedString)) { return false } } return true } return false } } }
0
Kotlin
0
0
9a7c56236d664f2b518310d12e5b0839382c2920
3,911
glib-android
Apache License 2.0
vector/src/main/java/vmodev/clearkeep/factories/viewmodels/SearchFilesInRoomFragmentViewModelFactory.kt
telred-llc
194,596,139
false
{"Java": 5914133, "Kotlin": 3855534, "JavaScript": 179733, "HTML": 22037, "Shell": 17049}
package vmodev.clearkeep.factories.viewmodels import androidx.lifecycle.ViewModelProvider import vmodev.clearkeep.factories.viewmodels.interfaces.IViewModelFactory import vmodev.clearkeep.fragments.Interfaces.IFragment import vmodev.clearkeep.viewmodels.interfaces.AbstractSearchFilesFragmentViewModel import vmodev.clearkeep.viewmodels.interfaces.AbstractSearchFilesInRoomFragmentViewModel import javax.inject.Inject import javax.inject.Named class SearchFilesInRoomFragmentViewModelFactory @Inject constructor(@Named(IFragment.SEARCH_FILES_IN_ROOM_FRAGMENT) fragment: IFragment, factory: ViewModelProvider.Factory) : IViewModelFactory<AbstractSearchFilesInRoomFragmentViewModel> { private val viewModel = ViewModelProvider(fragment.getFragment(), factory).get(AbstractSearchFilesInRoomFragmentViewModel::class.java); override fun getViewModel(): AbstractSearchFilesInRoomFragmentViewModel { return viewModel; } }
5
Java
1
3
2d20e94e9711b51aee89fa569efd61449cc7e9c3
936
clearkeep-android
Apache License 2.0
src/test/kotlin/ch/tutteli/spek/extensions/ScopeSpec.kt
robstoll
122,953,712
false
null
package ch.tutteli.spek.extensions import ch.tutteli.atrium.api.fluent.en_GB.* import ch.tutteli.atrium.api.verbs.expect import ch.tutteli.niok.delete import org.spekframework.spek2.Spek import org.spekframework.spek2.lifecycle.CachingMode import org.spekframework.spek2.style.specification.describe object ScopeSpec : Spek({ describe("memoized default is TEST") { val tempFolder by memoizedTempFolder { newFile("bla-default.txt") } context("first context") { it("it can be deleted") { val bla = tempFolder.resolve("bla-default.txt") bla.delete() expect(bla).notToExist() } it("it is recreated each time") { expect(tempFolder.resolve("bla-default.txt")).toExist() } } } describe("memoized per test") { val tmpFolder by memoizedTempFolder(CachingMode.TEST) { newFile("bla.txt") } context("first context") { it("it exists at the beginning") { expect(tmpFolder.resolve("bla.txt")).toExist() } it("it can be deleted") { val bla = tmpFolder.resolve("bla.txt") bla.delete() expect(bla).notToExist() } it("it is recreated each time") { val bla = tmpFolder.resolve("bla.txt") expect(bla).toExist() bla.delete() expect(bla).notToExist() } } context("second context") { it("it is also recreated for the second context") { expect(tmpFolder.resolve("bla.txt")).toExist() } } } describe("memoized per scope") { val tempFolder by memoizedTempFolder(CachingMode.SCOPE) { newFile("bla-per-scope.txt") } context("first context") { it("file from `memoized per test` does not exist") { expect(tempFolder.resolve("bla.txt")).notToExist() } it("it exists at the beginning") { expect(tempFolder.resolve("bla-per-scope.txt")).toExist() } it("it can be deleted") { val bla = tempFolder.resolve("bla-per-scope.txt") bla.delete() expect(bla).notToExist() } it("it does not exist afterwards") { expect(tempFolder.resolve("bla-per-scope.txt")).notToExist() } } context("second context") { it("it does also not exist in a second scope") { expect(tempFolder.resolve("bla-per-scope.txt")).notToExist() } } } describe("memoized per group") { val tmpFolder by memoizedTempFolder(CachingMode.EACH_GROUP) { newFile("bla-per-group.txt") } context("first context") { it("file from `memoized per test` does not exist") { expect(tmpFolder.resolve("bla.txt")).notToExist() } it("file from `memoized per scope` does not exist") { expect(tmpFolder.resolve("bla-per-scope.txt")).notToExist() } it("it exists at the beginning") { expect(tmpFolder.resolve("bla-per-group.txt")).toExist() } it("it can be deleted") { val bla = tmpFolder.resolve("bla-per-group.txt") bla.delete() expect(bla).notToExist() } it("it does not exist afterwards") { expect(tmpFolder.resolve("bla-per-group.txt")).notToExist() } context("nested context") { it("it is recreated in a nested context") { expect(tmpFolder.resolve("bla-per-group.txt")).toExist() } it("it can be deleted") { val bla = tmpFolder.resolve("bla-per-group.txt") bla.delete() expect(bla).notToExist() } it("it does not exist afterwards") { expect(tmpFolder.resolve("bla-per-group.txt")).notToExist() } } } context("second context") { it("it is recreated per context") { expect(tmpFolder.resolve("bla-per-group.txt")).toExist() } it("it can be deleted") { val bla = tmpFolder.resolve("bla-per-group.txt") bla.delete() expect(bla).notToExist() } it("it does not exist afterwards") { expect(tmpFolder.resolve("bla-per-group.txt")).notToExist() } } } })
2
Kotlin
3
2
fb0df45e648e1eda92d2d3093777283317cb6a6e
4,803
tutteli-spek-extensions
Apache License 2.0
app/src/main/java/info/infiniteloops/jgeeks/network/SessionManager.kt
ansarisufiyan777
179,932,756
false
null
package info.infiniteloops.jgeeks.network import android.content.Context import android.content.Intent import android.content.SharedPreferences import android.content.SharedPreferences.Editor import java.util.HashMap import info.infiniteloops.jgeeks.MainActivity class SessionManager(internal var _context: Context) { // Shared Preferences internal var pref: SharedPreferences // Editor for Shared preferences internal var editor: Editor // Shared pref mode internal var PRIVATE_MODE = 0 /** * Get stored session data */ // user name // user email id // return user val userDetails: HashMap<String, String> get() { val user = HashMap<String, String>() user[KEY_EMAIL] = pref.getString(KEY_EMAIL, null) user[KEY_DOCUMENT_ID] = pref.getString(KEY_DOCUMENT_ID, null) user[KEY_NAME] = pref.getString(KEY_NAME, null) return user } /** * Quick check for login */ // Get GoogleLogin State val isLoggedIn: Boolean get() = pref.getBoolean(IS_LOGIN, false) val email: String get() { return pref.getString(KEY_EMAIL, null) } val uid: String get() { return pref.getString(KEY_DOCUMENT_ID, null) } val name: String get() { return pref.getString(KEY_NAME, null) } init { pref = _context.getSharedPreferences(PREF_NAME, PRIVATE_MODE) editor = pref.edit() } /** * Create login session */ fun createLoginSession(email: String, document_id: String,name:String) { // Storing login value as TRUE editor.putBoolean(IS_LOGIN, true) // Storing email in pref editor.putString(KEY_EMAIL, email) // Storing document_id in pref editor.putString(KEY_DOCUMENT_ID, document_id) editor.putString(KEY_NAME, name) // commit changes editor.commit() } /** * Check login method wil check user login status * If false it will redirect user to login page * Else won't do anything */ fun checkLogin() { // Check login status if (!this.isLoggedIn) { // user is not logged in redirect him to GoogleLogin Activity val i = Intent(_context, MainActivity::class.java) // Closing all the Activities i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) // Add new Flag to start new Activity i.flags = Intent.FLAG_ACTIVITY_NEW_TASK // Staring GoogleLogin Activity _context.startActivity(i) } } /** * Clear session details */ fun logoutUser() { // Clearing all data from Shared Preferences editor.clear() editor.commit() // After logout redirect user to Loing Activity val i = Intent(_context, MainActivity::class.java) // Closing all the Activities i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP) // Add new Flag to start new Activity i.flags = Intent.FLAG_ACTIVITY_NEW_TASK // Staring GoogleLogin Activity _context.startActivity(i) } companion object { // Sharedpref file name private val PREF_NAME = "AndroidHivePref" // All Shared Preferences Keys private val IS_LOGIN = "IsLoggedIn" // User name (make variable public to access from outside) val KEY_EMAIL = "email" // Email address (make variable public to access from outside) val KEY_DOCUMENT_ID = "document_id" val KEY_NAME = "name" } }
1
null
1
1
0de1e1c873b40ecde33e0e06c584a7f46d4827db
3,679
Javascript-Geeks
Apache License 2.0
android/src/main/java/com/reactnativecappid/CappidPackage.kt
santhosh3614
316,453,967
false
{"Java": 6254, "Ruby": 4141, "Objective-C": 3478, "JavaScript": 1419, "Kotlin": 1326, "TypeScript": 932, "Swift": 289, "C": 103}
package com.reactnativecappid import java.util.Arrays import java.util.Collections import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ViewManager import com.facebook.react.bridge.JavaScriptModule class CappidPackage : ReactPackage { override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> { return Arrays.asList<NativeModule>(CappidModule(reactContext)) } override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> { return emptyList<ViewManager<*, *>>() } }
1
null
1
1
fdbda5442e4b9f3dfbe7ede495109e9709b81dbe
695
react-native-cappid
MIT License
android/src/main/java/com/reactnativecappid/CappidPackage.kt
santhosh3614
316,453,967
false
{"Java": 6254, "Ruby": 4141, "Objective-C": 3478, "JavaScript": 1419, "Kotlin": 1326, "TypeScript": 932, "Swift": 289, "C": 103}
package com.reactnativecappid import java.util.Arrays import java.util.Collections import com.facebook.react.ReactPackage import com.facebook.react.bridge.NativeModule import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.uimanager.ViewManager import com.facebook.react.bridge.JavaScriptModule class CappidPackage : ReactPackage { override fun createNativeModules(reactContext: ReactApplicationContext): List<NativeModule> { return Arrays.asList<NativeModule>(CappidModule(reactContext)) } override fun createViewManagers(reactContext: ReactApplicationContext): List<ViewManager<*, *>> { return emptyList<ViewManager<*, *>>() } }
1
null
1
1
fdbda5442e4b9f3dfbe7ede495109e9709b81dbe
695
react-native-cappid
MIT License
src/test/kotlin/thirdParty/spdlog/common.kt
kotlin-graphics
132,931,904
false
null
package thirdParty.spdlog enum class Sink { stdout_color_sink_mt, stdout_color_sink_st, stderr_color_sink_mt, stderr_color_sink_st }
2
Kotlin
7
96
3ae299c509d6c1fa75acd957083a827859cd7097
141
vkk
Apache License 2.0
lib/src/main/java/me/ameriod/lib/mvp/deligate/ActivityDelegate.kt
ameriod
72,384,726
false
{"Gradle": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 4, "Batchfile": 1, "Markdown": 1, "Proguard": 3, "Java": 22, "XML": 13, "Kotlin": 29}
package me.ameriod.lib.mvp.deligate import android.os.Bundle import me.ameriod.lib.mvp.Mvp interface ActivityDelegate<in V : Mvp.View, out P : Mvp.Presenter<in V>> { fun onCreate(savedInstanceState: Bundle?) fun onSaveInstanceState(outState: Bundle?) fun onDestroy() fun getPresenter(): P }
1
null
1
1
9a4b9317d2d53883c031e39114fb845fe08760ea
314
mvp
Apache License 2.0
publisher-sdk/src/test/java/com/criteo/publisher/util/AdvertisingInfoNoIdentifierTest.kt
vpathania1
283,532,067
true
{"Java": 1119725, "Kotlin": 311600, "Groovy": 3539}
/* * Copyright 2020 Criteo * * 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.criteo.publisher.util import android.content.Context import com.criteo.publisher.logging.Logger import com.criteo.publisher.logging.LoggerFactory import com.criteo.publisher.mock.MockBean import com.criteo.publisher.mock.MockedDependenciesRule import com.criteo.publisher.util.AdvertisingInfo.MissingPlayServicesAdsIdentifierException import com.nhaarman.mockitokotlin2.* import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatCode import org.junit.Before import org.junit.Rule import org.junit.Test import org.mockito.Mock import org.mockito.MockitoAnnotations import javax.inject.Inject class AdvertisingInfoNoIdentifierTest { @Rule @JvmField val mockedDependenciesRule = MockedDependenciesRule() @Inject private lateinit var context: Context @MockBean private lateinit var loggerFactory: LoggerFactory @Mock private lateinit var logger: Logger private lateinit var advertisingInfo: AdvertisingInfo @Before fun setUp() { assertThatCode { Class.forName("com.google.android.gms.ads.identifier.AdvertisingIdClient") }.withFailMessage( """ The tests in this file validate that AdvertisingInfo feature is only degraded, but do not throw, if the dependency is not provided at runtime. This assertion check this test is ran without PlayServices Ads Identifier provided. On IntelliJ, this assertion may appear wrong maybe because it takes some shortcut when creating test class path. To run those test locally and properly, you should use Gradle. Either via gradle command line or via IntelliJ delegating test run to Gradle. """ ).isInstanceOf(ClassNotFoundException::class.java) MockitoAnnotations.initMocks(this) doReturn(logger).whenever(loggerFactory).createLogger(any()) advertisingInfo = AdvertisingInfo(context) } @Test fun getAdvertisingId_GivenPlayServiceAdsIdentifierNotInClasspath_ReturnNull() { val advertisingId = advertisingInfo.advertisingId assertThat(advertisingId).isNull() verify(logger, times(2)).debug(any(), any<MissingPlayServicesAdsIdentifierException>()) } @Test fun isLimitAdTrackingEnabled_GivenPlayServiceAdsIdentifierNotInClasspath_ReturnFalse() { val isLimitAdTrackingEnabled = advertisingInfo.isLimitAdTrackingEnabled assertThat(isLimitAdTrackingEnabled).isFalse() verify(logger).debug(any(), any<MissingPlayServicesAdsIdentifierException>()) } }
0
null
0
0
b0d59098cb400d7c0ce7b5c510249f12afea716a
3,062
android-publisher-sdk
Apache License 2.0
app/src/main/kotlin/org/eurofurence/connavigator/ui/fragments/FragmentMap.kt
pbutylinski
73,627,278
false
null
package org.eurofurence.connavigator.ui.fragments import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import io.swagger.client.model.MapEntity import org.eurofurence.connavigator.R import org.eurofurence.connavigator.database.Database import org.eurofurence.connavigator.net.imageService import org.eurofurence.connavigator.ui.communication.ContentAPI import org.eurofurence.connavigator.util.delegators.view import org.eurofurence.connavigator.util.extensions.contains import org.eurofurence.connavigator.util.extensions.get import org.eurofurence.connavigator.util.extensions.jsonObjects import org.eurofurence.connavigator.util.extensions.letRoot import uk.co.senab.photoview.PhotoView /** * Created by david on 8/3/16. */ class FragmentMap() : Fragment(), ContentAPI { constructor(mapEntity: MapEntity) : this() { arguments = Bundle() arguments.jsonObjects["mapEntity"] = mapEntity } val mapTitle by view(TextView::class.java) val mapImage by view(PhotoView::class.java) var mapEntity: MapEntity? = null val database: Database get() = letRoot { it.database } ?: Database(activity) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) = inflater.inflate(R.layout.fragment_map, container, false) override fun onViewCreated(view: View?, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) if ("mapEntity" in arguments) { mapEntity = arguments.jsonObjects["mapEntity", MapEntity::class.java] mapTitle.text = mapEntity?.description mapTitle.visibility = View.GONE imageService.load(database.imageDb[mapEntity?.imageId]!!, mapImage, false) } else { mapImage.setImageResource(R.drawable.placeholder_event) } } }
1
null
1
1
1d2dc1ae67eef7992e3149dbc8d9c3a6af6654ec
1,986
gdakon-app_android
MIT License
app/src/main/java/com/foretree/shlibraryapp/widgets/refresh/IPagingRefresh.kt
xieyangxuejun
118,241,528
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 43, "XML": 18, "Java": 8}
package com.foretree.shlibraryapp.widgets.refresh; /** * Created by silen on 28/01/2018. */ interface IPagingRefresh { fun getStartPage(): Int fun getPage(): Int fun addPage() fun resetPage() }
0
Kotlin
0
0
0d6f9a8a3e1aeb49ee45fdea4bede721a5c1be8e
217
SHLibraryApp
Apache License 2.0
src/main/kotlin/leetcode/Problem2034.kt
fredyw
28,460,187
false
null
package leetcode import java.util.TreeMap /** * https://leetcode.com/problems/stock-price-fluctuation/ */ class Problem2034 { class StockPrice() { private val timestampToPriceMap = TreeMap<Int, Int>() private val priceToCountMap = TreeMap<Int, Int>() fun update(timestamp: Int, price: Int) { val existingPrice = timestampToPriceMap[timestamp] if (existingPrice != null) { val newCount = (priceToCountMap[existingPrice] ?: 0) - 1 if (newCount > 0) { priceToCountMap[existingPrice] = newCount } else if (newCount == 0) { priceToCountMap -= existingPrice } } priceToCountMap[price] = (priceToCountMap[price] ?: 0) + 1 timestampToPriceMap[timestamp] = price } fun current(): Int { return timestampToPriceMap[timestampToPriceMap.lastKey()]!! } fun maximum(): Int { return priceToCountMap.lastKey() } fun minimum(): Int { return priceToCountMap.firstKey() } } }
1
null
1
4
a59d77c4fd00674426a5f4f7b9b009d9b8321d6d
1,152
leetcode
MIT License
jetifier/jetifier/preprocessor/src/main/kotlin/com/android/tools/build/jetifier/preprocessor/Main.kt
RikkaW
389,105,112
true
{"Java": 49060640, "Kotlin": 36832495, "Python": 336507, "AIDL": 179831, "Shell": 150493, "C++": 38342, "ANTLR": 19860, "HTML": 10802, "TypeScript": 6933, "CMake": 3330, "JavaScript": 1343}
/* * Copyright 2018 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.build.jetifier.preprocessor import com.android.tools.build.jetifier.core.config.ConfigParser import com.android.tools.build.jetifier.core.utils.Log import org.apache.commons.cli.CommandLine import org.apache.commons.cli.DefaultParser import org.apache.commons.cli.HelpFormatter import org.apache.commons.cli.Option import org.apache.commons.cli.Options import org.apache.commons.cli.ParseException import java.io.File import java.nio.file.Paths class Main { companion object { const val TAG = "Main" const val TOOL_NAME = "preprocessor" val OPTIONS = Options() val OPTION_INPUT_LIBS = createOption("i", "Input libraries paths", multiple = true) val OPTION_INPUT_CONFIG = createOption("c", "Input config path") val OPTION_OUTPUT_CONFIG = createOption("o", "Output config path") val OPTION_LOG_LEVEL = createOption( "l", "Logging level. debug, verbose, default", isRequired = false ) internal fun createOption( argName: String, desc: String, isRequired: Boolean = true, multiple: Boolean = false ): Option { val op = Option(argName, true, desc) op.isRequired = isRequired if (multiple) { op.args = Option.UNLIMITED_VALUES } OPTIONS.addOption(op) return op } } fun run(args: Array<String>) { val cmd = parseCmdLine(args) if (cmd == null) { System.exit(1) return } Log.setLevel(cmd.getOptionValue(OPTION_LOG_LEVEL.opt)) val inputLibraries = cmd.getOptionValues(OPTION_INPUT_LIBS.opt).map { File(it) } val inputConfigPath = Paths.get(cmd.getOptionValue(OPTION_INPUT_CONFIG.opt)) val outputConfigPath = Paths.get(cmd.getOptionValue(OPTION_OUTPUT_CONFIG.opt)) val config = ConfigParser.loadFromFile(inputConfigPath) if (config == null) { System.exit(1) return } val generator = ConfigGenerator() generator.generateMapping(config, inputLibraries, outputConfigPath) } private fun parseCmdLine(args: Array<String>): CommandLine? { try { return DefaultParser().parse(OPTIONS, args) } catch (e: ParseException) { Log.e(TAG, e.message.orEmpty()) HelpFormatter().printHelp(TOOL_NAME, OPTIONS) } return null } } fun main(args: Array<String>) { Main().run(args) }
0
Java
0
7
6d53f95e5d979366cf7935ad7f4f14f76a951ea5
3,191
androidx
Apache License 2.0
FtcRobotController/src/main/java/org/firstinspires/ftc/robotcontroller/teamcode/opmodes/TeleOpMecanum.kt
LostInTime4324
146,838,772
false
{"Gradle": 7, "Shell": 1, "Ignore List": 1, "Batchfile": 1, "Text": 6, "Markdown": 8, "HTML": 336, "CSS": 1, "JavaScript": 1, "INI": 1, "XML": 21, "Java": 45, "Kotlin": 15, "Makefile": 8, "CMake": 31, "C++": 219, "C": 19, "Objective-C": 2}
package org.firstinspires.ftc.robotcontroller.teamcode.opmodes import com.qualcomm.robotcore.eventloop.opmode.OpMode import com.qualcomm.robotcore.eventloop.opmode.TeleOp import org.firstinspires.ftc.robotcontroller.teamcode.Direction.* import org.firstinspires.ftc.robotcontroller.teamcode.Navigation import kotlin.math.abs @TeleOp(name = "TeleOpMecanum") class TeleOpMecanum : OpMode() { val leftX: Double get() = gamepad1.left_stick_x.toDouble() val leftY: Double get() = gamepad1.left_stick_y.toDouble() val rightX: Double get() = gamepad1.right_stick_x.toDouble() val rightY: Double get() = gamepad1.right_stick_y.toDouble() val minPower = 0.15 var aPressed = false val nav by lazy { Navigation(this) } override fun init() { } override fun loop() { if (!aPressed && gamepad1.a) { aPressed = true nav.reverseDirection() } if (!gamepad1.a) { aPressed = false } if (abs(leftY) > minPower || abs(leftX) > minPower) { nav.setPower { addPower(leftY, FORWARD) addPower(leftX, RIGHT) } } else if (abs(rightX) > minPower) { nav.setPower(rightX, CW) } else if (gamepad1.right_bumper) { nav.setPower(0.5, RIGHT) } else if (gamepad1.left_bumper) { nav.setPower(0.5, LEFT) } else { nav.resetDrivePower() } if (abs(leftY) > abs(leftX) && abs(leftY) > minPower) { nav.setPower(leftY, FORWARD) } else if (abs(leftX) > minPower) { nav.setPower(leftX, RIGHT) } else if (abs(rightX) > minPower) { nav.setPower(rightX, CW) } else { nav.resetDrivePower() } nav.logEncoderValues() if (gamepad2.dpad_down || gamepad1.dpad_down) { nav.elevatorMotor.power = 1.0 } else if (gamepad2.dpad_up || gamepad1.dpad_up) { nav.elevatorMotor.power = -1.0 } else { nav.elevatorMotor.power = 0.0 } //Rev Extrusion if (abs(gamepad2.right_stick_y) > 0.1) { nav.extenderMotor.power = gamepad2.right_stick_y.toDouble() } else { nav.extenderMotor.power = 0.0 } //Tilt Arm Structure if (abs(gamepad2.right_stick_y) > 0.1) { nav.armMotor.power = gamepad2.left_stick_y.toDouble() } else { nav.armMotor.power = gamepad2.left_stick_y.toDouble() } //Run the intakeasdf if (gamepad2.left_bumper) { nav.intakeMotor.power = 1.0 } else if (gamepad2.right_bumper) { nav.intakeMotor.power = -1.0 } else { nav.intakeMotor.power = 0.0 } } }
1
null
1
1
7809b0ecc77f23da8b5dbeb1059c7047309690f3
2,832
LitCode2018-2019
MIT License
kotlin-mui-icons/src/main/generated/mui/icons/material/InfoTwoTone.kt
JetBrains
93,250,841
false
null
// Automatically generated - do not modify! @file:JsModule("@mui/icons-material/InfoTwoTone") @file:JsNonModule package mui.icons.material @JsName("default") external val InfoTwoTone: SvgIconComponent
12
Kotlin
145
983
372c0e4bdf95ba2341eda473d2e9260a5dd47d3b
204
kotlin-wrappers
Apache License 2.0
source/app_entry_point/src/main/kotlin/vn/edu/uit/pmcl2015/movie_recommender/entry_point/rest/AppController.kt
phuctm97
110,121,375
false
{"JavaScript": 158329, "CSS": 89813, "Kotlin": 62948, "HTML": 47460}
package vn.edu.uit.pmcl2015.movie_recommender.entry_point.rest import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController import vn.edu.uit.pmcl2015.movie_recommender.core.entity.DomainException import vn.edu.uit.pmcl2015.movie_recommender.entry_point.EntryPointBootstrap /*********************************************************************************************/ /* Models */ /*********************************************************************************************/ /* Controller */ @RestController open class AppController(private val entryPointConfig: RestEntryPointConfig, private val entryPointBootstrap: EntryPointBootstrap) { @GetMapping("/exit") fun exit(@RequestParam("secret_key", required = true) secretKey: String): String { if (secretKey != entryPointConfig.appExitSecretKey) throw DomainException("WRONG_EXIT_SECRET_KEY", "Incorrect exit secret code") Thread({ Thread.sleep(1000) entryPointBootstrap.exit(0) }).start() return "Accepted exit request. App is exiting in 1 second." } }
0
JavaScript
0
0
ce0218bef061dd3dda6614218d2de70d0af49bcb
1,215
movie-recommender
MIT License
oauth-discord/src/main/kotlin/me/devnatan/katan/oauth/discord/DiscordSubscription.kt
KatanPanel
324,854,028
false
null
package me.devnatan.katan.oauth.discord import me.devnatan.katan.oauth.subscription.Subscription import java.util.* data class DiscordSubscription( override val account: UUID, val discordId: String ) : Subscription { override fun toString(): String { return discordId } }
0
Kotlin
0
1
d44b7b44bed9b282930557a738be7fa601313781
299
katan-oauth-plugin
MIT License
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/ShieldExclamation.kt
walter-juan
868,046,028
false
{"Kotlin": 34345428}
package com.woowla.compose.icon.collections.tabler.tabler.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Round import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup public val OutlineGroup.ShieldExclamation: ImageVector get() { if (_shieldExclamation != null) { return _shieldExclamation!! } _shieldExclamation = Builder(name = "ShieldExclamation", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(15.04f, 19.745f) curveToRelative(-0.942f, 0.551f, -1.964f, 0.976f, -3.04f, 1.255f) arcToRelative(12.0f, 12.0f, 0.0f, false, true, -8.5f, -15.0f) arcToRelative(12.0f, 12.0f, 0.0f, false, false, 8.5f, -3.0f) arcToRelative(12.0f, 12.0f, 0.0f, false, false, 8.5f, 3.0f) arcToRelative(12.0f, 12.0f, 0.0f, false, true, 0.195f, 6.015f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(19.0f, 16.0f) verticalLineToRelative(3.0f) } path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 2.0f, strokeLineCap = Round, strokeLineJoin = StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(19.0f, 22.0f) verticalLineToRelative(0.01f) } } .build() return _shieldExclamation!! } private var _shieldExclamation: ImageVector? = null
0
Kotlin
0
3
eca6c73337093fbbfbb88546a88d4546482cfffc
2,635
compose-icon-collections
MIT License
feature/game-board/src/debug/kotlin/com/ekezet/othello/feature/gameboard/ui/components/Previews.kt
atomgomba
754,770,216
false
{"Kotlin": 208572}
package com.ekezet.othello.feature.gameboard.ui.components import androidx.compose.foundation.layout.ExperimentalLayoutApi import androidx.compose.runtime.Composable import androidx.compose.ui.tooling.preview.Preview import com.ekezet.othello.core.game.BoardFactory import com.ekezet.othello.core.ui.components.PreviewBase import com.ekezet.othello.feature.gameboard.ui.viewModels.toImmutableList @ExperimentalLayoutApi @Preview @Composable private fun GameBoardPreviewDefault() { PreviewBase { GameBoard( board = BoardFactory.starter().toImmutableList(), ) } } @ExperimentalLayoutApi @Preview @Composable private fun GameBoardPreviewShowPositions() { PreviewBase { GameBoard( board = BoardFactory.starter().toImmutableList(), showPositions = true, ) } }
0
Kotlin
0
1
59da4847f8e7f3a27e3f68eec77710bc2eb55ae7
842
othello
Apache License 2.0
compose/foundation/foundation-lint/src/test/java/androidx/compose/foundation/lint/UnrememberedMutableInteractionSourceDetectorTest.kt
androidx
256,589,781
false
null
/* * Copyright 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.foundation.lint import androidx.compose.lint.test.Stubs import androidx.compose.lint.test.bytecodeStub import com.android.tools.lint.checks.infrastructure.LintDetectorTest import com.android.tools.lint.checks.infrastructure.TestFile import com.android.tools.lint.detector.api.Detector import com.android.tools.lint.detector.api.Issue import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @RunWith(JUnit4::class) class UnrememberedMutableInteractionSourceDetectorTest : LintDetectorTest() { private val InteractionSourceStub: TestFile = bytecodeStub( filename = "InteractionSource.kt", filepath = "androidx/compose/foundation/interaction", checksum = 0xac2a176d, source = """ package androidx.compose.foundation.interaction interface InteractionSource interface MutableInteractionSource : InteractionSource fun MutableInteractionSource(): MutableInteractionSource = MutableInteractionSourceImpl() private class MutableInteractionSourceImpl : MutableInteractionSource """, """ META-INF/main.kotlin_module: H4sIAAAAAAAA/2NgYGBmYGBgBGJOBijgsuNST8xLKcrPTKnQS87PLcgvTtVL yy/NS0ksyczP08vMK0ktSkwGsYWEPRGc4PzSouRU7xIubi6WktTiEiHmeO8S JQYtBgD0QcfwZQAAAA== """, """ androidx/compose/foundation/interaction/InteractionSource.class: H4sIAAAAAAAA/52OP0/DMBDF3znQtOFfCq1UvgRuKxbUiQUpUhESSCyZ3MRF bhIbxW7VsZ+LAXXmQyGcdGBg4yw9/+5Ouve+vj8+AdxiSLgTOq+Nyrc8M9W7 sZIvzVrnwimjudJO1iJrOfnlF7OuMxmCCPFKbAQvhX7jT4uVzFyIgNCfF8aV SvNH6YS/JWYEVm0Cb0qN9BoBgQo/36qmG3vKJ4ThfteN2IhFLPa0HO13Uzam ZjklzOb/TusTeMPBn/lN4QjRgR9UKQnXz2vtVCVflVWLUt5rbVxrYDs+Bo5w KIarVi8x8P/EHz/2r5MiSBAm6CboIfKIkwSnOEtBFue4SMEsYov+D8H/p5CF AQAA """, """ androidx/compose/foundation/interaction/InteractionSourceKt.class: H4sIAAAAAAAA/61R308TQRD+5gpXevwqAtoWRbAv8OJR4xvGqBCSi7UmakhM n7a9lWx7t0vu9hoe+yf5ZqIJ6bN/lHG2kPDQkJDAPsx8M/vNN7szf//9vgTw Gk3CodBxZlR8EfZNem5yGf4whY6FVUaHSluZif4URzf4qymyvvxoyyBCdSBG IkyEPgs/9wayz9kSofapsKKXyJkqwvHefvuuTW9TOSQ02yY7CwfS9jKhdB4K rY2dKuRhx9hOkSTMOr5vpyg9T8pYIPhvlFb2LaG0t3+6hACLASpYIry7b4sy Vghr7aGxiWKWtIKLBT/eS0cl3hM5U3EGBBo64PHlhXLogFHcIqxPxn4wGQde zWv41cm44R2Qu3pF+PAQ496YSb4cWsLckYl5p6ttpWWnSHsy++YUCFtfCm1V ylojlStOvb/ZDyG4kjhRjlq/pp7OENGChzlc/byOefgcb3PUZO/O4h9Uvv/C 8gSrP6ek52x99sACdq5x2Q0Mu1P7DC/YtzhbZbm1LkoRHkVYj7CBzQiP8SRC DfUuKEcDW114OeZzPP0PDZ9NFzMDAAA= """, """ androidx/compose/foundation/interaction/MutableInteractionSource.class: H4sIAAAAAAAA/6VQvU7DMBi8L4E2DX8tBCgvQdqKBXUBBqRIRUggsWRyExe5 SW3UOFXHPhcD6sxDIb6EgYEOlRh8Pp/1ne/8+fX+AeAK54QbodO5UekyTMzs zRQynJhSp8Iqo0OlrZyLpOYPpRXjXEa/0rMp54lsggjtqViIMBf6NXwcT2Vi m3AJ19t6bzDdJXRGmbG54qelFTwlhgRntnA5OlXQqgAEylhfqurUY5b2CcF6 5flO16mWN+muVwOnR9XdgHA3+m9lzjHc2mTTdPBHvMwswf/h9yqXhIunUls1 ky+qUBziVmtja/eiwUWww8UbVX/mpzUGOOO9zzr/HrwYboRWBD/CHvaZ4iDC IY5iUIE2OjGcAscFTr4BtDhpnA4CAAA= """, """ androidx/compose/foundation/interaction/MutableInteractionSourceImpl.class: H4sIAAAAAAAA/61Sy04bMRQ91yEPpqEEyiO0ULa0i06KugOhFhDSSGkrFZQN K2fGUJMZG814EMt8S/+AFRILFLHsR6FeT5C66JIufHTOuQ9dX/v34909gE/Y JBxKk+RWJ9dhbLNLW6jwzJYmkU5bE2rjVC7jin8tnRymKvprHdsyj1WUXaZN EKFzIa9kmEpzHn4fXqjYNVEjfH5u/ybqhMauNtrtEWpb7wZtNNEKMINZwoz7 qQvCUf9/XGOHsNAfWZdqzlNOcrlkT2RXNV4XeZj1AAKN2L/WXvWYJR8Jm5Nx EIiuqM5k3BLdyXhb9Gi//vCrITrCp20T9p89Ko+09I/5YeR4Gwc2UYT5vjbq W5kNVX7iOxAW+zaW6UDm2usnM5hWHmkv1n6UxulMDXShOfrFGOuqkQr0IHjZ /AjTm/vtM75mFVYaqL+/RXDDROANY6MyA6wztqcJeMHMxzcqXMPb6gMS5jj2 8hS1CPMROhEWsMgUryIsYfkUVGAFqxwv0C7QLdD6A/UGq929AgAA """ ) override fun getDetector(): Detector = UnrememberedMutableInteractionSourceDetector() override fun getIssues(): MutableList<Issue> = mutableListOf( UnrememberedMutableInteractionSourceDetector.UnrememberedMutableInteractionSource ) @Test fun notRemembered() { lint().files( kotlin( """ package test import androidx.compose.foundation.interaction.* import androidx.compose.runtime.* @Composable fun Test() { val interactionSource = MutableInteractionSource() } val lambda = @Composable { val interactionSource = MutableInteractionSource() } val lambda2: @Composable () -> Unit = { val interactionSource = MutableInteractionSource() } @Composable fun LambdaParameter(content: @Composable () -> Unit) {} @Composable fun Test2() { LambdaParameter(content = { val interactionSource = MutableInteractionSource() }) LambdaParameter { val interactionSource = MutableInteractionSource() } } fun test3() { val localLambda1 = @Composable { val interactionSource = MutableInteractionSource() } val localLambda2: @Composable () -> Unit = { val interactionSource = MutableInteractionSource() } } @Composable fun Test4() { val localObject = object { val interactionSource = MutableInteractionSource() } } """ ), InteractionSourceStub, Stubs.Composable, ) .run() .expect( """ src/test/{.kt:9: Error: Creating a MutableInteractionSource during composition without using remember [UnrememberedMutableInteractionSource] val interactionSource = MutableInteractionSource() ~~~~~~~~~~~~~~~~~~~~~~~~ src/test/{.kt:13: Error: Creating a MutableInteractionSource during composition without using remember [UnrememberedMutableInteractionSource] val interactionSource = MutableInteractionSource() ~~~~~~~~~~~~~~~~~~~~~~~~ src/test/{.kt:17: Error: Creating a MutableInteractionSource during composition without using remember [UnrememberedMutableInteractionSource] val interactionSource = MutableInteractionSource() ~~~~~~~~~~~~~~~~~~~~~~~~ src/test/{.kt:26: Error: Creating a MutableInteractionSource during composition without using remember [UnrememberedMutableInteractionSource] val interactionSource = MutableInteractionSource() ~~~~~~~~~~~~~~~~~~~~~~~~ src/test/{.kt:29: Error: Creating a MutableInteractionSource during composition without using remember [UnrememberedMutableInteractionSource] val interactionSource = MutableInteractionSource() ~~~~~~~~~~~~~~~~~~~~~~~~ src/test/{.kt:35: Error: Creating a MutableInteractionSource during composition without using remember [UnrememberedMutableInteractionSource] val interactionSource = MutableInteractionSource() ~~~~~~~~~~~~~~~~~~~~~~~~ src/test/{.kt:39: Error: Creating a MutableInteractionSource during composition without using remember [UnrememberedMutableInteractionSource] val interactionSource = MutableInteractionSource() ~~~~~~~~~~~~~~~~~~~~~~~~ src/test/{.kt:46: Error: Creating a MutableInteractionSource during composition without using remember [UnrememberedMutableInteractionSource] val interactionSource = MutableInteractionSource() ~~~~~~~~~~~~~~~~~~~~~~~~ 8 errors, 0 warnings """ ) } @Test fun rememberedInsideComposableBody() { lint().files( kotlin( """ package test import androidx.compose.foundation.interaction.* import androidx.compose.runtime.* @Composable fun Test() { val interactionSource = remember { MutableInteractionSource() } } val lambda = @Composable { val interactionSource = remember { MutableInteractionSource() } } val lambda2: @Composable () -> Unit = { val interactionSource = remember { MutableInteractionSource() } } @Composable fun LambdaParameter(content: @Composable () -> Unit) {} @Composable fun Test2() { LambdaParameter(content = { val interactionSource = remember { MutableInteractionSource() } }) LambdaParameter { val interactionSource = remember { MutableInteractionSource() } } } fun test3() { val localLambda1 = @Composable { val interactionSource = remember { MutableInteractionSource() } } val localLambda2: @Composable () -> Unit = { val interactionSource = remember { MutableInteractionSource() } } } """ ), InteractionSourceStub, Stubs.Composable, Stubs.Remember ) .run() .expectClean() } @Test fun noErrors() { lint().files( kotlin( """ package test import androidx.compose.foundation.interaction.* import androidx.compose.runtime.* fun test() { val interactionSource = MutableInteractionSource() } val lambda = { val interactionSource = MutableInteractionSource() } val lambda2: () -> Unit = { val interactionSource = MutableInteractionSource() } fun LambdaParameter(content: () -> Unit) {} fun test2() { LambdaParameter(content = { val interactionSource = MutableInteractionSource() }) LambdaParameter { val interactionSource = MutableInteractionSource() } } fun test3() { val localLambda1 = { val interactionSource = MutableInteractionSource() } val localLambda2: () -> Unit = { val interactionSource = MutableInteractionSource() } } fun test3() { class Foo { val interactionSource = MutableInteractionSource() } val localObject = object { val interactionSource = MutableInteractionSource() } } @Composable fun Test4() { class Foo { val interactionSource = MutableInteractionSource() } } """ ), InteractionSourceStub, Stubs.Composable ) .run() .expectClean() } }
29
null
937
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
12,829
androidx
Apache License 2.0
app/src/main/java/com/howto/coredux/PlayVideoFragment.kt
mosofsky
264,519,104
false
null
package com.howto.coredux import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.webkit.WebSettings import android.webkit.WebView import android.webkit.WebViewClient import androidx.fragment.app.Fragment import androidx.fragment.app.activityViewModels import androidx.lifecycle.Observer import com.howto.coredux.HowToReduxAction.* class PlayVideoFragment : Fragment() { private val howToViewModel by activityViewModels<HowToViewModel>() private lateinit var playVideoWebView: WebView override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { return inflater.inflate(R.layout.play_video, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initViewIds() initUIObservers() configureWebView() } private fun initViewIds() { playVideoWebView = requireView().findViewById(R.id.playVideoWebView) } private fun configureWebView() { playVideoWebView.webViewClient = object : WebViewClient() { override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean { return false } override fun onPageFinished(view: WebView?, url: String?) { if (null != url && url != ABOUT_URL) { howToViewModel.dispatchAction(LoadVideo_Finish) } } } val ws: WebSettings = playVideoWebView.settings @SuppressLint("SetJavaScriptEnabled") // suppressed because this is just a demo app ws.javaScriptEnabled = true } private fun initUIObservers() { howToViewModel.isShowVideoFragmentInProgress.observe(viewLifecycleOwner, Observer { if (it) { requireView().visibility = View.VISIBLE howToViewModel.dispatchAction(LoadVideo_Start) howToViewModel.dispatchAction(ShowVideoFragment_Finish) } }) howToViewModel.isHideVideoFragmentInProgress.observe(viewLifecycleOwner, Observer { if (it) { playVideoWebView.loadUrl(ABOUT_URL) requireView().visibility = View.GONE howToViewModel.dispatchAction(HideVideoFragment_Finish) } }) howToViewModel.isLoadVideoInProgress.observe(viewLifecycleOwner, Observer { if (it) { maybeLoadVideoAsynchronously() } }) } private fun maybeLoadVideoAsynchronously() { val howToVideoShown = howToViewModel.state.value!!.howToVideoShown!! val videoStr = "<html><body>${howToVideoShown.name}<br><iframe width=\"380\" height=\"300\" src=\"${howToVideoShown.url}\" frameborder=\"0\" allowfullscreen></iframe></body></html>" if (null == playVideoWebView.url || !playVideoWebView.url.endsWith(videoStr)) { playVideoWebView.loadData(videoStr, "text/html", "utf-8") } else { howToViewModel.dispatchAction(LoadVideo_Finish) } } }
0
Kotlin
0
0
c8f001c09d5b4aec052c85368280596d3e23afcd
3,273
how-to-coredux
MIT License
app/src/main/java/com/example/wallpaper/utils/base/BaseActivity.kt
bardiau3fi
794,694,375
false
{"Kotlin": 236028}
package com.example.wallpaper.utils.base import android.content.Context import androidx.appcompat.app.AppCompatActivity import io.github.inflationx.viewpump.ViewPumpContextWrapper open class BaseActivity : AppCompatActivity() { //Calligraphy override fun attachBaseContext(newBase: Context) { super.attachBaseContext(ViewPumpContextWrapper.wrap(newBase)) } }
0
Kotlin
0
2
4d5126f554fe9331a71eddeba7fe8f4a08eca071
381
Wallpaper
MIT License
backend.native/compiler/ir/backend.native/src/org/jetbrains/kotlin/backend/konan/LinkStage.kt
nakijun
92,175,412
true
{"Kotlin": 2762317, "C++": 227482, "C": 121532, "Groovy": 43233, "Protocol Buffer": 10581, "Shell": 6532, "Java": 5274, "Pascal": 1546, "Makefile": 1341}
/* * Copyright 2010-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.kotlin.backend.konan import java.io.File import java.lang.ProcessBuilder import java.lang.ProcessBuilder.Redirect typealias BitcodeFile = String typealias ObjectFile = String typealias ExecutableFile = String // Use "clang -v -save-temps" to write linkCommand() method // for another implementation of this class. internal abstract class PlatformFlags(val distribution: Distribution) { val properties = distribution.properties val hostSuffix = TargetManager.host.suffix val targetSuffix = distribution.suffix val arch = propertyTargetString("arch") open val llvmLtoNooptFlags = propertyHostList("llvmLtoNooptFlags") open val llvmLtoOptFlags = propertyHostList("llvmLtoOptFlags") open val llvmLtoFlags = propertyHostList("llvmLtoFlags") open val entrySelector = propertyHostList("entrySelector") open val linkerOptimizationFlags = propertyHostList("linkerOptimizationFlags") open val linkerKonanFlags = propertyHostList("linkerKonanFlags") abstract val linker: String abstract fun linkCommand(objectFiles: List<ObjectFile>, executable: ExecutableFile, optimize: Boolean): List<String> protected fun propertyHostString(name: String) = properties.propertyString(name, hostSuffix)!! protected fun propertyHostList(name: String) = properties.propertyList(name, hostSuffix) protected fun propertyTargetString(name: String) = properties.propertyString(name, targetSuffix)!! protected fun propertyTargetList(name: String) = properties.propertyList(name, targetSuffix) protected fun propertyCommonString(name: String) = properties.propertyString(name, null)!! protected fun propertyCommonList(name: String) = properties.propertyList(name, null) } internal open class MacOSBasedPlatform(distribution: Distribution) : PlatformFlags(distribution) { override val linker = "${distribution.sysRoot}/usr/bin/ld" private val dsymutil = "${distribution.llvmBin}/llvm-dsymutil" open val osVersionMin = listOf( propertyTargetString("osVersionMinFlagLd"), propertyTargetString("osVersionMin")+".0") open val sysRoot = distribution.sysRoot open val targetSysRoot = distribution.targetSysRoot override fun linkCommand(objectFiles: List<String>, executable: String, optimize: Boolean): List<String> { return mutableListOf<String>(linker, "-demangle") + listOf("-object_path_lto", "temporary.o", "-lto_library", distribution.libLTO) + listOf( "-dynamic", "-arch", arch) + osVersionMin + listOf("-syslibroot", "$targetSysRoot", "-o", executable) + objectFiles + if (optimize) linkerOptimizationFlags else {listOf<String>()} + linkerKonanFlags + listOf("-lSystem") } open fun dsymutilCommand(executable: ExecutableFile): List<String> { return listOf(dsymutil, executable) } open fun dsymutilDryRunVerboseCommand(executable: ExecutableFile): List<String> { return listOf(dsymutil, "-dump-debug-map" ,executable) } } internal open class LinuxBasedPlatform(distribution: Distribution) : PlatformFlags(distribution) { open val sysRoot = distribution.sysRoot open val targetSysRoot = distribution.targetSysRoot val llvmLib = distribution.llvmLib val libGcc = distribution.libGcc override val linker = "${distribution.sysRoot}/../bin/ld.gold" open val pluginOptimizationFlags = propertyHostList("pluginOptimizationFlags") open val dynamicLinker = propertyTargetString("dynamicLinker") open val specificLibs = propertyTargetList("abiSpecificLibraries").map{it -> "-L${targetSysRoot}/$it"} override fun linkCommand(objectFiles: List<String>, executable: String, optimize: Boolean): List<String> { // TODO: Can we extract more to the konan.properties? return mutableListOf<String>("$linker", "--sysroot=${targetSysRoot}", "-export-dynamic", "-z", "relro", "--hash-style=gnu", "--build-id", "--eh-frame-hdr", // "-m", "elf_x86_64", "-dynamic-linker", dynamicLinker, "-o", executable, "${targetSysRoot}/usr/lib64/crt1.o", "${targetSysRoot}/usr/lib64/crti.o", "${libGcc}/crtbegin.o", "-L${llvmLib}", "-L${libGcc}") + specificLibs + listOf("-L${targetSysRoot}/../lib", "-L${targetSysRoot}/lib", "-L${targetSysRoot}/usr/lib") + if (optimize) listOf("-plugin", "$llvmLib/LLVMgold.so") + pluginOptimizationFlags else {listOf<String>()} + objectFiles + if (optimize) linkerOptimizationFlags else {listOf<String>()} + linkerKonanFlags + listOf("-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "-lc", "-lgcc", "--as-needed", "-lgcc_s", "--no-as-needed", "${libGcc}/crtend.o", "${targetSysRoot}/usr/lib64/crtn.o") } } internal class LinkStage(val context: Context) { val config = context.config.configuration val targetManager = TargetManager(config) private val distribution = Distribution(context.config.configuration) private val properties = distribution.properties val platform = when (TargetManager.host) { KonanTarget.LINUX -> LinuxBasedPlatform(distribution) KonanTarget.MACBOOK -> MacOSBasedPlatform(distribution) else -> error("Unexpected host platform") } val suffix = targetManager.currentSuffix() val optimize = config.get(KonanConfigKeys.OPTIMIZATION) ?: false val emitted = config.get(KonanConfigKeys.BITCODE_FILE)!! val nomain = config.get(KonanConfigKeys.NOMAIN) ?: false val libraries = context.config.libraries fun llvmLto(files: List<BitcodeFile>): ObjectFile { val tmpCombined = File.createTempFile("combined", ".o") tmpCombined.deleteOnExit() val combined = tmpCombined.absolutePath val tool = distribution.llvmLto val command = mutableListOf(tool, "-o", combined) command.addAll(platform.llvmLtoFlags) if (optimize) { command.addAll(platform.llvmLtoOptFlags) } else { command.addAll(platform.llvmLtoNooptFlags) } command.addAll(files) runTool(*command.toTypedArray()) return combined } fun llvmLlc(file: BitcodeFile): ObjectFile { val tmpObjectFile = File.createTempFile(File(file).name, ".o") tmpObjectFile.deleteOnExit() val objectFile = tmpObjectFile.absolutePath val command = listOf(distribution.llvmLlc, "-o", objectFile, "-filetype=obj") + properties.propertyList("llvmLlcFlags.$suffix") + listOf(file) runTool(*command.toTypedArray()) return objectFile } fun asLinkerArgs(args: List<String>): List<String> { val result = mutableListOf<String>() for (arg in args) { // If user passes compiler arguments to us - transform them to linker ones. if (arg.startsWith("-Wl,")) { result.addAll(arg.substring(4).split(',')) } else { result.add(arg) } } return result } // Ideally we'd want to have // #pragma weak main = Konan_main // in the launcher.cpp. // Unfortunately, anything related to weak linking on MacOS // only seems to be working with dynamic libraries. // So we stick to "-alias _main _konan_main" on Mac. // And just do the same on Linux. val entryPointSelector: List<String> get() = if (nomain) listOf() else platform.entrySelector fun link(objectFiles: List<ObjectFile>): ExecutableFile { val executable = config.get(KonanConfigKeys.EXECUTABLE_FILE)!! val linkCommand = platform.linkCommand(objectFiles, executable, optimize) + distribution.libffi + asLinkerArgs(config.getNotNull(KonanConfigKeys.LINKER_ARGS)) + entryPointSelector runTool(*linkCommand.toTypedArray()) if (platform is MacOSBasedPlatform && context.shouldContainDebugInfo()) { if (context.phase?.verbose ?: false) runTool(*platform.dsymutilDryRunVerboseCommand(executable).toTypedArray()) runTool(*platform.dsymutilCommand(executable).toTypedArray()) } return executable } fun executeCommand(vararg command: String): Int { context.log{""} context.log{command.asList<String>().joinToString(" ")} val builder = ProcessBuilder(command.asList()) // Inherit main process output streams. builder.redirectOutput(Redirect.INHERIT) builder.redirectInput(Redirect.INHERIT) builder.redirectError(Redirect.INHERIT) val process = builder.start() val exitCode = process.waitFor() return exitCode } fun runTool(vararg command: String) { val code = executeCommand(*command) if (code != 0) error("The ${command[0]} command returned non-zero exit code: $code.") } fun linkStage() { context.log{"# Compiler root: ${distribution.konanHome}"} val bitcodeFiles = listOf<BitcodeFile>(emitted, distribution.start, distribution.runtime, distribution.launcher) + libraries.map{it -> it.bitcodePaths}.flatten() var objectFiles: List<String> = listOf() val phaser = PhaseManager(context) phaser.phase(KonanPhase.OBJECT_FILES) { objectFiles = if (optimize) { listOf( llvmLto(bitcodeFiles ) ) } else { listOf( llvmLto(bitcodeFiles ) ) // Or, alternatively, go through llc bitcode compiler. //bitcodeFiles.map{ it -> llvmLlc(it) } } } phaser.phase(KonanPhase.LINKER) { link(objectFiles) } } }
0
Kotlin
0
0
8a789a9ac4123e836e733b504cab980f0416b2ed
10,772
kotlin-native
Apache License 2.0
src/main/kotlin/views/brainView/BrainView.kt
jackson-godfrey
455,049,973
false
{"Kotlin": 42674}
package views.brainView import brain.Brain import brain.brainItems.BrainItemLibrary import main.GameConfig import main.GameConfig.BASE_WINDOW_WIDTH import main.GameConfig.BRAIN_HEIGHT import main.GameConfig.BRAIN_ITEM_HEIGHT import main.GameConfig.BRAIN_ITEM_WIDTH import main.GameConfig.BRAIN_WIDTH import main.GameConfig.DEBUG_EXTRA_WIDTH import main.GameConfig.WINDOW_HEIGHT import main.GameConfig.isDebugMode import org.hexworks.zircon.api.Components import org.hexworks.zircon.api.component.ComponentAlignment import org.hexworks.zircon.api.data.Position import org.hexworks.zircon.api.data.Size import org.hexworks.zircon.api.grid.TileGrid import org.hexworks.zircon.api.view.base.BaseView import org.hexworks.zircon.internal.fragment.impl.VerticalScrollableList class BrainView( grid: TileGrid, private val brain: Brain ) : BaseView(grid, GameConfig.THEME){ init{ val itemGridPanel = Components.panel() .withPosition(0, 0) .withPreferredSize(BRAIN_ITEM_WIDTH * BRAIN_WIDTH, BRAIN_ITEM_HEIGHT * BRAIN_HEIGHT) .build() screen.addComponents(itemGridPanel) val focusedItemBox = FocusedItemBoxBuilder(brain=brain) .withAlignmentAround(itemGridPanel, ComponentAlignment.TOP_RIGHT) .build() screen.addComponent(focusedItemBox) itemGridPanel.apply { for(x in 0 until BRAIN_WIDTH) for(y in 0 until BRAIN_HEIGHT) addComponent( BrainBoxBuilder(x, y, brain) .withPosition(x*BRAIN_ITEM_WIDTH, y*BRAIN_ITEM_HEIGHT) .build() .apply{ onActivated { _ -> focusedItemBox.focusedItemPosition = Position.create(x, y) } // onDeactivated { // focusedItemBox.focusedItemPosition = FocusedItemBox.NO_FOCUSED_POSITION // } } ) } if(isDebugMode()) { val debugPanel = Components.panel() .withPosition(BASE_WINDOW_WIDTH, 0) .withPreferredSize(DEBUG_EXTRA_WIDTH, WINDOW_HEIGHT) .build() debugPanel.addFragment( VerticalScrollableList( size = Size.create(DEBUG_EXTRA_WIDTH, WINDOW_HEIGHT-10), position = Position.create(0, 0), BrainItemLibrary.allBrainItems, onItemActivated = { item, _ -> Brain.Debug.itemToPlace = item }, renderItem = { it.inGameName } ) ) screen.addComponent(debugPanel) } } }
0
Kotlin
0
0
eed9c10e67a4e53f07f799ed05faf68596e4ba3b
2,967
Roguelike
Apache License 2.0
messagingpush/src/sharedTest/java/io/customer/messagingpush/processor/PushMessageProcessorTest.kt
customerio
355,691,391
false
{"Kotlin": 459133, "Shell": 4485, "Makefile": 1568, "Ruby": 257}
package io.customer.messagingpush.processor import android.content.Intent import android.net.Uri import android.os.Bundle import androidx.core.app.TaskStackBuilder import androidx.test.ext.junit.runners.AndroidJUnit4 import io.customer.commontest.BaseTest import io.customer.messagingpush.MessagingPushModuleConfig import io.customer.messagingpush.ModuleMessagingPushFCM import io.customer.messagingpush.activity.NotificationClickReceiverActivity import io.customer.messagingpush.config.PushClickBehavior import io.customer.messagingpush.data.communication.CustomerIOPushNotificationCallback import io.customer.messagingpush.data.model.CustomerIOParsedPushPayload import io.customer.messagingpush.di.pushMessageProcessor import io.customer.messagingpush.util.DeepLinkUtil import io.customer.messagingpush.util.PushTrackingUtil import io.customer.sdk.CustomerIOConfig import io.customer.sdk.CustomerIOInstance import io.customer.sdk.data.request.MetricEvent import io.customer.sdk.extensions.random import io.customer.sdk.module.CustomerIOModule import io.customer.sdk.repository.TrackRepository import org.amshove.kluent.shouldBeEqualTo import org.amshove.kluent.shouldBeFalse import org.amshove.kluent.shouldBeTrue import org.amshove.kluent.shouldNotBe import org.junit.Before import org.junit.Ignore import org.junit.Test import org.junit.runner.RunWith import org.mockito.kotlin.any import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever import org.robolectric.Shadows @RunWith(AndroidJUnit4::class) class PushMessageProcessorTest : BaseTest() { private val modules = hashMapOf<String, CustomerIOModule<*>>() private val customerIOMock: CustomerIOInstance = mock() private val deepLinkUtilMock: DeepLinkUtil = mock() private val trackRepositoryMock: TrackRepository = mock() override fun setupConfig(): CustomerIOConfig = createConfig( modules = modules ) @Before override fun setup() { super.setup() di.overrideDependency(DeepLinkUtil::class.java, deepLinkUtilMock) di.overrideDependency(TrackRepository::class.java, trackRepositoryMock) } private fun pushMessageProcessor(): PushMessageProcessorImpl { return di.pushMessageProcessor as PushMessageProcessorImpl } private fun pushMessagePayload(deepLink: String? = null): CustomerIOParsedPushPayload { return CustomerIOParsedPushPayload( extras = Bundle.EMPTY, deepLink = deepLink, cioDeliveryId = String.random, cioDeliveryToken = String.random, title = String.random, body = String.random ) } private fun setupModuleConfig( pushClickBehavior: PushClickBehavior? = null, autoTrackPushEvents: Boolean? = null, notificationCallback: CustomerIOPushNotificationCallback? = null ) { modules[ModuleMessagingPushFCM.MODULE_NAME] = ModuleMessagingPushFCM( overrideCustomerIO = customerIOMock, overrideDiGraph = di, moduleConfig = with(MessagingPushModuleConfig.Builder()) { autoTrackPushEvents?.let { setAutoTrackPushEvents(it) } notificationCallback?.let { setNotificationCallback(it) } pushClickBehavior?.let { setPushClickBehavior(it) } build() } ) } @Test fun processMessage_givenDeliveryDataInvalid_expectDoNoProcessPush() { val givenDeliveryId = "" val processor = pushMessageProcessor() val result = processor.getOrUpdateMessageAlreadyProcessed(givenDeliveryId) result.shouldBeTrue() } @Test fun processMessage_givenMessageReceivedMultipleTimes_expectDoNoProcessPushMoreThanOnce() { val givenDeliveryId = String.random val processor = pushMessageProcessor() val resultFirst = processor.getOrUpdateMessageAlreadyProcessed(givenDeliveryId) val resultSecond = processor.getOrUpdateMessageAlreadyProcessed(givenDeliveryId) val resultThird = processor.getOrUpdateMessageAlreadyProcessed(givenDeliveryId) resultFirst.shouldBeFalse() resultSecond.shouldBeTrue() resultThird.shouldBeTrue() } @Test fun processMessage_givenNewMessageReceived_expectProcessPush() { val givenDeliveryId = String.random val processor = pushMessageProcessor() val result = processor.getOrUpdateMessageAlreadyProcessed(givenDeliveryId) result.shouldBeFalse() } @Test fun processMessage_givenQueueLimitReached_expectOldestToBeRemoved() { val processor = pushMessageProcessor() // Push first message and ignore result val givenDeliveryIdOldest = String.random processor.getOrUpdateMessageAlreadyProcessed(givenDeliveryIdOldest) // Fill the queue with random messages and ignore results for (i in 1..PushMessageProcessor.RECENT_MESSAGES_MAX_SIZE) { processor.getOrUpdateMessageAlreadyProcessed(String.random) } // Push last message and ignore result // Pushing this message should remove first message from the queue val givenDeliveryIdRecent = String.random processor.getOrUpdateMessageAlreadyProcessed(givenDeliveryIdRecent) val resultOldest = processor.getOrUpdateMessageAlreadyProcessed(givenDeliveryIdOldest) val resultRecent = processor.getOrUpdateMessageAlreadyProcessed(givenDeliveryIdRecent) resultOldest.shouldBeFalse() resultRecent.shouldBeTrue() } @Test fun processGCMMessageIntent_givenBundleWithoutDeliveryData_expectDoNoTrackPush() { val givenBundle = Bundle().apply { putString("message_id", String.random) } val processor = pushMessageProcessor() val gcmIntent: Intent = mock() whenever(gcmIntent.extras).thenReturn(givenBundle) processor.processGCMMessageIntent(gcmIntent) verifyNoInteractions(trackRepositoryMock) } @Test fun processGCMMessageIntent_givenAutoTrackPushEventsDisabled_expectDoNoTrackPush() { val givenDeliveryId = String.random val givenDeviceToken = String.random val givenBundle = Bundle().apply { putString(PushTrackingUtil.DELIVERY_ID_KEY, givenDeliveryId) putString(PushTrackingUtil.DELIVERY_TOKEN_KEY, givenDeviceToken) } val module = ModuleMessagingPushFCM( overrideCustomerIO = customerIOMock, overrideDiGraph = di, moduleConfig = MessagingPushModuleConfig.Builder().setAutoTrackPushEvents(false).build() ) modules[ModuleMessagingPushFCM.MODULE_NAME] = module val processor = pushMessageProcessor() val gcmIntent: Intent = mock() whenever(gcmIntent.extras).thenReturn(givenBundle) processor.processGCMMessageIntent(gcmIntent) verifyNoInteractions(trackRepositoryMock) } @Test fun processGCMMessageIntent_givenAutoTrackPushEventsEnabled_expectTrackPush() { val givenDeliveryId = String.random val givenDeviceToken = String.random val givenBundle = Bundle().apply { putString(PushTrackingUtil.DELIVERY_ID_KEY, givenDeliveryId) putString(PushTrackingUtil.DELIVERY_TOKEN_KEY, givenDeviceToken) } val module = ModuleMessagingPushFCM( overrideCustomerIO = customerIOMock, overrideDiGraph = di, moduleConfig = MessagingPushModuleConfig.Builder().setAutoTrackPushEvents(true).build() ) modules[ModuleMessagingPushFCM.MODULE_NAME] = module val processor = pushMessageProcessor() val gcmIntent: Intent = mock() whenever(gcmIntent.extras).thenReturn(givenBundle) processor.processGCMMessageIntent(gcmIntent) verify(trackRepositoryMock).trackMetric( givenDeliveryId, MetricEvent.delivered, givenDeviceToken ) } @Test fun processRemoteMessageDeliveredMetrics_givenAutoTrackPushEventsDisabled_expectDoNoTrackPush() { val givenDeliveryId = String.random val givenDeviceToken = String.random val module = ModuleMessagingPushFCM( overrideCustomerIO = customerIOMock, overrideDiGraph = di, moduleConfig = MessagingPushModuleConfig.Builder().setAutoTrackPushEvents(false).build() ) modules[ModuleMessagingPushFCM.MODULE_NAME] = module val processor = pushMessageProcessor() processor.processRemoteMessageDeliveredMetrics(givenDeliveryId, givenDeviceToken) verifyNoInteractions(trackRepositoryMock) } @Test fun processRemoteMessageDeliveredMetrics_givenAutoTrackPushEventsEnabled_expectTrackPush() { val givenDeliveryId = String.random val givenDeviceToken = String.random val module = ModuleMessagingPushFCM( overrideCustomerIO = customerIOMock, overrideDiGraph = di, moduleConfig = MessagingPushModuleConfig.Builder().setAutoTrackPushEvents(true).build() ) modules[ModuleMessagingPushFCM.MODULE_NAME] = module val processor = pushMessageProcessor() processor.processRemoteMessageDeliveredMetrics(givenDeliveryId, givenDeviceToken) verify(trackRepositoryMock).trackMetric( givenDeliveryId, MetricEvent.delivered, givenDeviceToken ) } @Test fun processNotificationClick_givenValidIntent_expectSuccessfulProcessing() { setupModuleConfig(autoTrackPushEvents = true) val processor = pushMessageProcessor() val givenDeepLink = "https://cio.example.com/" val givenPayload = pushMessagePayload(deepLink = givenDeepLink) val intent = Intent().apply { putExtra(NotificationClickReceiverActivity.NOTIFICATION_PAYLOAD_EXTRA, givenPayload) } processor.processNotificationClick(context, intent) verify(trackRepositoryMock).trackMetric( givenPayload.cioDeliveryId, MetricEvent.opened, givenPayload.cioDeliveryToken ) verify(deepLinkUtilMock).createDeepLinkHostAppIntent(context, givenDeepLink) verify(deepLinkUtilMock).createDeepLinkExternalIntent(context, givenDeepLink) verify(deepLinkUtilMock).createDefaultHostAppIntent(context) } @Test fun processNotificationClick_givenAutoTrackingDisabled_expectDoNotTrackOpened() { setupModuleConfig(autoTrackPushEvents = false) val processor = pushMessageProcessor() val givenPayload = pushMessagePayload() val intent = Intent().apply { putExtra(NotificationClickReceiverActivity.NOTIFICATION_PAYLOAD_EXTRA, givenPayload) } processor.processNotificationClick(context, intent) verifyNoInteractions(trackRepositoryMock) } @Test fun processNotificationClick_givenNoDeepLink_expectOpenLauncherIntent() { val processor = pushMessageProcessor() val givenPayload = pushMessagePayload() val intent = Intent().apply { putExtra(NotificationClickReceiverActivity.NOTIFICATION_PAYLOAD_EXTRA, givenPayload) } processor.processNotificationClick(context, intent) verify(deepLinkUtilMock, never()).createDeepLinkHostAppIntent(any(), any()) verify(deepLinkUtilMock, never()).createDeepLinkExternalIntent(any(), any()) verify(deepLinkUtilMock).createDefaultHostAppIntent(any()) } @Test fun processNotificationClick_givenCallbackWithDeepLink_expectOpenCallbackIntent() { val notificationCallback: CustomerIOPushNotificationCallback = mock() whenever(notificationCallback.createTaskStackFromPayload(any(), any())).thenReturn( TaskStackBuilder.create(context) ) val givenPayload = pushMessagePayload(deepLink = "https://cio.example.com/") // Make sure that the callback as expected for all behaviors for (pushClickBehavior in PushClickBehavior.values()) { setupModuleConfig( notificationCallback = notificationCallback, pushClickBehavior = pushClickBehavior ) val processor = pushMessageProcessor() val intent = Intent().apply { putExtra(NotificationClickReceiverActivity.NOTIFICATION_PAYLOAD_EXTRA, givenPayload) } processor.processNotificationClick(context, intent) verifyNoInteractions(deepLinkUtilMock) } } @Test fun processNotificationClick_givenCallbackWithoutDeepLink_expectOpenCallbackIntent() { val notificationCallback: CustomerIOPushNotificationCallback = mock() whenever(notificationCallback.createTaskStackFromPayload(any(), any())).thenReturn( TaskStackBuilder.create(context) ) val givenPayload = pushMessagePayload() // Make sure that the callback as expected for all behaviors for (pushClickBehavior in PushClickBehavior.values()) { setupModuleConfig( notificationCallback = notificationCallback, pushClickBehavior = pushClickBehavior ) val processor = pushMessageProcessor() val intent = Intent().apply { putExtra(NotificationClickReceiverActivity.NOTIFICATION_PAYLOAD_EXTRA, givenPayload) } processor.processNotificationClick(context, intent) verifyNoInteractions(deepLinkUtilMock) } } @Test fun processNotificationClick_givenExternalLink_expectOpenExternalIntent() { val processor = pushMessageProcessor() val givenPayload = pushMessagePayload(deepLink = "https://cio.example.com/") val intent = Intent().apply { putExtra(NotificationClickReceiverActivity.NOTIFICATION_PAYLOAD_EXTRA, givenPayload) } whenever(deepLinkUtilMock.createDeepLinkExternalIntent(any(), any())).thenReturn(Intent()) processor.processNotificationClick(context, intent) verify(deepLinkUtilMock).createDeepLinkHostAppIntent(any(), any()) verify(deepLinkUtilMock).createDeepLinkExternalIntent(any(), any()) verify(deepLinkUtilMock, never()).createDefaultHostAppIntent(any()) } @Test fun processNotificationClick_givenInternalLink_expectOpenInternalIntent() { val processor = pushMessageProcessor() val givenPayload = pushMessagePayload(deepLink = "https://cio.example.com/") val intent = Intent().apply { putExtra(NotificationClickReceiverActivity.NOTIFICATION_PAYLOAD_EXTRA, givenPayload) } whenever(deepLinkUtilMock.createDeepLinkExternalIntent(any(), any())).thenReturn(Intent()) whenever(deepLinkUtilMock.createDeepLinkHostAppIntent(any(), any())).thenReturn(Intent()) processor.processNotificationClick(context, intent) verify(deepLinkUtilMock).createDeepLinkHostAppIntent(any(), any()) verify(deepLinkUtilMock, never()).createDeepLinkExternalIntent(any(), any()) verify(deepLinkUtilMock).createDefaultHostAppIntent(any()) } @Test fun processNotificationClick_givenPushBehavior_expectResetTaskStack() { setupModuleConfig( autoTrackPushEvents = false, pushClickBehavior = PushClickBehavior.RESET_TASK_STACK ) val givenPackageName = "io.customer.example" val givenDeepLink = "https://cio.example.com/" whenever(deepLinkUtilMock.createDeepLinkHostAppIntent(any(), any())).thenReturn( Intent(Intent.ACTION_VIEW, Uri.parse(givenDeepLink)).apply { setPackage(givenPackageName) } ) val givenPayload = pushMessagePayload(deepLink = givenDeepLink) val processor = pushMessageProcessor() val intent = Intent().apply { putExtra(NotificationClickReceiverActivity.NOTIFICATION_PAYLOAD_EXTRA, givenPayload) } processor.processNotificationClick(context, intent) // The intent will be started with the default flags based on the activity launch mode // Also, we cannot verify the back stack as it is not exposed by the testing framework val expectedIntentFlags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_TASK_ON_HOME val nextStartedActivity = Shadows.shadowOf(application).nextStartedActivity nextStartedActivity shouldNotBe null nextStartedActivity.action shouldBeEqualTo Intent.ACTION_VIEW nextStartedActivity.dataString shouldBeEqualTo givenDeepLink nextStartedActivity.flags shouldBeEqualTo expectedIntentFlags nextStartedActivity.`package` shouldBeEqualTo givenPackageName } @Test fun processNotificationClick_givenPushBehavior_expectPreventRestart() { setupModuleConfig( autoTrackPushEvents = false, pushClickBehavior = PushClickBehavior.ACTIVITY_PREVENT_RESTART ) val givenPackageName = "io.customer.example" val givenDeepLink = "https://cio.example.com/" whenever(deepLinkUtilMock.createDeepLinkHostAppIntent(any(), any())).thenReturn( Intent(Intent.ACTION_VIEW, Uri.parse(givenDeepLink)).apply { setPackage(givenPackageName) } ) val givenPayload = pushMessagePayload(deepLink = givenDeepLink) val processor = pushMessageProcessor() val intent = Intent().apply { putExtra(NotificationClickReceiverActivity.NOTIFICATION_PAYLOAD_EXTRA, givenPayload) } processor.processNotificationClick(context, intent) val expectedIntentFlags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP val nextStartedActivity = Shadows.shadowOf(application).nextStartedActivity nextStartedActivity shouldNotBe null nextStartedActivity.action shouldBeEqualTo Intent.ACTION_VIEW nextStartedActivity.dataString shouldBeEqualTo givenDeepLink nextStartedActivity.flags shouldBeEqualTo expectedIntentFlags nextStartedActivity.`package` shouldBeEqualTo givenPackageName } @Ignore( "Current testing framework does not support verifying the flags. " + "We'll have to rely on manual testing for this for now." + "In future, we can use more advanced testing frameworks to verify this" ) @Test fun processNotificationClick_givenPushBehavior_expectNoFlags() { setupModuleConfig( autoTrackPushEvents = false, pushClickBehavior = PushClickBehavior.ACTIVITY_NO_FLAGS ) val givenPackageName = "io.customer.example" val givenDeepLink = "https://cio.example.com/" whenever(deepLinkUtilMock.createDeepLinkHostAppIntent(any(), any())).thenReturn( Intent(Intent.ACTION_VIEW, Uri.parse(givenDeepLink)).apply { setPackage(givenPackageName) } ) val givenPayload = pushMessagePayload(deepLink = givenDeepLink) val processor = pushMessageProcessor() val intent = Intent().apply { putExtra(NotificationClickReceiverActivity.NOTIFICATION_PAYLOAD_EXTRA, givenPayload) } processor.processNotificationClick(context, intent) // The intent will be started with the default flags based on the activity launch mode val nextStartedActivity = Shadows.shadowOf(application).nextStartedActivity nextStartedActivity shouldNotBe null nextStartedActivity.action shouldBeEqualTo Intent.ACTION_VIEW nextStartedActivity.dataString shouldBeEqualTo givenDeepLink nextStartedActivity.`package` shouldBeEqualTo givenPackageName } @Test fun processNotificationClick_givenEmptyIntent_expectNoProcessing() { setupModuleConfig(autoTrackPushEvents = true) val processor = pushMessageProcessor() val intent = Intent() processor.processNotificationClick(context, intent) verifyNoInteractions(trackRepositoryMock) verifyNoInteractions(deepLinkUtilMock) } }
2
Kotlin
9
9
bbc770d513026e679bb17a5cd0d9d25221138f06
20,413
customerio-android
MIT License
app/src/main/kotlin/com/amar/notesapp/fragments/ViewPagerFragment.kt
AMARJITVS
108,282,499
false
{"Gradle": 3, "Markdown": 1, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Java Properties": 1, "Proguard": 1, "XML": 86, "Kotlin": 41, "Java": 1}
package com.amar.NoteDirector.fragments import android.support.v4.app.Fragment abstract class ViewPagerFragment : Fragment() { var listener: FragmentListener? = null abstract fun fullscreenToggled(isFullscreen: Boolean) interface FragmentListener { fun fragmentClicked() fun videoEnded(): Boolean } }
1
null
1
1
5ce822ae6c1b38961765d7fda6a539b9fe465d1c
338
NoteDirector
Apache License 2.0
common/src/main/kotlin/com/kotcrab/fate/util/EbootPatcher.kt
RikuNoctis
165,883,449
false
null
/* * Copyright 2017-2018 See AUTHORS file. * * 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.kotcrab.fate.util import com.kotcrab.fate.file.ElfFile import kio.KioInputStream import kio.util.arrayCopy import kio.util.toWHex import kmips.Assembler import kmips.Endianness import kmips.Reg import kmips.Reg.ra import kmips.Reg.sp import kmips.assembleAsHexString import java.io.File import java.nio.ByteBuffer import java.nio.ByteOrder import java.util.* import javax.xml.bind.DatatypeConverter @Suppress("UNUSED_VARIABLE") /** @author Kotcrab */ class EbootPatcher( inFile: File, outFile: File, patchList: List<EbootPatch>, baseProgramHeaderIdx: Int, relocationSectionHeaderIdx: Int = -1 ) { init { val elf = ElfFile(inFile) val baseProgramHeader = elf.programHeaders[baseProgramHeaderIdx] val nextProgramHeader = elf.programHeaders.getOrNull(baseProgramHeaderIdx + 1) val outBytes = inFile.readBytes() patchList.forEach { patch -> if (patch.active == false) return@forEach patch.changes.forEach { change -> if (nextProgramHeader != null && change.startAddr > nextProgramHeader.offset) { error("Trying to patch unsafe address: ${change.startAddr.toWHex()}") } val patchBytes = DatatypeConverter.parseHexBinary(change.hexString) arrayCopy(src = patchBytes, dest = outBytes, destPos = change.startAddr + baseProgramHeader.offset) } if (relocationSectionHeaderIdx == -1 && patch.relocationsToRemove.isNotEmpty()) { error("To remove relocations you must specify index of relocation section header") } if (relocationSectionHeaderIdx != -1) { val relocationSectionHeader = elf.sectionHeaders[relocationSectionHeaderIdx] patch.relocationsToRemove.forEach relRemoveLoop@{ addrToRemove -> with(KioInputStream(outBytes)) { setPos(relocationSectionHeader.offset) while (pos() < relocationSectionHeader.offset + relocationSectionHeader.size) { val addr = readInt() val typePos = pos() val type = readInt() if (addr == addrToRemove) { arrayCopy(src = ByteArray(4), dest = outBytes, destPos = typePos) close() return@relRemoveLoop } } } error("Can't remove relocation: ${addrToRemove.toWHex()}, entry not found.") } } } outFile.writeBytes(outBytes) } } fun MutableCollection<EbootPatch>.patch(name: String, active: Boolean = true, init: EbootPatch.() -> Unit) { val patch = EbootPatch(name, active) patch.init() add(patch) } class EbootPatch(val name: String, var active: Boolean) { val changes: ArrayList<EbootChange> = ArrayList() val relocationsToRemove: ArrayList<Int> = ArrayList() fun change(startAddr: Int, init: Assembler.() -> Unit) { changes.add(EbootChange(startAddr, assembleAsHexString(startAddr + 0x8804000, Endianness.Little, init))) } fun removeRelocation(addr: Int) { relocationsToRemove.add(addr) } } class EbootChange(val startAddr: Int, val hexString: String) fun Assembler.zeroTerminatedString(string: String): Int { val addr = virtualPc var zeroWritten = false for (i in 0..string.length step 4) { val defaultChar: (Int) -> Char = { zeroWritten = true 0.toChar() } val char0 = string.getOrElse(i + 3, defaultChar).toInt() shl 24 val char1 = string.getOrElse(i + 2, defaultChar).toInt() shl 16 val char2 = string.getOrElse(i + 1, defaultChar).toInt() shl 8 val char3 = string.getOrElse(i, defaultChar).toInt() data(char0 or char1 or char2 or char3) } if (zeroWritten == false) { data(0) } return addr } fun Assembler.float(value: Float) { val buf = ByteBuffer.allocate(4).putFloat(value) buf.rewind() data(buf.order(ByteOrder.BIG_ENDIAN).int) } fun Assembler.writeBytes(bytes: ByteArray) { if (bytes.size % 4 != 0) error("Buffer size is not aligned to word size") with(KioInputStream(bytes)) { while (!eof()) { data(readInt()) } } } fun Assembler.word(intValue: Long): Int { val addr = virtualPc data(intValue.toInt()) return addr } fun Assembler.word(value: Int): Int { val addr = virtualPc data(value) return addr } fun Assembler.preserve(regs: Array<Reg>): FunctionContext { val ctx = FunctionContext(this, regs) ctx.preserve() return ctx } class FunctionContext(private val assembler: Assembler, private val regs: Array<Reg>) { fun byteSize() = regs.size * 4 fun preserve() = with(assembler) { addi(sp, sp, -regs.size * 4) regs.forEachIndexed { idx, reg -> sw(reg, idx * 4, sp) } } fun restore() = with(assembler) { restoreRegs() addi(sp, sp, regs.size * 4) } fun exit() = with(assembler) { jr(ra) nop() } fun restoreAndExit() = with(assembler) { restoreRegs() jr(ra) addi(sp, sp, regs.size * 4) nop() } private fun restoreRegs() = with(assembler) { regs.forEachIndexed { idx, reg -> lw(reg, idx * 4, sp) } } }
0
Kotlin
0
1
04d0a219269e17c97cca54f71ae11e348c9fb070
6,176
fate-explorer
Apache License 2.0
ktor-exposed/src/com/svprdga/ktorexposed/entities.kt
svprdga
199,045,526
false
null
package com.svprdga.ktorexposed import org.jetbrains.exposed.sql.Table data class Galaxy( val id: Int, val name: String, val description: String ) object Galaxies : Table("galaxy") { val id = integer("id").primaryKey().autoIncrement() val name = varchar("name", 100) val description = varchar("description",3000) }
8
Kotlin
0
0
7f4ce68874907d233da1507bbb9bdf5630fe4870
342
web-reactive-frameworks-comparison
Apache License 2.0
domain/src/main/java/dev/ricardoantolin/xceedtest/domain/executors/PostExecutionThread.kt
ricardoAntolin
258,513,082
false
null
package dev.ricardoantolin.xceedtest.domain.executors import io.reactivex.Scheduler interface PostExecutionThread { fun getScheduler(): Scheduler }
0
Kotlin
0
0
fc09560243c018878d21896f0ddac722411a9a25
154
xceed-test
MIT License
app/src/main/java/com/tans/tasciiartplayer/hwevent/PhoneObserver.kt
Tans5
793,945,539
false
{"Kotlin": 226024}
package com.tans.tasciiartplayer.hwevent import android.app.Application import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.telephony.TelephonyManager import com.tans.tasciiartplayer.AppLog import com.tans.tasciiartplayer.appGlobalCoroutineScope import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.launch object PhoneObserver { private val eventSubject: MutableSharedFlow<PhoneEvent> by lazy { MutableSharedFlow() } private val receiver: BroadcastReceiver by lazy { object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { if (intent?.action == TelephonyManager.ACTION_PHONE_STATE_CHANGED) { val state = intent.getStringExtra(TelephonyManager.EXTRA_STATE) when (state) { TelephonyManager.EXTRA_STATE_RINGING -> { AppLog.d(TAG, "Phone ringing.") appGlobalCoroutineScope.launch { eventSubject.emit(PhoneEvent.PhoneRinging) } } TelephonyManager.EXTRA_STATE_IDLE -> { AppLog.d(TAG, "Phone idle.") appGlobalCoroutineScope.launch { eventSubject.emit(PhoneEvent.PhoneIdle) } } TelephonyManager.EXTRA_STATE_OFFHOOK -> { AppLog.d(TAG, "Phone off hook.") appGlobalCoroutineScope.launch { eventSubject.emit(PhoneEvent.PhoneOffHook) } } } } } } } fun init(application: Application) { val filter = IntentFilter() filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED) application.registerReceiver(receiver, filter) } fun observeEvent(): Flow<PhoneEvent> = eventSubject private const val TAG = "PhoneObserver" enum class PhoneEvent { PhoneRinging, PhoneIdle, PhoneOffHook } }
0
Kotlin
0
2
bd65d4bd2f2a16b1b7e4e80f44a5aaa69a8d802f
2,391
tAsciiArtPlayer
Apache License 2.0
app/src/main/java/dalian/razvan/cucer/twitterusersearch/screens/search/UserSearchViewModel.kt
daliaan
385,481,991
false
null
package dalian.razvan.cucer.twitterusersearch.screens.search import android.util.Log import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.navigation.Navigation import dalian.razvan.cucer.twitterusersearch.R import dalian.razvan.cucer.twitterusersearch.core.networking.error.ErrorCallback import dalian.razvan.cucer.twitterusersearch.core.repository.Repository import dalian.razvan.cucer.twitterusersearch.core.repository.models.TwitterUser import dalian.razvan.cucer.twitterusersearch.screens.search.list.TwitterUsersAdapter import kotlinx.coroutines.launch class UserSearchViewModel(private val repository: Repository): ViewModel() { val errorText = MutableLiveData<String>() val adapter = TwitterUsersAdapter().also { adapter -> adapter.addSelectItemListener(object : TwitterUsersAdapter.SelectItem { override fun select(item: TwitterUser) { repository.setSelectedUser(item) } }) adapter.addSelectItemClickListener{ Log.e(javaClass.simpleName, " Go To Details ") Navigation.findNavController(it).navigate(R.id.go_to_details) } } fun onTextChanged(text: String) { Log.e(javaClass.simpleName, text) if (text.length > 2) { errorText.postValue("") viewModelScope.launch { repository.getUsers(text, adapter, object: ErrorCallback{ override fun onError(error: String) { errorText.postValue(error) } }) } } } }
0
Kotlin
0
0
72c65121d3e2d7f7bdbef68127a168425e915465
1,663
TwitterUserSearch
Apache License 2.0
app/src/main/java/com/kormax/universalreader/google/smarttap/SmartTapCollectorConfiguration.kt
kormax
813,025,174
false
{"Kotlin": 134187}
package com.kormax.universalreader.google.smarttap class SmartTapCollectorConfiguration( val collectorId: UInt, val cryptoProviders: Collection<SmartTapCryptoProvider> )
0
Kotlin
0
4
c4faab5d9aef822e78f2bc8d54fd355410486901
179
android-universal-reader
Apache License 2.0
data/common/src/main/kotlin/com/edricchan/studybuddy/data/repo/crud/HasQueryOperations.kt
EdricChan03
100,260,817
false
{"Kotlin": 840248, "Ruby": 202}
package com.edricchan.studybuddy.data.repo.crud import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.map /** * Repository that has query operations. * * This interface is separate from [CrudRepository] to facilitate * repositories that might not have the ability to perform queries on the * underlying data. * @see CrudRepository * @param T Concrete POJO class that the CRUD operations will return. * @param Query Type representing a class of some kind which can be used to query * data from the underlying database. */ interface HasQueryOperations<T, Query> { /** Retrieves items of type [T] that match the given [query] criteria. */ fun findAll(query: Query): Flow<List<T>> /** * Retrieves the first item of type [T] that matches the given [query] criteria, * or `null` if no items were matched. */ fun findFirst(query: Query): Flow<T?> = findAll(query).map { it.firstOrNull() } }
50
Kotlin
10
16
233aefa8cb095b88509951642eb65cb887a7178c
941
studybuddy-android
MIT License
app/src/main/java/it/reti/percorsi/school/db/dao/SchoolDao.kt
daviogg
233,260,713
false
null
package it.reti.percorsi.school.db.dao import androidx.lifecycle.LiveData import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import io.reactivex.Completable import it.reti.percorsi.school.db.entities.Classroom import it.reti.percorsi.school.db.entities.Student import it.reti.percorsi.school.db.entities.Vote @Dao interface SchoolDao { @Query("SELECT * FROM Student WHERE classroomId == :classId") fun getAllStudents(classId: Int): LiveData<List<Student>> @Query("SELECT * FROM Classroom") fun getAllClassrooms(): LiveData<List<Classroom>> @Query("SELECT * FROM Student WHERE uid == :studentId") fun getStudent(studentId: Int): LiveData<Student> @Query("SELECT * FROM Vote WHERE uid == :studentId") fun getAllVotes(studentId: Int): LiveData<List<Vote>> @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertClassrooms(classrooms : List<Classroom>) : Completable @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertStudents(students: List<Student>) : Completable @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertVotes(votes:List<Vote>) : Completable @Insert(onConflict = OnConflictStrategy.REPLACE) fun insertVote(votes:Vote) : Completable }
0
Kotlin
0
0
5f8c6161fae7ae9d8d370881ffa23fd3ffe30960
1,306
AndroidProject
MIT License
client/src/main/kotlin/com/ecwid/upsource/rpc/issuetrackers/IssueTrackerProviderSettingDTO.kt
turchenkoalex
266,583,029
false
null
// Generated by the codegen. Please DO NOT EDIT! // source: message.ftl package com.ecwid.upsource.rpc.issuetrackers /** * @param name Setting key * @param value Setting value */ @Suppress("unused") data class IssueTrackerProviderSettingDTO( /** * Setting key (required) */ val name: String, /** * Setting value (required) */ val value: String ) { @Suppress("unused") internal constructor() : this( name = "", value = "" ) }
0
Kotlin
1
3
bc93adb930157cd77b6955ed86b3b2fc7f78f6a2
451
upsource-rpc
Apache License 2.0
remote-config-slack-notification-service/src/main/kotlin/RemoteConfigDiff.kt
goobar-dev
517,209,823
false
{"Kotlin": 23204}
/** * Holds a diff between two Parameters or Conditions */ data class RemoteConfigDiff<T>( val key: String, val original: T, val updated: T )
0
Kotlin
0
2
9f198fd5a5337f8580abe5b88545374cc9e5a851
155
firebase-remote-config-guardrails
Apache License 2.0
app/src/main/java/com/annguyen/dmedandroiassignment/DmedAssignmentApplication.kt
anguyenqd
508,005,129
false
{"Kotlin": 60860}
package com.annguyen.dmedandroiassignment import android.app.Application import dagger.hilt.android.HiltAndroidApp import logcat.AndroidLogcatLogger import logcat.LogPriority @HiltAndroidApp class DmedAssignmentApplication : Application() { override fun onCreate() { super.onCreate() AndroidLogcatLogger.installOnDebuggableApp(this, minPriority = LogPriority.VERBOSE) } }
0
Kotlin
0
0
3e5af25a08ac11cd2f7d33377834d48a86f61f88
397
dmedexplorer
MIT License
livemap-demo/src/commonMain/kotlin/jetbrains/livemap/demo/RasterTilesDemoModel.kt
yanglv-onepunchman
361,674,348
true
{"Kotlin": 5066719, "Python": 747545, "C": 2832, "CSS": 1948, "Shell": 1773, "JavaScript": 1048}
/* * Copyright (c) 2019. JetBrains s.r.o. * Use of this source code is governed by the MIT license that can be found in the LICENSE file. */ package jetbrains.livemap.demo import jetbrains.datalore.base.geometry.DoubleVector import jetbrains.livemap.api.LiveMapBuilder import jetbrains.livemap.tiles.TileSystemProvider.RasterTileSystemProvider class RasterTilesDemoModel(dimension: DoubleVector) : DemoModelBase(dimension) { override fun createLiveMapSpec(): LiveMapBuilder { return basicLiveMap { tileSystemProvider = RasterTileSystemProvider("http://c.tile.stamen.com/toner/{z}/{x}/{y}@2x.png") attribution = "© stamen.com" } } }
0
null
0
0
ef6c27c175aa231e0067e024e18b353e11f7d789
686
lets-plot
MIT License
app/src/main/java/dev/shreyansh/weatherman/utils/SearchRecyclerAdapter.kt
binaryshrey
637,304,705
false
null
package dev.shreyansh.weatherman.utils import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import dev.shreyansh.weatherman.databinding.SearchListItemBinding import dev.shreyansh.weatherman.network.response.CitySearchResponse class SearchRecyclerAdapter( val onClickListener: OnClickListener) : ListAdapter<CitySearchResponse, SearchRecyclerAdapter.ViewHolder>(DiffUtilItemCallBackSearch()) { class ViewHolder private constructor(val binding : SearchListItemBinding) : RecyclerView.ViewHolder(binding.root) { fun bind(item: CitySearchResponse) { binding.search = item binding.executePendingBindings() } companion object { fun from(parent: ViewGroup): ViewHolder { val layoutInflater = LayoutInflater.from(parent.context) val binding = SearchListItemBinding.inflate(layoutInflater, parent, false) return ViewHolder(binding) } } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder.from(parent) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = getItem(position) holder.itemView.setOnClickListener { onClickListener.onClick(item) } holder.bind(item) } class OnClickListener(val clickListener: (search: CitySearchResponse) -> Unit) { fun onClick(search: CitySearchResponse) = clickListener(search) } } class DiffUtilItemCallBackSearch : DiffUtil.ItemCallback<CitySearchResponse>() { override fun areItemsTheSame(oldItem: CitySearchResponse, newItem: CitySearchResponse): Boolean { return oldItem.cityKey == newItem.cityKey } override fun areContentsTheSame(oldItem: CitySearchResponse, newItem: CitySearchResponse): Boolean { return oldItem == newItem } }
0
Kotlin
0
0
3c8fa99a6d62302537686abaf2a091ff03efe0c9
2,052
WeatherMan
MIT License
PayByBank/src/main/java/com/ecospend/paylinksdk/data/remote/model/frPayment/FrPaymentGetResponse.kt
ecospend
517,957,223
false
null
package com.ecospend.paybybank.data.remote.model.frPayment import com.ecospend.paybybank.data.remote.model.paylink.PayByBankAccountResponse import com.google.gson.annotations.SerializedName data class FrPaymentGetResponse( /** * Unique id value of FrPayment. */ @SerializedName("unique_id") val uniqueID: String? = null, /** * FrPayment amount in decimal format. */ val amount: Float? = null, /** * Payment reference that will be displayed on the bank statement. 18 characters MAX. */ val reference: String? = null, /** * Description for the payment. 255 character MAX. */ val description: String? = null, /** * The URL of the Tenant that the PSU will be redirected at the end of the FrPayment journey. * This URL must be registered by your Admin on the Ecospend Management Console, prior to being used in the API calls. */ @SerializedName("redirect_url") val redirectURL: String? = null, /** * The URL to open bank selection screen */ val url: String? = null, /** * Unique identification string assigned to the bank by our system. * If value is set, FrPayment will not display any UI and execute an instant redirect to the debtor's banking system. * If value is not set, FrPayment will display the PSU a bank selection screen. */ @SerializedName("bank_id") val bankID: String? = null, /** * If you are providing our Payment service to your own business clients (merchants), then you should set the Id of your merchant. */ @SerializedName("merchant_id") val merchantID: String? = null, /** * The Id of the end-user. * If you are providing this service directly to the end-users, then you can assign that Id to this parameter. * If you are providing this service to businesses, then you should assign the Id of that merchant’s user. */ @SerializedName("merchant_user_id") val merchantUserID: String? = null, /** * The Creditor Account model */ @SerializedName("creditor_account") val creditorAccount: PayByBankAccountResponse? = null, /** * The Debtor Account model */ @SerializedName("debtor_account") val debtorAccount: PayByBankAccountResponse? = null, /** * The FrPayment Options model */ @SerializedName("fr_payment_options") val frPaymentOptions: FrPaymentOptionsResponse? = null, /** * Date and time of the first payment in [ISO 8601](https://en.wikipedia.org/wiki/ISO_8601) format. * Warning: This date must be a work day. */ @SerializedName("first_payment_date") val firstPaymentDate: String? = null, /** * Number of total payments being set with this standing order. */ @SerializedName("number_of_payments") val numberOfPayments: Int? = null, /** * Period of FrPayment * Note: Enum: "Weekly" "Monthly" "Yearly" */ val period: FrPaymentPeriod? = null, /** * The user has the right to change the FrPayment related additional parameters * Note: Defaults to false. */ @SerializedName("allow_frp_customer_changes") val allowFrpCustomerChanges: Boolean? = null, ) data class FrPaymentOptionsResponse( /** * Client id of the API consumer */ @SerializedName("client_id") val clientID: String?, /** * Tenant id of the API consumer */ @SerializedName("tenant_id") val tenantID: String?, /** * Set true, if you would like to get back the debtor's account information that the payment is made from. * Note: If not provided, defaults to 'true'. */ @SerializedName("get_refund_info") val getRefundInfo: Boolean?, /** * Amount of first payment */ @SerializedName("first_payment_amount") val firstPaymentAmount: Float?, /** * Amount of last payment */ @SerializedName("last_payment_amount") val lastPaymentAmount: Float?, /** * Disables QR Code component on FrPayment */ @SerializedName("disable_qr_code") val disableQrCode: Boolean?, /** * Customizes editable option of fields */ @SerializedName("editable_fields") val editableFields: FrPaymentEditableField?, )
0
Kotlin
0
4
a35e8ecdd793db92f09df6ff9723a38516e86ad7
4,313
PayByBankSDK-Android
Apache License 2.0
java2taxi/src/main/java/lang/taxi/generators/java/TypeMappings.kt
adarro
458,750,628
false
null
package lang.taxi.generators.java import lang.taxi.TypeAliasRegistry import lang.taxi.TypeNames import lang.taxi.annotations.* import lang.taxi.jvm.common.PrimitiveTypes import lang.taxi.kapt.KotlinTypeAlias import lang.taxi.sources.SourceCode import lang.taxi.types.* import lang.taxi.types.Annotation import lang.taxi.utils.log import org.jetbrains.annotations.NotNull import org.springframework.core.ResolvableType import java.lang.reflect.AnnotatedElement import java.lang.reflect.Field import java.lang.reflect.Method import java.lang.reflect.Parameter import kotlin.reflect.KClass import kotlin.reflect.KParameter import kotlin.reflect.KProperty import kotlin.reflect.KProperty1 import kotlin.reflect.full.allSupertypes import kotlin.reflect.full.declaredMemberProperties import kotlin.reflect.full.findAnnotation import kotlin.reflect.full.memberProperties import kotlin.reflect.jvm.javaField import kotlin.reflect.jvm.javaGetter import kotlin.reflect.jvm.kotlinFunction import kotlin.reflect.jvm.kotlinProperty interface MapperExtension interface TypeMapper { fun getTaxiType(sourceType: Class<*>, existingTypes: MutableSet<Type>, containingMember: AnnotatedElement? = null): Type { val namespace = TypeNames.deriveNamespace(sourceType) return getTaxiType(sourceType, existingTypes, namespace) } fun getTaxiType(source: AnnotatedElement, existingTypes: MutableSet<Type>, defaultNamespace: String, containingMember: AnnotatedElement? = null): Type } class DefaultTypeMapper(private val constraintAnnotationMapper: ConstraintAnnotationMapper = ConstraintAnnotationMapper()) : TypeMapper { fun MutableSet<Type>.findByName(qualifiedTypeName: String): Type? { return this.firstOrNull { it.qualifiedName == qualifiedTypeName } } // A containingMember is typically a function, which has declared a returnType. // Since the annotations can't go directly on the return type, they go on the function itself, // meaning we need to evaluate the function when considering the type. override fun getTaxiType(element: AnnotatedElement, existingTypes: MutableSet<Type>, defaultNamespace: String, containingMember: AnnotatedElement?): Type { val elementType = TypeNames.typeFromElement(element) val declaresTypeAlias = declaresTypeAlias(element) if (isTaxiPrimitiveWithoutAnnotation(element) && !declaresTypeAlias) { if (containingMember == null) return PrimitiveTypes.getTaxiPrimitive(elementType.typeName) if (isTaxiPrimitiveWithoutAnnotation(containingMember)) { // If the type has a DataType annotation, we use that // Otherwise, return the primitive return PrimitiveTypes.getTaxiPrimitive(elementType.typeName) } } if (declaresTypeAlias) { val typeAliasName = getDeclaredTypeAliasName(element, defaultNamespace)!! // Don't examine the return type for collections, as the type we care about is lost in generics - just create the type alias if (element.isCollection()) { return getOrCreateTypeAlias(element, typeAliasName, existingTypes) } val aliasedTaxiType = getTypeDeclaredOnClass(element, existingTypes) if (typeAliasName != aliasedTaxiType.qualifiedName) { return getOrCreateTypeAlias(element, typeAliasName, existingTypes) } else { log().warn("Element $element declares a redundant type alias of $typeAliasName, which is already " + "declared on the type itself. Consider removing this name (replacing it with an " + "empty @DataType annotation, otherwise future refactoring bugs are likely to occur") } } val targetTypeName = getTargetTypeName(element, defaultNamespace, containingMember) if (isCollection(element)) { val collectionType = findCollectionType(element, existingTypes, defaultNamespace, containingMember) return ArrayType(collectionType, exportedCompilationUnit(element)) } if (containingMember != null && declaresTypeAlias(containingMember)) { val typeAliasName = getDeclaredTypeAliasName(containingMember, defaultNamespace)!! return getOrCreateTypeAlias(containingMember, typeAliasName, existingTypes) } // if (isImplicitAliasForPrimitiveType(targetTypeName,element)) { // // } if (PrimitiveTypes.isClassTaxiPrimitive(elementType)) { return PrimitiveTypes.getTaxiPrimitive(elementType) } val existing = existingTypes.findByName(targetTypeName) if (existing != null) { return existing } if (isEnum(element)) { val enumType = mapEnumType(element, defaultNamespace) // Note: We have to mutate the collection of types within the parent // loop, as adding objectTypes needs to be able to pre-emptively add empty types // before the definition is encountered. // This feels ugly, but it works for now. existingTypes.add(enumType) return enumType } return mapNewObjectType(element, defaultNamespace, existingTypes) } private fun mapEnumType(element: AnnotatedElement, defaultNamespace: String): EnumType { val enum = TypeNames.typeFromElement(element) val enumQualifiedName = getTargetTypeName(element, defaultNamespace) val enumValues = enum.getDeclaredField("\$VALUES").let { // This is a hack, as for some reason in tests enum.enumConstants is returning null. it.isAccessible = true it.get(null) as Array<Enum<*>> }.map { EnumValue( name = it.name, annotations = emptyList(), // TODO : Support annotations on EnumValues when exporting qualifiedName = Enums.enumValue(QualifiedName.from(enumQualifiedName), it.name), synonyms = emptyList() ) } return EnumType( enumQualifiedName, EnumDefinition( values = enumValues, annotations = emptyList(), // TODO : Support annotations on Enums when exporting compilationUnit = exportedCompilationUnit(element), basePrimitive = PrimitiveType.STRING // TODO ) ) } private fun isEnum(element: AnnotatedElement) = TypeNames.typeFromElement(element).isEnum private fun findCollectionType(element: AnnotatedElement, existingTypes: MutableSet<Type>, defaultNamespace: String, containingMember: AnnotatedElement?): Type { if (element is KTypeWrapper) { val argments = element.arguments require(argments.size == 1) { "expected type ${element.ktype} to have exactly 1 argument, but found ${argments.size}" } val typeArg = argments.first() val argumentType = typeArg.type ?: error("Unhandled: The argument type for ${element.ktype} did not return a type - unsure how this can happen") return getTaxiType(KTypeWrapper(argumentType), existingTypes, defaultNamespace) } val collectionType = when (element) { is Field -> ResolvableType.forField(element).generics[0] // returns T of List<T> / Set<T> else -> TODO("Collection types that aren't fields not supported yet - (got $element)") } return getTaxiType(collectionType.resolve(), existingTypes, defaultNamespace) } private fun isCollection(element: AnnotatedElement): Boolean { val clazz = TypeNames.typeFromElement(element) return (clazz.isArray) || Collection::class.java.isAssignableFrom(clazz) } // // This is typically for functions who's parameters are // // a primitive type (eg., String). These // private fun isImplicitAliasForPrimitiveType(targetTypeName: String, element: AnnotatedElement): Boolean { // // } private fun isTaxiPrimitiveWithoutAnnotation(element: AnnotatedElement?): Boolean { if (element == null) return false return (!TypeNames.declaresDataType(element) && PrimitiveTypes.isClassTaxiPrimitive(TypeNames.typeFromElement(element))) } private fun getOrCreateTypeAlias(element: AnnotatedElement, typeAliasName: String, existingTypes: MutableSet<Type>): TypeAlias { val existingAlias = existingTypes.findByName(typeAliasName) if (existingAlias != null) { return existingAlias as TypeAlias } val compilationUnit = CompilationUnit.ofSource(SourceCode("Exported from annotation", "Annotation")) val aliasedTaxiType = if (element.isCollection()) { val collectionType = findCollectionType(element, existingTypes, TypeNames.deriveNamespace(TypeNames.typeFromElement(element)), null) ArrayType(collectionType, compilationUnit) } else { getTypeDeclaredOnClass(element, existingTypes) } val typeAlias = TypeAlias(typeAliasName, aliasedTaxiType, compilationUnit) existingTypes.add(typeAlias) return typeAlias } fun getTypeDeclaredOnClass(element: AnnotatedElement, existingTypes: MutableSet<Type>): Type { val rawType = TypeNames.typeFromElement(element) return getTaxiType(rawType, existingTypes, element) } private fun declaresTypeAlias(element: AnnotatedElement): Boolean { return getDeclaredTypeAliasName(element, "") != null } private fun getDeclaredTypeAliasName(element: AnnotatedElement, defaultNamespace: String): String? { // TODO : We may consider type aliases for Objects later. val kotlinTypeAlias = kotlinTypeAlias(element) if (kotlinTypeAlias != null) return deriveQualifiedAliasName(kotlinTypeAlias) if (element !is Field && element !is Parameter && element !is Method) return null val dataType = element.getAnnotation(DataType::class.java) ?: return null return if (dataType.declaresName()) { dataType.qualifiedName(defaultNamespace) } else { null } } private fun kotlinTypeAlias(element: Any): KotlinTypeAlias? { val kotlinTypeAlias = when (element) { is KTypeWrapper -> TypeAliasRegistry.findTypeAlias(element.ktype) is Field -> TypeAliasRegistry.findTypeAlias(element.kotlinProperty) is Method -> TypeAliasRegistry.findTypeAlias(element.kotlinFunction) is Parameter -> TypeAliasRegistry.findTypeAlias(element.kotlinParam) else -> null } return kotlinTypeAlias } private fun deriveQualifiedAliasName(kotlinTypeAlias: KotlinTypeAlias): String { return kotlinTypeAlias.deriveNamespace() + "." + kotlinTypeAlias.simpleName } private fun mapNewObjectType(element: AnnotatedElement, defaultNamespace: String, existingTypes: MutableSet<Type>): ObjectType { val name = getTargetTypeName(element, defaultNamespace) val fields = mutableSetOf<lang.taxi.types.Field>() val modifiers = getTypeLevelModifiers(element) val inheritance = getInheritedTypes(TypeNames.typeFromElement(element), existingTypes, defaultNamespace) // TODO val definition = ObjectTypeDefinition( fields = fields, annotations = emptySet(), modifiers = modifiers, inheritsFrom = inheritance, format = null, typeDoc = null, compilationUnit = exportedCompilationUnit(element) ) val objectType = ObjectType(name, definition) // Note: Add the type while it's empty, and then collect the fields. // This allows circular references to resolve existingTypes.add(objectType) fields.addAll(this.mapTaxiFields(lang.taxi.TypeNames.typeFromElement(element), defaultNamespace, existingTypes)) return objectType } private fun getTypeLevelModifiers(element: AnnotatedElement): List<Modifier> { val modifiers = mutableListOf<Modifier>(); if (element.getAnnotation(ParameterType::class.java) != null) { modifiers.add(Modifier.PARAMETER_TYPE) } // Odd boolean comparison to account for nulls if (element.getAnnotation(DataType::class.java)?.closed == true) { modifiers.add(Modifier.CLOSED) } return modifiers } private fun getInheritedTypes(clazz: Class<*>, existingTypes: MutableSet<Type>, defaultNamespace: String): Set<ObjectType> { val superType = clazz.superclass val inheritedTypes = (clazz.interfaces.toList() + listOf(clazz.superclass)).filterNotNull() return inheritedTypes .filter { it.isAnnotationPresent(DataType::class.java) } .map { inheritedType -> getTaxiType(inheritedType, existingTypes, defaultNamespace) as ObjectType } .toSet() } private fun exportedCompilationUnit(element: AnnotatedElement) = CompilationUnit.ofSource(SourceCode("Exported from type $element", "Exported")) private fun getTargetTypeName(element: AnnotatedElement, defaultNamespace: String, containingMember: AnnotatedElement? = null): String { val rawType = TypeNames.typeFromElement(element) if (containingMember != null && TypeNames.declaresDataType(containingMember)) { return TypeNames.deriveTypeName(containingMember, defaultNamespace) } if (!TypeNames.declaresDataType(element) && PrimitiveTypes.isClassTaxiPrimitive(rawType)) { return PrimitiveTypes.getTaxiPrimitive(rawType.typeName).qualifiedName } return TypeNames.deriveTypeName(element, defaultNamespace) } private fun mapTaxiFields(javaClass: Class<*>, defaultNamespace: String, existingTypes: MutableSet<Type>): List<lang.taxi.types.Field> { val kClass = javaClass.kotlin val mappedProperties = kClass.memberProperties .filter { !propertyIsInheritedFromMappedSupertype(kClass, it) } .map { property -> val annotatedElement = when { property.javaField != null -> property.javaField property.javaGetter != null -> property.javaGetter else -> TODO() } as AnnotatedElement // Not sure what's going on here. // Sometimes the annotations appear on the Kotlin property, // sometimes they're on the underlying java type. // (Always for data class with a val). // For now, check both. This might result in duplicates, // but I'll cross that bridge when that happens val constraints = listOf(property.findAnnotation<Constraint>()).filterNotNull() + annotatedElement.getAnnotationsByType(Constraint::class.java).distinct().toList() val mappedConstraints = constraintAnnotationMapper.convert(constraints) lang.taxi.types.Field(name = property.name, type = getTaxiType(annotatedElement, existingTypes, defaultNamespace), nullable = property.returnType.isMarkedNullable, annotations = mapAnnotations(property), constraints = mappedConstraints) } return mappedProperties // // return javaClass.declaredFields.map { field -> // // val constraints = field.getAnnotationsByType(Constraint::class.java).toList() // // val mappedConstraints = constraintAnnotationMapper.convert(constraints) // lang.taxi.types.Field(name = field.name, // type = getTaxiType(field, existingTypes, defaultNamespace), // nullable = isNullable(field), // annotations = mapAnnotations(field), // constraints = mappedConstraints) // } } // Indicates if the field is actually present as an inherited / overridden // member from an superType. (ie., a field declared in an interface, that's overridden on a class) // In Taxi, we want those types to be declared on the supertype (since they're all innherited). private fun propertyIsInheritedFromMappedSupertype(kClass: KClass<out Any>, property: KProperty1<out Any, Any?>): Boolean { val isDeclaredOnSupertype = kClass.allSupertypes.filter { superType -> val classifier = superType.classifier when (classifier) { is KClass<*> -> classifier.findAnnotation<DataType>() != null else -> false } }.any { superType -> val classifer = superType.classifier as KClass<*> classifer.declaredMemberProperties.any { it.name == property.name } } return isDeclaredOnSupertype } private fun mapAnnotations(property: KProperty<*>): List<Annotation> { // TODO -- as with mapAnnotations(field) return emptyList(); } private fun mapAnnotations(field: java.lang.reflect.Field): List<Annotation> { // TODO // Note: When I do implement this, consider that fields // will have @Constraint annotations, which shouldn't be handled here, // but are instead handled in the constraint section return emptyList() } private fun isNullable(field: java.lang.reflect.Field): Boolean { val isNotNull = field.isAnnotationPresent(NotNull::class.java) || return field.isAnnotationPresent(javax.validation.constraints.NotNull::class.java) return !isNotNull } } private val Parameter.kotlinParam: KParameter? get() { val method = this.declaringExecutable as Method val paramIndex = method.parameters.indexOf(this) val function = method.kotlinFunction ?: return null val param = function.parameters[paramIndex + 1] // Note that Kotlin functions have the call site at index 0 return param } private fun AnnotatedElement.isCollection(): Boolean { val type = TypeNames.typeFromElement(this) return Collection::class.java.isAssignableFrom(type) } fun KotlinTypeAlias.deriveNamespace(): String { // Note : These rules should match whats in TypeNames.deriveNamespace. // In future, we should collapse the two functions, but right now, that's not happening val dataType = this.getAnnotation(DataType::class.qualifiedName!!) val namespaceAnnotation = this.getAnnotation(lang.taxi.annotations.Namespace::class.qualifiedName!!) val dataTypeValue = dataType?.arg("value") return when { namespaceAnnotation != null -> namespaceAnnotation.arg("value")!! dataTypeValue != null && Namespaces.hasNamespace(dataTypeValue) -> Namespaces.pluckNamespace(dataTypeValue)!! else -> this.packageName } } fun KProperty<*>.toAnnotatedElement(): KTypeWrapper { return KTypeWrapper(this.returnType) }
0
Kotlin
0
0
4e63dc633ef4dd28f6c92f1546640d9b67fa0826
18,409
quarkus-taxi-poc
Apache License 2.0
packages/library-base/src/commonMain/kotlin/io/realm/kotlin/internal/RealmImpl.kt
realm
235,075,339
false
null
/* * Copyright 2021 Realm 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.realm.kotlin.internal import io.realm.kotlin.Configuration import io.realm.kotlin.MutableRealm import io.realm.kotlin.Realm import io.realm.kotlin.dynamic.DynamicRealm import io.realm.kotlin.internal.dynamic.DynamicRealmImpl import io.realm.kotlin.internal.interop.RealmInterop import io.realm.kotlin.internal.interop.SynchronizableObject import io.realm.kotlin.internal.platform.copyAssetFile import io.realm.kotlin.internal.platform.fileExists import io.realm.kotlin.internal.platform.runBlocking import io.realm.kotlin.internal.schema.RealmSchemaImpl import io.realm.kotlin.internal.util.LiveRealmContext import io.realm.kotlin.internal.util.Validation.sdkError import io.realm.kotlin.internal.util.createLiveRealmContext import io.realm.kotlin.internal.util.terminateWhen import io.realm.kotlin.notifications.RealmChange import io.realm.kotlin.notifications.internal.InitialRealmImpl import io.realm.kotlin.notifications.internal.UpdatedRealmImpl import io.realm.kotlin.query.RealmQuery import io.realm.kotlin.types.TypedRealmObject import kotlinx.atomicfu.AtomicRef import kotlinx.atomicfu.atomic import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel import kotlinx.coroutines.channels.BufferOverflow import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.onStart import kotlinx.coroutines.launch import kotlinx.coroutines.sync.withLock import kotlin.reflect.KClass // TODO API-PUBLIC Document platform specific internals (RealmInitializer, etc.) // TODO Public due to being accessed from `SyncedRealmContext` public class RealmImpl private constructor( configuration: InternalConfiguration, ) : BaseRealmImpl(configuration), Realm, InternalTypedRealm, Flowable<RealmChange<Realm>> { public val notificationScheduler: LiveRealmContext = configuration.notificationDispatcherFactory.createLiveRealmContext() public val writeScheduler: LiveRealmContext = configuration.writeDispatcherFactory.createLiveRealmContext() internal val realmScope = CoroutineScope(SupervisorJob() + notificationScheduler.dispatcher) private val notifierFlow: MutableSharedFlow<RealmChange<Realm>> = MutableSharedFlow(extraBufferCapacity = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST) private val notifier = SuspendableNotifier( owner = this, scheduler = notificationScheduler, ) private val writer = SuspendableWriter( owner = this, scheduler = writeScheduler, ) // Internal flow to ease monitoring of realm state for closing active flows then the realm is // closed. internal val realmStateFlow = MutableSharedFlow<State>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST) // Initial realm reference that would be used until the notifier or writer are available. internal var initialRealmReference: AtomicRef<FrozenRealmReference?> = atomic(null) private val isClosed = atomic(false) /** * The current Realm reference that points to the underlying frozen C++ SharedRealm. * * NOTE: As this is updated to a new frozen version on notifications about changes in the * underlying realm, care should be taken not to spread operations over different references. */ override val realmReference: FrozenRealmReference get() = realmReference() // TODO Bit of an overkill to have this as we are only catching the initial frozen version. // Maybe we could just rely on the notifier to issue the initial frozen version, but that // would require us to sync that up. Didn't address this as we already have a todo on fixing // constructing the initial frozen version in the initialization of updatableRealm. internal val versionTracker = VersionTracker(this, log) // Injection point for synchronized Realms. This property should only be used to hold state // required by synchronized realms. See `SyncedRealmContext` for more details. @OptIn(ExperimentalStdlibApi::class) public var syncContext: AtomicRef<AutoCloseable?> = atomic(null) init { @Suppress("TooGenericExceptionCaught") // Track whether or not the file was created as part of opening the Realm. We need this // so we can remove the file again if case opening the Realm fails. var realmFileCreated = false try { runBlocking { var assetFileCopied = false configuration.initialRealmFileConfiguration?.let { val path = configuration.path if (!fileExists(path)) { // TODO We cannot ensure exclusive access to the realm file, so for now // just try avoid having multiple threads in the same process copying // asset files at the same time. // https://github.com/realm/realm-core/issues/6492 assetProcessingLock.withLock { if (!fileExists(path)) { log.debug("Copying asset file: ${it.assetFile}") assetFileCopied = true copyAssetFile(path, it.assetFile, it.checksum) } } } } val (frozenReference, fileCreated) = configuration.openRealm(this@RealmImpl) realmFileCreated = assetFileCopied || fileCreated versionTracker.trackReference(frozenReference) initialRealmReference.value = frozenReference configuration.initializeRealmData(this@RealmImpl, realmFileCreated) } realmScope.launch { notifier.realmChanged().collect { removeInitialRealmReference() // Closing this reference might be done by the GC: // https://github.com/realm/realm-kotlin/issues/1527 versionTracker.closeExpiredReferences() notifierFlow.emit(UpdatedRealmImpl(this@RealmImpl)) } } if (!realmStateFlow.tryEmit(State.OPEN)) { log.warn("Cannot signal internal open") } } catch (ex: Throwable) { // Something went wrong initializing Realm, delete the file, so initialization logic // can run again. close() if (realmFileCreated) { try { Realm.deleteRealm(configuration) } catch (ex: IllegalStateException) { // Ignore. See https://github.com/realm/realm-kotlin/issues/851 // Currently there is no reliable way to delete a synchronized // Realm. So ignore if this fails for now. log.debug( "An error happened while trying to reset the realm after " + "opening it for the first time failed. The realm must be manually " + "deleted if `initialData` and `initialSubscriptions` should run " + "again: $ex" ) } } throw ex } } /** * Manually force this Realm to update to the latest version. * The refresh will also trigger any relevant notifications. * TODO Public because it is called from `SyncSessionImpl`. */ public suspend fun refresh() { // We manually force a refresh of the notifier Realm and manually update the user // facing Realm with the updated version. Note, as the notifier asynchronously also update // the user Realm, we cannot guarantee that the Realm has this exact version when // this method completes. But we can guarantee that it has _at least_ this version. notifier.refresh() } // Required as Kotlin otherwise gets confused about the visibility and reports // "Cannot infer visibility for '...'. Please specify it explicitly" override fun <T : TypedRealmObject> query( clazz: KClass<T>, query: String, vararg args: Any? ): RealmQuery<T> { return super.query(clazz, query, *args) } // Currently just for internal-only usage in test, thus API is not polished internal suspend fun updateSchema(schema: RealmSchemaImpl) { this.writer.updateSchema(schema) } override suspend fun <R> write(block: MutableRealm.() -> R): R = writer.write(block) override fun <R> writeBlocking(block: MutableRealm.() -> R): R { writer.checkInTransaction("Cannot initiate transaction when already in a write transaction") return runBlocking { write(block) } } override fun asFlow(): Flow<RealmChange<Realm>> = scopedFlow { notifierFlow.onStart { emit(InitialRealmImpl(this@RealmImpl)) } } override fun writeCopyTo(configuration: Configuration) { if (fileExists(configuration.path)) { throw IllegalArgumentException("File already exists at: ${configuration.path}. Realm can only write a copy to an empty path.") } val internalConfig = (configuration as InternalConfiguration) val configPtr = internalConfig.createNativeConfiguration() RealmInterop.realm_convert_with_config( realmReference.dbPointer, configPtr, false // We don't want to expose 'merge_with_existing' all the way to the SDK - see docs in the C-API ) } override fun <T : CoreNotifiable<T, C>, C> registerObserver(t: Observable<T, C>): Flow<C> { return notifier.registerObserver(t) } /** * Removes the local reference to start relying on the notifier - writer for snapshots. */ private fun removeInitialRealmReference() { if (initialRealmReference.value != null) { log.trace("REMOVING INITIAL VERSION") // There is at least a new version available in the notifier, stop tracking the local one initialRealmReference.value = null } } public fun realmReference(): FrozenRealmReference { // We don't require to return the latest snapshot to the user but the closest the best. // `initialRealmReference` is accessed from different threads, grab a copy to safely operate on it. return initialRealmReference.value.let { localReference -> // Find whether the user-facing, notifier or writer has the latest snapshot. // Sort is stable, it will try to preserve the following order. listOf( { localReference } to localReference?.uncheckedVersion(), { writer.snapshot } to writer.version, { notifier.snapshot } to notifier.version, ).sortedByDescending { it.second }.first().first.invoke() } ?: sdkError("Accessing realmReference before realm has been opened") } public fun activeVersions(): VersionInfo { val mainVersions: VersionData = VersionData( current = initialRealmReference.value?.uncheckedVersion(), active = versionTracker.versions() ) return VersionInfo( main = mainVersions, notifier = notifier.versions(), writer = writer.versions() ) } override fun isClosed(): Boolean { // We cannot rely on `realmReference()` here. If something happens during open, this might // not be available and will throw, so we need to track closed state separately. return isClosed.value } override fun close() { // TODO Reconsider this constraint. We have the primitives to check is we are on the // writer thread and just close the realm in writer.close() writer.checkInTransaction("Cannot close the Realm while inside a transaction block") if (!isClosed.getAndSet(true)) { runBlocking { writer.close() realmScope.cancel() notifier.close() versionTracker.close() @OptIn(ExperimentalStdlibApi::class) syncContext.value?.close() // The local realmReference is pointing to a realm reference managed by either the // version tracker, writer or notifier, so it is already closed super.close() } if (!realmStateFlow.tryEmit(State.CLOSED)) { log.warn("Cannot signal internal close") } notificationScheduler.close() writeScheduler.close() } } internal companion object { // Mutex to ensure that only one thread is trying to copy asset files in place at a time. // https://github.com/realm/realm-core/issues/6492 private val assetProcessingLock = SynchronizableObject() internal fun create(configuration: InternalConfiguration): RealmImpl { return RealmImpl(configuration) } } /** * Internal state to be able to make a [State] flow that we can easily monitor and use to close * flows within a coroutine context. */ internal enum class State { OPEN, CLOSED, } /** * Flow wrapper that will complete the flow returned by [block] when the realm is closed. */ internal inline fun <T> scopedFlow(crossinline block: () -> Flow<T>): Flow<T> { return block().terminateWhen(realmStateFlow) { state -> state == State.CLOSED } } } // Returns a DynamicRealm of the current version of the Realm. Only used to be able to test the // DynamicRealm API outside of a migration. internal fun Realm.asDynamicRealm(): DynamicRealm { val dbPointer = (this as RealmImpl).realmReference.dbPointer return DynamicRealmImpl([email protected], dbPointer) }
242
null
57
942
df49eefacba8f57653e232203f44003643468463
14,660
realm-kotlin
Apache License 2.0
project/common-impl/src/main/kotlin/ink/ptms/adyeshach/impl/hologram/Hologram.kt
TabooLib
284,936,010
false
{"Kotlin": 1050024, "Java": 35966}
package ink.ptms.adyeshach.impl.hologram import ink.ptms.adyeshach.core.AdyeshachHologram import ink.ptms.adyeshach.core.entity.manager.Manager import ink.ptms.adyeshach.impl.hologram.DefaultAdyeshachHologramHandler.Companion.toHologramContents import org.bukkit.Location /** * Adyeshach * ink.ptms.adyeshach.impl.hologram.Hologram * * @author 坏黑 * @since 2022/12/16 20:48 */ class Hologram(val manager: Manager, var origin: Location, var content: List<AdyeshachHologram.Item>) : AdyeshachHologram { init { refresh() } override fun teleport(location: Location) { this.origin = location.clone() this.content.filterIsInstance<HoloEntity<*>>().reversed().forEach { it.teleport(origin) } } override fun update(content: List<Any>) { this.content.forEach { it.remove() } this.content = content.toHologramContents() refresh() } override fun remove() { this.content.forEach { it.remove() } this.content = emptyList() } override fun contents(): List<AdyeshachHologram.Item> { return content } fun refresh() { if (content.isEmpty()) { return } var offset = -content.first().space content.filterIsInstance<HoloEntity<*>>().reversed().forEach { it.spawn(offset, origin, manager) offset += it.space } } }
13
Kotlin
86
98
ac7098b62db19308c9f14182e33181c079b9e561
1,401
adyeshach
MIT License
fragula-compose/src/main/kotlin/com/fragula2/compose/Animation.kt
massivemadness
466,849,855
false
null
/* * Copyright 2023 Fragula 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. */ package com.fragula2.compose import android.animation.TimeInterpolator import androidx.compose.animation.core.Easing import androidx.compose.foundation.gestures.detectHorizontalDragGestures import androidx.compose.foundation.gestures.detectVerticalDragGestures import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.composed import androidx.compose.ui.geometry.Offset import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.input.pointer.positionChange import androidx.compose.ui.input.pointer.util.VelocityTracker import androidx.compose.ui.input.pointer.util.addPointerInputChange import com.fragula2.common.SwipeDirection import kotlin.math.abs internal fun Modifier.animateDrag( enabled: Boolean, swipeDirection: SwipeDirection, onDragChanged: (Float) -> Unit = {}, onDragFinished: (Float) -> Unit = {}, ): Modifier = composed { if (!enabled) return@composed this val velocityTracker = VelocityTracker() var dragOffset by remember { mutableFloatStateOf(0f) } pointerInput(swipeDirection) { if (!swipeDirection.isHorizontal()) { detectVerticalDragGestures( onVerticalDrag = { change, dragAmount -> dragOffset += dragAmount if (dragOffset < 0f && swipeDirection == SwipeDirection.TOP_TO_BOTTOM) { dragOffset = 0f } else if (dragOffset > 0f && swipeDirection == SwipeDirection.BOTTOM_TO_TOP) { dragOffset = 0f } velocityTracker.addPointerInputChange(change) if (change.positionChange() != Offset.Zero) { onDragChanged(dragOffset) change.consume() } }, onDragEnd = { // Don't allow swipe to the other side (i.e if dragOffset == 0f) val velocity = if (dragOffset == 0f) 0f else velocityTracker.calculateVelocity().y velocityTracker.resetTracking() onDragFinished(abs(velocity)) // Provide the absolute value as it might be negative dragOffset = 0f }, ) } else { detectHorizontalDragGestures( onHorizontalDrag = { change, dragAmount -> dragOffset += dragAmount if (dragOffset < 0f && swipeDirection == SwipeDirection.LEFT_TO_RIGHT) { dragOffset = 0f } else if (dragOffset > 0f && swipeDirection == SwipeDirection.RIGHT_TO_LEFT) { dragOffset = 0f } velocityTracker.addPointerInputChange(change) if (change.positionChange() != Offset.Zero) { onDragChanged(dragOffset) change.consume() } }, onDragEnd = { // Don't allow swipe to the other side (i.e if dragOffset == 0f) val velocity = if (dragOffset == 0f) 0f else velocityTracker.calculateVelocity().x velocityTracker.resetTracking() onDragFinished(abs(velocity)) // Provide the absolute value as it might be negative dragOffset = 0f }, ) } } } internal fun TimeInterpolator.toEasing() = Easing { x -> getInterpolation(x) }
3
null
19
313
b0bbd6da8fc5ef73098d84119df5e365ae0d318b
4,294
Fragula
Apache License 2.0
frontend/src/com/cdsap/monitor/data/MySqlApiImpl.kt
cybernetics
211,650,611
true
{"Kotlin": 154593, "Shell": 23167, "Smarty": 5312, "Dockerfile": 3649}
package com.cdsap.monitor.data import com.github.jasync.sql.db.QueryResult import com.github.jasync.sql.db.mysql.MySQLConnection import com.github.jasync.sql.db.mysql.exceptions.MySQLException import com.github.jasync.sql.db.pool.ConnectionPool import com.cdsap.monitor.data.Queries.GET_EXPERIMENTS import com.cdsap.monitor.data.Queries.GET_PODS_BY_EXPERIMENT import com.cdsap.monitor.data.Queries.GET_POD_BY_EXPERIMENT_AND_NAME import com.cdsap.monitor.data.Queries.INSERT_EXPERIMENT import com.cdsap.monitor.data.Queries.INSERT_POD import com.cdsap.monitor.data.Queries.UPDATE_POD_COUNTER import com.cdsap.monitor.entities.domain.Pod import kotlinx.coroutines.future.await import kotlinx.coroutines.runBlocking class MySqlApiImpl( private val connectionPool: ConnectionPool<MySQLConnection>) : MySqlApi { override fun insertPod(pod: Pod) = queryResult(INSERT_POD, listOf(pod.name, pod.iterations, pod.experiment_id, pod.values, pod.configMap)) override fun insertExperiment(name: String) = queryResult(INSERT_EXPERIMENT, listOf(name)) override fun updatePodCounter(pod: Pod) = queryResult(UPDATE_POD_COUNTER, listOf(pod.iterations, pod.name, pod.experiment_id)) override fun getExperiments() = queryResult(GET_EXPERIMENTS, emptyList()) override fun getPodsByExperiment(name: String) = queryResult(GET_PODS_BY_EXPERIMENT, listOf(name)) override fun getPodByExperimentAndName(experiment: String, name: String) = queryResult(GET_POD_BY_EXPERIMENT_AND_NAME, listOf(experiment, name)) private fun queryResult(query: String, list: List<Any?>): QueryResult { return try { println("executing $query with $list") runBlocking { connectionPool.sendPreparedStatement(query, values = list).await() } } catch (mysqlException: MySQLException) { QueryResult(rowsAffected = 0L, statusMessage = mysqlException.message) } } } object Queries { const val INSERT_POD = "INSERT INTO `POD`(NAME,DATEINIT,COUNTER,EXPERIMENT_ID,EXPERIMENTS,CONFIGMAP)" + " VALUES (?,now(),?,?,?,?);" const val GET_EXPERIMENTS = "SELECT * FROM EXPERIMENT ORDER BY DATEINIT" const val GET_PODS_BY_EXPERIMENT = "SELECT * FROM POD WHERE EXPERIMENT_ID = ? ORDER BY NAME" const val GET_POD_BY_EXPERIMENT_AND_NAME = "SELECT * FROM POD WHERE EXPERIMENT_ID = ? AND NAME = ?" const val INSERT_EXPERIMENT = "INSERT INTO `EXPERIMENT`(NAME,DATEINIT) VALUES (?,now());" const val UPDATE_POD_COUNTER = "UPDATE POD SET COUNTER=? WHERE NAME=? AND EXPERIMENT_ID=?" }
0
null
0
0
ef05bebad55a5c4d74701b1c4f99a7c9c6fe5e17
2,629
Bagan
MIT License
app/src/main/java/com/shubham/ycsplassignment/viewmodel/PropertyDetailsViewModelFactory.kt
ShubhamShinde96
565,535,365
false
null
package com.shubham.ycsplassignment.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.shubham.ycsplassignment.repository.PropertyRepository class PropertyDetailsViewModelFactory(private val propertyRepository: PropertyRepository) : ViewModelProvider.Factory { override fun <T : ViewModel> create(modelClass: Class<T>): T { if(modelClass.isAssignableFrom(PropertyDetailsViewModel::class.java)) { return PropertyDetailsViewModel(propertyRepository) as T } throw IllegalArgumentException("Unknown View Model Class") } }
0
Kotlin
0
0
fadc5d868b67e1cc4bc3b4721ba4944036e9972a
621
PropertyLocationTracker-YCSPL-
MIT License
src/main/kotlin/ru/justagod/processing/cutter/transformation/MembersDeletionAugment.kt
JustAGod1
179,755,842
false
{"Kotlin": 232299, "Java": 12281}
package ru.justagod.processing.cutter.transformation import org.objectweb.asm.Type import org.objectweb.asm.commons.LocalVariablesSorter import org.objectweb.asm.tree.AnnotationNode import org.objectweb.asm.tree.InsnList import org.objectweb.asm.tree.MethodNode import ru.justagod.mincer.control.MincerResultType import ru.justagod.mincer.processor.WorkerContext import ru.justagod.model.ClassTypeReference import ru.justagod.model.PrimitiveKind import ru.justagod.model.PrimitiveTypeReference import ru.justagod.model.toReference import ru.justagod.processing.cutter.base.MincerAugment import ru.justagod.processing.cutter.config.CutterConfig import ru.justagod.processing.cutter.model.* import ru.justagod.processing.cutter.transformation.validation.ValidationResult import ru.justagod.stackManipulation.* import ru.justagod.utils.PrimitivesAdapter import ru.justagod.utils.containsAny import ru.justagod.utils.nope class MembersDeletionAugment(private val config: CutterConfig, private val model: ProjectModel) : MincerAugment<Unit, ValidationResult>() { override fun process(context: WorkerContext<Unit, ValidationResult>): MincerResultType { if (context.name.simpleName == "package-info") { //if (model.sidesFor(FolderAtom(context.name.name.dropLast(13)))?.containsAny(config.targetSides) == false) { // return MincerResultType.DELETED //} return MincerResultType.DELETED } var modified = false modified = modified or deleteAnnotation(context.info.node().visibleAnnotations) modified = modified or deleteAnnotation(context.info.node().invisibleAnnotations) val root = ClassAtom(context.name) if (model.sidesFor(root)?.containsAny(config.targetSides) == false) return MincerResultType.DELETED context.info.node().interfaces?.removeIf { nterface -> val shouldBeDeleted = model.sidesFor(ClassAtom(ClassTypeReference.fromInternal(nterface)))?.containsAny(config.targetSides) == false modified = modified or shouldBeDeleted shouldBeDeleted } context.info.node().fields?.removeIf { field -> modified = modified or deleteAnnotation(field.visibleAnnotations) modified = modified or deleteAnnotation(field.invisibleAnnotations) val shouldBeDeleted = model.sidesFor(FieldAtom(context.name, field.name))?.containsAny(config.targetSides) == false modified = modified or shouldBeDeleted shouldBeDeleted } context.info.node().methods.removeIf { method -> modified = modified or deleteAnnotation(method.visibleAnnotations) modified = modified or deleteAnnotation(method.invisibleAnnotations) val atom = MethodAtom(context.name, method) val shouldBeDeleted = model.sidesFor(atom)?.containsAny(config.targetSides) == false if (shouldBeDeleted) { modified = true return@removeIf true } val shouldBeCleared = model.sidesFor(MethodBodyAtom(atom))?.containsAny(config.targetSides) == false if (shouldBeCleared) { modified = true cleanMethodBody(method) } false } return if (modified) MincerResultType.MODIFIED else MincerResultType.SKIPPED } private fun deleteAnnotation(annotations: MutableList<AnnotationNode>?) : Boolean { annotations ?: return false if (!config.removeAnnotations) return false return annotations.removeIf { it.desc == config.annotation.desc() } } private fun cleanMethodBody(method: MethodNode) { val returnType = Type.getReturnType(method.desc)!!.toReference() method.exceptions = arrayListOf() method.maxLocals = 0 method.maxStack = 0 method.tryCatchBlocks = arrayListOf() method.localVariables = null method.instructions = InsnList() val appender = SimpleAppender(LocalVariablesSorter(method.access, method.desc, method)) if (returnType == ClassTypeReference(Void::class)) { appender += LoadNullInstruction(returnType) appender += ReturnSomethingInstruction(returnType) return } val kind = if (returnType is PrimitiveTypeReference) returnType.kind else null if (kind != null) { if (kind == PrimitiveKind.VOID) { appender += ReturnInstruction return } when (kind) { PrimitiveKind.BOOLEAN -> appender += BooleanLoadInstruction(false) PrimitiveKind.BYTE -> appender += ByteLoadInstruction(0) PrimitiveKind.SHORT -> appender += ShortLoadInstruction(0) PrimitiveKind.INT -> appender += IntLoadInstruction(0) PrimitiveKind.CHAR -> appender += CharLoadInstruction(0.toChar()) PrimitiveKind.LONG -> appender += LongLoadInstruction(0) PrimitiveKind.FLOAT -> appender += FloatLoadInstruction(0f) PrimitiveKind.DOUBLE -> appender += DoubleLoadInstruction(0.0) PrimitiveKind.VOID -> {} } if (returnType is ClassTypeReference) { PrimitivesAdapter.wrap(appender, kind) } appender += ReturnSomethingInstruction(returnType) } else { appender += LoadNullInstruction(returnType) appender += ReturnSomethingInstruction(returnType) } } }
0
Kotlin
0
0
016ce0d70d0a6b330d74b8f6032fc44d713f3409
5,630
cutter
MIT License
app/src/androidTest/java/com/vidyacharan/urbandictionary/TestComponentRule.kt
marzappa
206,450,479
false
null
package com.vidyacharan.urbandictionary import android.content.Context import com.vidyacharan.urbandictionary.di.component.DaggerTestComponent import com.vidyacharan.urbandictionary.di.component.TestComponent import com.vidyacharan.urbandictionary.di.module.ApplicationTestModule import org.junit.rules.TestRule import org.junit.runner.Description import org.junit.runners.model.Statement class TestComponentRule(private val context: Context) : TestRule { private var testComponent: TestComponent? = null fun getContext() = context override fun apply(base: Statement, description: Description?): Statement { return object : Statement() { @Throws(Throwable::class) override fun evaluate() { try { setupDaggerApplicationComponent() base.evaluate() } finally { testComponent = null } } } } private fun setupDaggerApplicationComponent() { val application = context.applicationContext as DictionaryApplication testComponent = DaggerTestComponent.builder() .applicationTestModule(ApplicationTestModule(application)) .build() application.setComponent(testComponent!!) } }
0
Kotlin
0
0
7c1fc82e2c489e12dd0a779ec3afc568d2ec7b10
1,304
urban-dictionary
MIT License
app/src/main/java/tech/bitcube/template/ui/user/profile/ProfileViewModel.kt
RubenBez
223,260,073
false
null
package tech.bitcube.template.ui.user.profile import tech.bitcube.template.data.network.response.user.UserUpdateDto import tech.bitcube.template.data.repository.UserRepository import tech.bitcube.template.ui.user.UserViewModel class ProfileViewModel( private val repository: UserRepository, private val userId: Int ): UserViewModel(repository, userId) { suspend fun update(user: UserUpdateDto) { repository.updateUser(user) } }
0
Kotlin
0
1
04736c77754b99f6e88799f92e149187b5957f75
458
android-template
MIT License
src/main/kotlin/cn/therouter/idea/bean/VersionBean.kt
kymjs
700,777,348
false
{"Kotlin": 74273}
package cn.therouter.idea.bean class VersionBean { var toolVersionName: String? = null var toolVersionCode = 0 var url: String? = null var latestRelease: String? = null var latestVersion: String? = null var aarVersionArray: List<String>? = null var upgradeText: String? = null }
0
Kotlin
0
9
0c407ff2d6a4a95ad5a551dc89e751ed0968c47c
307
TheRouterIdeaPlugin
Apache License 2.0
hyphenate/src/main/java/com/hyphenate/easeim/modules/view/viewholder/NotifyViewHolder.kt
AgoraIO-Community
330,886,965
false
null
package com.hyphenate.easeim.modules.view.viewholder import android.content.Context import android.view.View import android.widget.ImageView import android.widget.TextView import com.hyphenate.chat.EMCustomMessageBody import com.hyphenate.easeim.R import com.hyphenate.easeim.modules.constant.EaseConstant import com.hyphenate.easeim.modules.utils.CommonUtil import com.hyphenate.easeim.modules.view.`interface`.MessageListItemClickListener /** * 提示消息ViewhHolder */ class NotifyViewHolder(view: View, itemClickListener: MessageListItemClickListener, context: Context ) : ChatRowViewHolder(view, itemClickListener, context) { val content: TextView = itemView.findViewById(R.id.notify_content) override fun onSetUpView() { val body = message.body as EMCustomMessageBody when(body.params[EaseConstant.OPERATION]){ EaseConstant.SET_ALL_MUTE -> { content.text = context.getString(R.string.muted_all) } EaseConstant.REMOVE_ALL_MUTE -> { content.text = context.getString(R.string.cancel_muted_all) } EaseConstant.DEL -> { content.text = String.format(context.getString(R.string.remove_message_notify), message.getStringAttribute(EaseConstant.NICK_NAME)) } EaseConstant.MUTE -> { content.text = String.format(context.getString(R.string.you_have_been_muted_by_teacher), message.getStringAttribute(EaseConstant.NICK_NAME)) } EaseConstant.UN_MUTE -> { content.text = String.format(context.getString(R.string.you_have_been_unmuted_by_teacher), message.getStringAttribute(EaseConstant.NICK_NAME)) } } } }
1
Kotlin
15
8
57902c698c876c7805faf8bd6272308cf5f97817
1,777
CloudClass-Android
MIT License
app/src/main/java/com/judahben149/fourthwall/FourthWallApplication.kt
judahben149
850,814,605
false
{"Kotlin": 286081}
package com.judahben149.fourthwall import android.app.Application import dagger.hilt.android.HiltAndroidApp import timber.log.Timber @HiltAndroidApp class FourthWallApplication: Application() { override fun onCreate() { super.onCreate() Timber.plant(Timber.DebugTree()) } }
0
Kotlin
0
0
90513585b7b89ea00b35a19a4b89c2a726187b18
301
FourthWall
MIT License
src/main/kotlin/klay/core/Tile.kt
cdietze
89,875,388
false
null
package klay.core import euklid.f.AffineTransform import euklid.f.Points import react.RFuture /** * Represents a square region of a texture. This makes it easy to render tiles from texture * atlases. */ abstract class Tile : TileSource { /** The texture which contains this tile. */ abstract val texture: Texture /** The width of this tile (in display units). */ abstract val width: Float /** The height of this tile (in display units). */ abstract val height: Float /** Returns the `s` texture coordinate for the x-axis. */ abstract val sx: Float /** Returns the `s` texture coordinate for the y-axis. */ abstract val sy: Float /** Returns the `t` texture coordinate for the x-axis. */ abstract val tx: Float /** Returns the `t` texture coordinate for the y-axis. */ abstract val ty: Float override val isLoaded: Boolean get() = true /** Adds this tile to the supplied quad batch. */ abstract fun addToBatch(batch: QuadBatch, tint: Int, tx: AffineTransform, x: Float, y: Float, width: Float, height: Float) /** Adds this tile to the supplied quad batch. */ abstract fun addToBatch(batch: QuadBatch, tint: Int, tx: AffineTransform, dx: Float, dy: Float, dw: Float, dh: Float, sx: Float, sy: Float, sw: Float, sh: Float) override fun tile(): Tile { return this } override fun tileAsync(): RFuture<Tile> { return RFuture.success(this) } override fun toString(): String { return "Tile[" + width + "x" + height + "/" + Points.pointToString(sx, sy) + "/" + Points.pointToString(tx, ty) + "] <- " + texture } }
0
Kotlin
0
4
72031aa267cd304a0612b31c871e2f5cf73d2c4c
1,780
klay
Apache License 2.0
app/src/main/java/com/kkt/dietadvisor/LoginActivity.kt
BT3X
830,543,512
false
{"Kotlin": 166018}
package com.kkt.dietadvisor import android.content.Intent import android.net.Uri import android.os.Bundle import android.text.SpannableString import android.text.Spanned import android.text.method.LinkMovementMethod import android.text.style.ClickableSpan import android.text.style.ForegroundColorSpan import android.text.style.UnderlineSpan import android.util.Log import android.view.View import android.widget.LinearLayout import android.widget.TextView import android.widget.Toast import androidx.activity.enableEdgeToEdge import androidx.activity.result.ActivityResult import androidx.activity.result.ActivityResultLauncher import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.kkt.dietadvisor.utility.AuthStateUtil import com.kkt.dietadvisor.utility.TokenStateUtil import com.kkt.dietadvisor.utility.UserInfoUtil import net.openid.appauth.AuthState import net.openid.appauth.AuthorizationException import net.openid.appauth.AuthorizationRequest import net.openid.appauth.AuthorizationResponse import net.openid.appauth.AuthorizationService import net.openid.appauth.AuthorizationServiceConfiguration import net.openid.appauth.ResponseTypeValues import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor class LoginActivity : AppCompatActivity() { private lateinit var authService: AuthorizationService private lateinit var authState: AuthState private lateinit var authorizationLauncher: ActivityResultLauncher<Intent> private val client: OkHttpClient by lazy { val logging = HttpLoggingInterceptor() logging.setLevel(HttpLoggingInterceptor.Level.BODY) OkHttpClient.Builder() .addInterceptor(logging) .build() } override fun onCreate(savedInstanceState: Bundle?) { supportActionBar?.hide() super.onCreate(savedInstanceState) enableEdgeToEdge() setContentView(R.layout.activity_login) ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } // Initialize AuthorizationService & AuthState authService = AuthorizationService(this) authState = AuthStateUtil.readAuthState(this) // Attempt silent login attemptSilentLogin() // Initialize the authorizationLauncher authorizationLauncher = registerForActivityResult( ActivityResultContracts.StartActivityForResult() ) { activityResult -> Log.d(TAG, "Activity Result Code: $activityResult") if (activityResult.resultCode == RESULT_OK) { handleAuthorizationResult(activityResult) } else { Log.e("Authorization", "Authorization failed or was cancelled.") } } /* Init views */ val signUpTextView = findViewById<TextView>(R.id.sign_up_request) signUpRequest(signUpTextView) val signIn = findViewById<LinearLayout>(R.id.sign_in_google) signIn.setOnClickListener { // Check if auth state is valid and has a valid access token if (authState.isAuthorized) { // Check if access token is expired and renew if necessary TokenStateUtil.checkAndRenewAccessToken(this, authState, authService) { _ -> // AuthState should have a valid access token val accessToken = authState.accessToken accessToken?.let { Log.d(TAG, "Access Token: $accessToken") // Check if user exists using the existing access token UserInfoUtil.getUserInfo(this, accessToken, client) { userExists, _ -> if (userExists) { // User exists -> Move to homepage runOnUiThread { Log.d(TAG, "User Exists, Signing In...") Toast.makeText(this, "Welcome back!", Toast.LENGTH_SHORT).show() startActivity(Intent(this, HomePage::class.java)) finish() // Prevent back navigation to login screen } } else { // User does not exist -> Move to sign-up screen runOnUiThread { Log.d(TAG, "User Not Found, Prompting Sign-up...") Toast.makeText(this, "Please sign up!", Toast.LENGTH_SHORT).show() startActivity(Intent(this, SignUpwithOAuth::class.java)) } } } } } } else { // AuthState is invalid or access token is null. Perform authorization request launchAuthorizationRequest() } } } override fun onDestroy() { super.onDestroy() // Dispose of the AuthorizationService to prevent leaks authService.dispose() } private fun launchAuthorizationRequest() { val serviceConfig = AuthorizationServiceConfiguration( Uri.parse(getString(R.string.GOOGLE_AUTHORIZATION_ENDPOINT)), // Authorization endpoint Uri.parse(getString(R.string.GOOGLE_TOKEN_ENDPOINT)) // Token endpoint ) val authRequest = AuthorizationRequest.Builder( serviceConfig, getString(R.string.ANDROID_CLIENT_ID), // Android Client ID ResponseTypeValues.CODE, Uri.parse(getString(R.string.GOOGLE_REDIRECT_URI)) // Redirect URI ) .setScopes("openid", "profile", "email") .build() val intent = authService.getAuthorizationRequestIntent(authRequest) authorizationLauncher.launch(intent) } private fun handleAuthorizationResult(authorizationResult: ActivityResult) { val data = authorizationResult.data val authResponse = data?.let { AuthorizationResponse.fromIntent(it) } val authException = data?.let { AuthorizationException.fromIntent(it) } authResponse?.let { val tokenRequest = authResponse.createTokenExchangeRequest() authService.performTokenRequest(tokenRequest) { tokenResponse, tokenException -> tokenResponse?.let { val accessToken = tokenResponse.accessToken val refreshToken = tokenResponse.refreshToken Log.i(TAG, "Access token: $accessToken") Log.i(TAG, "Refresh token: $refreshToken") // Update Auth state and save refresh token authState.update(tokenResponse, tokenException) AuthStateUtil.writeAuthState(this, authState) TokenStateUtil.saveRefreshToken(this, refreshToken) // Use the access token to get the user info from the backend accessToken?.let { UserInfoUtil.getUserInfo(this, accessToken, client) { userExists, _ -> if (userExists) { // User exists -> Move to home page runOnUiThread { Toast.makeText(this, "Welcome back to Diet Advisor!", Toast.LENGTH_SHORT).show() startActivity(Intent(this, HomePage::class.java)) finish() // Prevent navigation back to login screen } } else { // User doesn't exist -> Move to sign up screen runOnUiThread { Log.d(TAG, "Creating User Now") Toast.makeText(this, "Please create an account!", Toast.LENGTH_SHORT).show() startActivity(Intent(this, SignUpwithOAuth::class.java)) } } } } ?: Log.e(TAG, "Unable to retrieve access token") } ?: Log.e(TAG, "Token exchange failed: ${tokenException?.message}") } } ?: run { authException?.let { Log.e(TAG, "Authorization failed: ${authException.message}") } } } private fun attemptSilentLogin() { // Check if we have a saved refresh token val savedRefreshToken = TokenStateUtil.getRefreshToken(this) savedRefreshToken?.let { Log.d(TAG, "Attempting silent login using saved refresh token...") TokenStateUtil.checkAndRenewAccessToken(this, authState, authService) { _ -> val accessToken = authState.accessToken accessToken?.let { Log.d(TAG, "Silent Login Success! Access Token: $accessToken") UserInfoUtil.getUserInfo(this, accessToken, client) { userExists, _ -> if (userExists) { runOnUiThread { Log.d(TAG, "User Exists!. Signing in...") Toast.makeText(this, "Logging In", Toast.LENGTH_SHORT).show() startActivity(Intent(this, HomePage::class.java )) finish() // Prevent back navigation to the login screen } } } } } } ?: Log.d(TAG, "Silent Login Failed! No stored refresh token") } private fun signUpRequest(signUpTextView: TextView) { val text = "Not a member? Sign up now!" val spannableString = SpannableString(text) val clickableSpan = object : ClickableSpan() { override fun onClick(widget: View) { // Just move to the sign-up screen val intent = Intent(this@LoginActivity, SignUpwithOAuth::class.java) widget.context.startActivity(intent) } } val startIndex = text.indexOf("Sign up now!") val endIndex = startIndex + "Sign up now!".length spannableString.setSpan( clickableSpan, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) val colorSpan = ForegroundColorSpan(ContextCompat.getColor(this, R.color.greenText)) spannableString.setSpan(colorSpan, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) val underlineSpan = UnderlineSpan() spannableString.setSpan( underlineSpan, startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) signUpTextView.text = spannableString signUpTextView.movementMethod = LinkMovementMethod.getInstance() } companion object { const val TAG: String = "LoginActivity" } }
0
Kotlin
0
1
f89b5039ecea60c26999e56458da17cd02e02f96
11,500
DietAdvisor
MIT License
rm_10/src/main/java/com/example/rm_10/BluetoothConstants.kt
TurdubekovAli
728,393,228
false
{"Kotlin": 15840, "Java": 9956}
package com.example.rm_10 object BluetoothConstants { const val PREFERENCES = "main_preferences" const val MAC = "mac" }
0
Kotlin
0
0
ddd4f98fb678e85d3db4fa79d24ab453edd6d3bb
129
rm_10
The Unlicense
mailbox-lib/src/main/java/org/briarproject/mailbox/system/TestSystemModule.kt
briar
639,349,226
false
{"Kotlin": 403807, "Java": 85810, "Shell": 1362, "Dockerfile": 362}
package org.briarproject.mailbox.system import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import org.briarproject.mailbox.core.system.System import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) internal class TestSystemModule { @Singleton @Provides fun provideSystem(system: TestSystem): System = system @Singleton @Provides fun provideTestSystem(): TestSystem = TestSystem() }
1
Kotlin
2
4
5b4fa2fb8f0b09a7caba90c6f95278d7627a95d2
502
briar-mailbox
Apache License 2.0
app/src/main/java/com/cjmobileapps/quidditchplayersandroid/hilt/module/CoroutinesModule.kt
CJMobileApps
750,394,460
false
{"Kotlin": 195996}
package com.cjmobileapps.quidditchplayersandroid.hilt.module import com.cjmobileapps.quidditchplayersandroid.util.coroutine.CoroutineDispatchers import com.cjmobileapps.quidditchplayersandroid.util.coroutine.CoroutineDispatchersImpl import com.cjmobileapps.quidditchplayersandroid.util.time.TimeUtil import com.cjmobileapps.quidditchplayersandroid.util.time.TimeUtilImpl import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module class CoroutinesModule { @Singleton @Provides fun coroutinesDispatchers(): CoroutineDispatchers { return CoroutineDispatchersImpl } @Singleton @Provides fun timeUtil(): TimeUtil = TimeUtilImpl }
0
Kotlin
0
0
7c9cc15409c43a9b2057a96100a2c91e4f629478
803
quidditch-players-android-2023
MIT License
app/src/main/java/com/example/amonic/classes/SingletoneForRequests.kt
AMONIC-Airlines
596,846,140
false
null
package com.example.amonic.classes import android.content.Context import com.android.volley.Request import com.android.volley.RequestQueue import com.android.volley.toolbox.Volley class SingletoneForRequests constructor(context: Context) { companion object { @Volatile private var INSTANCE: SingletoneForRequests? = null fun getInstance(context: Context) = INSTANCE ?: synchronized(this) { INSTANCE ?: SingletoneForRequests(context).also { INSTANCE = it } } } val requestQueue: RequestQueue by lazy { Volley.newRequestQueue(context.applicationContext) } fun <T> addToRequestQueue(req: Request<T>) { requestQueue.add(req) } }
0
Kotlin
1
0
96f557187c9cd566c9ab65eb0764fe1836cf51b7
766
android_app_amonic
Apache License 2.0
app/src/main/java/me/tartikov/map/app/HomeScreen.kt
t-artikov
466,374,937
false
{"Kotlin": 51445}
package me.tartikov.map.app import androidx.compose.foundation.layout.* import androidx.compose.material.Button import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp @Composable fun HomeScreen() { val screens = listOf( Screen("Hello world") { HelloWorldScreen() }, Screen("Drag") { DragScreen() }, Screen("Animation") { AnimationScreen() }, Screen("Overlay") { OverlayScreen() }, Screen("Camera") { CameraScreen() }, Screen("Zoom Dependent") { ZoomDependentScreen() }, Screen("Clustering") { ClusteringScreen() }, ) val router = LocalRouter.current Box(modifier = Modifier.fillMaxSize()) { Column( modifier = Modifier .width(IntrinsicSize.Max) .align(Alignment.Center) ) { screens.forEach { Button( onClick = { router.goTo(it) }, modifier = Modifier .padding(2.dp) .fillMaxWidth() ) { Text(it.name) } } } } }
0
Kotlin
0
2
a6be05538c48938b29f4f672775d27f912219163
1,270
compose-map
MIT License
src/main/kotlin/me/moe/logbot/listeners/MemberListener.kt
the-programmers-hangout
259,049,943
false
null
package me.moe.logbot.listeners import com.google.common.eventbus.Subscribe import me.moe.logbot.data.Configuration import me.moe.logbot.services.LoggingService import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent class MemberListener(private val configuration: Configuration, private val logger: LoggingService) { @Subscribe fun onMemberJoin(event: GuildMemberJoinEvent) { if (configuration.isTrackingMembers(event.guild.id)) logger.buildMemberJoinEmbed(event) } @Subscribe fun onMemberLeave(event: GuildMemberRemoveEvent) { if (event.guild.retrieveBanList().complete().any { it.user.id == event.user.id }) { if (configuration.isTrackingBans(event.guild.id)) logger.buildMemberBanEmbed(event) } else { if (configuration.isTrackingMembers(event.guild.id)) logger.buildMemberLeaveEmbed(event) } } }
0
Kotlin
0
3
b38a27c4fc7ed4c9ec1be25b3a9664a8b316ee93
1,011
LogBot-archived
MIT License
server/src/main/kotlin/uk/tvidal/kraft/engine/RaftRole.kt
tvidal-net
99,751,401
false
null
package uk.tvidal.kraft.engine import uk.tvidal.kraft.logging.KRaftLogger import uk.tvidal.kraft.message.raft.AppendAckMessage import uk.tvidal.kraft.message.raft.AppendMessage import uk.tvidal.kraft.message.raft.RaftMessage import uk.tvidal.kraft.message.raft.RequestVoteMessage import uk.tvidal.kraft.message.raft.VoteMessage enum class RaftRole { FOLLOWER { override fun work(now: Long, raft: RaftEngine): RaftRole? = raft.checkElectionTimeout(now) override fun enterRole(now: Long, raft: RaftEngine) { raft.resetElectionTimeout(now) } override fun exitRole(now: Long, raft: RaftEngine) { raft.resetLeader() } override fun append(now: Long, msg: AppendMessage, raft: RaftEngine): RaftRole? { raft.appendEntries(now, msg) return null } override fun requestVote(now: Long, msg: RequestVoteMessage, raft: RaftEngine): RaftRole? { raft.processRequestVote(now, msg) return null } }, CANDIDATE { override fun work(now: Long, raft: RaftEngine): RaftRole? = raft.checkElectionTimeout(now) override fun enterRole(now: Long, raft: RaftEngine) { raft.startElection(now) } override fun requestVote(now: Long, msg: RequestVoteMessage, raft: RaftEngine): RaftRole? = reset() override fun vote(now: Long, msg: VoteMessage, raft: RaftEngine) = raft.processVote(msg) override fun append(now: Long, msg: AppendMessage, raft: RaftEngine) = reset() }, LEADER { override fun work(now: Long, raft: RaftEngine): RaftRole? { raft.heartbeatFollowers(now) return null } override fun enterRole(now: Long, raft: RaftEngine) { raft.becomeLeader() } override fun exitRole(now: Long, raft: RaftEngine) { raft.resetLeader() } override fun appendAck(now: Long, msg: AppendAckMessage, raft: RaftEngine): RaftRole? { raft.processAck(msg) return null } }, ERROR { override fun reset(): RaftRole? = null override fun enterRole(now: Long, raft: RaftEngine) { raft.cancelElectionTimeout() } }; @Suppress("LeakingThis") protected val log = KRaftLogger(this) protected open fun reset(): RaftRole? = FOLLOWER internal open fun work(now: Long, raft: RaftEngine): RaftRole? = null internal fun enter(now: Long, raft: RaftEngine) { log.info { "[${raft.self}] Enter $name T${raft.term}" } enterRole(now, raft) } internal open fun enterRole(now: Long, raft: RaftEngine) {} internal fun exit(now: Long, raft: RaftEngine) { raft.resetElection() exitRole(now, raft) } internal open fun exitRole(now: Long, raft: RaftEngine) {} internal open fun append(now: Long, msg: AppendMessage, raft: RaftEngine): RaftRole? = null internal open fun appendAck(now: Long, msg: AppendAckMessage, raft: RaftEngine): RaftRole? = null internal open fun requestVote(now: Long, msg: RequestVoteMessage, raft: RaftEngine): RaftRole? = null internal open fun vote(now: Long, msg: VoteMessage, raft: RaftEngine): RaftRole? = null private fun processMessage(now: Long, msg: RaftMessage, raft: RaftEngine): RaftRole? = when (msg) { is AppendMessage -> append(now, msg, raft) is AppendAckMessage -> appendAck(now, msg, raft) is RequestVoteMessage -> requestVote(now, msg, raft) is VoteMessage -> vote(now, msg, raft) else -> null } internal fun process(now: Long, msg: RaftMessage, raft: RaftEngine): RaftRole? = when { // There's a new term on the cluster, reset back to follower msg.term > raft.term -> { raft.updateTerm(msg.term) reset() } // We're in the right term, just process it raft.term == msg.term -> { log.trace { "[${raft.self}] process $msg" } processMessage(now, msg, raft) } else -> null } }
1
Kotlin
0
0
9cfca67330b27c1f2f834dc430d3a369d2538255
4,161
kraft
MIT License
src/main/kotlin/io/mverse/kslack/api/methods/response/groups/GroupsCloseResponse.kt
mverse
161,946,116
true
{"Kotlin": 403852}
package io.mverse.kslack.api.methods.response.groups import io.mverse.kslack.api.methods.SlackApiResponse data class GroupsCloseResponse ( override val ok: Boolean = false, override val warning: String? = null, override val error: String? = null, val isNoOp: Boolean = false, val isAlreadyClosed: Boolean = false): SlackApiResponse
0
Kotlin
0
0
9ebf1dc13f6a3d89a03af11a83074a4d636cb071
355
jslack
MIT License
app/src/main/java/xyz/harmonyapp/olympusblog/utils/DataChannelManager.kt
sentrionic
351,882,310
false
null
package xyz.harmonyapp.olympusblog.utils import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.cancel import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.onEach import kotlinx.coroutines.isActive import kotlinx.coroutines.withContext abstract class DataChannelManager<ViewState> { private val TAG: String = "AppDebug" private val _activeStateEvents: HashSet<String> = HashSet() private val _numActiveJobs: MutableLiveData<Int> = MutableLiveData() private var channelScope: CoroutineScope? = null val messageStack = MessageStack() val numActiveJobs: LiveData<Int> get() = _numActiveJobs fun setupChannel() { cancelJobs() setupNewChannelScope(CoroutineScope(IO)) } abstract fun handleNewData(data: ViewState) fun launchJob( stateEvent: StateEvent, jobFunction: Flow<DataState<ViewState>?> ) { if (!isStateEventActive(stateEvent) && messageStack.size == 0) { addStateEvent(stateEvent) jobFunction .onEach { dataState -> withContext(Main) { dataState?.data?.let { data -> handleNewData(data) } dataState?.stateMessage?.let { stateMessage -> handleNewStateMessage(stateMessage) } dataState?.stateEvent?.let { stateEvent -> removeStateEvent(stateEvent) } } } .launchIn(getChannelScope()) } } private fun handleNewStateMessage(stateMessage: StateMessage) { appendStateMessage(stateMessage) } private fun appendStateMessage(stateMessage: StateMessage) { messageStack.add(stateMessage) } fun clearStateMessage(index: Int = 0) { messageStack.removeAt(index) } private fun clearActiveStateEventCounter() { _activeStateEvents.clear() syncNumActiveStateEvents() } private fun addStateEvent(stateEvent: StateEvent) { _activeStateEvents.add(stateEvent.toString()) syncNumActiveStateEvents() } private fun removeStateEvent(stateEvent: StateEvent?) { _activeStateEvents.remove(stateEvent.toString()) syncNumActiveStateEvents() } fun isJobAlreadyActive(stateEvent: StateEvent): Boolean { return isStateEventActive(stateEvent) } private fun isStateEventActive(stateEvent: StateEvent): Boolean { return _activeStateEvents.contains(stateEvent.toString()) } fun getChannelScope(): CoroutineScope { return channelScope ?: setupNewChannelScope(CoroutineScope(IO)) } private fun setupNewChannelScope(coroutineScope: CoroutineScope): CoroutineScope { channelScope = coroutineScope return channelScope as CoroutineScope } fun cancelJobs() { if (channelScope != null) { if (channelScope?.isActive == true) { channelScope?.cancel() } channelScope = null } clearActiveStateEventCounter() } private fun syncNumActiveStateEvents() { _numActiveJobs.value = _activeStateEvents.size } }
0
Kotlin
0
0
3b784bf9dd60f6cc6889813f2e2932fa3a9b211d
3,538
OlympusAndroid
MIT License
app/src/main/java/com/novatech/zmailclone/components/HomeAppBar.kt
novjean
818,703,051
false
{"Kotlin": 14107}
package com.novatech.zmailclone.components import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.requiredHeight import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Menu import androidx.compose.material3.Card import androidx.compose.material3.CardDefaults import androidx.compose.material3.DrawerState import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.novatech.gmailclone.R import com.novatech.zmailclone.ZmailApp import com.novatech.zmailclone.ui.theme.ZmailCloneTheme import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @Composable fun HomeAppBar(drawerState: DrawerState, scope: CoroutineScope) { Box(modifier = Modifier.padding(10.dp)) { Card( modifier = Modifier.requiredHeight(50.dp), shape = RoundedCornerShape(10.dp), elevation = CardDefaults.cardElevation( defaultElevation = 6.dp ) ) { Row( verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxSize() .padding(8.dp) ) { IconButton( onClick = { scope.launch { drawerState.open() } }) { Icon(Icons.Default.Menu, "Menu") } Text( text = "Search in emails", modifier = Modifier.weight(2.0f) // this will cause it to take more of the available space ) Image( painter = painterResource(id = R.drawable.tutorials), contentDescription = "Profile", modifier = Modifier .size(30.dp) .clip(CircleShape) .background( color = Color.Gray ) ) } } } } @Preview @Composable fun DefaultPreview() { ZmailCloneTheme { ZmailApp() } }
0
Kotlin
0
0
e7a0ed384bd0f29d7131f93c7a04168f000ffbc5
2,979
Zap-Mail
MIT License
spring-boot-image/src/main/kotlin/cz/petrbalat/klib/spring/image/FtpImageService.kt
petrbalat
228,852,482
false
null
package cz.petrbalat.klib.spring.image import cz.petrbalat.klib.ftp.use import cz.petrbalat.klib.jdk.tryOrNull import cz.petrbalat.klib.spring.image.cwebp.convertToWebP import cz.petrbalat.klib.spring.image.image.ReadImageDto import cz.petrbalat.klib.spring.image.image.readImageDto import cz.petrbalat.klib.spring.image.image.resizeImageIfGreaterThan import cz.petrbalat.klib.spring.image.image.toByteArray import org.apache.commons.net.ftp.FTP import org.apache.commons.net.ftp.FTPClient import org.imgscalr.Scalr import org.slf4j.LoggerFactory import java.awt.image.BufferedImage import java.io.ByteArrayInputStream import java.io.InputStream class FtpImageService( private val host: String, private val user: String, private val password: String, override val baseUrl: String, ) : ImageService { private val logger = LoggerFactory.getLogger(javaClass) override suspend fun uploadImage( stream: InputStream, name: String, directory: String, override: Boolean, maxPx: Int, mode: Scalr.Mode ): ImageDto { val bytes = stream.readBytes() val dto: ReadImageDto = ByteArrayInputStream(bytes).readImageDto(name) val fileName = dto.name val webFileName = "${dto.nameWithoutExtension}.webp" //convert to webp val image: BufferedImage? = dto.image.resizeImageIfGreaterThan(maxPx, mode) val imageArray = image?.toByteArray(dto.extension) ?: bytes val webpByteArray = dto.image.convertToWebP() // upload origin useFtpClient(directory) { client -> if (override) { tryOrNull { client.deleteFile(fileName) } tryOrNull { client.deleteFile(webFileName) } } //upload origin image client.storeFile(fileName, ByteArrayInputStream(imageArray)) client.storeFile(webFileName, ByteArrayInputStream(webpByteArray)) } val baseUrl = "$baseUrl/$directory" return ImageDto("$baseUrl/$fileName", webpUrl = "$baseUrl/$webFileName") } override suspend fun upload(stream: InputStream, name: String, directory: String, override: Boolean): String { useFtpClient(directory) { client -> directory.split("/").forEach { dir -> logger.info("makeDirectory ${client.makeDirectory(dir)}") val changeDir = client.changeWorkingDirectory(dir) logger.info("Change directory $dir $changeDir") } if (override) { tryOrNull { client.deleteFile(name) } } stream.use { client.storeFile(name, it) } } return "$baseUrl/$directory/$name" } override suspend fun toWebpAndUploadImage( stream: InputStream, name: String, directory: String, override: Boolean ): String { val dto: ReadImageDto = stream.readImageDto(name) val webFileName = "${dto.nameWithoutExtension}.webp" //convert to webp val webpByteArray = dto.image.convertToWebP() // upload origin useFtpClient(directory) { client -> if (override) { tryOrNull { client.deleteFile(webFileName) } } //upload origin image client.storeFile(webFileName, ByteArrayInputStream(webpByteArray)) } return upload(stream, name, directory, override) } private fun useFtpClient(directory: String? = null, block: (FTPClient) -> Unit) { FTPClient().use(logger, hostname = host, user = user, password = <PASSWORD>, fileType = FTP.BINARY_FILE_TYPE) { it.changeWorkingDirectory("www") if (directory != null) { logger.info("makeDirectory ${it.makeDirectory(directory)}") val dir = it.changeWorkingDirectory(directory) logger.info("Change directory $directory $dir") } block(it) } } }
0
Kotlin
0
2
647d9daa241cfc751788e11b1ab84310fe998990
4,184
klib
MIT License
rpgJavaInterpreter-core/src/test/kotlin/com/smeup/rpgparser/db/sql/DBSQLTest.kt
BezouwenR
227,047,172
false
null
package com.smeup.rpgparser.db.sql import com.smeup.rpgparser.interpreter.* import org.junit.Test import java.math.BigDecimal import kotlin.test.* class DBSQLTest { @Test fun dbSQLSmokeTest() { connectionForTest() } @Test fun dbMetaDataTest() { val tableName = "TSTTAB01" val formatName = "TSTRECF" val fields = listOf( "TSTFLDCHR" withType StringType(5), "TSTFLDNBR" withType NumberType(5, 2)) val fileMetadata = FileMetadata(tableName, formatName, fields) val db = connectionForTest(listOf(fileMetadata)) val metadata = db.metadataOf(tableName) assertNotNull(metadata) assertEquals(tableName, metadata.tableName) assertEquals(formatName, metadata.formatName) assertEquals(fields.size, metadata.fields.size) assertEquals(fields, metadata.fields) } @Test fun dbChainTest() { val tableName = "TSTTAB02" val formatName = "TSTRECF" val fields = listOf( "TSTFLDCHR" primaryKeyWithType StringType(3), "TSTFLDNBR" withType NumberType(5, 2)) val bigDecimalValue = BigDecimal("123.45").setScale(2) val fileMetadata = FileMetadata(tableName, formatName, fields) val db = connectionForTest(listOf(fileMetadata)) val values: List<Pair<String, Value>> = listOf( "TSTFLDCHR" to StringValue("XXX"), "TSTFLDNBR" to DecimalValue(bigDecimalValue)) db.insertRow(tableName, values) val dbFile = db.open(tableName) assertTrue(dbFile!!.chain(StringValue("ABC")).isEmpty()) val chainedRecord = dbFile.chain(StringValue("XXX")) assertEquals(2, chainedRecord.size) val fieldsIterator = chainedRecord.iterator() assertEquals(StringValue("XXX"), fieldsIterator.next().value) assertEquals(DecimalValue(bigDecimalValue), fieldsIterator.next().value) } }
0
null
0
1
fe6e72c95b3ee7280c3a39b4370d505fc4905a7f
1,983
jariko
Apache License 2.0
composeApp/src/commonMain/kotlin/com/revenuecat/purchases/kmp/sample/MainScreen.kt
RevenueCat
758,647,648
false
{"Kotlin": 391318, "Ruby": 17650, "Swift": 594}
package com.revenuecat.purchases.kmp.sample import androidx.compose.animation.AnimatedContent import androidx.compose.foundation.background import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer 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.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.Button import androidx.compose.material.LocalTextStyle import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.TextField import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.State import androidx.compose.runtime.collectAsState import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import arrow.core.Either import com.revenuecat.purchases.kmp.Purchases import com.revenuecat.purchases.kmp.PurchasesConfiguration import com.revenuecat.purchases.kmp.PurchasesDelegate import com.revenuecat.purchases.kmp.either.awaitOfferingsEither import com.revenuecat.purchases.kmp.ktx.awaitCustomerInfo import com.revenuecat.purchases.kmp.models.CustomerInfo import com.revenuecat.purchases.kmp.models.Offering import com.revenuecat.purchases.kmp.models.Offerings import com.revenuecat.purchases.kmp.models.PurchasesError import com.revenuecat.purchases.kmp.models.StoreProduct import com.revenuecat.purchases.kmp.models.StoreTransaction import com.revenuecat.purchases.kmp.sample.components.CustomerInfoSection import com.revenuecat.purchases.kmp.sample.components.OfferingsSection import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.channels.trySendBlocking import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.flow.onStart @Composable fun MainScreen( onShowPaywallClick: (offering: Offering?, footer: Boolean) -> Unit, modifier: Modifier = Modifier ) { Column( modifier = modifier .verticalScroll(state = rememberScrollState()) .padding(all = 16.dp) ) { var isConfigured by remember { mutableStateOf(Purchases.isConfigured) } AnimatedContent(targetState = isConfigured) { configured -> if (!configured) Column { Text( text = "Configuration", modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, style = MaterialTheme.typography.h6, ) Spacer(modifier = Modifier.size(8.dp)) var configuration by remember { mutableStateOf( Configuration(apiKey = BuildKonfig.apiKey, userId = BuildKonfig.appUserId) ) } ConfigurationSettings( configuration = configuration, onConfigurationChanged = { configuration = it }, modifier = Modifier.fillMaxWidth() ) Spacer(modifier = Modifier.size(8.dp)) Button( onClick = { Purchases.configure(configuration.toPurchasesConfiguration()) isConfigured = Purchases.isConfigured }, modifier = Modifier.align(Alignment.CenterHorizontally), enabled = configuration.userId.isNotBlank() && configuration.apiKey.isNotBlank(), ) { Text("Configure") } Spacer(modifier = Modifier.size(16.dp)) ConfigurationTip(modifier = Modifier.fillMaxWidth()) } else Column { var offeringsState: AsyncState<Offerings> by remember { mutableStateOf(AsyncState.Loading) } LaunchedEffect(Unit) { offeringsState = when (val offerings = Purchases.sharedInstance.awaitOfferingsEither()) { is Either.Left -> AsyncState.Error is Either.Right -> AsyncState.Loaded(offerings.value) } } val customerInfo by Purchases.sharedInstance.rememberCustomerInfoState() val customerInfoState by remember { derivedStateOf { customerInfo?.let { AsyncState.Loaded(it) } ?: AsyncState.Loading } } Spacer(modifier = Modifier.size(16.dp)) Text( text = "CustomerInfo", modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, style = MaterialTheme.typography.h6, ) Spacer(modifier = Modifier.size(8.dp)) CustomerInfoSection( state = customerInfoState, modifier = Modifier.fillMaxWidth(), ) Spacer(modifier = Modifier.size(16.dp)) Text( text = "Offerings", modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, style = MaterialTheme.typography.h6, ) Spacer(modifier = Modifier.size(8.dp)) OfferingsSection( state = offeringsState, onShowPaywallClick = onShowPaywallClick, modifier = Modifier.fillMaxWidth(), ) } } } } @Composable private fun ConfigurationSettings( configuration: Configuration, onConfigurationChanged: (Configuration) -> Unit, modifier: Modifier = Modifier, ) { Column(modifier) { Text( text = "API key", modifier = Modifier.fillMaxWidth() ) TextField( value = configuration.apiKey, onValueChange = { onConfigurationChanged(configuration.copy(apiKey = it)) }, modifier = Modifier.fillMaxWidth(), textStyle = LocalTextStyle.current.copy(fontFamily = FontFamily.Monospace) ) Spacer(modifier = Modifier.size(DefaultSpacingVertical)) Text( text = "user ID", modifier = Modifier.fillMaxWidth() ) TextField( value = configuration.userId, onValueChange = { onConfigurationChanged(configuration.copy(userId = it)) }, modifier = Modifier.fillMaxWidth(), textStyle = LocalTextStyle.current.copy(fontFamily = FontFamily.Monospace) ) } } @Composable private fun ConfigurationTip(modifier: Modifier = Modifier) { Column( modifier = modifier .background( color = Color.Green.copy(alpha = 0.1f), shape = RoundedCornerShape(size = 16.dp) ) .padding(horizontal = 16.dp, vertical = 8.dp) ) { Text(text = "Tip: you can configure these values in your local.properties file using the following keys:") Spacer(modifier = Modifier.size(4.dp)) Text(text = "revenuecat.apiKey.google", fontFamily = FontFamily.Monospace) Text(text = "revenuecat.apiKey.apple", fontFamily = FontFamily.Monospace) Text(text = "revenuecat.appUserId", fontFamily = FontFamily.Monospace) } } private data class Configuration(val apiKey: String, val userId: String) { fun toPurchasesConfiguration(builder: PurchasesConfiguration.Builder.() -> Unit = { }) = PurchasesConfiguration(apiKey) { appUserId = userId apply(builder) } } private val Purchases.customerInfoFlow: Flow<CustomerInfo> get() = callbackFlow { delegate = object : PurchasesDelegate { override fun onPurchasePromoProduct( product: StoreProduct, startPurchase: (onError: (error: PurchasesError, userCancelled: Boolean) -> Unit, onSuccess: (storeTransaction: StoreTransaction, customerInfo: CustomerInfo) -> Unit) -> Unit ) { // Not implemented } override fun onCustomerInfoUpdated(customerInfo: CustomerInfo) { trySendBlocking(customerInfo) } } awaitClose { delegate = null } }.onStart { emit(awaitCustomerInfo()) } @Composable private fun Purchases.rememberCustomerInfoState(): State<CustomerInfo?> = remember { customerInfoFlow }.collectAsState(initial = null)
6
Kotlin
3
88
af9d4f70c0af9a7a346f56dcf34d1ca621c41297
9,214
purchases-kmp
MIT License
src/main/kotlin/de/doctari/kotlinTutorial/kotlinxSerialization/slide_09.kt
doctariDev
454,115,767
false
{"Kotlin": 104723}
@file:Suppress("unused", "MemberVisibilityCanBePrivate") package de.doctari.kotlinTutorial.kotlinxSerialization import kotlinx.serialization.Serializable import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString import kotlinx.serialization.json.Json /* ************************************************************************************** * ************************************************************************************** * * ᐅ default values are not encoded (by default) * ᐅ properties with default values are optional when decoding * * ************************************************************************************** * ************************************************************************************** */ @Serializable class Dog09(val name: String, val age: Int = 5) fun main() { val dog1 = Dog09("Spark") println("Our dog's age is ${dog1.age}") val json = Json.encodeToString(dog1) println("""After encoding, the age is not present in json $json """) val dog2: Dog09 = Json.decodeFromString(json) println("""After decoding from a json with missing age property, the default value will be used: ${dog2.age} """) // This will throw an error because name does not have a default: // val dog3: Dog09 = Json.decodeFromString("""{"age": 10}""") }
0
Kotlin
0
1
00594b25490c54d75e0496dd58078a24fc5da3cc
1,351
kotlin-tutorials
Apache License 2.0
src/main/kotlin/org/geepawhill/hangman/Response.kt
GeePawHill
179,342,704
false
null
package org.geepawhill.hangman open class Response( protected val dictionary: List<String>, val revealed: String, val status: Status, val badGuesses: String = "" ) { constructor(word: String, revealed: String, status: Status, badGuesses: String = "" ) : this(listOf(word),revealed,status,badGuesses) enum class Status { WON, LOST, ONGOING } open fun make(dictionary: List<String>,revealed: String, status: Status, badGuesses: String) = Response(dictionary,revealed,status,badGuesses) fun guess(letter: Char, badGuessesAllowed: Int): Response { if(isHit(letter)) return makeHitResponse(letter) if(missIsDuplicate(letter)) return this return makeMissResponse(letter, badGuessesAllowed) } private fun isHit(letter: Char): Boolean { return dictionary.filter { !it.contains(letter) }.isEmpty() } private fun missIsDuplicate(letter: Char) = badGuesses.contains(letter) private fun makeMissResponse(letter: Char, badGuessesAllowed: Int): Response { val newStatus = if (badGuesses.length == badGuessesAllowed - 1) Status.LOST else Status.ONGOING return make(dictionary.filter { !it.contains(letter) }, revealed, newStatus, badGuesses + letter) } private fun makeHitResponse(letter: Char): Response { val newRevealed = replaceAllCorrectLetters(letter) val newStatus = when (newRevealed) { dictionary[0] -> Status.WON else -> Status.ONGOING } return make(dictionary, newRevealed, newStatus, badGuesses) } private fun replaceAllCorrectLetters(letter: Char): String { var result = "" for (index in 0 until dictionary[0].length) { if (dictionary[0][index] == letter) result += letter else result += revealed[index] } return result } }
0
Kotlin
0
0
1f3df7eccc82f5b867dd88b1e3ac89f3c5e886ec
1,965
kotlin-experiments
MIT License
binary-array-ld-netcdf/src/main/kotlin/net/bald/netcdf/NetCdfLdConverter.kt
binary-array-ld
262,018,000
false
null
package net.bald.netcdf import net.bald.Converter import net.bald.alias.AliasDefinition import net.bald.context.ModelContext import net.bald.model.ModelAliasDefinition import net.bald.model.ModelBinaryArrayConverter import org.apache.jena.rdf.model.Model import org.apache.jena.rdf.model.ModelFactory import java.net.URI /** * NetCDF to LD converter API. * Use [getInstance] to obtain an instance. */ class NetCdfLdConverter: Converter { companion object { /** * Factory method for obtaining [NetCdfLdConverter]. * @return The converter. */ fun getInstance(): Converter { return NetCdfLdConverter() } } override fun convert(input: URI, uri: String?, contexts: List<URI>?, aliases: List<URI>?, downloadUrl: String?): Model { val fileLoc = input.toString() val context = context(contexts) val alias = alias(aliases) val ba = NetCdfBinaryArray.create(fileLoc, uri, context, alias, downloadUrl) return ba.use(ModelBinaryArrayConverter::convert) } private fun context(contextLocs: List<URI>?): ModelContext { val prefixes = contextLocs?.map { contextLoc -> ModelFactory.createDefaultModel().read(contextLoc.toString(), "json-ld") } ?: emptyList() return ModelContext.create(prefixes) } private fun alias(aliasLocs: List<URI>?): AliasDefinition { return ModelFactory.createDefaultModel().apply { aliasLocs?.forEach { aliasLoc -> aliasLoc.toString().let(::read) } }.let(ModelAliasDefinition::create) } }
4
Kotlin
3
0
4c31fb273f70375457d1771ac86429aa3458ddd4
1,632
net.binary_array_ld.bald
Apache License 2.0