path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
src/test/SuspendedFourthChordsTest.kt
|
UrielSarrazin
| 243,283,788
| false
| null |
import Note.*
import Quality.*
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Test
@DisplayName("Suspended Fourth Chords")
class SuspendedFourthChordsTest {
@Test
fun keyOfC() {
val notes = listOf(C, F, G)
val chord = resolve(notes)
assertSuspendedFourth(chord, C)
}
@Test
fun keyOfD() {
val notes = listOf(D, G, A)
val chord = resolve(notes)
assertSuspendedFourth(chord, D)
}
@Test
fun keyOfE() {
val notes = listOf(E, A, B)
val chord = resolve(notes)
assertSuspendedFourth(chord, E)
}
@Test
fun keyOfF() {
val notes = listOf(F, A_SHARP, C)
val chord = resolve(notes)
assertSuspendedFourth(chord, F)
}
@Test
fun keyOfG() {
val notes = listOf(G, C, D)
val chord = resolve(notes)
assertSuspendedFourth(chord, G)
}
@Test
fun keyOfA() {
val notes = listOf(A, D, E)
val chord = resolve(notes)
assertSuspendedFourth(chord, A)
}
@Test
fun keyOfB() {
val notes = listOf(B, E, F_SHARP)
val chord = resolve(notes)
assertSuspendedFourth(chord, B)
}
private fun assertSuspendedFourth(chord: Chord, expectedKey: Note) {
assertChordEquals(chord, expectedKey, SUSPENDED_FOURTH)
}
}
| 1
|
Kotlin
|
0
| 0
|
407934faeafd420244d37be9f03b49b8e1b40bf9
| 1,366
|
chords
|
Apache License 2.0
|
scalechain-api/src/main/kotlin/io/scalechain/blockchain/api/command/wallet/GetAccount.kt
|
ScaleChain
| 45,332,311
| false
| null |
package io.scalechain.blockchain.api.command.wallet
import io.scalechain.blockchain.chain.Blockchain
import io.scalechain.blockchain.transaction.CoinAddress
import io.scalechain.blockchain.api.command.RpcCommand
import io.scalechain.blockchain.api.domain.StringResult
import io.scalechain.blockchain.api.domain.RpcError
import io.scalechain.blockchain.api.domain.RpcRequest
import io.scalechain.blockchain.api.domain.RpcResult
import io.scalechain.wallet.Wallet
import io.scalechain.util.Either
import io.scalechain.util.Either.Right
/*
CLI command :
bitcoin-cli -testnet getaccount mjSk1Ny9spzU2fouzYgLqGUD8U41iR35QN
CLI output :
doc test
Json-RPC request :
{"jsonrpc": "1.0", "id":"curltest", "method": "getaccount", "params": ["mjSk1Ny9spzU2fouzYgLqGUD8U41iR35QN"] }
Json-RPC response :
{
"result": << Same to CLI Output >> ,
"error": null,
"id": "curltest"
}
*/
/** GetAccount: returns the name of the account associated with the given address.
*
* Parameter #1 : Address (String;base58, Required)
* A P2PKH or P2SH address belonging either to a specific account or the default account (“”).
*
* Result: (String)
* The name of an account, or an empty string (“”, the default account).
* Also return "" if the address was not found in the wallet database.
*
* See the getaccount function of the rpcwallet.cpp of the core implementation for the details.
*
* https://bitcoin.org/en/developer-reference#getaccount
*/
object GetAccount : RpcCommand() {
override fun invoke(request : RpcRequest) : Either<RpcError, RpcResult?> {
return handlingException {
val address: String = request.params.get<String>("Address", 0)
val coinAddress = CoinAddress.from(address)
val accountNameOption : String? = Wallet.get().getAccount(Blockchain.get().db, coinAddress)
Right(StringResult(accountNameOption ?: ""))
}
}
override fun help() : String =
"""getaccount "bitcoinaddress"
|
|DEPRECATED. Returns the account associated with the given address.
|
|Arguments:
|1. "bitcoinaddress" (string, required) The bitcoin address for account lookup.
|
|Result:
|"accountname" (string) the account address
|
|Examples:
|> bitcoin-cli getaccount "1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ"
|> curl --user myusername --data-binary '{"jsonrpc": "1.0", "id":"curltest", "method": "getaccount", "params": ["1D1ZrZNe3JUo7ZycKEYQQiQAWd9y54F4XZ"] }' -H 'content-type: text/plain;' http://127.0.0.1:8332/
""".trimMargin()
}
| 11
|
Kotlin
|
67
| 234
|
702ac4d65febb05dc8283e8c165df454efa339b8
| 2,600
|
scalechain
|
Intel Open Source License
|
app/src/main/java/org/stepik/android/view/injection/calendar/CalendarDataModule.kt
|
StepicOrg
| 42,045,161
| false
| null |
package org.stepik.android.view.injection.calendar
import dagger.Binds
import dagger.Module
import org.stepik.android.cache.calendar.CalendarCacheDataSourceImpl
import org.stepik.android.data.calendar.repository.CalendarRepositoryImpl
import org.stepik.android.data.calendar.source.CalendarCacheDataSource
import org.stepik.android.domain.calendar.repository.CalendarRepository
@Module
abstract class CalendarDataModule {
@Binds
internal abstract fun bindCalendarRepository(
calendarRepositoryImpl: CalendarRepositoryImpl
): CalendarRepository
@Binds
internal abstract fun bindCalendarCacheDataSource(
calendarCacheDataSourceImpl: CalendarCacheDataSourceImpl
): CalendarCacheDataSource
}
| 13
| null |
54
| 189
|
dd12cb96811a6fc2a7addcd969381570e335aca7
| 731
|
stepik-android
|
Apache License 2.0
|
compiler/src/main/kotlin/eu/nitok/jitsu/compiler/parser/Location.kt
|
nbrugger-tgm
| 683,089,096
| false
|
{"Kotlin": 148008, "TypeScript": 4002}
|
package eu.nitok.jitsu.compiler.parser
import kotlinx.serialization.Serializable
@Serializable
data class Location(val line: Int, val column: Int, var file: String? = null) : Locatable {
override fun format() = "$line:$column"
override fun absoluteFormat(): String {
return if (file != null) {
"$file:${format()}"
} else {
format()
}
}
override fun mark(text: String, note: String?): String {
val lines = text.split("\n").toMutableList()
val pointer = " ".repeat(column - 1) + "^"
val noteString = if (note != null) " ($note)" else ""
lines.add(this.line, pointer + noteString)
return lines.joinToString("\n")
}
override fun toString() = absoluteFormat()
fun rangeTo(location: Location): Range {
return Range(this, location)
}
fun isBefore(other: Location): Boolean {
return line < other.line || (line == other.line && column < other.column)
}
fun isAfter(other: Location): Boolean {
return line > other.line || (line == other.line && column > other.column)
}
}
| 0
|
Kotlin
|
0
| 0
|
e4b72909c01fb09e8e8f7890e22696546e1fcb27
| 1,130
|
jitsu
|
Apache License 2.0
|
app/src/main/java/at/guger/moneybook/ui/home/accounts/addeditaccount/AddEditAccountBottomSheetDialogFragment.kt
|
ashishkharcheiuforks
| 256,960,657
| true
|
{"Kotlin": 297842, "Java": 2697}
|
/*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package at.guger.moneybook.ui.home.accounts.addeditaccount
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.navigation.fragment.findNavController
import androidx.navigation.fragment.navArgs
import at.guger.moneybook.core.ui.viewmodel.EventObserver
import at.guger.moneybook.data.model.Account
import at.guger.moneybook.databinding.DialogFragmentAddEditAccountBinding
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import kotlinx.android.synthetic.main.dialog_fragment_add_edit_account.*
import org.koin.androidx.viewmodel.ext.android.viewModel
/**
* Dialog fragment for creating a new [accounts][Account].
*/
class AddEditAccountBottomSheetDialogFragment : BottomSheetDialogFragment() {
//region Variables
private val args: AddEditAccountBottomSheetDialogFragmentArgs by navArgs()
private val viewModel: AddEditAccountDialogFragmentViewModel by viewModel()
//endregion
//region DialogFragment
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val binding = DialogFragmentAddEditAccountBinding.inflate(inflater, container, false)
binding.viewModel = viewModel
binding.lifecycleOwner = viewLifecycleOwner
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
args.account?.let { viewModel.setupAccount(it) }
setupEvents()
edtAddEditAccountName.requestFocus()
if (args.account != null) Handler().postDelayed({ edtAddEditAccountName.setSelection(edtAddEditAccountName.text?.length ?: 0) }, 200)
}
//endregion
//region Methods
private fun setupEvents() {
viewModel.accountName.observe(viewLifecycleOwner, Observer { btnAddEditAccountSave.isEnabled = it.isNotBlank() })
viewModel.accountSaved.observe(viewLifecycleOwner, EventObserver { findNavController().navigateUp() })
}
//endregion
}
| 0
| null |
0
| 0
|
f2df55b9ff55bcd01dc7458d779ee49da22b8292
| 2,780
|
MoneyBook
|
Apache License 2.0
|
yde-impl/src/main/kotlin/io/github/ydwk/yde/impl/entities/builder/guild/channel/VoiceChannelBuilderImpl.kt
|
YDWK
| 527,250,343
| false
|
{"Kotlin": 1184155}
|
/*
* Copyright 2024 YDWK inc.
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
*
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.ydwk.yde.impl.entities.builder.guild.channel
import com.fasterxml.jackson.databind.JsonNode
import io.github.ydwk.yde.YDE
import io.github.ydwk.yde.entities.builder.guild.channel.VoiceChannelBuilder
import io.github.ydwk.yde.entities.channel.enums.ChannelType
import io.github.ydwk.yde.entities.channel.guild.message.text.PermissionOverwrite
import io.github.ydwk.yde.entities.channel.guild.vc.GuildVoiceChannel
import io.github.ydwk.yde.rest.EndPoint
import io.github.ydwk.yde.rest.RestResult
import io.github.ydwk.yde.rest.json
import io.github.ydwk.yde.rest.toTextContent
internal class VoiceChannelBuilderImpl(val yde: YDE, val guildId: String?, val name: String) :
VoiceChannelBuilder {
private var isVoiceChannel: Boolean = true
private var bitrate: Int? = null
private var userLimit: Int? = null
private var position: Int? = null
private var permissionOverwrites: MutableList<PermissionOverwrite> = mutableListOf()
private var parentId: String? = null
override fun isStageChannel(): VoiceChannelBuilder {
this.isVoiceChannel = false
return this
}
override fun setBitrate(bitrate: Int): VoiceChannelBuilder {
this.bitrate = bitrate
return this
}
override fun setUserLimit(userLimit: Int): VoiceChannelBuilder {
this.userLimit = userLimit
return this
}
override fun setPosition(position: Int): VoiceChannelBuilder {
this.position = position
return this
}
override fun setPermissionOverwrites(
permissionOverwrites: List<PermissionOverwrite>,
): VoiceChannelBuilder {
this.permissionOverwrites.addAll(permissionOverwrites)
return this
}
override fun setParentId(parentId: String): VoiceChannelBuilder {
this.parentId = parentId
return this
}
override val json: JsonNode
get() {
val json = yde.objectMapper.createObjectNode()
json.put("name", name)
json.put(
"type",
if (isVoiceChannel) ChannelType.VOICE.getId() else ChannelType.STAGE_VOICE.getId())
if (bitrate != null) json.put("bitrate", bitrate)
if (userLimit != null) json.put("user_limit", userLimit)
if (position != null) json.put("position", position)
// if (permissionOverwrites != null) json.put("permission_overwrites",
// yde.objectMapper.valueToTree(permissionOverwrites))
if (parentId != null) json.put("parent_id", parentId)
return json
}
override suspend fun create(): RestResult<GuildVoiceChannel> {
requireNotNull(guildId) { "Guild id is not set" }
val requestBody = json.toString().toTextContent()
return yde.restApiManager
.post(requestBody, EndPoint.GuildEndpoint.CREATE_CHANNEL, guildId)
.execute { response ->
val jsonBody = response.json(yde)
yde.entityInstanceBuilder.buildGuildVoiceChannel(jsonBody)
}
}
}
| 9
|
Kotlin
|
1
| 1
|
bfbebb7f51e651b8103ae185dd8c7cabe72f6043
| 3,673
|
YDWK
|
Apache License 2.0
|
app/src/main/java/com/mokelab/demo/samcollection/jetpack/arch/livedata/JetpackLiveDataFragment.kt
|
mokelab
| 177,933,256
| false
| null |
package com.mokelab.demo.samcollection.jetpack.arch.livedata
import android.os.Bundle
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.mokelab.demo.binding.BindingFragment
import com.mokelab.demo.samcollection.databinding.JetpackLivedataFragmentBinding
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
class JetpackLiveDataFragment: BindingFragment<JetpackLivedataFragmentBinding>(),
CoroutineScope{
private val job = Job()
override val coroutineContext: CoroutineContext
get() = Dispatchers.Main + job
private lateinit var viewModel: JetpackLiveDataViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.viewModel = ViewModelProviders.of(this).get(JetpackLiveDataViewModel::class.java)
}
override fun onCreateViewDataBinding(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): JetpackLivedataFragmentBinding {
val binding = JetpackLivedataFragmentBinding.inflate(inflater, container, false)
binding.loading = true
return binding
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
this.viewModel.user.observe(this, Observer<User> {
val user = it ?: return@Observer
binding.nameText.text = user.name
binding.emailText.text = user.email
binding.loading = false
})
}
override fun onStart() {
super.onStart()
// Note: It's not good to do async operation here.
// Configuration change(ex. rotation) cancels operation..
launch {
// simulate network communication
val user = withContext(Dispatchers.IO) {
delay(3000)
User("moke", "<EMAIL>")
}
viewModel.user.value = user
}
}
override fun onStop() {
super.onStop()
coroutineContext.cancelChildren()
}
}
| 0
|
Kotlin
|
0
| 0
|
c0c882dffcc0abc4d198f4808dd22ed3e2079270
| 2,161
|
android-samcollection
|
Apache License 2.0
|
save-cloud-common/src/jvmMain/kotlin/com/saveourtool/save/utils/BlockingBridge.kt
|
saveourtool
| 300,279,336
| false
| null |
package com.saveourtool.common.utils
import org.jetbrains.annotations.NonBlocking
import org.springframework.stereotype.Component
import reactor.core.publisher.Flux
import reactor.core.publisher.Mono
import reactor.core.scheduler.Scheduler
import reactor.core.scheduler.Schedulers
import reactor.kotlin.core.publisher.toMono
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
/**
* A bridge for blocking (IO) operations
*
* @property ioScheduler [Scheduler] for IO operations for [Mono] and [Flux]
* @property ioDispatcher [CoroutineDispatcher] for IO operations in suspend function
*/
@Component
class BlockingBridge(
val ioScheduler: Scheduler = Schedulers.boundedElastic(),
val ioDispatcher: CoroutineDispatcher = Dispatchers.IO,
) {
/**
* Taking from https://projectreactor.io/docs/core/release/reference/#faq.wrap-blocking
*
* @param supplier blocking operation like JDBC
* @return [Mono] from result of blocking operation [T]
* @see blockingToFlux
*/
@NonBlocking
fun <T : Any> blockingToMono(supplier: () -> T?): Mono<T> = supplier.toMono().subscribeOn(ioScheduler)
/**
* @param supplier blocking operation like JDBC
* @return [Flux] from result of blocking operation [List] of [T]
* @see blockingToMono
*/
@NonBlocking
fun <T> blockingToFlux(supplier: () -> Iterable<T>): Flux<T> = blockingToMono(supplier).flatMapIterable { it }
/**
* @param supplier blocking operation like JDBC
* @return suspend result of blocking operation [T]
* @see blockingToMono
*/
@NonBlocking
suspend fun <T> blockingToSuspend(supplier: () -> T): T = withContext(ioDispatcher) {
supplier()
}
companion object {
/**
* A default instance of [BlockingBridge]
*/
val default: BlockingBridge = BlockingBridge()
}
}
| 201
| null |
3
| 38
|
7e126d4fb23f8527c47ca9fa27282379759d154e
| 1,945
|
save-cloud
|
MIT License
|
project-course/kotlin-android/Flickr-Browser/app/src/main/java/kiz/learnwithvel/flickrbrowser/util/RecyclerItemClickListener.kt
|
vel02
| 261,988,454
| false
| null |
package kiz.learnwithvel.flickrbrowser.util
import android.content.Context
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import androidx.core.view.GestureDetectorCompat
import androidx.recyclerview.widget.RecyclerView
private const val TAG = "RecyclerItemClickListen"
class RecyclerItemClickListener(
context: Context,
recyclerView: RecyclerView,
private val listener: OnRecyclerClickListener
) : RecyclerView.SimpleOnItemTouchListener() {
interface OnRecyclerClickListener {
fun onItemClick(view: View, position: Int);
fun onItemLongClick(view: View, position: Int);
}
private val gestureDetector =
GestureDetectorCompat(context, object : GestureDetector.SimpleOnGestureListener() {
override fun onSingleTapUp(e: MotionEvent): Boolean {
val childView = recyclerView.findChildViewUnder(e.x, e.y)
childView?.let {
listener.onItemClick(
it,
recyclerView.getChildAdapterPosition(it)
)
}
return true
}
override fun onLongPress(e: MotionEvent) {
val childView = recyclerView.findChildViewUnder(e.x, e.y)
childView?.let {
listener.onItemLongClick(
it,
recyclerView.getChildAdapterPosition(it)
)
}
}
})
override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
return gestureDetector.onTouchEvent(e)
}
}
| 1
| null |
1
| 1
|
7644d1911ff35fda44e45b1486bcce5d790fe7c0
| 1,680
|
learn-kotlin-android
|
MIT License
|
app/src/main/java/com/eurobond/features/orderhistory/activitiesapi/LocationFetchRepository.kt
|
DebashisINT
| 467,012,976
| false
| null |
package com.eurobond.features.orderhistory.activitiesapi
import com.eurobond.app.Pref
import com.eurobond.base.BaseResponse
import com.eurobond.features.orderhistory.model.FetchLocationRequest
import com.eurobond.features.orderhistory.model.FetchLocationResponse
import com.eurobond.features.orderhistory.model.SubmitLocationInputModel
import com.eurobond.features.orderhistory.model.UnknownReponseModel
import io.reactivex.Observable
/**
* Created by Pratishruti on 30-11-2017.
*/
class LocationFetchRepository(val apiService: LocationFetchApi){
fun fetchLocationUpdate(location: FetchLocationRequest): Observable<FetchLocationResponse> {
return apiService.getLocationUpdates(location)
}
fun fetchLocationUpdate(date: String): Observable<FetchLocationResponse> {
return apiService.getLocationUpdates(Pref.session_token!!, Pref.user_id!!, date)
}
fun fetchUnknownLocation(): Observable<UnknownReponseModel> {
return apiService.getUnknownLocation(Pref.session_token!!, Pref.user_id!!)
}
fun submitLoc(loc: SubmitLocationInputModel): Observable<BaseResponse> {
return apiService.submitLocation(loc)
}
}
| 0
|
Kotlin
|
0
| 0
|
236c74a32aeef737fd476312fbc23eac367cbd75
| 1,171
|
Eurobond
|
Apache License 2.0
|
resources-generator/src/test/kotlin/dev/icerock/gradle/generator/stringsGenerator/XmlStringsAndroidFormatTest.kt
|
icerockdev
| 204,874,263
| false
|
{"Kotlin": 456033, "Shell": 1362}
|
/*
* Copyright 2024 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.gradle.generator.stringsGenerator
import dev.icerock.gradle.utils.convertXmlStringToAndroidLocalization
import dev.icerock.gradle.utils.removeAndroidMirroringFormat
import kotlin.test.Test
import kotlin.test.assertEquals
class XmlStringsAndroidFormatTest {
@Test
fun quotesAndroidFormat() {
assertEquals(
expected = """Same text with symbol's @ ? somet'ing "word"""",
actual = TEXT_WITH_QUOTES.removeAndroidMirroringFormat()
)
}
@Test
fun quotesAndroidInOutFormat() {
assertEquals(
expected = """Same text with symbol\'s @ ? somet\'ing \"word\"""",
actual = TEXT_WITH_QUOTES
.removeAndroidMirroringFormat()
.convertXmlStringToAndroidLocalization()
)
}
private companion object {
private const val TEXT_WITH_QUOTES = """Same text with symbol's @ ? somet\'ing \"word""""
}
}
| 147
|
Kotlin
|
121
| 1,077
|
2c484808c928a13ab4d0523b82db3b5ab4e90db5
| 1,076
|
moko-resources
|
Apache License 2.0
|
app/src/main/java/com/kyungeun/mvc_mvp_mvvm_mvi_demo/mvp/model/Memo.kt
|
shruddms
| 518,024,752
| false
|
{"Kotlin": 16650}
|
package com.kyungeun.mvc_mvp_mvvm_mvi_demo.mvp.model
import com.kyungeun.mvc_mvp_mvvm_mvi_demo.mvp.presenter.Contract
class Memo(presenter: Contract.Presenter) {
private var presenter: Contract.Presenter
init {
this.presenter = presenter
}
}
| 0
|
Kotlin
|
0
| 0
|
2d830d101c90de2436be39ee07890b7130cd418a
| 265
|
MVC-MVP-MVVM-MVI-Demo
|
Apache License 2.0
|
app/src/main/kotlin/com/arnaudpiroelle/conference/ui/explore/model/Group.kt
|
Gropoid
| 71,445,494
| false
| null |
package com.arnaudpiroelle.conference.ui.explore.model
data class Group<T>(val data: T, val type: GroupType) {
enum class GroupType {
MESSAGE,
KEYNOTE,
TAG
}
}
| 0
|
Kotlin
|
1
| 0
|
4d0a4b18f05d9ab389abcccc94820ab90fa7f202
| 197
|
conference-android
|
Apache License 2.0
|
src/main/kotlin/eu/boxwork/dhbw/capturethecode/model/Player.kt
|
harkle-the-cake
| 547,371,196
| false
|
{"Kotlin": 171929, "HTML": 5140}
|
package eu.boxwork.dhbw.capturethecode.model
import com.fasterxml.jackson.annotation.JsonIgnore
import eu.boxwork.dhbw.capturethecode.dto.PlayerDto
import eu.boxwork.dhbw.capturethecode.enums.PlayerState
import org.hibernate.annotations.OnDelete
import org.hibernate.annotations.OnDeleteAction
import java.util.UUID
import javax.persistence.Column
import javax.persistence.Entity
import javax.persistence.FetchType
import javax.persistence.Id
import javax.persistence.JoinColumn
import javax.persistence.ManyToOne
import javax.persistence.Table
import javax.validation.Valid
import javax.validation.constraints.Pattern
@Entity
@Table(name = "player")
data class Player(
@Id @Column(name = "uuid") val uuid: UUID,
@Pattern(regexp = "\\S{1,20}") @Column(name = "name") var name: String,
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "teamid", nullable = false)
@OnDelete(action = OnDeleteAction.CASCADE)
@JsonIgnore
val team: Team
) {
fun dto() = PlayerDto(
uuid,
name,
team.teamName
)
}
| 0
|
Kotlin
|
0
| 0
|
8f1c6a5476bc674c23e98ae04afe2d95b84b78f4
| 1,074
|
dhbw_capturethecode
|
MIT License
|
src/main/kotlin/no/nav/aap/proxy/rest/FellesRestBeanConfig.kt
|
navikt
| 422,128,379
| false
| null |
package no.nav.aap.proxy.rest
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import io.micrometer.observation.ObservationRegistry
import io.micrometer.observation.aop.ObservedAspect
import io.netty.handler.logging.LogLevel.DEBUG
import io.netty.handler.logging.LogLevel.TRACE
import io.swagger.v3.oas.models.OpenAPI
import io.swagger.v3.oas.models.info.Info
import io.swagger.v3.oas.models.info.License
import no.nav.aap.proxy.arena.ArenaOIDCClient
import no.nav.aap.proxy.sts.StsClient
import no.nav.aap.rest.AbstractWebClientAdapter.Companion.correlatingFilterFunction
import no.nav.aap.rest.HeadersToMDCFilter
import no.nav.aap.util.AuthContext
import no.nav.aap.util.Constants.STS
import no.nav.aap.util.StartupInfoContributor
import no.nav.aap.util.StringExtensions.asBearer
import no.nav.boot.conditionals.EnvUtil.isDevOrLocal
import no.nav.security.token.support.client.spring.oauth2.ClientConfigurationPropertiesMatcher
import no.nav.security.token.support.core.context.TokenValidationContextHolder
import org.springframework.beans.factory.annotation.Qualifier
import org.springframework.beans.factory.annotation.Value
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer
import org.springframework.boot.info.BuildProperties
import org.springframework.boot.web.reactive.function.client.WebClientCustomizer
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.context.ApplicationContext
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.core.Ordered.HIGHEST_PRECEDENCE
import org.springframework.core.env.Environment
import org.springframework.http.HttpHeaders.*
import org.springframework.http.client.reactive.ReactorClientHttpConnector
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder
import org.springframework.web.reactive.function.client.ClientRequest
import org.springframework.web.reactive.function.client.ExchangeFilterFunction
import org.zalando.problem.jackson.ProblemModule
import reactor.netty.http.client.HttpClient
import reactor.netty.transport.logging.AdvancedByteBufFormat.TEXTUAL
@Configuration
class FellesRestBeanConfig(@Value("\${spring.application.name}") val applicationName: String) {
@Bean
fun jacksonCustomizer() =
Jackson2ObjectMapperBuilderCustomizer {
b: Jackson2ObjectMapperBuilder -> b.modules(ProblemModule(), JavaTimeModule(), KotlinModule.Builder().build())
}
@Bean
fun swagger(p: BuildProperties): OpenAPI {
return OpenAPI()
.info(Info()
.title("AAP fss proxy")
.description("Proxy mot tjenester som ikke støtter AAD/TokenX")
.version(p.version)
.license(License()
.name("MIT")
.url("https://nav.no"))
)
}
@Bean
fun observedAspect(observationRegistry: ObservationRegistry) = ObservedAspect(observationRegistry)
@Bean
fun startupInfoContributor(ctx: ApplicationContext) = StartupInfoContributor(ctx)
@Bean
fun authContext(ctxHolder: TokenValidationContextHolder) = AuthContext(ctxHolder)
@Bean
fun configMatcher() = object : ClientConfigurationPropertiesMatcher {}
@Bean
@Qualifier(STS)
fun stsExchangeFilterFunction(stsClient: StsClient) =
ExchangeFilterFunction {
req, next -> next.exchange(ClientRequest.from(req).header(AUTHORIZATION, "${stsClient.oidcToken().asBearer()}")
.build())
}
@Bean
fun headersToMDCFilterRegistrationBean() =
FilterRegistrationBean(HeadersToMDCFilter(applicationName))
.apply {
urlPatterns = listOf("/*")
setOrder(HIGHEST_PRECEDENCE)
}
@Bean
fun webClientCustomizer(env: Environment) =
WebClientCustomizer { b ->
b.clientConnector(ReactorClientHttpConnector(client(env)))
.filter(correlatingFilterFunction(applicationName))
}
private fun client(env: Environment) =
if (isDevOrLocal(env))
HttpClient.create().wiretap(javaClass.canonicalName, TRACE, TEXTUAL)
else HttpClient.create()
}
| 0
|
Kotlin
|
0
| 2
|
c20c7138057e30d27fa939d6e9662501b442df3a
| 4,355
|
aap-fss-proxy
|
MIT License
|
vk-api/src/main/kotlin/name/alatushkin/api/vk/generated/common/Reason.kt
|
alatushkin
| 156,866,851
| false
| null |
package name.alatushkin.api.vk.generated.common
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonValue
enum class Reason(@JsonValue val jsonValue: String) {
SPAM("0"), CHILD_PORNOGRAPHY("1"), EXTREMISM("2"),
VIOLENCE("3"), DRUG_PROPAGANDA("4"),
ADULT_MATERIAL("5"), INSULT_ABUSE("6");
override fun toString() = jsonValue
companion object {
@JvmStatic
@JsonCreator
fun fromJsonValue(value: String): Reason =
Reason.values().find { it.jsonValue == value }!!
}
}
| 2
|
Kotlin
|
3
| 10
|
123bd61b24be70f9bbf044328b98a3901523cb1b
| 572
|
kotlin-vk-api
|
MIT License
|
starrysky/src/main/java/com/lzx/starrysky/imageloader/ImageLoader.kt
|
xiongsongyu2016
| 214,321,300
| true
|
{"Java Properties": 2, "Markdown": 14, "Gradle": 4, "Shell": 1, "Batchfile": 1, "Text": 1, "Ignore List": 3, "XML": 33, "Proguard": 2, "Java": 41, "Kotlin": 28}
|
package com.lzx.starrysky.imageloader
import android.content.Context
/**
* 图片加载类
* 策略或者静态代理模式,开发者只需要关心ImageLoader + ImageLoaderOptions
*/
class ImageLoader(private val context: Context) {
private var mLoader: ImageLoaderStrategy? = null
fun init(loader: ImageLoaderStrategy) {
this.mLoader = loader
}
fun load(url: String, callBack: ImageLoaderCallBack) {
if (mLoader == null) {
mLoader = DefaultImageLoader()
}
mLoader!!.loadImage(context, url, callBack)
}
}
| 0
| null |
0
| 1
|
e83d70726ce5a8008669d4244ca705f858da9200
| 531
|
StarrySky
|
MIT License
|
MusicPlayer/app/src/main/java/com/example/musicplayer/ui/MainFragment.kt
|
rafgasinski
| 378,656,544
| false
| null |
package com.example.musicplayer.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.activity.OnBackPressedCallback
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.setupWithNavController
import com.example.musicplayer.R
import com.example.musicplayer.databinding.FragmentMainBinding
import com.example.musicplayer.viewmodels.PlayerViewModel
class MainFragment : Fragment() {
private var _binding: FragmentMainBinding? = null
private val binding get() = _binding!!
private lateinit var playerModel: PlayerViewModel
private lateinit var navController: NavController
private val TIME_INTERVAL = 1500
private var mBackPressed: Long = 0
private var toast: Toast? = null
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
_binding = FragmentMainBinding.inflate(inflater, container, false)
playerModel = ViewModelProvider(this).get(PlayerViewModel::class.java)
toast = Toast.makeText(inflater.context, "Press back again to exit", Toast.LENGTH_SHORT)
val navHostFragment =
childFragmentManager.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
navController = navHostFragment.navController
binding.lifecycleOwner = this
binding.bottomBar.setupWithNavController(navController)
playerModel.track.observe(viewLifecycleOwner) { track ->
if (track == null) {
binding.smallPlayer.visibility = View.GONE
} else {
binding.smallPlayer.visibility = View.VISIBLE
}
}
activity?.onBackPressedDispatcher?.addCallback(viewLifecycleOwner, object : OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
if(binding.bottomBar.selectedItemId == R.id.tracksFragment){
if(!navController.navigateUp()){
if (mBackPressed + TIME_INTERVAL > System.currentTimeMillis()) {
toast?.cancel()
activity?.moveTaskToBack(true)
}
else {
toast?.show()
}
mBackPressed = System.currentTimeMillis()
}
} else {
toast?.cancel()
navController.navigateUp()
}
}
})
return binding.root
}
}
| 0
|
Kotlin
|
0
| 0
|
6619a6025b5e8183719b6e2dd4d83bd104a1453d
| 2,845
|
Music-Player
|
MIT License
|
Demos/Micronaut/src/main/kotlin/com/groupdocs/ui/modules/home/HomeController.kt
|
groupdocs-comparison
| 65,550,714
| false
| null |
package com.groupdocs.ui.modules.home
import com.groupdocs.ui.config.ApplicationConfig
import com.groupdocs.ui.util.setGroupdocsLicense
import io.micronaut.http.HttpResponse
import io.micronaut.http.annotation.Controller
import io.micronaut.http.annotation.Get
import io.micronaut.views.View
import jakarta.inject.Inject
import jakarta.inject.Singleton
import java.net.URI
@Singleton
@Controller("/")
class HomeController(
@Inject private val appConfig: ApplicationConfig
) {
private var isLicenseSet: Boolean = false
@Get("/")
fun home(): HttpResponse<String> {
return HttpResponse.redirect(URI("/comparison"))
}
@View("comparison")
@Get("/comparison")
fun comparison() {
if (!isLicenseSet) {
isLicenseSet = true
val licensePath = appConfig.licensePathOrDefault
setGroupdocsLicense(licensePath)
}
}
@Get("/comparison/app-name")
fun appName(): HttpResponse<String> {
return HttpResponse.ok("comparison-micronaut")
}
}
| 5
| null |
9
| 7
|
4d289958d8fc6ab338bbcfca8e82d237b71838be
| 1,037
|
GroupDocs.Comparison-for-Java
|
MIT License
|
app/src/main/java/com/example/androiddevchallenge/MainActivity.kt
|
takahirom
| 347,238,508
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge
import android.os.Bundle
import androidx.activity.compose.setContent
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.paddingFromBaseline
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Button
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.constraintlayout.compose.ConstraintLayout
import androidx.core.view.WindowCompat
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.navigate
import androidx.navigation.compose.rememberNavController
import com.example.androiddevchallenge.ui.theme.MyTheme
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
WindowCompat.setDecorFitsSystemWindows(window, false)
setContent {
MyTheme {
MyApp()
}
}
}
}
// Start building your app here!
@Composable
fun MyApp() {
val navController = rememberNavController()
NavHost(navController, startDestination = "welcome") {
composable(
route = "welcome",
) { backStackEntry ->
WelcomeScreen {
navController.navigate("login")
}
}
composable(
route = "login",
) { backStackEntry ->
LoginScreen {
navController.navigate("home")
}
}
composable(
route = "home",
) { backStackEntry ->
HomeScreen()
}
}
}
@Composable
fun WelcomeScreen(onLogin: () -> Unit) {
Surface(color = MaterialTheme.colors.primary) {
Box {
Image(
painter = painterResource(id = R.drawable.ic_welcome_bg),
"background",
modifier = Modifier.fillMaxSize(),
contentScale = ContentScale.Crop,
)
ConstraintLayout(
modifier = Modifier.fillMaxWidth()
) {
val (image, box, login) = createRefs()
Image(
painter = painterResource(id = R.drawable.ic_welcome_illos),
"illos",
modifier = Modifier
.padding(
start = 88.dp,
top = 72.dp
)
.constrainAs(image) {
top.linkTo(parent.top)
end.linkTo(parent.end)
}
)
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.padding(start = 16.dp, end = 16.dp)
.constrainAs(box) {
top.linkTo(image.bottom, 48.dp)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
) {
Image(
painter = painterResource(id = R.drawable.ic_logo),
"logo",
modifier = Modifier
)
Text(
text = "Beautiful home garden solutions",
style = MaterialTheme.typography.subtitle1,
textAlign = TextAlign.End,
modifier = Modifier
.paddingFromBaseline(
top = 32.dp,
bottom = 40.dp
)
)
val text = "Create account"
MyButton({}, text)
}
Text(
text = "Log in",
modifier = Modifier
.padding(top = 8.dp)
.clickable { onLogin() }
.constrainAs(login) {
top.linkTo(box.bottom)
start.linkTo(parent.start)
end.linkTo(parent.end)
}
)
}
}
}
}
@Composable
fun MyButton(onClick: () -> Unit, text: String) {
Button(
{ onClick() },
modifier = Modifier
.height(48.dp)
.fillMaxWidth(),
shape = RoundedCornerShape(24.dp),
colors = ButtonDefaults.buttonColors(backgroundColor = MaterialTheme.colors.secondary)
) {
Text(
text = text,
style = MaterialTheme.typography.button
)
}
}
@Preview(widthDp = 360, heightDp = 640)
@Composable
fun PreviewWelcome() {
MyTheme {
WelcomeScreen(onLogin = { /*TODO*/ })
}
}
@Preview("Light Theme", widthDp = 360, heightDp = 640)
@Composable
fun LightPreview() {
MyTheme(darkTheme = true) {
WelcomeScreen(onLogin = { /*TODO*/ })
}
}
| 0
|
Kotlin
|
0
| 0
|
1b3b8de36946e7fc6f574596fe789d7a4d75fad3
| 6,592
|
android-dev-challenge-3
|
Apache License 2.0
|
grundlagen-tag-27-konstruktoren-just1984/Aufgabe 6/src/Car.kt
|
just1984
| 639,436,580
| false
| null |
class Car {
var color: String
var brand: String
var attribute: String // neues Feld hinzugefügt
constructor(color: String, brand: String, attribute: String) { // Konstruktor angepasst
this.color = color
this.brand = brand
this.attribute = attribute // neues Feld initialisiert
}
}
| 0
|
Kotlin
|
0
| 0
|
3b6a84bb526f2c2151fe761526bdb1253f343df1
| 325
|
school_progress_kotlin
|
MIT License
|
lib/src/main/kotlin/com/lemonappdev/konsist/api/ext/list/KoParentProviderListExt.kt
|
LemonAppDev
| 621,181,534
| false
|
{"Kotlin": 3830717, "Python": 17471}
|
@file:Suppress("detekt.TooManyFunctions")
package com.lemonappdev.konsist.api.ext.list
import com.lemonappdev.konsist.api.declaration.KoParentDeclaration
import com.lemonappdev.konsist.api.provider.KoParentProvider
import kotlin.reflect.KClass
/**
* List containing parent declarations.
*/
@Deprecated("Will be removed in v0.16.0", ReplaceWith("parents()"))
val <T : KoParentProvider> List<T>.parents: List<KoParentDeclaration>
get() = flatMap { it.parents }
/**
* List containing parent declarations.
*
* @param indirectParents Whether to include indirect parents.
* @return A list containing parent declarations.
*/
fun <T : KoParentProvider> List<T>.parents(indirectParents: Boolean = false): List<KoParentDeclaration> =
flatMap { it.parents(indirectParents) }
/**
* List containing declarations with any parent.
*
* @param indirectParents Whether to include indirect parents.
* @return A list containing declarations with any parent.
*/
fun <T : KoParentProvider> List<T>.withParents(indirectParents: Boolean = false): List<T> = filter { it.hasParents(indirectParents) }
/**
* List containing declarations with none parent - declaration does not extend any class and does not implement any interface.
*
* @param indirectParents Whether to include indirect parents.
* @return A list containing declarations with no parent - declaration does not extend any class and does not implement any
* interface.
*/
fun <T : KoParentProvider> List<T>.withoutParents(indirectParents: Boolean = false): List<T> = filterNot { it.hasParents(indirectParents) }
/**
* List containing declarations that have at least one parent with the specified name(s).
*
* @param name The name of the parent to include.
* @param names The names of additional parents to include.
* @param indirectParents Whether to include indirect parents.
* @return A list containing declarations with at least one of the specified parent(s).
*/
fun <T : KoParentProvider> List<T>.withParentNamed(
name: String,
vararg names: String,
indirectParents: Boolean = false,
): List<T> =
filter {
it.hasParentWithName(name, *names, indirectParents = indirectParents)
}
/**
* List containing declarations without any of specified parents.
*
* @param name The name of the parent to exclude.
* @param names The names of additional parents to exclude.
* @param indirectParents Whether to include indirect parents.
* @return A list containing declarations without any of specified parents.
*/
fun <T : KoParentProvider> List<T>.withoutParentNamed(
name: String,
vararg names: String,
indirectParents: Boolean = false,
): List<T> =
filterNot {
it.hasParentWithName(name, *names, indirectParents = indirectParents)
}
/**
* List containing declarations that have all specified parents.
*
* @param name The name of the parent to include.
* @param names The name(s) of the parent(s) to include.
* @param indirectParents Whether to include indirect parents.
* @return A list containing declarations with all specified parent(s).
*/
fun <T : KoParentProvider> List<T>.withAllParentsNamed(
name: String,
vararg names: String,
indirectParents: Boolean = false,
): List<T> =
filter {
it.hasParentsWithAllNames(name, *names, indirectParents = indirectParents)
}
/**
* List containing declarations without all specified parents.
*
* @param name The name of the parent to exclude.
* @param names The name(s) of the parent(s) to exclude.
* @param indirectParents Whether to include indirect parents.
* @return A list containing declarations without all specified parent(s).
*/
fun <T : KoParentProvider> List<T>.withoutAllParentsNamed(
name: String,
vararg names: String,
indirectParents: Boolean = false,
): List<T> =
filterNot {
it.hasParentsWithAllNames(name, *names, indirectParents = indirectParents)
}
/**
* List containing declarations that have at least one parent satisfying the provided predicate.
*
* @param indirectParents Whether to include indirect parents.
* @param predicate A function that defines the condition to be met by a parent declaration.
* @return A list containing declarations with at least one parent satisfying the predicate.
*/
fun <T : KoParentProvider> List<T>.withParent(
indirectParents: Boolean = false,
predicate: (KoParentDeclaration) -> Boolean,
): List<T> =
filter {
it.hasParent(indirectParents, predicate)
}
/**
* List containing declarations that not have parent satisfying the provided predicate.
*
* @param indirectParents Whether to include indirect parents.
* @param predicate A function that defines the condition to be met by a parent declaration.
* @return A list containing declarations without parent satisfying the provided predicate.
*/
fun <T : KoParentProvider> List<T>.withoutParent(
indirectParents: Boolean = false,
predicate: (KoParentDeclaration) -> Boolean,
): List<T> =
filterNot {
it.hasParent(indirectParents, predicate)
}
/**
* List containing declarations that have all parents satisfying the provided predicate.
*
* @param indirectParents Whether to include indirect parents.
* @param predicate A function that defines the condition to be met by all parent declarations.
* @return A filtered list containing declarations with all parents satisfying the predicate.
*/
fun <T : KoParentProvider> List<T>.withAllParents(
indirectParents: Boolean = false,
predicate: (KoParentDeclaration) -> Boolean,
): List<T> =
filter {
it.hasAllParents(indirectParents, predicate)
}
/**
* List containing declarations that have at least one parent not satisfying the provided predicate.
*
* @param indirectParents Whether to include indirect parents.
* @param predicate A function that defines the condition to be met by all parent declarations.
* @return A list containing declarations that have at least one parent not satisfying the provided predicate.
*/
fun <T : KoParentProvider> List<T>.withoutAllParents(
indirectParents: Boolean = false,
predicate: (KoParentDeclaration) -> Boolean,
): List<T> =
filterNot {
it.hasAllParents(indirectParents, predicate)
}
/**
* List containing declarations with parent declarations satisfying the predicate.
*
* @param indirectParents Whether to include indirect parents.
* @param predicate A function that defines the condition to be met by the list of parent declarations.
* @return A list containing declarations with parent declarations satisfying the predicate.
*/
fun <T : KoParentProvider> List<T>.withParents(
indirectParents: Boolean = false,
predicate: (List<KoParentDeclaration>) -> Boolean,
): List<T> =
filter {
predicate(it.parents(indirectParents))
}
/**
* List containing declarations without parent declarations satisfying the predicate.
*
* @param indirectParents Whether to include indirect parents.
* @param predicate A function that defines the condition to be met by the list of parent declarations.
* @return A list containing declarations without parent declarations satisfying the predicate.
*/
fun <T : KoParentProvider> List<T>.withoutParents(
indirectParents: Boolean = false,
predicate: (List<KoParentDeclaration>) -> Boolean,
): List<T> = filterNot { predicate(it.parents(indirectParents)) }
/**
* List containing declarations that have at least one parent of the specified `KClass` type.
*
* @param kClass The Kotlin class representing parent to include.
* @param kClasses The Kotlin classes representing parents to include.
* @param indirectParents Whether to include indirect parents.
* @return A list containing declarations with at least one parent of the specified `KClass` type.
*/
fun <T : KoParentProvider> List<T>.withParentOf(
kClass: KClass<*>,
vararg kClasses: KClass<*>,
indirectParents: Boolean = false,
): List<T> = filter { it.hasParentOf(kClass, *kClasses, indirectParents = indirectParents) }
/**
* List containing declarations without any parent of the specified `KClass` type.
*
* @param kClass The Kotlin class representing parent to exclude.
* @param kClasses The Kotlin classes representing parents to exclude.
* @param indirectParents Whether to include indirect parents.
* @return A list containing declarations without any of the specified parents.
*/
fun <T : KoParentProvider> List<T>.withoutParentOf(
kClass: KClass<*>,
vararg kClasses: KClass<*>,
indirectParents: Boolean = false,
): List<T> = filterNot { it.hasParentOf(kClass, *kClasses, indirectParents = indirectParents) }
/**
* List containing declarations that have all parents of the specified `KClass` type.
*
* @param kClass The Kotlin class representing parent to include.
* @param kClasses The Kotlin classes representing parents to include.
* @param indirectParents Whether to include indirect parents.
* @return A list containing declarations that have all parents of the specified `KClass` type.
*/
fun <T : KoParentProvider> List<T>.withAllParentsOf(
kClass: KClass<*>,
vararg kClasses: KClass<*>,
indirectParents: Boolean = false,
): List<T> = filter { it.hasAllParentsOf(kClass, *kClasses, indirectParents = indirectParents) }
/**
* List containing declarations without all specified `KClass` type parents.
*
* @param kClass The Kotlin class representing parent to exclude.
* @param kClasses The Kotlin classes representing parents to exclude.
* @param indirectParents Whether to include indirect parents.
* @return A list containing declarations without all specified `KClass` type parents.
*/
fun <T : KoParentProvider> List<T>.withoutAllParentsOf(
kClass: KClass<*>,
vararg kClasses: KClass<*>,
indirectParents: Boolean = false,
): List<T> = filterNot { it.hasAllParentsOf(kClass, *kClasses, indirectParents = indirectParents) }
/**
* List containing declarations with some named parents.
*
* @param kClass The Kotlin class representing the parent to include.
* @param kClasses The Kotlin declarations representing the parents to include.
* @return A list containing declarations with at least one of the specified parent(s).
*/
@Deprecated("Will be removed in v0.16.0.", ReplaceWith("withParentOf(*kClasses"))
fun <T : KoParentProvider> List<T>.withSomeParentsOf(
kClass: KClass<*>,
vararg kClasses: KClass<*>,
): List<T> =
filter {
it.parents.any { parent -> parent.name == kClass.simpleName } ||
kClasses.any { kClass ->
it
.parents
.any { parent -> parent.name == kClass.simpleName }
}
}
/**
* List containing declarations without some named parents.
*
* @param kClass The Kotlin class representing the parent to exclude.
* @param kClasses The Kotlin declarations representing the parents to exclude.
* @return A list containing declarations without at least one of the specified parent(s).
*/
@Deprecated("Will be removed in v0.16.0.", ReplaceWith("withoutParentOf(*kClasses"))
fun <T : KoParentProvider> List<T>.withoutSomeParentsOf(
kClass: KClass<*>,
vararg kClasses: KClass<*>,
): List<T> =
filter {
val missesAtLeastOneParent =
if (kClasses.isNotEmpty()) {
kClasses.any { kClass ->
it
.parents
.none { parent -> parent.name == kClass.simpleName }
}
} else {
true
}
it.parents.none { parent -> parent.name == kClass.simpleName } && missesAtLeastOneParent
}
/**
* List containing declarations with all specified parents.
*
* @param name The name of the parent to include.
* @param names The name(s) of the parent(s) to include.
* @return A list containing declarations with all specified parent(s).
*/
@Deprecated(
"""
Will be removed in v0.16.0.
If you passed one argument - replace with `withParentNamed`, otherwise with `withAllParentsNamed`.
""",
ReplaceWith("withParentNamed/withAllParentsNamed"),
)
fun <T : KoParentProvider> List<T>.withAllParents(
name: String,
vararg names: String,
): List<T> =
filter {
it.hasParents(name, *names)
}
/**
* List containing declarations with some parents.
*
* @param name The name of the parent to include.
* @param names The names of the parents to include.
* @return A list containing declarations with at least one of the specified parent(s).
*/
@Deprecated("Will be removed in v0.16.0.", ReplaceWith("withParentNamed(*names"))
fun <T : KoParentProvider> List<T>.withSomeParents(
name: String,
vararg names: String,
): List<T> =
filter {
it.hasParents(name) || names.any { name -> it.hasParents(name) }
}
/**
* List containing declarations without all specified parents.
*
* @param name The name of the parent to exclude.
* @param names The name(s) of the parent(s) to exclude.
* @return A list containing declarations without all specified parent(s).
*/
@Deprecated(
"""
Will be removed in v0.16.0.
If you passed one argument - replace with `withoutParentNamed`, otherwise with `withoutAllParentsNamed`.
""",
ReplaceWith("withoutParentNamed/withoutAllParentsNamed"),
)
fun <T : KoParentProvider> List<T>.withoutAllParents(
name: String,
vararg names: String,
): List<T> =
filter {
!it.hasParents(name, *names)
}
/**
* List containing declarations without some parents represented by name.
*
* @param name The name of the parent to exclude.
* @param names The names of the parents to exclude.
* @return A list containing declarations without at least one of the specified parent(s).
*/
@Deprecated("Will be removed in v0.16.0.", ReplaceWith("withoutParentNamed(*names"))
fun <T : KoParentProvider> List<T>.withoutSomeParents(
name: String,
vararg names: String,
): List<T> =
filter {
val hasNoMatchingParents =
if (names.isNotEmpty()) {
names.any { name -> !it.hasParents(name) }
} else {
true
}
!it.hasParents(name) && hasNoMatchingParents
}
| 4
|
Kotlin
|
22
| 840
|
81324e09fe46c9f1095b133713ae0062e742c2e3
| 14,271
|
konsist
|
Apache License 2.0
|
kat/src/main/kotlin/msg/kat/encodings/formats/TypedKafkaRecord.kt
|
MarkOSIndustries
| 107,061,415
| false
|
{"Kotlin": 136360, "JavaScript": 116828, "HTML": 6120, "Dockerfile": 3104, "Shell": 1504, "Batchfile": 366}
|
package msg.kat.encodings.formats
import com.google.protobuf.ByteString
import msg.encodings.Transport
import msg.kat.encodings.KafkaEncoding
import msg.schemas.MSG
import org.apache.kafka.clients.consumer.ConsumerRecord
import org.apache.kafka.clients.producer.ProducerRecord
import org.apache.kafka.common.header.internals.RecordHeader
class KafkaRecord(transport: Transport<ByteArray>) : KafkaEncoding.OfBinary(transport) {
override fun toProducerRecord(topic: String, data: ByteArray): ProducerRecord<ByteArray, ByteArray> {
val record = MSG.KafkaRecord.parseFrom(data)
return ProducerRecord(
topic,
null,
record.key.toByteArray(),
record.value.toByteArray(),
record.headersList.map { header -> RecordHeader(header.keyBytes.asReadOnlyByteBuffer(), header.value.asReadOnlyByteBuffer()) }
)
}
override fun fromConsumerRecord(consumerRecord: ConsumerRecord<ByteArray, ByteArray>, schema: String): ByteArray {
val builder = MSG.KafkaRecord.newBuilder()
.setTopic(consumerRecord.topic())
.setPartition(consumerRecord.partition())
.setOffset(consumerRecord.offset())
.setTimestamp(consumerRecord.timestamp())
if (consumerRecord.key() != null) {
builder.key = ByteString.copyFrom(consumerRecord.key())
}
if (consumerRecord.value() != null) {
builder.value = ByteString.copyFrom(consumerRecord.value())
}
builder.addAllHeaders(consumerRecord.headers().map { header -> MSG.KafkaHeader.newBuilder().setValue(ByteString.copyFrom(header.value())).setKey(header.key()).build() })
return builder.build().toByteArray()
}
override fun toRecordKey(data: ByteArray): ByteArray {
val record = MSG.KafkaRecord.parseFrom(data)
return record.key.toByteArray()
}
}
| 9
|
Kotlin
|
1
| 6
|
a7bde01bae21085e36d971fc0ae994f1e2a41d5c
| 1,778
|
monosodium-glutamate
|
MIT License
|
app/src/main/java/com/example/andretortolano/githubsearch/ui/screens/showuser/ShowUserView.kt
|
andretortolano
| 94,994,900
| false
| null |
package com.example.andretortolano.githubsearch.ui.screens.showuser
import android.os.Bundle
import android.view.*
import com.example.andretortolano.githubsearch.R
import com.example.andretortolano.githubsearch.api.github.GithubService
import com.example.andretortolano.githubsearch.api.github.responses.User
import com.example.andretortolano.githubsearch.ui.screens.BaseFragment
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.fragment_user.*
class ShowUserView : BaseFragment<ShowUserContract.Presenter>(), ShowUserContract.View {
override lateinit var mPresenter: ShowUserContract.Presenter
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mPresenter = ShowUserPresenter(this, GithubService(), arguments.getString(USER_LOGIN))
}
override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {
super.onCreateOptionsMenu(menu, inflater)
menu?.clear()
}
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?)
= inflater!!.inflate(R.layout.fragment_user, container, false)!!
override fun showProgress() {
progress_view.visibility = View.VISIBLE
}
override fun hideProgress() {
progress_view.visibility = View.GONE
}
override fun showErrorMessage(message: String) {
showToast(message)
}
override fun showUser(user: User) {
user_name.text = user.name
Picasso.with(context)
.load(user.avatarUrl)
.placeholder(R.drawable.harrypotter_cat)
.into(user_avatar)
}
companion object {
var USER_LOGIN = "BUNDLE_USER_LOGIN"
fun newInstance(login: String): ShowUserView {
val fragment: ShowUserView = ShowUserView()
val args: Bundle = Bundle()
args.putString(USER_LOGIN, login)
fragment.arguments = args
return fragment
}
}
}
| 0
|
Kotlin
|
0
| 0
|
8bfd6f24ff3b3053ab193db1b6340ca0e4433428
| 2,029
|
GithubSearch
|
MIT License
|
app/src/main/java/com/mohammadfayaz/hn/ui/adapters/loading/LoadingIndicatorViewHolder.kt
|
fayaz07
| 431,064,021
| false
|
{"Kotlin": 109519}
|
package com.mohammadfayaz.hn.ui.adapters.loading
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.paging.LoadState
import androidx.recyclerview.widget.RecyclerView
import com.mohammadfayaz.hn.databinding.LayoutLoadingIndicatorBinding
class LoadingIndicatorViewHolder private constructor(
private val binding: LayoutLoadingIndicatorBinding,
retry: () -> Unit
) :
RecyclerView.ViewHolder(binding.root) {
init {
binding.retryButton.setOnClickListener { retry() }
}
fun bind(loadState: LoadState) {
binding.apply {
progressbar.isVisible = loadState is LoadState.Loading
statusTextView.isVisible = loadState !is LoadState.Loading
retryButton.isVisible = loadState !is LoadState.Loading
}
}
companion object {
fun from(parent: ViewGroup, retry: () -> Unit): LoadingIndicatorViewHolder {
return LoadingIndicatorViewHolder(
LayoutLoadingIndicatorBinding.inflate(
LayoutInflater.from(
parent.context
),
parent,
false
),
retry
)
}
}
}
| 13
|
Kotlin
|
2
| 4
|
498917164eeea6b7808ff30b8f772cf557e1c4e6
| 1,142
|
HackerNews
|
MIT License
|
viewlegacy/src/androidMain/kotlin/tech/skot/libraries/map/SkMapClusterRenderer.kt
|
useradgents
| 470,093,737
| true
|
{"Kotlin": 156431}
|
package tech.skot.libraries.map
import android.content.Context
import com.google.android.gms.maps.GoogleMap
import com.google.maps.android.clustering.Cluster
import com.google.maps.android.clustering.ClusterManager
import com.google.maps.android.clustering.view.DefaultClusterRenderer
class SkMapClusterRenderer(
context: Context,
map: GoogleMap,
clusterManager: ClusterManager<SKClusterMarker>,
val clusteringInteractionSettings: SKMapVC.MapClusteringInteractionSettings
) : DefaultClusterRenderer<SKClusterMarker>(context, map, clusterManager) {
}
| 0
|
Kotlin
|
0
| 0
|
9fb2c59c672cb1fad467c968d70c8d7b5040dfd4
| 572
|
sk-map
|
Apache License 2.0
|
app/src/main/java/com/alissonmanfron/busaocampolargo/fragment/favoritos/FragmentFavoritos.kt
|
AlissonManfron
| 143,551,272
| false
| null |
package com.alissonmanfron.busaocampolargo.fragment.favoritos
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.DefaultItemAnimator
import android.support.v7.widget.LinearLayoutManager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.alissonmanfron.busaocampolargo.R
import com.alissonmanfron.busaocampolargo.activity.detail.LinhaDetailActivity
import com.alissonmanfron.busaocampolargo.adapter.LinhasFavAdapter
import com.alissonmanfron.busaocampolargo.extensions.toast
import com.alissonmanfron.busaocampolargo.listener.FavoriteAddEvent
import com.alissonmanfron.busaocampolargo.listener.FavoriteRemoveEvent
import com.alissonmanfron.busaocampolargo.model.Linha
import kotlinx.android.synthetic.main.fragment_favoritos.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.koin.android.ext.android.inject
class FragmentFavoritos : Fragment(), FragFavoritosContract.LinhasView {
// Variables
override val presenter: FragFavoritosContract.LinhasPresenter by inject()
private var adapter: LinhasFavAdapter? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Registra para receber eventos do bus
EventBus.getDefault().register(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_favoritos, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
// Config recycler view
setupRecyclerView()
// Get instance presenter
presenter.subscribe(this)
// Get Linhas
presenter.loadLinhas()
}
private fun setupRecyclerView() {
rv_linhas_fav.layoutManager = LinearLayoutManager(activity)
rv_linhas_fav.itemAnimator = DefaultItemAnimator()
rv_linhas_fav.setHasFixedSize(true)
}
override fun setListLinhasObj(linhas: List<Linha>) {
// Atualiza a lista
activity?.runOnUiThread {
rv_linhas_fav.visibility = View.VISIBLE
adapter = LinhasFavAdapter(linhas) { linha: Linha, clickFavorite: Boolean ->
if (clickFavorite) onClickFavoriteLinha(linha) else onClickLinha(linha)
}
rv_linhas_fav.adapter = adapter
}
}
override fun setErrorLoadLinhas() {
toast("Ocorreu um erro ao carregar as listas. Tente novamente!")
}
override fun showProgressBar() {
activity?.runOnUiThread { pbLinhasFav.visibility = View.VISIBLE }
}
override fun hideProgressBar() {
activity?.runOnUiThread { pbLinhasFav.visibility = View.GONE }
}
override fun navigateToLinhaDetail(linha: Linha) {
val intent = Intent(activity, LinhaDetailActivity::class.java)
val bundle = Bundle()
bundle.putParcelable("linha", linha)
intent.putExtra("linhaBundle", bundle)
startActivity(intent)
}
override fun successRemoveFavorite(linha: Linha, msg: String) {
// Show message
toast(msg)
// Trigger an event to refresh the list
EventBus.getDefault().post(FavoriteRemoveEvent(linha))
// Remove current Linha
adapter?.removeLinha(linha)
}
override fun errorSetFavorite(msg: String) {
toast(msg)
}
fun onClickLinha(linha: Linha) {
presenter.onClickLinha(linha)
}
fun onClickFavoriteLinha(linha: Linha) {
presenter.onClickFavoriteLinha(linha)
}
@Subscribe
fun onRefresh(event: FavoriteAddEvent) {
println("event = [${event.linha.isFavorite}]")
presenter.loadLinhas()
}
override fun onDestroy() {
super.onDestroy()
presenter.unSubscribe()
// Cancela os eventos do bus
EventBus.getDefault().unregister(this)
}
}
| 0
|
Kotlin
|
0
| 0
|
2001d4dd96fac05e48b97e3004f61551b56ea5bf
| 4,164
|
Bus
|
Apache License 2.0
|
TrendAnalyzer/app/src/main/java/vorotilenko/trendanalyzer/fragments/chart/TradeData.kt
|
P-Vorotilenko
| 384,447,785
| false
| null |
package vorotilenko.trendanalyzer.fragments.chart
import android.os.Parcel
import android.os.Parcelable
/**
* Stores data about trades including only time and price.
*/
data class TradeData(
/**
* Trade time in milliseconds.
*/
val tradeTimeMillis: Long,
/**
* Price of the trade.
*/
val price: Double
) : Parcelable {
constructor(parcel: Parcel) : this(
parcel.readLong(),
parcel.readDouble()
)
override fun writeToParcel(parcel: Parcel, flags: Int) {
parcel.writeLong(tradeTimeMillis)
parcel.writeDouble(price)
}
override fun describeContents() = 0
companion object CREATOR : Parcelable.Creator<TradeData> {
override fun createFromParcel(parcel: Parcel) = TradeData(parcel)
override fun newArray(size: Int): Array<TradeData?> = arrayOfNulls(size)
}
}
| 0
|
Kotlin
|
0
| 0
|
09a65b0dd516e29a0624d19f3f6f0a523ba825dd
| 873
|
TrendAnalyzer
|
Apache License 2.0
|
src/test/kotlin/org/axonframework/intellij/ide/plugin/specifics/ConstantsInAnnotationTest.kt
|
AxonFramework
| 10,942,246
| false
|
{"Kotlin": 330266}
|
/*
* Copyright (c) 2022. Axon Framework
*
* 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.axonframework.intellij.ide.plugin.specifics
import org.assertj.core.api.Assertions.assertThat
import org.axonframework.intellij.ide.plugin.AbstractAxonFixtureTestCase
import org.axonframework.intellij.ide.plugin.resolving.MessageHandlerResolver
/**
* Test reference resolving in annotations
*/
class ConstantsInAnnotationTest : AbstractAxonFixtureTestCase() {
fun `test can handle kotlin to kotlin object constant references`() {
addFile(
"myfile.kt", """
object ProcessingGroupName {
const val SOME_PROJECTOR = "some-projector"
}
data class SomeEvent(val data: String)
@ProcessingGroup(ProcessingGroupName.SOME_PROJECTOR)
class LevelOneProcessingGroupProcessor {
@EventHandler
fun on(event: SomeEvent) {
}
}
"""
)
val resolver = project.getService(MessageHandlerResolver::class.java)
val handlers = resolver.findAllHandlers()
assertThat(handlers).anyMatch { it.payload == "test.SomeEvent" && it.renderContainerText() == "some-projector" }
}
fun `test can handle java to kotlin object constant references`() {
addFile(
"myfile.kt", """
object ProcessingGroupName {
const val SOME_PROJECTOR = "some-projector"
}
data class SomeEvent(val data: String)
"""
)
this.addFile(
"EventHandler.java", """
@ProcessingGroup(ProcessingGroupName.SOME_PROJECTOR)
public class LevelOneProcessingGroupProcessor {
@EventHandler
public void on(SomeEvent event) {
}
}
"""
)
val resolver = project.getService(MessageHandlerResolver::class.java)
val handlers = resolver.findAllHandlers()
// Java can't reach kotlin constant declarations somehow. For now the fallback is to show the text, can be improved in the future
// Ideally, we would test for "some-projector" here.
assertThat(handlers).anyMatch { it.payload == "test.SomeEvent" && it.renderContainerText() == "some-projector" }
}
fun `test can handle kotlin to java object constant references`() {
this.addFile(
"ProcessingGroupName.java", """
public class ProcessingGroupName {
public static final String SOME_PROJECTOR = "some-projector";
}
"""
)
addFile("event.kt", "data class SomeEvent(val data: String)")
addFile(
"myfile.kt", """
@ProcessingGroup(ProcessingGroupName.SOME_PROJECTOR)
class LevelOneProcessingGroupProcessor {
@EventHandler
fun on(event: SomeEvent) {
}
}
"""
)
val resolver = project.getService(MessageHandlerResolver::class.java)
val handlers = resolver.findAllHandlers()
// Will just return the package name because kotlin will return null resolving the value
// At least it won't crash, but this would be something to improve in the future.
assertThat(handlers).anyMatch { it.payload == "test.SomeEvent" && it.renderContainerText() == "test" }
}
}
| 22
|
Kotlin
|
19
| 34
|
781f71ca1707df9d23e624adddefa7050a408307
| 3,997
|
IdeaPlugin
|
Apache License 2.0
|
libraries/matrix/impl/src/main/kotlin/io/element/android/libraries/matrix/impl/roomlist/RoomListDynamicEvents.kt
|
element-hq
| 546,522,002
| false
| null |
/*
* Copyright (c) 2023 New Vector Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.element.android.libraries.matrix.impl.roomlist
import org.matrix.rustcomponents.sdk.RoomListEntriesDynamicFilterKind
internal sealed interface RoomListDynamicEvents {
data object Reset : RoomListDynamicEvents
data object LoadMore : RoomListDynamicEvents
data class SetFilter(val filter: RoomListEntriesDynamicFilterKind) : RoomListDynamicEvents
}
| 263
| null |
129
| 955
|
31d0621fa15fe153bfd36104e560c9703eabe917
| 975
|
element-x-android
|
Apache License 2.0
|
app/src/main/java/com/pt/mysociety/dashboard/events/EventsViewModelFactory.kt
|
Prathy
| 528,724,668
| false
| null |
package com.pt.mysociety.dashboard.events
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
/**
* ViewModel provider factory to instantiate LoginViewModel.
* Required given LoginViewModel has a non-empty constructor
*/
class EventsViewModelFactory : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
if (modelClass.isAssignableFrom(EventsViewModel::class.java)) {
return EventsViewModel() as T
}
throw IllegalArgumentException("Unknown ViewModel class")
}
}
| 0
|
Kotlin
|
0
| 0
|
2261e245887f46063b37e9dfbfbd851c9380cf7a
| 610
|
MySociety
|
Apache License 2.0
|
app/src/main/java/com/phantom/banguminote/detail/character/web/CharacterRelatedWebFragment.kt
|
PhantomLGZ
| 741,144,233
| false
|
{"Kotlin": 247864}
|
package com.phantom.banguminote.detail.character.web
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.navigation.fragment.findNavController
import com.phantom.banguminote.R
import com.phantom.banguminote.base.BaseFragment
import com.phantom.banguminote.databinding.FragmentCharacterRelatedWebBinding
import com.phantom.banguminote.detail.character.CharacterViewModel
import com.phantom.banguminote.detail.web.RelatedWebViewActivity
import com.phantom.banguminote.detail.web.getBangumiCharacterUrl
import com.phantom.banguminote.detail.web.getPixivUrl
class CharacterRelatedWebFragment : BaseFragment<FragmentCharacterRelatedWebBinding>() {
private val viewModel: CharacterViewModel by viewModels({ requireParentFragment() })
override fun inflateViewBinding(
inflater: LayoutInflater,
container: ViewGroup?
): FragmentCharacterRelatedWebBinding =
FragmentCharacterRelatedWebBinding.inflate(inflater, container, false)
override fun init() {
binding?.btBangumi?.setOnClickListener(onClickListener)
binding?.btPixiv?.setOnClickListener(onClickListener)
}
private val onClickListener = View.OnClickListener {
when (it) {
binding?.btBangumi -> {
findNavController().navigate(
R.id.action_nav_to_activity_related_web,
RelatedWebViewActivity.createBundle(viewModel.id.value?.getBangumiCharacterUrl())
)
}
binding?.btPixiv -> {
findNavController().navigate(
R.id.action_nav_to_activity_related_web,
RelatedWebViewActivity.createBundle(viewModel.characterRes.value?.name?.getPixivUrl())
)
}
}
}
}
| 0
|
Kotlin
|
0
| 3
|
f47b57c45c57eded74c80980a9d9853f61724c8d
| 1,867
|
BangumiNote
|
MIT License
|
src/main/kotlin/dev/fakek/fakes/FakerTypeAliases.kt
|
RafaelPereiraSantos
| 299,042,364
| true
|
{"Kotlin": 31759}
|
package dev.fakek.fakes
import com.github.javafaker.Address
import com.github.javafaker.Internet
import com.github.javafaker.Name
internal typealias FakerAddress = Address
internal typealias FakerInternet = Internet
internal typealias FakerName = Name
| 0
| null |
0
| 0
|
7535dc457df1aa7f248e25ad263511d411b4f36a
| 254
|
fakek
|
Apache License 2.0
|
src/test/kotlin/io/andrewohara/tabbychat/auth/dao/AuthorizationDaoTest.kt
|
oharaandrew314
| 391,217,773
| false
| null |
package io.andrewohara.tabbychat.auth.dao
import io.andrewohara.tabbychat.TestDriver
import io.andrewohara.tabbychat.auth.AccessToken
import io.andrewohara.tabbychat.auth.Realm
import io.andrewohara.tabbychat.contacts.Authorization
import io.andrewohara.tabbychat.createUser
import io.kotest.matchers.shouldBe
import org.http4k.core.Uri
import org.junit.jupiter.api.Test
class AuthorizationDaoTest {
private val driver = TestDriver()
private val provider = driver.createProvider(Realm(Uri.of("http://tabby.chat")))
private val testObj = provider.authDao
private val user1 = provider.createUser("user1")
private val user2 = provider.createUser("user2")
@Test
fun `create and get contact authorization`() {
val authorization = Authorization(
type = Authorization.Type.Contact,
principal = user1.id,
bearer = user2.id,
value = AccessToken("token2"),
expires = null
)
testObj += authorization
testObj[authorization.value] shouldBe authorization
}
}
| 0
|
Kotlin
|
0
| 0
|
a48f7604dd30180c9c88e40530480707e9cbcf43
| 1,076
|
tabby-chat-server
|
The Unlicense
|
src/scripts/kt/lumbridge/raider/api/behaviors/combat/magic/CombatMagicBehavior.kt
|
its-jackson
| 536,221,289
| false
|
{"Java": 132902, "Kotlin": 91701}
|
package scripts.kt.lumbridge.raider.api.behaviors.combat.magic
import org.tribot.script.sdk.Combat
import org.tribot.script.sdk.frameworks.behaviortree.*
import scripts.kt.lumbridge.raider.api.ScriptTask
import scripts.kt.lumbridge.raider.api.behaviors.banking.initializeBankTask
import scripts.kt.lumbridge.raider.api.behaviors.combat.completeCombatAction
fun IParentNode.combatMagicBehavior(scriptTask: ScriptTask?) = sequence {
// ensure the bank task is initialized,
// and the character has the correct items/equipment
initializeBankTask(scriptTask)
// ensure spell is auto selected
selector {
condition {
scriptTask?.combatMagicData?.autoCastableSpell
?.let {
Combat.getAutocastSpell()
.map { spell -> spell == it }
.orElse(false)
}
}
condition { scriptTask?.combatMagicData?.autoCastableSpell?.let { Combat.setAutocastSpell(it) } }
}
// execute the complete combat action {
// walking,
// waiting,
// attacking,
// eating
// banking,
// looting,
// get hyper,
// }
completeCombatAction(scriptTask)
}
| 1
| null |
1
| 1
|
a03aacb5748507fd9a9dbbc44b5329d1a1b02daa
| 1,218
|
lumbridge-raider-kt
|
MIT License
|
library/src/main/java/io/syslogic/colorpicker/compose/LayoutId.kt
|
syslogic
| 366,586,612
| false
|
{"Gradle": 4, "Java Properties": 2, "YAML": 3, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "XML": 26, "TOML": 1, "Java": 14, "Kotlin": 13, "Proguard": 1}
|
package io.syslogic.colorpicker.compose
/**
* Jetpack Compose Layout Ids
*
* @author Martin Zeitler
*/
enum class LayoutId {
AlphaPanel,
SatValPanel,
HuePanel,
OldColor,
NewColor,
EmbeddedColorPicker,
DialogSurface,
DialogTitleText,
DialogCloseIcon
}
| 0
|
Java
|
0
| 6
|
f2d68ad5c4a0f434c7a5254288ed5985d840624a
| 292
|
androidx-colorpicker
|
MIT License
|
src/core/src/main/kotlin/org/apache/jmeter/testelement/TestElementSchema.kt
|
hongweichang
| 650,399,793
| true
|
{"Java Properties": 220, "Gradle Kotlin DSL": 75, "XML": 215, "Shell": 14, "Markdown": 16, "EditorConfig": 1, "JSON": 17, "YAML": 10, "Git Attributes": 3, "Batchfile": 15, "Text": 47, "XSLT": 7, "Ignore List": 4, "Public Key": 218, "Kotlin": 72, "Java": 1406, "Groovy": 43, "HTML": 29, "SVG": 14, "E-mail": 1, "JavaScript": 38, "Less": 17, "CSS": 14, "SCSS": 14, "Makefile": 1, "Java Server Pages": 1, "Ant Build System": 1, "ApacheConf": 1, "Regular Expression": 1}
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you 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.apache.jmeter.testelement
import org.apache.jmeter.gui.JMeterGUIComponent
import org.apache.jmeter.testelement.schema.BooleanPropertyDescriptor
import org.apache.jmeter.testelement.schema.ClassPropertyDescriptor
import org.apache.jmeter.testelement.schema.EmptyTestElementSchema
import org.apache.jmeter.testelement.schema.StringPropertyDescriptor
import org.apiguardian.api.API
/**
* Lists properties of a [TestElement].
* @see TestElement
* @since 5.6
*/
@API(status = API.Status.EXPERIMENTAL, since = "5.6")
public open class TestElementSchema protected constructor() : EmptyTestElementSchema() {
public companion object INSTANCE : TestElementSchema()
public val name: StringPropertyDescriptor<TestElementSchema> =
string("TestElement.name")
public val comments: StringPropertyDescriptor<TestElementSchema> =
string("TestElement.comments")
public open val guiClass: ClassPropertyDescriptor<TestElementSchema, JMeterGUIComponent> =
classProperty(JMeterGUIComponent::class, "TestElement.gui_class")
public val testClass: ClassPropertyDescriptor<TestElementSchema, Any> =
classProperty(Any::class, "TestElement.testClass")
public val enabled: BooleanPropertyDescriptor<TestElementSchema> =
boolean("TestElement.enabled", default = true)
}
| 0
| null |
0
| 0
|
4e5b9df4579489f13d4c4ca3da4ff4ca6bc06c03
| 2,121
|
jmeter
|
Apache License 2.0
|
app/src/test/java/com/gzaber/forexviewer/ui/home/HomeViewModelTest.kt
|
gzaber
| 734,830,877
| false
|
{"Kotlin": 131338}
|
package com.gzaber.forexviewer.ui.home
import com.gzaber.forexviewer.util.fake.repository.FakeApiKeyRepository
import com.gzaber.forexviewer.util.fake.repository.FakeFavoritesRepository
import com.gzaber.forexviewer.data.repository.favorites.model.Favorite
import com.gzaber.forexviewer.util.fake.repository.FakeForexDataRepository
import com.gzaber.forexviewer.data.repository.forexdata.model.ExchangeRate
import com.gzaber.forexviewer.util.MainDispatcherRule
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import kotlinx.coroutines.test.UnconfinedTestDispatcher
import kotlinx.coroutines.test.runTest
import org.junit.Before
import org.junit.Rule
import org.junit.Test
@OptIn(ExperimentalCoroutinesApi::class)
class HomeViewModelTest {
private lateinit var viewModel: HomeViewModel
private lateinit var apiKeyRepository: FakeApiKeyRepository
private lateinit var favoritesRepository: FakeFavoritesRepository
private lateinit var forexDataRepository: FakeForexDataRepository
private val favorite = Favorite(1, "EUR/USD", "Euro", "US Dollar")
private val exchangeRate = ExchangeRate("EUR/USD", 1.1021)
@get:Rule
val rule = MainDispatcherRule()
@Before
fun setupViewModel() {
apiKeyRepository = FakeApiKeyRepository()
favoritesRepository =
FakeFavoritesRepository(initialFavorites = listOf(favorite))
forexDataRepository = FakeForexDataRepository(exchangeRate = exchangeRate)
viewModel = HomeViewModel(
apiKeyRepository = apiKeyRepository,
favoritesRepository = favoritesRepository,
forexDataRepository = forexDataRepository
)
}
@Test
fun initialState_emitsCorrectInitialState() = runTest {
val result = viewModel.uiState.value
assert(result == HomeUiState())
}
@Test
fun init_emitsApiKey() = runTest {
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect()
}
assert(viewModel.uiState.value.apiKeyText == "demo")
}
@Test
fun init_apiKeyRepositoryThrowsException_emitsFailureMessage() = runTest {
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect()
}
apiKeyRepository.setShouldThrowError(true)
assert(viewModel.uiState.value.failureMessage == "failure")
}
@Test
fun init_emitsUiFavorites() = runTest {
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect()
}
assert(viewModel.uiState.value.uiFavorites.size == 1)
assert(viewModel.uiState.value.uiFavorites.first().symbol == favorite.symbol)
assert(viewModel.uiState.value.uiFavorites.first().exchangeRate == exchangeRate.rate)
}
@Test
fun init_emptyFavoritesListCollected_emitsEmptyUiFavoritesList() = runTest {
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect()
}
favoritesRepository.clearFavorites()
assert(viewModel.uiState.value.uiFavorites.isEmpty())
}
@Test
fun init_favoritesRepositoryThrowsException_emitsFailureMessage() = runTest {
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect()
}
favoritesRepository.setShouldThrowFlowError(true)
assert(viewModel.uiState.value.failureMessage == "failure")
}
@Test
fun init_forexDataRepositoryThrowsException_emitsFailureMessage() = runTest {
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect()
}
forexDataRepository.setShouldThrowError(true)
assert(viewModel.uiState.value.failureMessage == "failure")
}
@Test
fun toggleShowingDialog_emitsToggledBooleanVariable() = runTest {
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect()
}
assert(!viewModel.uiState.value.showDialog)
viewModel.toggleShowingDialog()
assert(viewModel.uiState.value.showDialog)
}
@Test
fun onApiKeyTextChanged_emitsChangedApiKeyText() = runTest {
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect()
}
assert(viewModel.uiState.value.apiKeyText == "demo")
viewModel.onApiKeyTextChanged("changed")
assert(viewModel.uiState.value.apiKeyText == "changed")
}
@Test
fun saveApiKey_savesApiKey() = runTest {
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect()
}
viewModel.saveApiKey("newapikey")
assert(viewModel.uiState.value.apiKeyText == "newapikey")
}
@Test
fun saveApiKey_apiKeyRepositoryThrowsException_emitsFailureMessage() = runTest {
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect()
}
apiKeyRepository.setShouldThrowError(true)
viewModel.saveApiKey("newapikey")
assert(viewModel.uiState.value.failureMessage == "failure")
}
@Test
fun snackbarMessageShown_emitsResetFailureMessage() = runTest {
backgroundScope.launch(UnconfinedTestDispatcher(testScheduler)) {
viewModel.uiState.collect()
}
apiKeyRepository.setShouldThrowError(true)
viewModel.saveApiKey("newapikey")
assert(viewModel.uiState.value.failureMessage == "failure")
viewModel.snackbarMessageShown()
assert(viewModel.uiState.value.failureMessage == null)
}
}
| 0
|
Kotlin
|
0
| 0
|
b15832ebb0bb90cf844d7d7777fce9592be719d0
| 5,837
|
ForexViewer
|
MIT License
|
app/src/main/java/net/ddns/rkdawenterprises/weather_gov_api/Gridpoint.kt
|
rkdawenterprises
| 538,289,740
| false
| null |
/*
* Copyright (c) 2023 RKDAW Enterprises and <NAME>.
* email: <EMAIL>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:Suppress("ClassName",
"FunctionName",
"RedundantSemicolon",
"PrivatePropertyName",
"LocalVariableName",
"PropertyName",
"PackageName",
"unused")
package net.ddns.rkdawenterprises.weather_gov_api
class Gridpoint
{
var context: List<String>? = null
var id: String? = null
var type: String? = null
var geometry: Geometry? = null
var properties: Properties? = null
}
class Geometry
{
var type: String? = null
var coordinates: List<List<List<Double>>>? = null
}
class Properties
{
var id: String? = null
var type: String? = null
var updateTime: String? = null
var validTimes: String? = null
var elevation: Elevation? = null
var forecastOffice: String? = null
var gridId: String? = null
var gridX: String? = null
var gridY: String? = null
var temperature: Temperature? = null
var dewpoint: Dewpoint? = null
var maxTemperature: MaxTemperature? = null
var minTemperature: MinTemperature? = null
var relativeHumidity: RelativeHumidity? = null
var apparentTemperature: ApparentTemperature? = null
var wetBulbGlobeTemperature: WetBulbGlobeTemperature? = null
var heatIndex: HeatIndex? = null
var windChill: WindChill? = null
var skyCover: SkyCover? = null
var windDirection: WindDirection? = null
var windSpeed: WindSpeed? = null
var windGust: WindGust? = null
var weather: Weather? = null
var hazards: Hazards? = null
var probabilityOfPrecipitation: ProbabilityOfPrecipitation? = null
var quantitativePrecipitation: QuantitativePrecipitation? = null
var iceAccumulation: IceAccumulation? = null
var snowfallAmount: SnowfallAmount? = null
var snowLevel: SnowLevel? = null
var ceilingHeight: CeilingHeight? = null
var visibility: Visibility? = null
var transportWindSpeed: TransportWindSpeed? = null
var transportWindDirection: TransportWindDirection? = null
var mixingHeight: MixingHeight? = null
var hainesIndex: HainesIndex? = null
var lightningActivityLevel: LightningActivityLevel? = null
var twentyFootWindSpeed: TwentyFootWindSpeed? = null
var twentyFootWindDirection: TwentyFootWindDirection? = null
var waveHeight: WaveHeight? = null
var wavePeriod: WavePeriod? = null
var waveDirection: WaveDirection? = null
var primarySwellHeight: PrimarySwellHeight? = null
var primarySwellDirection: PrimarySwellDirection? = null
var secondarySwellHeight: SecondarySwellHeight? = null
var secondarySwellDirection: SecondarySwellDirection? = null
var wavePeriod2: WavePeriod2? = null
var windWaveHeight: WindWaveHeight? = null
var dispersionIndex: DispersionIndex? = null
var pressure: Pressure? = null
var probabilityOfTropicalStormWinds: ProbabilityOfTropicalStormWinds? = null
var probabilityOfHurricaneWinds: ProbabilityOfHurricaneWinds? = null
var potentialOf15mphWinds: PotentialOf15mphWinds? = null
var potentialOf25mphWinds: PotentialOf25mphWinds? = null
var potentialOf35mphWinds: PotentialOf35mphWinds? = null
var potentialOf45mphWinds: PotentialOf45mphWinds? = null
var potentialOf20mphWindGusts: PotentialOf20mphWindGusts? = null
var potentialOf30mphWindGusts: PotentialOf30mphWindGusts? = null
var potentialOf40mphWindGusts: PotentialOf40mphWindGusts? = null
var potentialOf50mphWindGusts: PotentialOf50mphWindGusts? = null
var potentialOf60mphWindGusts: PotentialOf60mphWindGusts? = null
var grasslandFireDangerIndex: GrasslandFireDangerIndex? = null
var probabilityOfThunder: ProbabilityOfThunder? = null
var davisStabilityIndex: DavisStabilityIndex? = null
var atmosphericDispersionIndex: AtmosphericDispersionIndex? = null
var lowVisibilityOccurrenceRiskIndex: LowVisibilityOccurrenceRiskIndex? = null
var stability: Stability? = null
var redFlagThreatIndex: RedFlagThreatIndex? = null
}
class Elevation
{
var unitCode: String? = null
var value: Double? = null
}
class Temperature
{
var uom: String? = null
var values: List<Value>? = null
}
class Dewpoint
{
var uom: String? = null
var values: List<Value>? = null
}
class MaxTemperature
{
var uom: String? = null
var values: List<Value>? = null
}
class MinTemperature
{
var uom: String? = null
var values: List<Value>? = null
}
class RelativeHumidity
{
var uom: String? = null
var values: List<Value>? = null
}
class ApparentTemperature
{
var uom: String? = null
var values: List<Value>? = null
}
class WetBulbGlobeTemperature
{
var uom: String? = null
var values: List<Value>? = null
}
class HeatIndex
{
var uom: String? = null
var values: List<Value>? = null
}
class WindChill
{
var uom: String? = null
var values: List<Value>? = null
}
class SkyCover
{
var uom: String? = null
var values: List<Value>? = null
}
class WindDirection
{
var uom: String? = null
var values: List<Value>? = null
}
class WindSpeed
{
var uom: String? = null
var values: List<Value>? = null
}
class WindGust
{
var uom: String? = null
var values: List<Value>? = null
}
class Weather
{
var values: List<Value_weather>? = null
}
class Hazards
{
var values: List<Value_hazards>? = null
}
class ProbabilityOfPrecipitation
{
var uom: String? = null
var values: List<Value>? = null
}
class QuantitativePrecipitation
{
var uom: String? = null
var values: List<Value>? = null
}
class IceAccumulation
{
var uom: String? = null
var values: List<Value>? = null
}
class SnowfallAmount
{
var uom: String? = null
var values: List<Value>? = null
}
class SnowLevel
{
var values: List<Any>? = null
}
class CeilingHeight
{
var uom: String? = null
var values: List<Value>? = null
}
class Visibility
{
var uom: String? = null
var values: List<Value>? = null
}
class TransportWindSpeed
{
var uom: String? = null
var values: List<Value>? = null
}
class TransportWindDirection
{
var uom: String? = null
var values: List<Value>? = null
}
class MixingHeight
{
var uom: String? = null
var values: List<Value>? = null
}
class HainesIndex
{
var values: List<Value>? = null
}
class LightningActivityLevel
{
var values: List<Any>? = null
}
class TwentyFootWindSpeed
{
var uom: String? = null
var values: List<Value>? = null
}
class TwentyFootWindDirection
{
var uom: String? = null
var values: List<Value>? = null
}
class WaveHeight
{
var values: List<Any>? = null
}
class WavePeriod
{
var values: List<Any>? = null
}
class WaveDirection
{
var values: List<Any>? = null
}
class PrimarySwellHeight
{
var values: List<Any>? = null
}
class PrimarySwellDirection
{
var values: List<Any>? = null
}
class SecondarySwellHeight
{
var values: List<Any>? = null
}
class SecondarySwellDirection
{
var values: List<Any>? = null
}
class WavePeriod2
{
var values: List<Any>? = null
}
class WindWaveHeight
{
var values: List<Any>? = null
}
class DispersionIndex
{
var values: List<Any>? = null
}
class Pressure
{
var values: List<Any>? = null
}
class ProbabilityOfTropicalStormWinds
{
var values: List<Any>? = null
}
class ProbabilityOfHurricaneWinds
{
var values: List<Any>? = null
}
class PotentialOf15mphWinds
{
var values: List<Any>? = null
}
class PotentialOf20mphWindGusts
{
var values: List<Any>? = null
}
class PotentialOf25mphWinds
{
var values: List<Any>? = null
}
class PotentialOf30mphWindGusts
{
var values: List<Any>? = null
}
class PotentialOf35mphWinds
{
var values: List<Any>? = null
}
class PotentialOf40mphWindGusts
{
var values: List<Any>? = null
}
class PotentialOf45mphWinds
{
var values: List<Any>? = null
}
class PotentialOf50mphWindGusts
{
var values: List<Any>? = null
}
class PotentialOf60mphWindGusts
{
var values: List<Any>? = null
}
class GrasslandFireDangerIndex
{
var values: List<Any>? = null
}
class ProbabilityOfThunder
{
var values: List<Any>? = null
}
class DavisStabilityIndex
{
var values: List<Value>? = null
}
class AtmosphericDispersionIndex
{
var values: List<Any>? = null
}
class LowVisibilityOccurrenceRiskIndex
{
var values: List<Value>? = null
}
class Stability
{
var values: List<Value>? = null
}
class RedFlagThreatIndex
{
var values: List<Any>? = null
}
class Value
{
var validTime: String? = null
var value: String? = null
}
class Value_weather
{
var validTime: String? = null
var value: List<Value>? = null
class Value
{
var coverage: String? = null
var weather: String? = null
var intensity: String? = null
var visibility: Visibility? = null
var attributes: List<Any>? = null
class Visibility
{
var unitCode: String? = null
var value: Any? = null
}
}
}
class Value_hazards
{
var validTime: String? = null
var value: List<Value>? = null
class Value
{
var phenomenon: String? = null
var significance: String? = null
var eventNumber: Any? = null
}
}
| 0
|
Kotlin
|
0
| 0
|
bd4195667c416504b0cb7d4c99ad796cbac2bcd9
| 9,895
|
weatherstationdonna
|
Apache License 2.0
|
shared/src/commonMain/kotlin/nowplaying/Constants.kt
|
exyte
| 662,910,206
| false
| null |
package nowplaying
const val ANIM_DURATION = 500
| 0
|
Kotlin
|
5
| 44
|
822d1bdc2149e855db16c65570f2ccc3e650ba1f
| 50
|
ComposeMultiplatformDribbbleAudio
|
Apache License 2.0
|
src/main/kotlin/cn/gongyinan/yasha/task/db/converter/DefaultDbDataConverter.kt
|
gyn7561
| 239,718,549
| false
|
{"Java": 188789, "Kotlin": 89409}
|
package cn.gongyinan.yasha.task.db.converter
import cn.gongyinan.yasha.YashaDbModal
import cn.gongyinan.yasha.task.YashaTask
import java.net.URI
class DefaultDbDataConverter : IDbDataConverter {
override fun toYashaDbModal(yashaTask: YashaTask): YashaDbModal {
val dbModal = YashaDbModal(
yashaTask.taskIdentifier,
taskDepth = yashaTask.taskDepth,
requestUrl = yashaTask.uri.toString(),
taskCommand = yashaTask.taskCommand,
requestBody = yashaTask.requestBody,
ready = true,
requestMethod = yashaTask.method,
parentTaskIdentifier = yashaTask.parentTaskIdentifier,
extraData = yashaTask.extraData,
createTime = yashaTask.createTime
)
dbModal.requestHeaders = yashaTask.headers
return dbModal
}
override fun toYashaTask(yashaDbModal: YashaDbModal): YashaTask {
return YashaTask(
URI(yashaDbModal.requestUrl),
yashaDbModal.taskDepth,
yashaDbModal.requestBody,
yashaDbModal.requestMethod,
yashaDbModal.requestHeaders,
yashaDbModal.extraData,
yashaDbModal.parentTaskIdentifier,
yashaDbModal.taskIdentifier,
yashaDbModal.taskCommand,
yashaDbModal.createTime
)
}
}
| 0
|
Java
|
0
| 1
|
255d184b08232f09f939fc7ce2d7e869ef895d8a
| 1,446
|
yasha
|
MIT License
|
0872.Leaf-Similar Trees.kt
|
sarvex
| 842,260,390
| false
|
{"Kotlin": 1775678, "PowerShell": 418}
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
internal class Solution {
fun leafSimilar(root1: TreeNode, root2: TreeNode): Boolean {
val l1: List<Int> = ArrayList()
val l2: List<Int> = ArrayList()
dfs(root1, l1)
dfs(root2, l2)
return l1.equals(l2)
}
private fun dfs(root: TreeNode, nums: List<Int>) {
if (root.left === root.right) {
nums.add(root.`val`)
return
}
if (root.left != null) {
dfs(root.left, nums)
}
if (root.right != null) {
dfs(root.right, nums)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
17a80985d970c8316fb694e4952692e598d700af
| 803
|
kotlin-leetcode
|
MIT License
|
buildSrc/src/main/kotlin/Application.kt
|
wkchae
| 576,075,411
| false
|
{"Kotlin": 86734}
|
import org.gradle.api.JavaVersion
/**
* @author hubtwork (alenheo)
* @contacts hubtwork@gmail.com
*/
object Application {
// create proper namespace with root path
fun namespace(modulePath: String): String {
return "com.hubtwork.clean_android.$modulePath"
}
const val ID = "com.hubtwork.clean_android.app"
// about android SDK version
const val compileSdk = 33
const val minSdk = 21
const val targetSdk = 33
// about app version
const val versionCode = 1
const val versionName = "0.0.1"
// about jvm
const val jvmTarget = "11"
val jvmTargetCompat = JavaVersion.VERSION_11
val jvmSourceCompat = JavaVersion.VERSION_11
}
| 0
| null |
0
| 0
|
a7ac7a6180b1d14aedf4ebef963fa58646b8a43f
| 691
|
Android-CleanArchitecture-Template
|
Apache License 2.0
|
src/providers/implementations/Guilded.kt
|
DRSchlaubi
| 842,196,978
| false
|
{"Kotlin": 94736, "HTML": 1973, "Dockerfile": 214}
|
package dev.schlaubi.openid.helper.providers.implementations
import dev.schlaubi.openid.helper.providers.ProviderRegistry
import dev.schlaubi.openid.helper.providers.registerProvider
fun ProviderRegistry.guilded() = registerProvider("guilded") {
authorize("https://authlink.app/auth")
token("https://authlink.app/api/v1/token")
userEndpoint {
request { url("https://authlink.app/api/v1/users/@me") }
response {
json { (data) ->
put("sub", data["id"]!!)
put("preferred_username", data["name"]!!)
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
b0e599f8c34c6e56a16b4e3ca6ec55fa41dd47c7
| 603
|
openid-helper
|
MIT License
|
app/src/main/java/vn/loitp/a/cv/et/autoResize/AutoResizeEditTextActivityFont.kt
|
tplloi
| 126,578,283
| false
| null |
package vn.loitp.a.cv.et.autoResize
import android.os.Bundle
import androidx.core.view.isVisible
import com.loitp.annotation.IsFullScreen
import com.loitp.annotation.LogTag
import com.loitp.core.base.BaseActivityFont
import com.loitp.core.ext.setSafeOnClickListenerElastic
import kotlinx.android.synthetic.main.a_et_auto_resize.*
import vn.loitp.R
@LogTag("AutoResizeEditTextActivity")
@IsFullScreen(false)
class AutoResizeEditTextActivityFont : BaseActivityFont() {
override fun setLayoutResourceId(): Int {
return R.layout.a_et_auto_resize
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setupViews()
}
private fun setupViews() {
lActionBar.apply {
this.ivIconLeft.setSafeOnClickListenerElastic(
runnable = {
onBaseBackPressed()
}
)
this.ivIconRight?.isVisible = false
this.tvTitle?.text = AutoResizeEditTextActivityFont::class.java.simpleName
}
}
}
| 0
|
Kotlin
|
0
| 10
|
333bebaf3287b1633f35d29b8adaf25b19c1859f
| 1,063
|
base
|
Apache License 2.0
|
trixnity-utils/src/jvmMain/kotlin/net/folivo/trixnity/utils/ByteBufferExtensions.kt
|
benkuly
| 330,904,570
| false
|
{"Kotlin": 4226967, "JavaScript": 5352, "TypeScript": 2906, "Dockerfile": 2635, "CSS": 1454}
|
package net.folivo.trixnity.utils
import kotlinx.coroutines.flow.flowOf
import java.nio.ByteBuffer
fun ByteBuffer.toByteArrayFlow(): ByteArrayFlow {
return flowOf(array().copyOf())
}
| 0
|
Kotlin
|
3
| 30
|
ae3045394cb661f8ac31dbbd8e4fc0e2daea661b
| 188
|
trixnity
|
Apache License 2.0
|
app/src/main/java/com/wisnu/kurniawan/composetodolist/features/todo/detail/ui/ListDetailAction.kt
|
wisnukurniawan
| 409,054,048
| false
| null |
package com.wisnu.kurniawan.composetodolist.features.todo.detail.ui
import androidx.compose.ui.text.input.TextFieldValue
import com.wisnu.kurniawan.composetodolist.model.ToDoTask
sealed class ListDetailAction {
sealed class ListAction : ListDetailAction() {
object Create : ListAction()
object Update : ListAction()
object CancelUpdate : ListAction()
data class ApplyColor(val color: ColorItem) : ListAction()
data class ChangeName(val name: String) : ListAction()
data class InitName(val name: String) : ListAction()
}
sealed class TaskAction : ListDetailAction() {
object ClickImeDone : TaskAction()
object ClickSubmit : TaskAction()
object OnShow : TaskAction()
data class Delete(val task: ToDoTask) : TaskAction()
data class OnToggleStatus(val task: ToDoTask) : TaskAction()
data class ChangeTaskName(val name: TextFieldValue) : TaskAction()
}
}
| 0
|
Kotlin
|
4
| 73
|
784a7b86014f4d0b3ee0d2055aaa64f731bcbfd6
| 971
|
Compose-ToDo
|
Apache License 2.0
|
library/src/commonMain/kotlin/component/PasscodeHeader.kt
|
akashmeruva9
| 852,982,975
| false
|
{"Kotlin": 64924}
|
package component
import androidx.compose.animation.core.MutableTransitionState
import androidx.compose.animation.core.Transition
import androidx.compose.animation.core.animateFloat
import androidx.compose.animation.core.animateOffset
import androidx.compose.animation.core.updateTransition
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.offset
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.scale
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.mifos.library.resources.Res
import com.mifos.library.resources.confirm_passcode
import com.mifos.library.resources.create_passcode
import com.mifos.library.resources.enter_your_passcode
import utility.Step
import org.jetbrains.compose.resources.stringResource
@Composable
fun PasscodeHeader(
modifier: Modifier = Modifier,
activeStep: Step,
isPasscodeAlreadySet: Boolean,
) {
val transitionState = remember { MutableTransitionState(activeStep) }
transitionState.targetState = activeStep
val transition: Transition<Step> = updateTransition(
transitionState = transitionState,
label = "Headers Transition"
)
val offset = 200.0F
val zeroOffset = Offset(x = 0.0F, y = 0.0F)
val negativeOffset = Offset(x = -offset, y = 0.0F)
val positiveOffset = Offset(x = offset, y = 0.0F)
val xTransitionHeader1 by transition.animateOffset(label = "Transition Offset Header 1") {
if (it == Step.Create) zeroOffset else negativeOffset
}
val xTransitionHeader2 by transition.animateOffset(label = "Transition Offset Header 2") {
if (it == Step.Confirm) zeroOffset else positiveOffset
}
val alphaHeader1 by transition.animateFloat(label = "Transition Alpha Header 1") {
if (it == Step.Create) 1.0F else 0.0F
}
val alphaHeader2 by transition.animateFloat(label = "Transition Alpha Header 2") {
if (it == Step.Confirm) 1.0F else 0.0F
}
val scaleHeader1 by transition.animateFloat(label = "Transition Alpha Header 1") {
if (it == Step.Create) 1.0F else 0.5F
}
val scaleHeader2 by transition.animateFloat(label = "Transition Alpha Header 2") {
if (it == Step.Confirm) 1.0F else 0.5F
}
Box(
modifier = modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
Box(
modifier = modifier.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
if (isPasscodeAlreadySet) {
Text(
modifier = Modifier
.offset(x = xTransitionHeader1.x.dp)
.alpha(alpha = alphaHeader1)
.scale(scale = scaleHeader1),
text = stringResource(resource = Res.string.enter_your_passcode),
style = TextStyle(fontSize = 20.sp)
)
} else {
if (activeStep == Step.Create) {
Text(
modifier = Modifier
.offset(x = xTransitionHeader1.x.dp)
.alpha(alpha = alphaHeader1)
.scale(scale = scaleHeader1),
text = stringResource(resource = Res.string.create_passcode),
style = TextStyle(fontSize = 20.sp)
)
} else if (activeStep == Step.Confirm) {
Text(
modifier = Modifier
.offset(x = xTransitionHeader2.x.dp)
.alpha(alpha = alphaHeader2)
.scale(scale = scaleHeader2),
text = stringResource(resource = Res.string.confirm_passcode),
style = TextStyle(fontSize = 20.sp)
)
}
}
}
}
}
//@Preview
//@Composable
//fun PasscodeHeaderPreview() {
// PasscodeHeader(activeStep = Step.Create, isPasscodeAlreadySet = true)
//}
| 0
|
Kotlin
|
0
| 0
|
6f32a16d9850703940d38952a35ca10764a6d9ca
| 4,449
|
cmp-mifos-passcode
|
Apache License 2.0
|
app/src/main/java/com/samirmaciel/gerenciadorbancoimobiliario/ui/Components.kt
|
samirmaciel
| 775,724,117
| false
|
{"Kotlin": 43205}
|
package com.samirmaciel.gerenciadorbancoimobiliario.ui
import android.annotation.SuppressLint
import android.bluetooth.BluetoothDevice
import androidx.annotation.ColorInt
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.Divider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.rotate
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.samirmaciel.gerenciadorbancoimobiliario.R
import com.samirmaciel.gerenciadorbancoimobiliario.domain.models.Player
import com.samirmaciel.gerenciadorbancoimobiliario.ui.theme.SfProRoundedTypography
import com.samirmaciel.gerenciadorbancoimobiliario.ui.theme.dark_yellow
import com.samirmaciel.gerenciadorbancoimobiliario.ui.theme.light_white
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieCompositionSpec
import com.airbnb.lottie.compose.LottieConstants
import com.airbnb.lottie.compose.animateLottieCompositionAsState
import com.airbnb.lottie.compose.rememberLottieComposition
import com.samirmaciel.gerenciadorbancoimobiliario.domain.models.MoneyTransaction
import com.samirmaciel.gerenciadorbancoimobiliario.ui.theme.blue
import com.samirmaciel.gerenciadorbancoimobiliario.ui.theme.light_black
@Composable
fun PlayerCard(player: Player, enabledSendMoney: Boolean = false, onSendMoney: (String) -> Unit) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp), verticalAlignment = Alignment.CenterVertically
) {
PlayerImage(playerInitial = player.name[0], playerColor = player.color)
Column(
modifier = Modifier
.weight(1f)
.padding(start = 8.dp),
verticalArrangement = Arrangement.Center
) {
Text(
modifier = Modifier.height(20.dp),
text = player.name,
style = SfProRoundedTypography.titleSmall.copy(color = Color.Black)
)
Text(
modifier = Modifier.height(20.dp),
text = player.type,
style = SfProRoundedTypography.labelSmall.copy(color = light_black)
)
}
IconButton(modifier = Modifier
.background(dark_yellow, RoundedCornerShape(5.dp))
.height(40.dp)
.width(40.dp), colors = IconButtonDefaults.iconButtonColors(
contentColor = Color.Black
), enabled = enabledSendMoney,
onClick = { onSendMoney(player.id) }) {
Icon(
modifier = Modifier.padding(0.dp),
painter = painterResource(id = R.drawable.send_icon),
contentDescription = "Send money"
)
}
}
}
@Composable
fun AnimationLottie(modifier: Modifier = Modifier, rawAnimationResource: Int) {
val composition by rememberLottieComposition(LottieCompositionSpec.RawRes(rawAnimationResource))
val progress by animateLottieCompositionAsState(composition = composition, iterations = LottieConstants.IterateForever)
LottieAnimation(
modifier = modifier,
composition = composition,
progress = { progress },
)
}
@Composable
fun CustomSearchTextField(
modifier: Modifier = Modifier,
hint: String,
value: String,
keyboardType: KeyboardType = KeyboardType.Text,
onTextChange: (String) -> Unit
) {
OutlinedTextField(
modifier = modifier.padding(0.dp), colors = OutlinedTextFieldDefaults.colors(
focusedBorderColor = Color.Black,
unfocusedBorderColor = Color.Black,
), label = {
Text(
text = hint,
style = SfProRoundedTypography.titleMedium.copy(
color = Color.Gray,
fontSize = 15.sp
),
)
}, value = value,
onValueChange = onTextChange,
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = keyboardType
),
shape = RoundedCornerShape(15.dp),
leadingIcon = {
Icon(imageVector = Icons.Default.Search, contentDescription = "Search")
}
)
}
@Composable
fun CustomTextField(
modifier: Modifier = Modifier,
hint: String,
value: String,
keyboardType: KeyboardType = KeyboardType.Text,
onTextChange: (String) -> Unit
) {
OutlinedTextField(
modifier = modifier, colors = OutlinedTextFieldDefaults.colors(
focusedBorderColor = Color.Black,
unfocusedBorderColor = Color.Black,
), label = {
Text(
text = hint,
style = SfProRoundedTypography.titleMedium.copy(color = Color.Gray, fontSize = 15.sp),
)
}, value = value,
onValueChange = onTextChange,
keyboardOptions = KeyboardOptions.Default.copy(
keyboardType = keyboardType
),
shape = RoundedCornerShape(15.dp)
)
}
@Composable
fun CustomTopBar(title: String, navController: NavController) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(50.dp), contentAlignment = Alignment.BottomCenter
) {
Divider(
color = Color.Gray, modifier = Modifier
.fillMaxWidth()
.height(0.5.dp)
)
Row(modifier = Modifier.matchParentSize(), horizontalArrangement = Arrangement.Start) {
IconButton(onClick = { navController.navigateUp() }) {
Icon(imageVector = Icons.Default.ArrowBack, contentDescription = "Arrow back")
}
}
Row(
modifier = Modifier.matchParentSize(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = title,
color = Color.Black,
style = SfProRoundedTypography.titleMedium
)
}
}
}
@SuppressLint("MissingPermission")
@Composable
fun BluetoothConnectionList(
deviceList: List<BluetoothDevice>,
onClick: (BluetoothDevice) -> Unit,
modifier: Modifier = Modifier
) {
LazyColumn(
modifier = modifier.padding(16.dp), verticalArrangement = Arrangement.Top
) {
items(deviceList) {device ->
Row {
Text(
text = device.name,
modifier = Modifier
.clickable { onClick(device) }
.padding(16.dp)
)
}
}
}
}
@SuppressLint("MissingPermission")
@Composable
fun DeviceConnectionCard(device: BluetoothDevice, onClickConnection: (BluetoothDevice) -> Unit){
Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
Text(modifier = Modifier.weight(1f), text = device.name, style = SfProRoundedTypography.titleMedium.copy(color = Color.Black))
IconButton(modifier = Modifier
.background(blue, RoundedCornerShape(5.dp))
.height(40.dp)
.width(40.dp), colors = IconButtonDefaults.iconButtonColors(
contentColor = Color.Black
), onClick = { onClickConnection(device) }) {
Icon(
modifier = Modifier
.padding(0.dp)
.rotate(90f),
painter = painterResource(id = R.drawable.send_icon),
contentDescription = "Connect bluetooth"
)
}
}
}
@Composable
fun PlayerImage(modifier: Modifier = Modifier, size: Dp = 40.dp, playerInitial: Char, playerColor: Color = light_white){
Box(modifier = modifier){
Box(
modifier = Modifier
.size(size)
.background(playerColor, CircleShape), contentAlignment = Alignment.Center
) {
Text(
text = playerInitial.toString(),
style = SfProRoundedTypography.titleSmall.copy(
fontWeight = FontWeight.Bold,
color = Color.Black
)
)
}
}
}
@Composable
fun TransactionsList(moneyTransactionList: List<MoneyTransaction>) {
LazyColumn {
items(moneyTransactionList) { moneyTransaction ->
MoneyTransactionCard(moneyTransaction = moneyTransaction)
}
}
}
@Composable
fun MoneyTransactionCard(moneyTransaction: MoneyTransaction) {
val sender = moneyTransaction.playerSender
val receiver = moneyTransaction.playerReceiver
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start
) {
Row(modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {
PlayerImage(
modifier = Modifier.padding(end = 10.dp),
size = 30.dp,
playerInitial = sender.name[0],
playerColor = sender.color
)
Text(
modifier = Modifier.padding(end = 10.dp),
text = sender.name,
style = SfProRoundedTypography.titleSmall
)
Icon(
modifier = Modifier
.padding(end = 10.dp)
.rotate(90f),
painter = painterResource(id = R.drawable.send_icon),
contentDescription = "Send Icon"
)
Text(
modifier = Modifier.padding(end = 10.dp),
text = receiver.name,
style = SfProRoundedTypography.titleSmall
)
PlayerImage(
playerInitial = receiver.name[0],
size = 30.dp,
playerColor = receiver.color
)
}
Text(
modifier = Modifier,
text = moneyTransaction.value.toString(),
style = SfProRoundedTypography.labelMedium
)
}
}
| 0
|
Kotlin
|
0
| 0
|
2a4d71839c1d00273efb0182e1276f0fdd5c65ac
| 11,647
|
GerenciadorBancoImobiliario-App
|
MIT License
|
app/src/main/java/com/lighthouse/sendbird_demo/CustomFactory.kt
|
flash159483
| 680,804,161
| false
| null |
package com.lighthouse.sendbird_demo
import android.os.Bundle
import androidx.fragment.app.Fragment
import com.sendbird.uikit.fragments.UIKitFragmentFactory
class CustomFactory : UIKitFragmentFactory() {
override fun newChannelListFragment(args: Bundle): Fragment {
val fragment = CustomChannelList()
fragment.arguments = args
return fragment
}
}
| 1
|
Kotlin
|
0
| 0
|
92f90eab34abde0e834af4e11baa73a7797122f2
| 380
|
sendbird_customization
|
Apache License 2.0
|
formbuilder/src/main/java/it/ciaosonokekko/formbuilder/form/view/FormRecyclerView.kt
|
ciaosonokekko
| 305,103,256
| false
| null |
package it.ciaosonokekko.formbuilder.form.view
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import it.ciaosonokekko.formbuilder.databinding.ViewRecyclerFormBinding
import it.ciaosonokekko.formbuilder.form.Form
import it.ciaosonokekko.formbuilder.form.adapter.FormRecyclerViewAdapter
class FormRecyclerView : ConstraintLayout {
private var view: ViewRecyclerFormBinding? = null
private var adapter: FormRecyclerViewAdapter? = null
private var elements = mutableListOf<Form>()
private var setupped: Boolean = false
constructor(context: Context) : super(context) {
initView()
}
constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
initView()
}
private fun initView() {
view = ViewRecyclerFormBinding.inflate(LayoutInflater.from(context))
view?.root?.layoutParams = LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT
)
addView(view?.root)
}
fun setup(_elements: MutableList<Form>? = null, layoutManager: RecyclerView.LayoutManager? = LinearLayoutManager(context, LinearLayoutManager.VERTICAL,false)) {
_elements?.let {
elements = it
}
view?.container?.layoutManager = layoutManager
adapter = FormRecyclerViewAdapter(elements)
view?.container?.adapter = adapter
setupped = true
}
private fun checkSetup() {
if(!setupped) {
setup()
setupped = true
}
}
fun addElement(element: Form) {
checkSetup()
adapter?.addElement(element)
}
fun addElements(elements: MutableList<Form>) {
checkSetup()
elements.forEach {
adapter?.addElement(it)
}
}
fun addElements(vararg elements: Form) {
checkSetup()
elements.forEach {
adapter?.addElement(it)
}
}
fun updateElementAt(element: Form, position: Int) {
elements[position] = element
adapter?.updateElementAt(element, position)
}
fun updateElement(element: Form) {
val position = positionFromId(element.id)
if (position > -1) {
elements[position] = element
adapter?.updateElementAt(element, position)
} else {
addElement(element)
}
}
fun updateElements(_elements: MutableList<Form>) {
elements = _elements
adapter?.updateElements(elements)
}
fun updateElementValueFromId(value: String? = null, id: String) {
val position = positionFromId(id)
if (position > -1) {
elements[position].value = value
adapter?.updateElementAt(elements[position], position)
}
}
private fun positionFromId(id: String) : Int {
elements.forEachIndexed { position, form ->
if (form.id.equals(id, true)) {
return position
}
}
return -1
}
val invalidElements: MutableList<Form>
get() {
val invalidElements: MutableList<Form> = mutableListOf()
elements.forEach { form ->
if (form.isValid()) {
invalidElements.add(form)
}
}
return invalidElements
}
val validateForm: Boolean
get() {
return invalidElements.isEmpty()
}
}
| 0
|
Kotlin
|
0
| 2
|
030afcadef342d8bf3cbd527d2a095c0edffe293
| 3,587
|
KBuilder
|
MIT License
|
daemon/src/main/kotlin/dev/krud/boost/daemon/actuator/model/HealthActuatorResponse.kt
|
krud-dev
| 576,882,508
| false
| null |
package dev.krud.boost.daemon.actuator.model
data class HealthActuatorResponse(
val status: Status = Status.UNKNOWN,
val components: Map<String, Component>? = null,
val groups: List<String>? = null,
val details: Map<String, Any>? = null
) {
enum class Status {
UP, DOWN, OUT_OF_SERVICE, UNKNOWN
}
data class Component(
val status: Status = Status.UNKNOWN,
val description: String? = null,
val components: Map<String, Component>? = null,
val details: Map<String, Any>? = null
)
}
| 41
|
TypeScript
|
6
| 251
|
1f3db028ac7d60faa6c30daabbb41482e814d23f
| 552
|
ostara
|
Apache License 2.0
|
core/src/main/kotlin/com/github/quillraven/quillycrawler/ashley/component/ItemComponent.kt
|
Quillraven
| 336,620,410
| false
|
{"Kotlin": 395446}
|
package com.github.quillraven.quillycrawler.ashley.component
import com.badlogic.ashley.core.Component
import com.badlogic.ashley.core.Entity
import com.badlogic.gdx.utils.GdxRuntimeException
import com.badlogic.gdx.utils.I18NBundle
import com.badlogic.gdx.utils.Pool
import ktx.ashley.get
import ktx.ashley.mapperFor
enum class ItemType(val gearType: GearType = GearType.UNDEFINED) {
UNDEFINED,
HAT(GearType.HELMET),
ROBE(GearType.ARMOR),
CURSED_NECKLACE(GearType.AMULET),
ROD(GearType.WEAPON),
LEATHER_GLOVES(GearType.GLOVES),
LEATHER_BOOTS(GearType.BOOTS),
BUCKLER(GearType.SHIELD),
HEALTH_POTION,
MANA_POTION,
TOME_PROTECT,
TOME_FIREBOLT,
TOME_EXPLOSION,
TOME_HEAL,
TOME_STRENGTH,
TOME_AGILITY,
TOME_INTELLIGENCE;
companion object {
private val GEAR_ITEM_TYPES = values().filter { it.gearType != GearType.UNDEFINED }
fun randomGearItem() = GEAR_ITEM_TYPES.random()
}
}
class ItemComponent : Component, Pool.Poolable {
var itemType = ItemType.UNDEFINED
var gearType = GearType.UNDEFINED
var amount = 1
var baseCost: Int = 0
fun cost(entity: Entity): Int {
return when (itemType) {
ItemType.TOME_STRENGTH -> {
val currentStr = entity[StatsComponent.MAPPER]?.get(StatsType.STRENGTH) ?: 0f
val strDiff = if (currentStr > StatsComponent.BASE_STRENGTH) currentStr - StatsComponent.BASE_STRENGTH else 0f
baseCost + 100 * strDiff.toInt()
}
ItemType.TOME_AGILITY -> {
val currentAgi = entity[StatsComponent.MAPPER]?.get(StatsType.AGILITY) ?: 0f
val agiDiff = if (currentAgi > StatsComponent.BASE_AGILITY) currentAgi - StatsComponent.BASE_AGILITY else 0f
baseCost + 100 * agiDiff.toInt()
}
ItemType.TOME_INTELLIGENCE -> {
val crnInt = entity[StatsComponent.MAPPER]?.get(StatsType.INTELLIGENCE) ?: 0f
val intDiff = if (crnInt > StatsComponent.BASE_INTELLIGENCE) crnInt - StatsComponent.BASE_INTELLIGENCE else 0f
baseCost + 100 * intDiff.toInt()
}
else -> baseCost
}
}
fun name(bundle: I18NBundle): String = bundle["Item.${this.itemType.name}.name"]
fun description(bundle: I18NBundle): String = bundle["Item.${this.itemType.name}.description"]
fun regionKey(bundle: I18NBundle): String {
val regionKey = bundle["Item.${this.itemType.name}.skinRegionKey"]
if (regionKey.startsWith("???")) {
// regionKey not defined in bundle -> return undefined region which represents a fallback region in the atlas
return "undefined"
}
return regionKey
}
override fun reset() {
gearType = GearType.UNDEFINED
itemType = ItemType.UNDEFINED
amount = 1
baseCost = 0
}
companion object {
val MAPPER = mapperFor<ItemComponent>()
}
}
val Entity.itemCmp: ItemComponent
get() = this[ItemComponent.MAPPER]
?: throw GdxRuntimeException("ItemComponent for entity '$this' is null")
| 1
|
Kotlin
|
8
| 28
|
1c528e533709cfb6437d088c459402014b8f9475
| 2,909
|
Quilly-Crawler
|
MIT License
|
app/src/main/java/com/schaefer/mymovies/data/model/EpisodeResponseItem.kt
|
arturschaefer
| 318,792,328
| false
|
{"Kotlin": 160961}
|
package com.schaefer.mymovies.data.model
data class EpisodeResponseItem(
val _links: Links?,
val airdate: String?,
val airstamp: String?,
val airtime: String?,
val id: Int,
val image: Image?,
val name: String?,
val number: Int?,
val runtime: Int?,
val season: Int?,
val summary: String?,
val type: String?,
val url: String?
)
| 0
|
Kotlin
|
0
| 0
|
a2580e6020ef40b2efbbafd95c3e5db7ab3b1bb3
| 378
|
My-Shows
|
MIT License
|
src/main/kotlin/SnakeGame.kt
|
DavidEdwards
| 346,445,114
| false
| null |
import java.awt.Color
import java.awt.event.KeyEvent
import java.awt.event.KeyListener
import java.util.*
import kotlin.system.exitProcess
data class Position(val x: Int, val y: Int)
class SnakeGame : SnakeApp(), KeyListener {
val playerSnake = LinkedList<Position>()
// var playerx = 100
// var playery = 100
var direction = 1
init {
addKeyListener(this)
playerSnake.add(Position(100, 100))
}
override fun loop(tick: Int) {
// println("Game loop: $tick (delay $currentDelay)")
val modDirection = direction % 4
val movex = when (modDirection) {
0 -> 0
1 -> 1
2 -> 0
3 -> -1
else -> 0
}
val movey = when (modDirection) {
0 -> -1
1 -> 0
2 -> 1
3 -> 0
else -> 0
}
val head = playerSnake.last
var newPosition = Position(head.x + movex, head.y + movey)
if (newPosition.x < 0) {
newPosition = newPosition.copy(x = width - 1)
}
if (newPosition.y < 0) {
newPosition = newPosition.copy(y = height - 1)
}
if (newPosition.x >= width) {
newPosition = newPosition.copy(x = 0)
}
if (newPosition.y >= height) {
newPosition = newPosition.copy(y = 0)
}
val pixelAtPlayer = getPixel(newPosition.x, newPosition.y)
if (pixelAtPlayer == Color.RED) {
print("You lost")
exitProcess(0)
}
setPixel(newPosition.x, newPosition.y, Color.RED)
repaint(newPosition.x, newPosition.y, 1, 1)
playerSnake.add(newPosition)
while (playerSnake.size > 30) {
val position = playerSnake.pop()
setPixel(position.x, position.y, Color.BLACK)
repaint(position.x, position.y, 1, 1)
}
currentDelay = (currentDelay - 50).coerceIn(10L..1000L)
reschedule()
}
override fun keyTyped(e: KeyEvent) {
}
override fun keyPressed(e: KeyEvent) {
val LEFT = 37
val UP = 38
val RIGHT = 39
val DOWN = 40
when (e.keyCode) {
LEFT -> {
println("GO LEFT")
direction = direction - 1
}
// UP -> {
// println("GO UP")
// movey = -1
// movex = 0
// }
RIGHT -> {
println("GO RIGHT")
direction = direction + 1
}
// DOWN -> {
// println("GO DOWN")
// movey = 1
// movex = 0
// }
}
}
override fun keyReleased(e: KeyEvent) {
}
}
| 0
|
Kotlin
|
0
| 0
|
e59c4eabba4bb738968b3d0c3e63e9989c2331e1
| 2,781
|
parent1
|
MIT License
|
app/src/main/java/eu/kanade/presentation/components/Badges.kt
|
CFManuel
| 134,889,201
| true
|
{"Kotlin": 2276037}
|
package eu.kanade.presentation.components
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.RowScope
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.RectangleShape
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
@Composable
fun BadgeGroup(
modifier: Modifier = Modifier,
shape: Shape = RoundedCornerShape(4.dp),
content: @Composable RowScope.() -> Unit,
) {
Row(modifier = modifier.clip(shape)) {
content()
}
}
@Composable
fun Badge(
text: String,
color: Color = MaterialTheme.colorScheme.secondary,
textColor: Color = MaterialTheme.colorScheme.onSecondary,
shape: Shape = RectangleShape,
) {
Box(
modifier = Modifier
.clip(shape)
.background(color),
) {
Text(
text = text,
modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp),
style = LocalTextStyle.current.copy(
color = textColor,
fontWeight = FontWeight.Medium,
),
)
}
}
| 0
|
Kotlin
|
0
| 0
|
1c8da5fa974b4cfd0fd762b0b1c2a07622ac7662
| 1,622
|
tachiyomi
|
Apache License 2.0
|
embrace-android-core/src/main/kotlin/io/embrace/android/embracesdk/internal/spans/EmbraceSpanBuilder.kt
|
embrace-io
| 704,537,857
| false
|
{"Kotlin": 2807710, "C": 190147, "Java": 175321, "C++": 13140, "CMake": 4261}
|
package io.embrace.android.embracesdk.internal.spans
import io.embrace.android.embracesdk.internal.arch.schema.EmbType
import io.embrace.android.embracesdk.internal.arch.schema.FixedAttribute
import io.embrace.android.embracesdk.internal.arch.schema.KeySpan
import io.embrace.android.embracesdk.internal.arch.schema.PrivateSpan
import io.embrace.android.embracesdk.internal.arch.schema.TelemetryType
import io.embrace.android.embracesdk.spans.EmbraceSpan
import io.opentelemetry.api.trace.Span
import io.opentelemetry.api.trace.SpanBuilder
import io.opentelemetry.api.trace.SpanKind
import io.opentelemetry.api.trace.Tracer
import io.opentelemetry.context.Context
import java.util.concurrent.TimeUnit
/**
* Wrapper for the [SpanBuilder] that stores the input data so that they can be accessed
*/
public class EmbraceSpanBuilder(
tracer: Tracer,
name: String,
telemetryType: TelemetryType,
public val internal: Boolean,
private: Boolean,
parentSpan: EmbraceSpan?,
) {
public lateinit var parentContext: Context
private set
public val spanName: String = if (internal) {
name.toEmbraceObjectName()
} else {
name
}
public var startTimeMs: Long? = null
private val sdkSpanBuilder = tracer.spanBuilder(spanName)
private val fixedAttributes = mutableListOf<FixedAttribute>(telemetryType)
private val customAttributes = mutableMapOf<String, String>()
init {
// If there is a parent, extract the wrapped OTel span and set it as the parent in the wrapped OTel SpanBuilder
if (parentSpan is PersistableEmbraceSpan) {
val newParentContext = parentSpan.asNewContext() ?: Context.root()
setParentContext(newParentContext.with(parentSpan))
} else {
setNoParent()
}
if (private) {
fixedAttributes.add(PrivateSpan)
}
}
public fun startSpan(startTimeMs: Long): Span {
sdkSpanBuilder.setStartTimestamp(startTimeMs, TimeUnit.MILLISECONDS)
return sdkSpanBuilder.startSpan()
}
public fun getFixedAttributes(): List<FixedAttribute> = fixedAttributes
public fun getCustomAttributes(): Map<String, String> = customAttributes
public fun setCustomAttribute(key: String, value: String) {
customAttributes[key] = value
}
public fun getParentSpan(): EmbraceSpan? = parentContext.getEmbraceSpan()
public fun setParentContext(context: Context) {
parentContext = context
sdkSpanBuilder.setParent(parentContext)
updateKeySpan()
}
public fun setNoParent() {
parentContext = Context.root()
sdkSpanBuilder.setNoParent()
updateKeySpan()
}
public fun setSpanKind(spanKind: SpanKind) {
sdkSpanBuilder.setSpanKind(spanKind)
}
private fun updateKeySpan() {
if (fixedAttributes.contains(EmbType.Performance.Default)) {
if (getParentSpan() == null) {
fixedAttributes.add(KeySpan)
} else {
fixedAttributes.remove(KeySpan)
}
}
}
}
| 19
|
Kotlin
|
8
| 133
|
c3d8b882d91f7200c812d8ffa2dee5b820263c0d
| 3,111
|
embrace-android-sdk
|
Apache License 2.0
|
PluginsAndFeatures/azure-toolkit-for-intellij/rider/src/org/jetbrains/plugins/azure/functions/run/AzureFunctionsDotNetCoreAttachSuspendedProfileState.kt
|
JetBrains
| 137,064,201
| true
|
{"Java": 6824035, "Kotlin": 2388176, "C#": 183917, "Scala": 151332, "Gherkin": 108427, "JavaScript": 98350, "HTML": 23518, "CSS": 21770, "Groovy": 21447, "Shell": 21354, "XSLT": 7141, "Dockerfile": 3518, "Batchfile": 2155}
|
/**
* Copyright (c) 2019-2021 JetBrains s.r.o.
*
* All rights reserved.
*
* MIT License
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
* documentation files (the "Software"), to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
* to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial portions of
* the Software.
*
* THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
* THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.jetbrains.plugins.azure.functions.run
import com.intellij.execution.impl.ConsoleViewImpl
import com.intellij.execution.runners.ExecutionEnvironment
import com.jetbrains.rd.util.lifetime.Lifetime
import com.jetbrains.rider.model.debuggerHelper.PlatformArchitecture
import com.jetbrains.rider.model.debuggerWorker.DebuggerStartInfoBase
import com.jetbrains.rider.model.debuggerWorker.DotNetCoreAttachSuspendedStartInfo
import com.jetbrains.rider.run.dotNetCore.DotNetCoreAttachProfileState
import com.jetbrains.rider.runtime.RunningAssemblyInfo
import kotlin.io.path.absolutePathString
class AzureFunctionsDotNetCoreAttachSuspendedProfileState(
private val runtime: AzureFunctionsDotNetCoreRuntime,
private val runningAssemblyInfo: RunningAssemblyInfo,
environment: ExecutionEnvironment,
targetPlatform: PlatformArchitecture,
private val consoleInitializer: (ConsoleViewImpl) -> Unit
) : DotNetCoreAttachProfileState(runningAssemblyInfo.processInfo, environment, targetPlatform) {
override fun initializeConsole(consoleView: ConsoleViewImpl) = consoleInitializer(consoleView)
override suspend fun createModelStartInfo(lifetime: Lifetime): DebuggerStartInfoBase =
DotNetCoreAttachSuspendedStartInfo(
dotNetCoreRuntimeExecutable = runtime.coreToolsInfo.coreToolsExecutable.absolutePathString(),
processId = processInfo.pid,
threadId = runningAssemblyInfo.threadId,
assemblyPath = runningAssemblyInfo.executableAssemblyPath
)
}
| 73
|
Java
|
10
| 41
|
a8b64627376a5144a71725853ba4217b97044722
| 2,727
|
azure-tools-for-intellij
|
MIT License
|
core/kmpp/libJs/src/jsMain/kotlin/com/kanastruk/mvi/JsFbServiceModel.kt
|
kanawish
| 480,934,685
| false
| null |
package com.kanastruk.mvi
import com.kanastruk.data.core.Address
import com.kanastruk.data.core.Contact
import com.kanastruk.data.core.Profile
import com.kanastruk.mvi.fb.FbAuthState
import com.kanastruk.mvi.fb.FbServiceModel
import firebase.database.Query
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.StateFlow
import mvi.fb.FbServices
import mvi.fb.suspendGet
import mvi.fb.suspendSet
import utils.debug
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
import kotlin.js.Json
import kotlin.js.json
/**
* NOTE: Comparing Android and Js implementations, we can see they're very similar looking.
* That's a side effect of Firebase having very closely matching APIs between JS and JVM
* implementations.
*
* TODO: To improve code re-use consider writing a 'common' shim over
* Firebase libraries, when we have enough time to do so.
*/
class JsFbServiceModel(
private val fbServices: FbServices,
override val fbAuthStore: StateFlow<FbAuthState>
) :FbServiceModel {
private val profileRef by lazy { fbServices.firebaseDb.ref("userProfile") }
private val contactRef by lazy { fbServices.firebaseDb.ref("userContact") }
private val addressRef by lazy { fbServices.firebaseDb.ref("userAddress") }
override suspend fun loadProfile(): Triple<Profile, Contact, Address>? {
console.log("JsFbServiceModel.loadProfile() called")
return ifSignedIn { signedIn ->
coroutineScope {
val profile = async { profileRef.child(signedIn.authId).suspendGet<Json?>()?.toProfile() }
val contact = async { contactRef.child(signedIn.authId).suspendGet<Json?>()?.toContact() }
val address = async { addressRef.child(signedIn.authId).suspendGet<Json?>()?.toAddress() }
Triple(
profile.await() ?: Profile(),
contact.await() ?: Contact(),
address.await() ?: Address()
).also { (p,c,a) ->
debug { console.log("🐞 %o, %o, %o", p, c, a) }
}
}
}
}
private fun Json.toProfile():Profile = Profile(
this.get("locale") as? String ?: ""
)
fun Profile.toJson():Json = json(
"locale" to locale
)
private fun Json.toContact():Contact = Contact(
this["firstName"] as? String ?: "",
this["lastName"] as? String ?:"",
this["companyName"] as? String ?:"",
this["email"] as? String ?:"",
this["phone"] as? String ?:""
)
fun Contact.toJson():Json = json(
"firstName" to firstName,
"lastName" to lastName,
"companyName" to companyName,
"email" to email,
"phone" to phone
)
private fun Json.toAddress():Address = Address(
this["address1"] as? String ?: "",
this["address2"] as? String ?:"",
this["city"] as? String ?:"",
this["countrySub"] as? String ?:"",
this["postalCode"] as? String ?:"",
this["country"] as? String ?:"",
)
fun Address.toJson():Json = json(
"address1" to address1,
"address2" to address2,
"city" to city,
"countrySub" to countrySub,
"postalCode" to postalCode,
"country" to country
)
/*
suspend fun Query.suspendGet():Json? = suspendCoroutine { continuation ->
get()
.then { snap ->
val json = snap.`val`().unsafeCast<Json?>()
continuation.resume(json)
}.catch { throwable ->
continuation.resumeWithException(throwable)
}
}
*/
fun foo() {
val default = Address()
}
override suspend fun saveUserProfile(profile: Profile, address: Address, contact: Contact) {
console.log("JsFbServiceModel.saveUserProfile() called")
console.log("🐞 %o, %o, %o", profile, contact, address)
ifSignedIn { signedIn ->
coroutineScope {
val results = awaitAll(
async { profileRef.child(signedIn.authId).suspendSet(profile.toJson()) },
async { contactRef.child(signedIn.authId).suspendSet(contact.toJson()) },
async { addressRef.child(signedIn.authId).suspendSet(address.toJson()) }
)
if( !results.all { success -> success } ) {
console.error("Failed to save part(s) of the user profile.")
}
}
}
}
private suspend fun <T> ifSignedIn(block:suspend (FbAuthState.SignedIn)->T):T? {
return when ( val state = fbAuthStore.value ) {
is FbAuthState.SignedIn -> {
block(state)
}
else -> {
console.error(
"Can't complete request, expecting FbAuthState.SignedIn, was %o.",
fbAuthStore.value
)
null
}
}
}
}
| 3
|
Kotlin
|
1
| 1
|
24da293e6511f80d1678963bfbfe8fe4a4ad49e0
| 5,120
|
ks-community
|
MIT License
|
compose/material3/material3/src/commonMain/kotlin/androidx/compose/material3/internal/BackHandler.kt
|
VexorMC
| 838,305,267
| false
|
{"Kotlin": 104238872, "Java": 66757679, "C++": 9111230, "AIDL": 628952, "Python": 306842, "Shell": 199496, "Objective-C": 47117, "TypeScript": 38627, "HTML": 28384, "Swift": 21386, "Svelte": 20307, "ANTLR": 19860, "C": 15043, "CMake": 14435, "JavaScript": 6457, "GLSL": 3842, "CSS": 1760, "Batchfile": 295}
|
/*
* Copyright 2024 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.material3.internal
import androidx.compose.runtime.Composable
import kotlinx.coroutines.flow.Flow
// TODO: Remove once this API will be available in common
internal expect class BackEventCompat {
val touchX: Float
val touchY: Float
val progress: Float
val swipeEdge: Int
companion object {
val EDGE_LEFT: Int
val EDGE_RIGHT: Int
}
}
@Composable
internal expect fun BackHandler(enabled: Boolean = true, onBack: () -> Unit)
@Composable
internal expect fun PredictiveBackHandler(
enabled: Boolean = true,
onBack: suspend (progress: Flow<BackEventCompat>) -> Unit
)
| 0
|
Kotlin
|
0
| 2
|
9730aa39ce1cafe408f28962a59b95b82c68587f
| 1,258
|
compose
|
Apache License 2.0
|
app/src/main/kotlin/com/monoid/hackernews/view/itemlist/ItemList.kt
|
zirman
| 477,438,501
| false
| null |
package com.monoid.hackernews.view.itemlist
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.snapshotFlow
import androidx.compose.ui.Modifier
import androidx.metrics.performance.PerformanceMetricsState
import com.monoid.hackernews.BuildConfig
import com.monoid.hackernews.common.api.ItemId
import com.monoid.hackernews.common.data.ItemListRow
import com.monoid.hackernews.common.data.LoginAction
import com.monoid.hackernews.common.data.Username
import com.monoid.hackernews.common.util.rememberMetricsStateHolder
import kotlinx.collections.immutable.ImmutableList
import kotlinx.coroutines.launch
@Composable
fun ItemList(
itemRows: ImmutableList<ItemListRow>?,
paddingValues: PaddingValues,
onClickDetail: (ItemId?) -> Unit,
onClickUser: (Username?) -> Unit,
onClickReply: (ItemId) -> Unit,
onClickBrowser: (String?) -> Unit,
onNavigateLogin: (LoginAction) -> Unit,
modifier: Modifier = Modifier,
listState: LazyListState = rememberLazyListState(),
) {
if (BuildConfig.DEBUG.not()) {
val metricsStateHolder: PerformanceMetricsState.Holder =
rememberMetricsStateHolder()
// Reporting scrolling state from compose should be done from side effect to prevent
// recomposition.
LaunchedEffect(metricsStateHolder) {
snapshotFlow { listState.isScrollInProgress }.collect { isScrolling ->
metricsStateHolder.state!!.run {
if (isScrolling) {
putState("ItemList", "Scrolling")
} else {
removeState("ItemList")
}
}
}
}
}
LazyColumn(
modifier = modifier,
state = listState,
contentPadding = paddingValues
) {
items(itemRows ?: emptyList(), { it.itemId.long }) { itemRow ->
val itemUiState = remember(itemRow.itemId) { itemRow.itemUiFlow }
.collectAsState(initial = null)
val coroutineScope = rememberCoroutineScope()
Item(
itemUi = itemUiState.value,
onClickDetail = { itemUiState.value?.item?.id?.let { onClickDetail(ItemId(it)) } },
onClickReply = { itemUiState.value?.item?.id?.let { onClickReply(ItemId(it)) } },
onClickUser = { onClickUser(it) },
onClickBrowser = { onClickBrowser(itemUiState.value?.item?.url) },
onClickUpvote = {
coroutineScope.launch {
itemUiState.value?.toggleUpvote(onNavigateLogin)
}
},
onClickFavorite = {
coroutineScope.launch {
itemUiState.value?.toggleFavorite(onNavigateLogin)
}
},
onClickFlag = {
coroutineScope.launch {
itemUiState.value?.toggleFlag(onNavigateLogin)
}
},
modifier = Modifier.fillMaxWidth()
)
}
}
}
| 0
|
Kotlin
|
0
| 3
|
eed737963d5cd49960cc8d507e488a28db00e313
| 3,646
|
hacker_news
|
Apache License 2.0
|
app/src/main/java/com/recipe/search/data/network/RecipeService.kt
|
ChetanAshtivkar
| 249,130,749
| false
| null |
package com.recipe.search.data.network
import com.recipe.search.data.RecipeResponse
import okhttp3.OkHttpClient
import retrofit2.Call
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.GET
import retrofit2.http.Path
import retrofit2.http.Query
import java.util.concurrent.TimeUnit
/**
* Created by Chetan on 22/03/20.
*/
interface RecipeService {
@GET("api/search")
fun getRecipes(
@Query("q") searchText: String
): Call<RecipeResponse>
}
object RetrofitFactory {
const val BASE_URL = "https://recipesapi.herokuapp.com/"
fun makeRetrofitService(): RecipeService {
val okHttpClient = OkHttpClient.Builder()
.connectTimeout(1, TimeUnit.MINUTES)
.readTimeout(1, TimeUnit.MINUTES)
.writeTimeout(1, TimeUnit.MINUTES)
.build()
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build().create(RecipeService::class.java)
}
}
| 0
|
Kotlin
|
0
| 0
|
8c74dd96df72af63f34f2ed9549711361be6f119
| 1,088
|
Recipe-search
|
Apache License 2.0
|
app/src/main/java/com/livewire/audax/locale/models/TemperatureDisplayType.kt
|
HDSANAULLAHS
| 466,947,990
| false
|
{"Kotlin": 211156, "Java": 919}
|
package com.livewire.audax.locale.models
import com.livewire.audax.R
enum class TemperatureDisplayType {
FAHRENHEIT {
override val rawValue = "fahrenheit"
override val titleResource = R.string.temperature_display_type_fahrenheit
override val titleWithSymbolsResource = R.string.temperature_display_type_fahrenheit_with_symbols
},
CELSIUS {
override val rawValue = "celsius"
override val titleResource = R.string.temperature_display_type_celsius
override val titleWithSymbolsResource = R.string.temperature_display_type_celsius_with_symbols
};
abstract val rawValue : String
abstract val titleResource : Int
abstract val titleWithSymbolsResource : Int
companion object {
fun getObjectForRawValue(rawValue: String): TemperatureDisplayType {
return values().firstOrNull { it.rawValue == rawValue } ?: FAHRENHEIT
}
}
}
| 0
|
Kotlin
|
0
| 0
|
356cfa88f3685882abd1336398defe12ea04f93f
| 933
|
Livewire
|
Apache License 2.0
|
client/src/test/java/com/rarible/ethereum/client/HaEthereumTransportProviderTest.kt
|
rarible
| 358,506,329
| false
|
{"Kotlin": 277476, "Java": 16048, "Scala": 620}
|
package com.rarible.ethereum.client
import com.rarible.ethereum.client.failover.NoopFailoverPredicate
import com.rarible.ethereum.client.failover.SimplePredicate
import io.daonomic.rpc.domain.Request
import kotlinx.coroutines.delay
import kotlinx.coroutines.reactive.awaitSingle
import kotlinx.coroutines.runBlocking
import okhttp3.Credentials
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.springframework.http.HttpHeaders
import org.springframework.http.MediaType
import scala.jdk.javaapi.CollectionConverters
import scala.reflect.Manifest
import scalether.abi.Uint32Type
import java.math.BigInteger
import java.net.ServerSocket
import java.time.Duration
import java.time.Instant
internal class HaEthereumTransportProviderTest {
@Test
fun `fallback to external and then reconnect to internal`() = runBlocking<Unit> {
val rpcInternalServer = MockWebServer()
rpcInternalServer.start()
val rpcInternalServer2 = MockWebServer()
val rpcInternalServer2Port = ServerSocket(0).use { it.localPort }
val rpcExternalServer = MockWebServer()
rpcExternalServer.start()
rpcInternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockNumberResponse(1))
)
rpcInternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockResponse())
)
rpcInternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody("""{"jsonrpc": "2.0","id": 2,"result": "response1"}""")
)
rpcInternalServer2.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockNumberResponse(2))
)
rpcInternalServer2.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockResponse())
)
rpcInternalServer2.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody("""{"jsonrpc": "2.0","id": 2,"result": "response3"}""")
)
rpcExternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockNumberResponse(4))
)
rpcExternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockResponse())
)
rpcExternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody("""{"jsonrpc": "2.0","id": 2,"result": "response2"}""")
)
val provider = HaEthereumTransportProvider(
monitoringThreadInterval = Duration.ofMillis(100),
localNodes = listOf(
EthereumNode(
httpUrl = "http://127.0.0.1:${rpcInternalServer.port}",
),
EthereumNode(
httpUrl = "http://127.0.0.1:$rpcInternalServer2Port",
)
),
externalNodes = listOf(
EthereumNode(
httpUrl = "http://127.0.0.1:${rpcExternalServer.port}",
)
),
maxFrameSize = 1024 * 1024,
retryMaxAttempts = 5,
retryBackoffDelay = 0,
requestTimeoutMs = 0,
readWriteTimeoutMs = 10000,
maxBlockDelay = Duration.ofSeconds(10),
)
val response1 = FailoverRpcTransport(
ethereumTransportProvider = provider,
failoverPredicate = NoopFailoverPredicate(),
).send(
Request(
1L,
"GET",
CollectionConverters.asScala(emptyList<Any>()).toList(),
""
),
Manifest.Any(),
).awaitSingle()
assertThat(response1.result().get()).isEqualTo("response1")
// Should receive event from server1
rpcInternalServer.shutdown()
// Should get response from external server
val response = FailoverRpcTransport(
ethereumTransportProvider = provider,
failoverPredicate = NoopFailoverPredicate(),
).send(
Request(
1L,
"GET",
CollectionConverters.asScala(emptyList<Any>()).toList(),
""
),
Manifest.Any(),
)
.retry(3)
.awaitSingle()
assertThat(response.result().get()).isEqualTo("response2")
// Starting internal server 2
rpcInternalServer2.start(rpcInternalServer2Port)
delay(2000)
// Should get response from internal server 2
val response2 = FailoverRpcTransport(
ethereumTransportProvider = provider,
failoverPredicate = NoopFailoverPredicate(),
).send(
Request(
1L,
"GET",
CollectionConverters.asScala(emptyList<Any>()).toList(),
""
),
Manifest.Any(),
).awaitSingle()
assertThat(response2.result().get()).isEqualTo("response3")
}
@Test
fun `retry if no block return`() = runBlocking<Unit> {
val rpcInternalServer = MockWebServer()
rpcInternalServer.start()
rpcInternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockNumberResponse(1))
)
rpcInternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getNullResponse())
)
rpcInternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockNumberResponse(1))
)
rpcInternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockResponse())
)
rpcInternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody("""{"jsonrpc": "2.0","id": 2,"result": "response1"}""")
)
val provider = HaEthereumTransportProvider(
monitoringThreadInterval = Duration.ofMillis(100),
localNodes = listOf(
EthereumNode(
httpUrl = "http://127.0.0.1:${rpcInternalServer.port}",
),
),
externalNodes = emptyList(),
maxFrameSize = 1024 * 1024,
retryMaxAttempts = 5,
retryBackoffDelay = 0,
requestTimeoutMs = 0,
readWriteTimeoutMs = 10000,
maxBlockDelay = Duration.ofSeconds(10),
)
val response1 = FailoverRpcTransport(
ethereumTransportProvider = provider,
failoverPredicate = NoopFailoverPredicate(),
).send(
Request(
1L,
"GET",
CollectionConverters.asScala(emptyList<Any>()).toList(),
""
),
Manifest.Any(),
).awaitSingle()
assertThat(response1.result().get()).isEqualTo("response1")
}
@Test
fun `fallback to external if block delay`() = runBlocking<Unit> {
val rpcInternalServer = MockWebServer()
rpcInternalServer.start()
val rpcExternalServer = MockWebServer()
rpcExternalServer.start()
rpcInternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockNumberResponse(1))
)
rpcInternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockResponse(Instant.MIN.epochSecond))
)
rpcExternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockNumberResponse(4))
)
rpcExternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockResponse())
)
rpcExternalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody("""{"jsonrpc": "2.0","id": 2,"result": "response2"}""")
)
val provider = HaEthereumTransportProvider(
monitoringThreadInterval = Duration.ofMillis(100),
localNodes = listOf(
EthereumNode(
httpUrl = "http://127.0.0.1:${rpcInternalServer.port}",
),
),
externalNodes = listOf(
EthereumNode(
httpUrl = "http://127.0.0.1:${rpcExternalServer.port}",
)
),
maxFrameSize = 1024 * 1024,
retryMaxAttempts = 5,
retryBackoffDelay = 0,
requestTimeoutMs = 0,
readWriteTimeoutMs = 10000,
maxBlockDelay = Duration.ofSeconds(10),
)
val response1 = FailoverRpcTransport(
ethereumTransportProvider = provider,
failoverPredicate = NoopFailoverPredicate(),
).send(
Request(
1L,
"GET",
CollectionConverters.asScala(emptyList<Any>()).toList(),
""
),
Manifest.Any(),
).awaitSingle()
assertThat(response1.result().get()).isEqualTo("response2")
}
@Test
fun `rpc failover to external node`() = runBlocking<Unit> {
val internalServer = MockWebServer()
internalServer.start()
val externalServer = MockWebServer()
externalServer.start()
val provider = HaEthereumTransportProvider(
monitoringThreadInterval = Duration.ofMillis(100),
localNodes = listOf(
EthereumNode(
httpUrl = "http://127.0.0.1:${internalServer.port}",
),
),
externalNodes = listOf(
EthereumNode(
httpUrl = "http://127.0.0.1:${externalServer.port}",
)
),
maxFrameSize = 1024 * 1024,
retryMaxAttempts = 5,
retryBackoffDelay = 100,
requestTimeoutMs = 10000,
readWriteTimeoutMs = 10000,
maxBlockDelay = Duration.ofSeconds(10),
)
internalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockNumberResponse(1))
)
internalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockResponse())
)
internalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody("""{"jsonrpc": "2.0","id": 2,"result": "response1", "error": { "message": "test", "code": -32000 }}""")
)
externalServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody("""{"jsonrpc": "2.0","id": 2,"result": "response2"}""")
)
val response = FailoverRpcTransport(
ethereumTransportProvider = provider,
failoverPredicate = SimplePredicate(code = -32000, errorMessagePrefix = "test"),
).send(
Request(
1L,
"GET",
CollectionConverters.asScala(emptyList<Any>()).toList(),
""
),
Manifest.Any(),
).awaitSingle()
assertThat(response.result().get()).isEqualTo("response2")
}
@Test
fun `rpc no failover already on external node`() = runBlocking<Unit> {
val externalServer1 = MockWebServer()
externalServer1.start()
val externalServer2 = MockWebServer()
externalServer2.start()
val provider = HaEthereumTransportProvider(
monitoringThreadInterval = Duration.ofMillis(100),
localNodes = emptyList(),
externalNodes = listOf(
EthereumNode(
httpUrl = "http://127.0.0.1:${externalServer1.port}",
),
EthereumNode(
httpUrl = "http://127.0.0.1:${externalServer2.port}",
)
),
maxFrameSize = 1024 * 1024,
retryMaxAttempts = 5,
retryBackoffDelay = 100,
requestTimeoutMs = 10000,
readWriteTimeoutMs = 10000,
maxBlockDelay = Duration.ofSeconds(10),
)
externalServer1.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockNumberResponse(1))
)
externalServer1.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockResponse())
)
externalServer1.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody("""{"jsonrpc": "2.0","id": 2,"result": "response1", "error": { "message": "test", "code": -32000 }}""")
)
externalServer2.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody("""{"jsonrpc": "2.0","id": 2,"result": "response2"}""")
)
val response = FailoverRpcTransport(
ethereumTransportProvider = provider,
failoverPredicate = SimplePredicate(code = -32000, errorMessagePrefix = "test"),
).send(
Request(
1L,
"GET",
CollectionConverters.asScala(emptyList<Any>()).toList(),
""
),
Manifest.Any(),
).awaitSingle()
assertThat(response.result().get()).isEqualTo("response1")
}
@Test
fun `rpc basic auth`() = runBlocking<Unit> {
val nodeServer = MockWebServer()
nodeServer.start()
val provider = HaEthereumTransportProvider(
monitoringThreadInterval = Duration.ofMillis(100),
localNodes = listOf(
EthereumNode(
httpUrl = "http://user:password@127.0.0.1:${nodeServer.port}",
)
),
externalNodes = emptyList(),
maxFrameSize = 1024 * 1024,
retryMaxAttempts = 5,
retryBackoffDelay = 100,
requestTimeoutMs = 10000,
readWriteTimeoutMs = 10000,
maxBlockDelay = Duration.ofSeconds(10),
)
nodeServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockNumberResponse(1))
)
nodeServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody(getBlockResponse())
)
nodeServer.enqueue(
MockResponse()
.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
.setBody("""{"jsonrpc": "2.0","id": 1,"result": "0xa4b1"}""")
)
val response = FailoverRpcTransport(
ethereumTransportProvider = provider,
failoverPredicate = SimplePredicate(code = -32000, errorMessagePrefix = "test"),
).send(
Request(
1L,
"eth_chainId",
CollectionConverters.asScala(emptyList<Any>()).toList(),
"2.0"
),
Manifest.Any(),
).awaitSingle()
assertThat(response.result().get()).isEqualTo("0xa4b1")
repeat(3) {
val recordedRequest = nodeServer.takeRequest()
val expectedCredentials = Credentials.basic("user", "password")
val actualCredentials = recordedRequest.getHeader("Authorization")
assertThat(actualCredentials).isEqualTo(expectedCredentials)
}
}
private fun getBlockNumberResponse(number: Long): String {
return """
{
"jsonrpc": "2.0",
"id": 1,
"result": "${Uint32Type.encode(BigInteger.valueOf(number)).slice(28, 32).prefixed()}"
}
""".trimIndent()
}
private fun getNullResponse(): String {
return """
{
"jsonrpc": "2.0",
"id": 1,
"result": null
}
""".trimIndent()
}
private fun getBlockResponse(timestamp: Long = Instant.now().epochSecond): String {
return """
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"difficulty": "0x0",
"extraData": "0x",
"gasLimit": "0x112a8800",
"gasUsed": "0x0",
"hash": "0xe0594250efac73640aeff78ec40aaaaa87f91edb54e5af926ee71a32ef32da34",
"l1BlockNumber": "0x0",
"logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"miner": "0x0000000000000000000000000000000000000000",
"mixHash": "0x0000000000000000000000000000000000000000000000000000000000000000",
"nonce": "0x0000000000000000",
"number": "0x1",
"parentHash": "0x7ee576b35482195fc49205cec9af72ce14f003b9ae69f6ba0faef4514be8b442",
"receiptsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"sha3Uncles": "0x1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347",
"size": "0x1fd",
"stateRoot": "0x0000000000000000000000000000000000000000000000000000000000000000",
"timestamp": "${Uint32Type.encode(BigInteger.valueOf(timestamp)).slice(28, 32).prefixed()}",
"totalDifficulty": "0x0",
"transactions": [],
"transactionsRoot": "0x56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421",
"uncles": []
}
}
""".trimIndent()
}
}
| 1
|
Kotlin
|
7
| 6
|
0ee922402da2344d227d6d36a7d7d1f59505141b
| 20,190
|
ethereum-core
|
MIT License
|
kotlin-node/src/jsMain/generatedLegacy/node/inspector/NodeRuntimeEvent.kt
|
JetBrains
| 93,250,841
| false
|
{"Kotlin": 11989651, "JavaScript": 231504}
|
// Automatically generated - do not modify!
@file:Suppress(
"NESTED_CLASS_IN_EXTERNAL_INTERFACE",
)
package node.inspector
import node.events.EventType
import seskar.js.JsValue
import seskar.js.JsVirtual
@JsVirtual
sealed external interface NodeRuntimeEvent {
companion object {
@JsValue("NodeRuntime.waitingForDisconnect")
val WAITING_FOR_DISCONNECT: WAITING_FOR_DISCONNECT
}
sealed interface WAITING_FOR_DISCONNECT : EventType
}
| 33
|
Kotlin
|
176
| 1,266
|
167767803bf3245ff9277386e261c9f2eab60d6e
| 468
|
kotlin-wrappers
|
Apache License 2.0
|
cruddemo-security/src/main/kotlin/com/deepblue/cruddemo/dao/EmployeeDAOImp.kt
|
DeepBlue-dot
| 848,954,541
| false
|
{"Kotlin": 35341}
|
package com.deepblue.cruddemo.dao
import com.deepblue.cruddemo.entity.Employee
import jakarta.persistence.EntityManager
import jakarta.persistence.TypedQuery
import org.springframework.stereotype.Repository
@Repository
class EmployeeDAOImp(
private val entityManager: EntityManager
): EmployeeDAO {
override fun findAll(): List<Employee> {
val theQuery: TypedQuery<Employee> = entityManager.createQuery("FROM Employee", Employee::class.java)
return theQuery.resultList
}
override fun findById(id: Int): Employee {
return entityManager.find(Employee::class.java, id)
}
override fun save(employee: Employee): Employee {
return entityManager.merge(employee)
}
override fun deleteById(id: Int) {
val emp = entityManager.find(Employee::class.java, id)
entityManager.remove(emp)
}
}
| 0
|
Kotlin
|
0
| 0
|
c452f02312b583e25fda087cd0ca8999a11c3c97
| 866
|
Kotlin
|
MIT License
|
app/src/main/java/com/treplabs/ddm/ddmapp/screens/signin/SignInViewModel.kt
|
TREP-LABS
| 240,090,919
| false
| null |
package com.treplabs.ddm.ddmapp.screens.signin
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.google.android.gms.auth.api.signin.GoogleSignInAccount
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import com.treplabs.ddm.base.BaseViewModel
import com.treplabs.ddm.ddmapp.PrefsValueHelper
import com.treplabs.ddm.ddmapp.models.request.SignInRequest
import com.treplabs.ddm.ddmapp.datasources.repositories.FirebaseAuthRepository
import com.treplabs.ddm.ddmapp.screens.signin.NavigationFlow.RETURNING_USER
import com.treplabs.ddm.networkutils.LoadingStatus
import com.treplabs.ddm.networkutils.Result
import com.treplabs.ddm.networkutils.disposeBy
import com.treplabs.ddm.utils.Event
import io.reactivex.Single
import io.reactivex.rxkotlin.Singles
import io.reactivex.rxkotlin.subscribeBy
import timber.log.Timber
import javax.inject.Inject
enum class NavigationFlow { NEW_USER, RETURNING_USER }
class SignInViewModel @Inject constructor(
private val firebaseAuthRepository: FirebaseAuthRepository,
private val prefsValueHelper: PrefsValueHelper
) : BaseViewModel() {
private val _lastSignedInEmail = MutableLiveData<String>(prefsValueHelper.getLastSignedInEmail())
val lastSignedInEmail: LiveData<String>
get() = _lastSignedInEmail
private val _navigationFlow = MutableLiveData<Event<NavigationFlow>>()
val navigationFlow: LiveData<Event<NavigationFlow>>
get() = _navigationFlow
private val _signInComplete = MutableLiveData<Event<Boolean>>()
val signInComplete: LiveData<Event<Boolean>>
get() = _signInComplete
init {
_navigationFlow.value =
Event(if (prefsValueHelper.getIsDemoShown()) RETURNING_USER else NavigationFlow.NEW_USER)
}
fun signInWithPassword(signInRequest: SignInRequest) {
_loadingStatus.value = LoadingStatus.Loading("Signing in, please wait")
firebaseAuthRepository.signInWithPassword(signInRequest)
.subscribeBy {
when (it) {
is Result.Success -> {
prefsValueHelper.setLastSignedInEmail(signInRequest.email)
getUser(it.data.uid)
}
is Result.Error -> _loadingStatus.value = LoadingStatus.Error(it.errorCode, it.errorMessage)
}
}.disposeBy(disposeBag)
}
fun getUser(userId: String) {
firebaseAuthRepository.getUser(userId).subscribeBy {
if (it is Result.Success){
prefsValueHelper.saveUser(it.data)
}
_loadingStatus.value = LoadingStatus.Success
_signInComplete.value = Event(true)
}.disposeBy(disposeBag)
}
fun signInWithGoogle(acct: GoogleSignInAccount) {
_loadingStatus.value = LoadingStatus.Loading("Signing in, please wait")
firebaseAuthRepository.signInWithGoogle(acct).subscribeBy {
when (it) {
is Result.Success -> getUser(it.data.uid)
is Result.Error -> _loadingStatus.value = LoadingStatus.Error(it.errorCode, it.errorMessage)
}
}.disposeBy(disposeBag)
}
override fun addAllLiveDataToObservablesList() {
}
}
| 0
|
Kotlin
|
0
| 1
|
66dd9ca8e3ea6a0c6a91d7956bd97224c5534291
| 3,290
|
DDMAndroid
|
Apache License 2.0
|
app/src/main/java/com/gwj/sem4_anime_app/ui/search/SearchViewModel.kt
|
GWJian
| 730,619,677
| false
|
{"Kotlin": 141201}
|
package com.gwj.sem4_anime_app.ui.search
import androidx.lifecycle.viewModelScope
import com.gwj.sem4_anime_app.ui.base.BaseViewModel
import com.gwj.sem4_anime_app.data.model.Data
import com.gwj.sem4_anime_app.data.model.DataX
import com.gwj.sem4_anime_app.data.repo.anime.AnimeRepo
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject
@HiltViewModel
class SearchViewModel @Inject constructor(
private val Animes: AnimeRepo,
) : BaseViewModel() {
private val _searchAnimes: MutableStateFlow<List<Data>> = MutableStateFlow(emptyList())
val searchAnimes: MutableStateFlow<List<Data>> = _searchAnimes
private val _animeGenres: MutableStateFlow<List<DataX>> = MutableStateFlow(emptyList())
val animeGenres: MutableStateFlow<List<DataX>> = _animeGenres
//Job to stop the search when user is typing too fast
var searchJob: Job? = null
var currentPage = 1
/**
* we need this to store the current query,if we pass empty string "", after search result reach end, then it will back to "" and show all anime again
* let say https://api.jikan.moe/v4/anime?q=overlord&sfw=true&page=1&limit=25 {"pagination":{"last_visible_page":1,"has_next_page":false,"current_page":1,"items":{"count":19,"total":19,"per_page":25}}
* after we reach the end,it will auto go back https://api.jikan.moe/v4/anime?q=&sfw=true&page=1&limit=25 to show all data again
*/
var currentQuery = ""
var currentGenresId = ""
init {
getAllAnimes()
getAnimeGenres()
searchAnime("", "")
}
//show default anime setting
private fun getAllAnimes() {
viewModelScope.launch(Dispatchers.IO) {
delay(1500)
_isFetchingData.emit(true)
safeApiCall {
Animes.searchAnime("", "").let {
_searchAnimes.value = it
_isFetchingData.emit(false)
}
}
}
}
private fun getAnimeGenres() {
viewModelScope.launch(Dispatchers.IO) {
delay(1500)
_isFetchingData.emit(true)
safeApiCall {
Animes.getAnimeGenres().let {
_animeGenres.value = it
_isFetchingData.emit(false)
}
}
}
}
//target the anime that we want to search
//we use Job to prevent user from typing too fast and keep searching and cause 429 - Too Many Request
fun searchAnime(genres: String, query: String?) {
//Log.d("debugging_SearchViewModel", "Genres ID: $genres, Query: $query")
searchJob?.cancel() //cancel to prevent user from typing too fast.
if (!query.isNullOrBlank() || genres.isNotBlank() || genres.isBlank()) {
currentGenresId = genres //Store the current genres
currentQuery = query!! // Store the current query
searchJob = viewModelScope.launch(Dispatchers.IO) {
delay(300) //delay use to control the rate of the request if user is typing too fast
safeApiCall {
Animes.searchAnime(genres, query).let {
_searchAnimes.value = it
if (_searchAnimes.value.isEmpty()) {
_noData.emit(true)
//Log.d("debugging_SearchViewModel", "No Data")
} else {
_noData.emit(false)
//Log.d("debugging_SearchViewModel", "Have Data")
}
}
}
}
}
}
/**
* Loads more items when the user scrolls to the end of the list.
* Join Two List
*/
fun loadMoreItems() {
// if isLoading is false and has_next_page is true run the code
if (!_isLoading.value) {
// if true, let the page increment and load new data into the list
_isLoading.value = true
// page +1.
currentPage++
viewModelScope.launch(Dispatchers.IO) {
delay(1000) //delay to control the rate of the request
safeApiCall {
Animes.searchAnime(currentGenresId, currentQuery, currentPage).let { newItems ->
// get current loaded list from _searchAnimes
val currentItems = _searchAnimes.value
// add newItems list to currentItems list => join two list
_searchAnimes.value = currentItems + newItems
// if done loading, set it back to false so it can prevent user from keep scrolling and get 429 RateLimitException error warning
_isLoading.value = false
}
}
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
bc0e0d52caadcacf33c0b01e6dd3acc6f9f546d7
| 5,035
|
sem4_anime_app
|
MIT License
|
app/src/main/java/com/example/kd/priceemitter/di/PriceRepositoryManagerModule.kt
|
kdotdi
| 296,287,999
| false
| null |
package com.example.kd.priceemitter.di
import com.example.kd.priceemitter.datasource.PriceRepository
import com.example.kd.priceemitter.datasource.PriceRepositoryImpl
import dagger.Binds
import dagger.Module
@Module
abstract class PriceRepositoryManagerModule {
@Binds
abstract fun bindPriceRepositoryImpl(priceRepositoryImpl: PriceRepositoryImpl): PriceRepository
}
| 0
|
Kotlin
|
0
| 0
|
1ed525f8d70f41c24d04f164f997532ae59fac49
| 376
|
PriceEmitter
|
MIT License
|
app/src/main/java/com/smlnskgmail/jaman/deviceinfo/info/components/system/realization/infoitems/ApiLevelInfoItem.kt
|
DexterDsd
| 224,637,905
| true
|
{"Kotlin": 69371}
|
package com.smlnskgmail.jaman.deviceinfo.info.components.system.realization.infoitems
import android.content.Context
import com.smlnskgmail.jaman.deviceinfo.R
import com.smlnskgmail.jaman.deviceinfo.info.components.system.structure.SystemInfo
import com.smlnskgmail.jaman.deviceinfo.info.ui.list.InfoItem
class ApiLevelInfoItem(private val context: Context, private val systemInfo: SystemInfo) : InfoItem {
override fun title() = context.getString(R.string.item_info_title_system_api_level)
override fun body() = systemInfo.apiLevel()
}
| 0
| null |
0
| 0
|
dee2b0d1dbf18d6c2f290ed715fed9e853f78156
| 549
|
android-device-info
|
The Unlicense
|
src/main/java/com/aillen/shopmall/module/asynwork/TaskRunnable.kt
|
anlonglong
| 138,116,731
| false
|
{"Kotlin": 234110, "HTML": 390}
|
package com.aillen.shopmall.module.asynwork
import android.os.Looper
import android.os.Message
/**
* Created by anlonglong on 2018/5/31.
* Email: <EMAIL>
*/
abstract class TaskRunnable<T>(result: Result<T>) : Runnable {
private var mResult: Result<T> = result
private lateinit var mThreadHandler:ThreadHandler<T>
override fun run() {
if (mResult.mThreadHandler == ThreadHolder.MAIN) {
sendMainMsg()
}else{
doSubThreadWork()
}
}
private fun doSubThreadWork() = try {
val t: T = doWork()
mResult.setSuccess(t)
} catch (e: Exception) {
println("error msg = ${e.message}")
mResult.setError(e)
}
private fun sendMainMsg() {
mThreadHandler = ThreadHandler(mResult, Looper.getMainLooper())
val message: Message = mThreadHandler.obtainMessage()
mThreadHandler.sendMessage(
try {
val t: T = doWork()
message.what = mResult.mThreadHandler.code
message.obj = t
message
} catch (e: Exception) {
message.what = ThreadHolder.ERROR.code
message.obj = e
message
}
)
}
abstract fun doWork(): T
}
| 0
|
Kotlin
|
2
| 2
|
6ceafeca69702605c08a04957c57ab66bff01d08
| 1,329
|
ShopMall
|
Apache License 2.0
|
ooxml-spreadsheet/src/main/kotlin/io/github/nillerr/ooxml/table/Table.kt
|
Nillerr
| 657,676,368
| false
|
{"Kotlin": 59525}
|
package io.github.nillerr.ooxml.table
/**
* Represents a table that can be rendered in a spreadsheet or document.
*
* @param name The name of the sheet this table is rendered in (if supported by the target format).
* @param columns The styles of the columns in the sheet this table is rendered in (if supported by the target format).
* @param rows The rows of the table.
*/
data class Table(
val name: String? = null,
val columns: List<ColumnStyle> = emptyList(),
val rows: List<Row>,
)
| 0
|
Kotlin
|
0
| 2
|
a184fbaa4b75011e9dd78904fea8f9677c4133b4
| 506
|
ooxml-kotlin
|
MIT License
|
app/src/main/java/com/thatsmanmeet/tasky/TodoItemCard.kt
|
thatsmanmeet
| 603,736,595
| false
| null |
package com.thatsmanmeet.tasky
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.thatsmanmeet.tasky.room.Todo
import com.thatsmanmeet.tasky.room.TodoViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TodoItemCard(
todo: Todo,
viewModel: TodoViewModel,
modifier: Modifier = Modifier
){
val currentCheckBoxState = remember {
mutableStateOf(todo.isCompleted)
}
val context = LocalContext.current
Row(
modifier = modifier
.fillMaxWidth()
.clip(RoundedCornerShape(10.dp))
.background(MaterialTheme.colorScheme.inverseOnSurface)
.heightIn(min = 60.dp)
.padding(5.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start
) {
Checkbox(
checked = currentCheckBoxState.value,
onCheckedChange = {
currentCheckBoxState.value = it
viewModel.updateTodo(Todo(todo.ID,todo.title,currentCheckBoxState.value))
if(currentCheckBoxState.value){
viewModel.playCompletedSound(context)
}
})
Spacer(modifier = Modifier.width(10.dp))
Text(text = todo.title!!,
textDecoration = if (currentCheckBoxState.value) TextDecoration.LineThrough else TextDecoration.None,
fontSize = 18.sp
)
}
Spacer(modifier = Modifier.height(12.dp))
}
| 0
|
Kotlin
|
0
| 2
|
b85f40b55157cbbcafec1871964da1ae5c10ab4b
| 2,153
|
Tasky
|
MIT License
|
app/src/main/java/com/thatsmanmeet/tasky/TodoItemCard.kt
|
thatsmanmeet
| 603,736,595
| false
| null |
package com.thatsmanmeet.tasky
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Checkbox
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.thatsmanmeet.tasky.room.Todo
import com.thatsmanmeet.tasky.room.TodoViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TodoItemCard(
todo: Todo,
viewModel: TodoViewModel,
modifier: Modifier = Modifier
){
val currentCheckBoxState = remember {
mutableStateOf(todo.isCompleted)
}
val context = LocalContext.current
Row(
modifier = modifier
.fillMaxWidth()
.clip(RoundedCornerShape(10.dp))
.background(MaterialTheme.colorScheme.inverseOnSurface)
.heightIn(min = 60.dp)
.padding(5.dp),
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.Start
) {
Checkbox(
checked = currentCheckBoxState.value,
onCheckedChange = {
currentCheckBoxState.value = it
viewModel.updateTodo(Todo(todo.ID,todo.title,currentCheckBoxState.value))
if(currentCheckBoxState.value){
viewModel.playCompletedSound(context)
}
})
Spacer(modifier = Modifier.width(10.dp))
Text(text = todo.title!!,
textDecoration = if (currentCheckBoxState.value) TextDecoration.LineThrough else TextDecoration.None,
fontSize = 18.sp
)
}
Spacer(modifier = Modifier.height(12.dp))
}
| 0
|
Kotlin
|
0
| 2
|
b85f40b55157cbbcafec1871964da1ae5c10ab4b
| 2,153
|
Tasky
|
MIT License
|
compiler/src/main/java/com/squareup/anvil/compiler/codegen/dagger/ProvidesMethodFactoryGenerator.kt
|
jzbrooks
| 312,558,967
| true
|
{"Kotlin": 480092, "Shell": 694}
|
package com.squareup.anvil.compiler.codegen.dagger
import com.squareup.anvil.compiler.AnvilCompilationException
import com.squareup.anvil.compiler.codegen.CodeGenerator.GeneratedFile
import com.squareup.anvil.compiler.codegen.PrivateCodeGenerator
import com.squareup.anvil.compiler.codegen.addGeneratedByComment
import com.squareup.anvil.compiler.codegen.asArgumentList
import com.squareup.anvil.compiler.codegen.asClassName
import com.squareup.anvil.compiler.codegen.classesAndInnerClasses
import com.squareup.anvil.compiler.codegen.findAnnotation
import com.squareup.anvil.compiler.codegen.functions
import com.squareup.anvil.compiler.codegen.hasAnnotation
import com.squareup.anvil.compiler.codegen.isNullable
import com.squareup.anvil.compiler.codegen.mapToParameter
import com.squareup.anvil.compiler.codegen.properties
import com.squareup.anvil.compiler.codegen.requireFqName
import com.squareup.anvil.compiler.codegen.requireTypeName
import com.squareup.anvil.compiler.codegen.requireTypeReference
import com.squareup.anvil.compiler.codegen.withJvmSuppressWildcardsIfNeeded
import com.squareup.anvil.compiler.codegen.writeToString
import com.squareup.anvil.compiler.daggerModuleFqName
import com.squareup.anvil.compiler.daggerProvidesFqName
import com.squareup.anvil.compiler.generateClassName
import com.squareup.kotlinpoet.ClassName
import com.squareup.kotlinpoet.FileSpec
import com.squareup.kotlinpoet.FunSpec
import com.squareup.kotlinpoet.KModifier.OVERRIDE
import com.squareup.kotlinpoet.KModifier.PRIVATE
import com.squareup.kotlinpoet.ParameterizedTypeName.Companion.parameterizedBy
import com.squareup.kotlinpoet.PropertySpec
import com.squareup.kotlinpoet.TypeSpec
import com.squareup.kotlinpoet.asClassName
import com.squareup.kotlinpoet.jvm.jvmStatic
import dagger.internal.Factory
import dagger.internal.Preconditions
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.psi.KtCallableDeclaration
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtProperty
import org.jetbrains.kotlin.psi.psiUtil.parents
import java.io.File
import java.util.Locale.US
internal class ProvidesMethodFactoryGenerator : PrivateCodeGenerator() {
override fun generateCodePrivate(
codeGenDir: File,
module: ModuleDescriptor,
projectFiles: Collection<KtFile>
) {
projectFiles
.asSequence()
.flatMap { it.classesAndInnerClasses() }
.filter { it.hasAnnotation(daggerModuleFqName) }
.forEach { clazz ->
clazz
.functions(includeCompanionObjects = true)
.asSequence()
.filter { it.hasAnnotation(daggerProvidesFqName) }
.also { functions ->
// Check for duplicate function names.
val duplicateFunctions = functions
.groupBy { it.requireFqName() }
.filterValues { it.size > 1 }
if (duplicateFunctions.isNotEmpty()) {
throw AnvilCompilationException(
element = clazz,
message = "Cannot have more than one binding method with the same name in " +
"a single module: ${duplicateFunctions.keys.joinToString()}"
)
}
}
.forEach { function ->
generateFactoryClass(codeGenDir, module, clazz, function)
}
clazz
.properties(includeCompanionObjects = true)
.asSequence()
.filter { property ->
// Must be '@get:Provides'.
property.findAnnotation(daggerProvidesFqName)?.useSiteTarget?.text == "get"
}
.forEach { property ->
generateFactoryClass(codeGenDir, module, clazz, property)
}
}
}
@OptIn(ExperimentalStdlibApi::class)
private fun generateFactoryClass(
codeGenDir: File,
module: ModuleDescriptor,
clazz: KtClassOrObject,
declaration: KtCallableDeclaration
): GeneratedFile {
val isCompanionObject = declaration.parents
.filterIsInstance<KtObjectDeclaration>()
.firstOrNull()
?.isCompanion()
?: false
val isObject = isCompanionObject || clazz is KtObjectDeclaration
val isProperty = declaration is KtProperty
val packageName = clazz.containingKtFile.packageFqName.asString()
val className = buildString {
append(clazz.generateClassName())
append('_')
if (isCompanionObject) {
append("Companion_")
}
if (isProperty) {
append("Get")
}
append(declaration.requireFqName().shortName().asString().capitalize(US))
append("Factory")
}
val callableName = declaration.nameAsSafeName.asString()
val parameters = declaration.valueParameters.mapToParameter(module)
val returnType = declaration.requireTypeReference().requireTypeName(module)
.withJvmSuppressWildcardsIfNeeded(declaration)
val returnTypeIsNullable = declaration.typeReference?.isNullable() ?: false
val factoryClass = ClassName(packageName, className)
val moduleClass = clazz.asClassName()
val byteCodeFunctionName = if (isProperty) {
"get" + callableName.capitalize(US)
} else {
callableName
}
val content = FileSpec.builder(packageName, className)
.apply {
val canGenerateAnObject = isObject && parameters.isEmpty()
val classBuilder = if (canGenerateAnObject) {
TypeSpec.objectBuilder(factoryClass)
} else {
TypeSpec.classBuilder(factoryClass)
}
classBuilder.addSuperinterface(Factory::class.asClassName().parameterizedBy(returnType))
.apply {
if (!canGenerateAnObject) {
primaryConstructor(
FunSpec.constructorBuilder()
.apply {
if (!isObject) {
addParameter("module", moduleClass)
}
parameters.forEach { parameter ->
addParameter(parameter.name, parameter.providerTypeName)
}
}
.build()
)
if (!isObject) {
addProperty(
PropertySpec.builder("module", moduleClass)
.initializer("module")
.addModifiers(PRIVATE)
.build()
)
}
parameters.forEach { parameter ->
addProperty(
PropertySpec.builder(parameter.name, parameter.providerTypeName)
.initializer(parameter.name)
.addModifiers(PRIVATE)
.build()
)
}
}
}
.addFunction(
FunSpec.builder("get")
.addModifiers(OVERRIDE)
.returns(returnType)
.apply {
val argumentList = parameters.asArgumentList(
asProvider = true,
includeModule = !isObject
)
addStatement("return $byteCodeFunctionName($argumentList)")
}
.build()
)
.apply {
val builder = if (canGenerateAnObject) this else TypeSpec.companionObjectBuilder()
builder
.addFunction(
FunSpec.builder("create")
.jvmStatic()
.apply {
if (canGenerateAnObject) {
addStatement("return this")
} else {
if (!isObject) {
addParameter("module", moduleClass)
}
parameters.forEach { parameter ->
addParameter(parameter.name, parameter.providerTypeName)
}
val argumentList = parameters.asArgumentList(
asProvider = false,
includeModule = !isObject
)
addStatement("return %T($argumentList)", factoryClass)
}
}
.returns(factoryClass)
.build()
)
.addFunction(
FunSpec.builder(byteCodeFunctionName)
.jvmStatic()
.apply {
if (!isObject) {
addParameter("module", moduleClass)
}
parameters.forEach { parameter ->
addParameter(
name = parameter.name,
type = parameter.originalTypeName
)
}
val argumentsWithoutModule = if (isProperty) {
""
} else {
"(${parameters.joinToString { it.name }})"
}
when {
isObject && returnTypeIsNullable ->
addStatement(
"return %T.$callableName$argumentsWithoutModule",
moduleClass
)
isObject && !returnTypeIsNullable ->
addStatement(
"return %T.checkNotNull(%T.$callableName" +
"$argumentsWithoutModule, %S)",
Preconditions::class,
moduleClass,
"Cannot return null from a non-@Nullable @Provides method"
)
!isObject && returnTypeIsNullable ->
addStatement(
"return module.$callableName$argumentsWithoutModule"
)
!isObject && !returnTypeIsNullable ->
addStatement(
"return %T.checkNotNull(module.$callableName" +
"$argumentsWithoutModule, %S)",
Preconditions::class,
"Cannot return null from a non-@Nullable @Provides method"
)
}
}
.returns(returnType)
.build()
)
.build()
.let {
if (!canGenerateAnObject) {
addType(it)
}
}
}
.build()
.let { addType(it) }
}
.build()
.writeToString()
.addGeneratedByComment()
val directory = File(codeGenDir, packageName.replace('.', File.separatorChar))
val file = File(directory, "$className.kt")
check(file.parentFile.exists() || file.parentFile.mkdirs()) {
"Could not generate package directory: ${file.parentFile}"
}
file.writeText(content)
return GeneratedFile(file, content)
}
}
| 1
|
Kotlin
|
0
| 0
|
a188af94796e982cfcc03212c1d073f1110d30ec
| 12,317
|
anvil
|
Apache License 2.0
|
android/app/src/main/java/cloud/multipos/pos/devices/DefaultCustomerDisplay.kt
|
multipos-app
| 773,180,579
| false
|
{"Kotlin": 548453, "Java": 306036}
|
/**
* Copyright (C) 2023 multiPOS, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cloud.multipos.pos.devices
import cloud.multipos.pos.models.Ticket
class DefaultCustomerDisplay (): CustomerDisplay () {
init {
success (this)
}
override fun deviceName (): String { return "Default customer display" }
override fun clear () { }
override fun update (ticket: Ticket) { }
override fun text (text: String, lineNo: Int) { }
}
| 0
|
Kotlin
|
1
| 7
|
119bb0c86a5f9589e0219249b02f0f56d43120f7
| 977
|
pos
|
Apache License 2.0
|
app/src/main/java/io/horizontalsystems/bankwallet/modules/addtoken/AddTokenFragment.kt
|
fahimaltinordu
| 312,207,740
| true
|
{"Kotlin": 1883211, "Java": 33448, "Ruby": 5803, "Shell": 2024}
|
package io.horizontalsystems.bankwallet.modules.addtoken
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import io.horizontalsystems.bankwallet.R
import io.horizontalsystems.bankwallet.core.BaseFragment
import io.horizontalsystems.bankwallet.entities.ApiError
import io.horizontalsystems.core.findNavController
import io.horizontalsystems.core.helpers.HudHelper
import io.horizontalsystems.ethereumkit.core.AddressValidator
import io.horizontalsystems.snackbar.SnackbarDuration
import kotlinx.android.synthetic.main.fragment_add_token.*
class AddTokenFragment : BaseFragment() {
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
return inflater.inflate(R.layout.fragment_add_token, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
toolbar.setNavigationOnClickListener {
findNavController().popBackStack()
}
val tokenType = arguments?.getParcelable<TokenType>(TOKEN_TYPE_KEY) ?: run {
findNavController().popBackStack()
return
}
val model: AddTokenViewModel by viewModels { AddTokenModule.Factory(tokenType) }
toolbar.title = getString(model.titleTextRes)
addressInputView.setEditable(false)
addressInputView.setHint(getString(model.hintTextRes))
btnAddToken.setOnClickListener {
model.onAddClick()
}
addressInputView.onTextChange {
model.onTextChange(it)
}
addressInputView.onPasteText {
model.onTextChange(it)
addressInputView.setText(it)
}
observeViewModel(model)
}
private fun observeViewModel(model: AddTokenViewModel) {
model.loadingLiveData.observe(viewLifecycleOwner, Observer { visible ->
progressLoading.isVisible = visible
})
model.showSuccess.observe(viewLifecycleOwner, Observer {
HudHelper.showSuccessMessage(requireView(), R.string.Hud_Text_Success, SnackbarDuration.LONG)
Handler().postDelayed({
findNavController().popBackStack()
}, 1500)
})
model.viewItemLiveData.observe(viewLifecycleOwner, Observer {
setCoinDetails(it)
})
model.cautionLiveData.observe(viewLifecycleOwner, Observer { caution ->
addressInputView.setError(caution)
})
model.showAddButton.observe(viewLifecycleOwner, Observer { visible ->
btnAddToken.isVisible = visible
})
}
private fun setCoinDetails(viewItem: AddTokenModule.ViewItem?) {
coinNameTitle.isVisible = viewItem != null
coinNameValue.isVisible = viewItem != null
symbolTitle.isVisible = viewItem != null
symbolValue.isVisible = viewItem != null
decimalTitle.isVisible = viewItem != null
decimalsValue.isVisible = viewItem != null
coinNameValue.text = viewItem?.coinName ?: ""
symbolValue.text = viewItem?.symbol ?: ""
decimalsValue.text = viewItem?.decimal?.toString() ?: ""
}
companion object {
const val TOKEN_TYPE_KEY = "token_type_key"
}
}
| 0
|
Kotlin
|
0
| 4
|
d3094c4afaa92a5d63ce53583bc07c8fb343f90b
| 3,486
|
WILC-wallet-android
|
MIT License
|
sample/src/main/kotlin/com/infinum/halley/sample/data/models/serialization/ProductResource.kt
|
infinum
| 515,133,770
| false
| null |
package com.infinum.halley.sample.data.models.serialization
import com.infinum.halley.core.annotations.HalEmbedded
import com.infinum.halley.core.annotations.HalLink
import com.infinum.halley.core.serializers.hal.models.HalResource
import com.infinum.halley.core.serializers.link.models.Link
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
@Serializable
data class ProductResource(
@HalLink
@SerialName(value = "self")
val self: Link? = null,
@SerialName(value = "name")
val name: String? = null,
@SerialName(value = "weight")
val weight: Int = 0,
@SerialName(value = "description")
val description: String? = null,
@HalEmbedded
@SerialName(value = "manufacturer")
val manufacturer: ManufacturerResource? = null,
@HalLink
@SerialName(value = "other")
val other: List<Link>? = null,
@SerialName(value = "pages")
val pages: List<Page>? = null,
@SerialName(value = "hello")
val hello: HelloWorld? = null
) : HalResource
| 0
|
Kotlin
|
0
| 0
|
0af19cf3a4ffeebb10b5b053dff01bb1acd15dbc
| 1,038
|
android-halley
|
Apache License 2.0
|
platform/src/main/kotlin/com/samsung/healthcare/platform/application/config/Constants.kt
|
S-HealthStack
| 520,365,362
| false
| null |
package com.samsung.healthcare.platform.application.config
object Constants {
const val DEFAULT_TENANT_NAME = "DEFAULT"
}
| 2
|
Kotlin
|
2
| 7
|
8600eaa7c1d10734a0c90fe396eaf42ffdc10e73
| 127
|
backend-system
|
Apache License 2.0
|
openai/src/main/kotlin/herbaccara/openai/model/model/Model.kt
|
herbaccara
| 611,054,860
| false
| null |
package herbaccara.openai.model.model
import com.fasterxml.jackson.annotation.JsonProperty
data class Model(
val id: String,
@field:JsonProperty("object")
val `object`: String,
val created: Int,
@field:JsonProperty("owned_by")
val ownedBy: String,
val permission: List<Permission>,
val root: String,
val parent: String?
)
| 1
|
Kotlin
|
1
| 2
|
7a3558a5e771d9ce5b8c1bf0cf44ade310471c85
| 360
|
openai
|
MIT License
|
visionforge-solid/src/commonTest/kotlin/space/kscience/visionforge/solid/VisionUpdateTest.kt
|
mipt-npm
| 174,502,624
| false
| null |
package space.kscience.visionforge.solid
import space.kscience.dataforge.context.Global
import space.kscience.dataforge.context.fetch
import space.kscience.dataforge.meta.MetaItem
import space.kscience.dataforge.names.toName
import space.kscience.visionforge.VisionChange
import space.kscience.visionforge.get
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class VisionUpdateTest {
val solidManager = Global.fetch(Solids)
val visionManager = solidManager.visionManager
@Test
fun testVisionUpdate(){
val targetVision = SolidGroup {
box(200,200,200, name = "origin")
}
val dif = VisionChange(visionManager){
group("top") {
color(123)
box(100,100,100)
}
propertyChanged("top".toName(), SolidMaterial.MATERIAL_COLOR_KEY, MetaItem.of("red"))
propertyChanged("origin".toName(), SolidMaterial.MATERIAL_COLOR_KEY, MetaItem.of("red"))
}
targetVision.update(dif)
assertTrue { targetVision["top"] is SolidGroup }
assertEquals("red", (targetVision["origin"] as Solid).color.string) // Should work
assertEquals("#00007b", (targetVision["top"] as Solid).color.string) // new item always takes precedence
}
@Test
fun testVisionChangeSerialization(){
val change = VisionChange(visionManager){
group("top") {
color(123)
box(100,100,100)
}
propertyChanged("top".toName(), SolidMaterial.MATERIAL_COLOR_KEY, MetaItem.of("red"))
propertyChanged("origin".toName(), SolidMaterial.MATERIAL_COLOR_KEY, MetaItem.of("red"))
}
val serialized = visionManager.jsonFormat.encodeToString(VisionChange.serializer(), change)
println(serialized)
val reconstructed = visionManager.jsonFormat.decodeFromString(VisionChange.serializer(), serialized)
assertEquals(change.properties,reconstructed.properties)
}
@Test
fun testDeserialization(){
val str = """
{
"propertyChange": {
"layer[4]": {
"material": {
"color": 123
}
},
"layer[2]": {
"material": {
}
}
},
"childrenChange": {
}
}
""".trimIndent()
val reconstructed = visionManager.jsonFormat.decodeFromString(VisionChange.serializer(), str)
}
}
| 11
|
Kotlin
|
5
| 25
|
456e01fcfa48f798a03cc5866acc5d4c557e00c3
| 2,649
|
visionforge
|
Apache License 2.0
|
plugins/src/main/java/com/google/gradle/tasks/WarnAboutApiChangesTask.kt
|
google
| 727,310,537
| false
|
{"Kotlin": 193548, "Shell": 1825}
|
/*
* Copyright 2023 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.gradle.tasks
import com.google.gradle.types.LinesChanged
import com.google.gradle.types.VersionType.*
import com.google.gradle.util.SkipTask
import com.google.gradle.util.spoiler
import java.io.File
import org.gradle.api.DefaultTask
import org.gradle.api.provider.Property
import org.gradle.api.tasks.InputFile
import org.gradle.api.tasks.OutputFile
import org.gradle.api.tasks.TaskAction
/**
* A Gradle task to warn about API changes made during development.
*
* By default, saved in the root project's build directory under `api_changes.md`. The task uses the
* provided [changesFile] to infer if merging the changes currently present in the repo will have an
* impact on the public api.
*
* This should help developers avoid accidentally leaking internal implementation details into the
* public API, and causing breaking changes without noticing.
*
* The generated message is intended to be safe to display straight to the developer.
*
* If no public api changes are found, then no message will be generated and the task will skip
* itself.
*
* @property changesFile a file contained a [LinesChanged]; representing the changes made in this
* repo
* @property outputFile where to save the warning message to
* @throws SkipTask if no public api changes are found
*/
abstract class WarnAboutApiChangesTask : DefaultTask() {
@get:InputFile abstract val changesFile: Property<File>
@get:OutputFile abstract val outputFile: Property<File>
@TaskAction
fun add() {
val diff = LinesChanged.fromFile(changesFile.get())
val added = spoiler("APIs Added", diff.added.joinToString("\n\n") { it.trim() })
val removed = spoiler("APIs Removed", diff.removed.joinToString("\n\n") { it.trim() })
val message =
when (diff.bump) {
MAJOR ->
"""
|You've removed things from the public API. This means your change will cause a
|**major** version bump during release time. If you're okay with this, you can ignore
|this message.
|
|${removed.takeUnless { diff.removed.isEmpty() }.orEmpty()}
|${added.takeUnless { diff.added.isEmpty() }.orEmpty()}
"""
.trimMargin()
MINOR ->
"""
|You've added things to the public API. This means your change will cause a
|**minor** version bump during release time. If you're okay with this, you can ignore
|this message.
|
|${added.takeUnless { diff.added.isEmpty() }.orEmpty()}
"""
.trimMargin()
else -> throw SkipTask("No public api changes found")
}
outputFile.get().writeText(message)
}
}
| 26
|
Kotlin
|
153
| 78
|
440f960d8ddd96b846ded23d7f20a983b635fa03
| 3,360
|
generative-ai-android
|
Apache License 2.0
|
sample/src/main/java/com/example/webtrekk/androidsdk/mapp/SecondActivity.kt
|
Webtrekk
| 166,987,236
| false
| null |
package com.example.webtrekk.androidsdk.mapp
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.View
import com.example.webtrekk.androidsdk.R
class SecondActivity : Activity() {
private val DEEPLINK_SCHEME = "com.appoxee.test"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
findViewById<View>(R.id.open_link).setOnClickListener {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse("http://google.com")
startActivity(intent)
}
}
override fun onResume() {
super.onResume()
if (intent != null) {
if (DEEPLINK_SCHEME == intent.action) {
val uri = intent.data
}
}
}
}
| 1
|
Kotlin
|
1
| 12
|
24cdccd048b5ff80935934fc00cf36da6321f580
| 887
|
webtrekk-android-sdk-v5
|
MIT License
|
database/src/main/java/com/danielwaiguru/touristnews/database/entities/TouristEntity.kt
|
daniel-waiguru
| 680,273,793
| false
|
{"Kotlin": 123694, "Shell": 254}
|
package com.danielwaiguru.touristnews.database.entities
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import com.danielwaiguru.touristnews.database.entities.TouristEntity.Companion.TOURISTS_TABLE_NAME
@Entity(tableName = TOURISTS_TABLE_NAME)
data class TouristEntity(
@ColumnInfo(name = "created_at")
val createdAt: String,
@PrimaryKey(autoGenerate = false)
val id: Int,
@ColumnInfo(name = "tourist_email")
val touristEmail: String,
@ColumnInfo(name = "tourist_location")
val touristLocation: String,
@ColumnInfo(name = "tourist_name")
val touristName: String?,
val nextPage: Int? = null
) {
companion object {
const val TOURISTS_TABLE_NAME = "tb_tourists"
}
}
| 11
|
Kotlin
|
0
| 0
|
96955bb7fe4e2565947f96358b64d277b69512ab
| 768
|
Tourist-App
|
The Unlicense
|
app/src/main/java/cz/palda97/lpclient/model/entities/pipeline/DialogJsFactory.kt
|
Palda97
| 280,530,029
| false
| null |
package cz.palda97.lpclient.model.entities.pipeline
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import cz.palda97.lpclient.Injector
/**
* Factory for transforming dialog.js to [DialogJs].
*/
class DialogJsFactory(private val js: String, private val componentId: String) {
/**
* Parse javascript to [DialogJs].
* @return DialogJs or null on error.
*/
fun parse(): DialogJs? {
if (js.isEmpty()) {
return DialogJs("", mapOf(), componentId)
}
val json = js
.substringAfter(CONST_DESC)
.replaceAfter(JSON_END, "")
.replace(",\\s*\\};".toRegex(), "\n};")
.removeSuffix(SEMICOLON)
.removeAnonFunctions()
val jsonObject = try {
Gson().fromJson(json, Any::class.java) as? Map<*, *>
} catch (e: JsonSyntaxException) {
null
} ?: return null.also {
l(0)
l(json)
}
val namespace = jsonObject[NAMESPACE] as? String ?: return null.also {
l(1)
}
val map: MutableMap<String, String> = HashMap()
jsonObject.forEach {
if (it.key is String) {
val key = (it.key as? String) ?: return null.also {
l(2)
}
val skip = key.startsWith(PREFIX)
if (!skip) {
val innerMap = it.value as? Map<*, *>
val prop = innerMap?.get(PROPERTY) as? String
if (prop == null) {
map[key] = key
} else {
map[key] = prop
}
}
}
}
return DialogJs(namespace, map, componentId)
}
companion object {
private const val CONST_DESC = "const DESC = "
private const val PREFIX = "$"
private const val JSON_END = "};"
private const val SEMICOLON = ";"
private const val PROPERTY = "\$property"
private const val NAMESPACE = "\$namespace"
private val l = Injector.generateLogFunction(this)
/**
* Removes anonymous functions like this:
*
*
*
* "$onLoad": (value) => {
*
* return value.join(",");
*
* }
*/
fun String.removeAnonFunctions(): String {
val r = "\\n\\s*\".+\"\\s*:\\s*\\(.+\\)\\s*=>\\s*\\{"
val r1 = ",\\s*$r".toRegex()
val r2 = r.toRegex()
tailrec fun loop(comma: Boolean, json: String): String {
val regex = if (comma) r1 else r2
fun findEnd(json: String): Int? {
var openCnt = 0
json.forEachIndexed { i, c ->
when(c) {
'{' -> openCnt += 1
'}' -> openCnt -= 1
}
if (openCnt == 0) {
return i
}
}
return null
}
val match = regex.find(json) ?: return json
val start = match.range.first
val tmpEnd = findEnd(json.removeRange(0, match.range.last)) ?: return json
val tmpEnd2 = tmpEnd + match.range.last + 1
val end = if (!comma && json[tmpEnd2] == ',') {
tmpEnd2 + 1
} else {
tmpEnd2
}
val newJson = json.removeRange(start, end)
return loop(comma, newJson)
}
val firstStage = loop(true, this)
return loop(false, firstStage)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e2e1c188a21dac4cd78d9242633dc094ba50ef64
| 3,837
|
LinkedPipesAndroidClient
|
MIT License
|
spring/support/src/main/kotlin/io/bluetape4k/spring/ui/ModelExtensions.kt
|
debop
| 625,161,599
| false
|
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
|
package io.bluetape4k.spring.ui
import org.springframework.ui.Model
fun Model.addAttributes(vararg pairs: Pair<String, Any?>): Model =
addAllAttributes(pairs.toMap())
fun Model.mergeAttributes(vararg pairs: Pair<String, Any?>): Model =
mergeAttributes(pairs.toMap())
| 0
|
Kotlin
|
0
| 1
|
ce3da5b6bddadd29271303840d334b71db7766d2
| 278
|
bluetape4k
|
MIT License
|
riskscore/src/main/java/uk/nhs/riskscore/RiskScoreCalculatorConfiguration.kt
|
klinker41
| 330,272,308
| true
|
{"Kotlin": 76046}
|
package uk.nhs.riskscore
/**
* Configuration for the [RiskScoreCalculator]
*
* @param sampleResolution: The resolution of samples taken in seconds.
* @param expectedDistance: The expected distance moved per second in meters.
* @param minimumDistance: The minimum distance in meters. Any estimated distance lower than this will be replaced with this value.
* @param rssiParameters: Parameters for the RSSI emission model.
* @param powerLossParameters: Parameters used in the Friis function for RSSi to estimated distance calculation.
* @param observationType: The observation model to use.
* @param initialData: Prior values for the Kalman smoother.
* @param smootherParameters: Parameters for the Kalman smoother
*/
public class RiskScoreCalculatorConfiguration(
internal val sampleResolution: Double,
internal val expectedDistance: Double,
internal val minimumDistance: Double,
internal val rssiParameters: RssiParameters,
internal val powerLossParameters: PowerLossParameters,
internal val observationType: ObservationType,
internal val initialData: InitialData,
internal val smootherParameters: SmootherParameters
) {
public companion object {
public val exampleConfiguration: RiskScoreCalculatorConfiguration get() =
RiskScoreCalculatorConfiguration(
sampleResolution = 1.0,
expectedDistance = 0.1,
minimumDistance = 1.0,
rssiParameters = RssiParameters(
weightCoefficient = 0.1270547531082051,
intercept = 4.2309333657856945,
covariance = 0.4947614361027773
),
powerLossParameters = PowerLossParameters(
wavelength = 0.125,
pathLossFactor = 20.0,
refDeviceLoss = 0.0
),
observationType = ObservationType.log,
initialData = InitialData(
mean = 2.0,
covariance = 10.0
),
smootherParameters = SmootherParameters(
alpha = 1.0,
beta = 0.0,
kappa = 0.0
)
)
}
}
/**
Parameters for the RSSI emissions model.
*/
public class RssiParameters(
internal val weightCoefficient: Double,
internal val intercept: Double,
internal val covariance: Double
)
public enum class ObservationType {
log, gen
}
/**
* @param wavelength: The signal wavelength in meters.
* @param pathLossFactor: The free-space loss factor.
* @param refDeviceLoss: The reference device losses.
*/
public class PowerLossParameters(
internal val wavelength: Double,
internal val pathLossFactor: Double,
internal val refDeviceLoss: Double
)
/**
* Initial data for the Kalman smoother
*/
public class InitialData(
internal val mean: Double,
internal val covariance: Double
)
public class SmootherParameters(
internal val alpha: Double,
internal val beta: Double,
internal val kappa: Double
)
| 0
|
Kotlin
|
0
| 0
|
31e7235d807b5701fee138ff8ca38b2174edad59
| 3,096
|
riskscore-kt-public
|
MIT License
|
app/src/main/java/com/etasdemir/ethinspector/utils/Utils.kt
|
etasdemir
| 584,191,764
| false
| null |
package com.etasdemir.ethinspector.utils
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.sp
import com.etasdemir.ethinspector.R
import com.etasdemir.ethinspector.ui.theme.Negative
import com.etasdemir.ethinspector.ui.theme.Positive
import java.text.*
import java.util.Locale
import kotlin.math.abs
fun Double.format(digits: Int): Double {
val pattern = StringBuilder("#.")
for (i in 0 until digits) {
pattern.append("#")
}
val df = DecimalFormat(pattern.toString())
return df.format(this).toDouble()
}
fun String.format(digits: Int): String {
if (digits == 0) {
return this.split('.')[0]
}
val delimiter = "."
val parts = this.split(delimiter)
val lastPart = parts.last().toCharArray()
val formattedString = StringBuilder("")
for (i in 0 until parts.size - 1) {
formattedString.append(parts[i] + delimiter)
}
for (i in lastPart.indices) {
if (i < digits) {
formattedString.append(lastPart[i])
}
}
return formattedString.toString()
}
fun String.clip(digits: Int): String {
return if (digits >= (this.length / 2)) {
this
} else {
this.take(digits) + "..." + this.takeLast(digits)
}
}
@Composable
fun ColoredAmountText(modifier: Modifier = Modifier, amount: Double, digits: Int = 5) {
val formattedNumber = remember { amount.format(digits) }
val amountTextColor: Color?
val amountText: String?
if (amount >= 0) {
amountText = "+$formattedNumber"
amountTextColor = Positive
} else {
amountText = "-$formattedNumber"
amountTextColor = Negative
}
Text(
modifier = modifier,
text = stringResource(
id = R.string.eth_with_amount, amountText
), color = amountTextColor, fontSize = 16.sp
)
}
fun amountColor(amount: Double) = if (amount >= 0) Positive else Negative
fun ULong.toHex() = "0x${this.toString(16)}"
fun String.toDecimal() = this.substring(2).toULong(16)
fun String.addDots(): String {
val len = this.length
if (len < 3) return this
var current = 0
val part = StringBuilder()
val result = StringBuilder()
part.insert(0, "")
for (i in len - 1 downTo 0) {
current++
part.insert(0, this[i])
if (current % 3 == 0) {
result.insert(0, part)
if (i != 0) {
result.insert(0, ".")
}
part.clear()
current = 0
}
}
if (len % 3 != 0) {
result.insert(0, this.substring(0, len % 3))
}
return result.toString()
}
private val simpleDateFormat = SimpleDateFormat("dd MMMM yyyy, HH:mm:ss", Locale.ENGLISH)
fun getDateString(time: Long) : String = simpleDateFormat.format(time * 1000L)
fun Double.toPlainString(): String {
val df = DecimalFormat("0", DecimalFormatSymbols.getInstance(Locale.ENGLISH))
df.maximumFractionDigits = 340
return df.format(this)
}
fun convertTokenAmountFromDecimal(amount: String, tokenDecimal: Int): Double {
val numbers = amount.toMutableList()
val diff = numbers.size - tokenDecimal
if (diff <= 0) {
for (i in 0 .. abs(diff)) {
numbers.add(0, '0')
}
}
numbers.add(numbers.size - tokenDecimal, '.')
return String(numbers.toCharArray()).format(3).toDouble()
}
| 0
|
Kotlin
|
0
| 2
|
96a74f3f31bf6aeaa9516110065405ea606f9702
| 3,580
|
eth-inspector
|
MIT License
|
app/src/main/java/com/diana/test/meddrawer/view/medicine/MedicineAdapter.kt
|
dianaiosifescu
| 273,247,013
| false
| null |
package com.diana.test.meddrawer.view.medicine
import android.app.DatePickerDialog
import android.content.Context
import android.graphics.Color
import android.text.InputType
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnTouchListener
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import androidx.recyclerview.widget.RecyclerView
import com.diana.test.meddrawer.R
import com.diana.test.meddrawer.extensions.toDate
import com.diana.test.meddrawer.model.AddMedModel
import com.diana.test.meddrawer.model.MedicineModel
import kotlinx.android.synthetic.main.activity_medicine_v2.view.*
import kotlinx.android.synthetic.main.recyclerview_addmed_row_details.view.*
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.util.*
class MedicineAdapter (
val context : Context,
val hideKeyboardListener: (view: View?) -> Unit) :
RecyclerView.Adapter<MedicineAdapter.MedicineViewHolder> () {
var items : ArrayList<AddMedModel> = arrayListOf()
var medicine: MedicineModel? = null
var medicine2 : MedicineModel? = null
var areFieldsEditable: Boolean = false
override fun getItemCount(): Int {
return items.size
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MedicineViewHolder {
return MedicineViewHolder(
LayoutInflater.from(context).inflate(
R.layout.recyclerview_addmed_row_details,
parent,
false
)
)
}
override fun onBindViewHolder(holder: MedicineViewHolder, position: Int) {
val med= items[position]
holder.bind(med, context, medicine, medicine2, areFieldsEditable, hideKeyboardListener)
}
fun makeFieldsEditable () {
areFieldsEditable = true
medicine2 = if (medicine == null) {
MedicineModel(name = "", totalAmount = 0, amountLeft = 0, expDate = "", medForm = 0, comments = "" )
} else {
medicine?.deepCopy()
}
}
fun makeFieldsNonEditable () {
areFieldsEditable = false
}
fun saveEntry () : MedicineModel? {
return medicine2
}
class MedicineViewHolder (view: View) : RecyclerView.ViewHolder (view) {
val imageViewIcon = view.imageViewIcon
val tvTitleRow = view.tvTitleRow
val tvItemDetail = view.tvItemDetail
val spinner = view.spinner
val recyclerView = view.recyclerAddMed
var cal = Calendar.getInstance()
fun bind (med : AddMedModel, context : Context, medicine : MedicineModel?, medicine2 : MedicineModel?, areFieldsEditable : Boolean, hideKeyboardListener: (view: View?) -> Unit) {
val dateSetListener =
DatePickerDialog.OnDateSetListener { view, year, monthOfYear, dayOfMonth ->
cal.set(Calendar.YEAR, year)
cal.set(Calendar.MONTH, monthOfYear)
cal.set(Calendar.DAY_OF_MONTH, dayOfMonth)
updateDateInView(medicine2)
}
when (med.fieldType) {
AddMedModel.FieldType.TEXT -> {
tvItemDetail.setOnClickListener { }
tvItemDetail?.visibility = View.VISIBLE
spinner.visibility = View.GONE
tvItemDetail?.setInputType(InputType.TYPE_CLASS_TEXT)
tvItemDetail?.setTextColor(Color.BLACK)
tvItemDetail?.setHint("Type name here")
tvItemDetail.setText(medicine?.name)
makeEditable(areFieldsEditable)
if (areFieldsEditable) {
tvItemDetail.setOnFocusChangeListener { view, hasFocus ->
if(!hasFocus) {
medicine2?.name = tvItemDetail.text.toString()
}
}
}
}
AddMedModel.FieldType.AMOUNT -> {
tvItemDetail.setOnClickListener { }
tvItemDetail?.visibility = View.VISIBLE
spinner.visibility = View.GONE
tvItemDetail?.setInputType(InputType.TYPE_CLASS_NUMBER)
tvItemDetail?.setTextColor(Color.BLACK)
tvItemDetail?.setHint("Quantity")
if (medicine?.name !== null)
tvItemDetail.setText(medicine?.totalAmount.toString())
makeEditable(areFieldsEditable)
if (areFieldsEditable) {
tvItemDetail.setOnFocusChangeListener { view, hasFocus ->
if (!hasFocus) {
if (tvItemDetail.text.toString().isNullOrEmpty()) {
medicine2?.totalAmount = 0
} else {
medicine2?.totalAmount =
tvItemDetail.text.toString().toInt()
}
}
}
}
}
AddMedModel.FieldType.AMOUNT_LEFT -> {
ArrayAdapter.createFromResource(
context,
R.array.med_amount_left_array,
android.R.layout.simple_spinner_item
).also {
it.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item)
spinner.adapter = it
}
tvItemDetail?.setOnClickListener {
}
spinner.visibility = View.GONE
tvItemDetail?.visibility = View.VISIBLE
tvItemDetail?.setTextColor(Color.BLACK)
tvItemDetail.setText(medicine?.getAmountText())
makeEditable(areFieldsEditable)
if (areFieldsEditable) {
spinner.visibility = View.VISIBLE
tvItemDetail?.visibility = View.GONE
spinner.setSelection(medicine?.amountLeft ?: 0)
spinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
medicine2?.amountLeft = position
hideKeyboardListener(view)
}
}
spinner.setOnTouchListener(OnTouchListener { view, event ->
hideKeyboardListener(view)
false
})
}
}
AddMedModel.FieldType.PICKER -> {
ArrayAdapter.createFromResource(
context,
R.array.med_type_array,
android.R.layout.simple_spinner_item
).also {
it.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item)
spinner.adapter = it
}
tvItemDetail?.setOnClickListener {
}
spinner.visibility = View.GONE
tvItemDetail?.visibility = View.VISIBLE
tvItemDetail.setText(medicine?.getFormText())
tvItemDetail?.setTextColor(Color.BLACK)
makeEditable(areFieldsEditable)
if (areFieldsEditable) {
spinner.visibility = View.VISIBLE
tvItemDetail?.visibility = View.GONE
spinner.setSelection(medicine?.medForm ?: 0)
spinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
medicine2?.medForm = position
}
}
spinner.setOnTouchListener(OnTouchListener { view, event ->
hideKeyboardListener(view)
false
})
}
}
AddMedModel.FieldType.DATE -> {
tvItemDetail.setOnClickListener {
}
spinner.visibility = View.GONE
tvItemDetail?.visibility = View.VISIBLE
//exp date with red
if (! medicine?.expDate.isNullOrEmpty()) {
if (medicine?.expDate?.toDate()!!.isBefore(LocalDate.now())) {
tvItemDetail?.setTextColor(Color.RED)
}
}
tvItemDetail?.setText(medicine?.expDate)
tvItemDetail?.setHint("Choose expiration date")
makeEditable(false)
tvItemDetail.isClickable = areFieldsEditable
if (areFieldsEditable) {
tvItemDetail?.setOnClickListener {
DatePickerDialog(
context, dateSetListener,
cal.get(Calendar.YEAR),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)
).show()
hideKeyboardListener(it)
}
}
}
AddMedModel.FieldType.COMMENTS -> {
tvItemDetail.setOnClickListener { }
tvItemDetail?.visibility = View.VISIBLE
spinner.visibility = View.GONE
tvItemDetail?.setInputType(InputType.TYPE_CLASS_TEXT)
tvItemDetail?.setHint("Type comments here")
tvItemDetail.setText(medicine?.comments)
tvItemDetail?.setTextColor(Color.BLACK)
makeEditable(areFieldsEditable)
if (areFieldsEditable) {
tvItemDetail.setOnFocusChangeListener { view, hasFocus ->
if(!hasFocus) {
medicine2?.comments = tvItemDetail.text.toString()
}
}
}
}
}
imageViewIcon.setImageResource(med.icon)
tvTitleRow?.text = med.field
}
private fun makeEditable(enable : Boolean) {
tvItemDetail.isClickable = enable
tvItemDetail.isCursorVisible = enable
tvItemDetail.isFocusable = enable
tvItemDetail.isFocusableInTouchMode = enable
}
private fun updateDateInView(medicine2: MedicineModel?) {
val myFormat = "dd/MM/yyyy" // mention the format you need
val sdf = SimpleDateFormat(myFormat, Locale.FRANCE)
tvItemDetail?.text?.apply {
clear()
append(sdf.format(cal.time))
}
medicine2?.expDate = tvItemDetail?.text.toString()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
a3443991f9070c14c470b37577c9ad1d61716794
| 12,501
|
MedDrawer-Public
|
MIT License
|
benchmarks/src/jmh/kotlin/com/github/kdbc/benchmarks/postgresql/JdbcBenchmarkConcurrentSingle.kt
|
ClasicRando
| 722,364,579
| false
|
{"Kotlin": 861814}
|
package com.github.kdbc.benchmarks.postgresql
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.runBlocking
import kotlinx.datetime.toKotlinLocalDateTime
import org.openjdk.jmh.annotations.Benchmark
import org.openjdk.jmh.annotations.BenchmarkMode
import org.openjdk.jmh.annotations.Fork
import org.openjdk.jmh.annotations.Measurement
import org.openjdk.jmh.annotations.Mode
import org.openjdk.jmh.annotations.OutputTimeUnit
import org.openjdk.jmh.annotations.Scope
import org.openjdk.jmh.annotations.Setup
import org.openjdk.jmh.annotations.State
import org.openjdk.jmh.annotations.TearDown
import org.openjdk.jmh.annotations.Warmup
import java.util.concurrent.TimeUnit
@Warmup(iterations = 4, time = 10, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 20, time = 10, timeUnit = TimeUnit.SECONDS)
@Fork(2)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MICROSECONDS)
@State(Scope.Benchmark)
open class JdbcBenchmarkConcurrentSingle {
private var id = 0
private val dataSource = getJdbcDataSource()
@Setup
open fun start() {
dataSource.connection.use { connection ->
connection.createStatement().use { statement ->
statement.execute(setupQuery)
}
}
}
private fun step(): Int {
id++
if (id > 5000) id = 1
return id
}
// @Benchmark
open fun queryData() = runBlocking(Dispatchers.IO) {
val result = (1..concurrencyLimit).map {
val stepId = step()
async {
dataSource.connection.use {
it.prepareStatement(jdbcQuerySingle).use { preparedStatement ->
preparedStatement.setInt(1, stepId)
preparedStatement.executeQuery().use { resultSet ->
val items = mutableListOf<PostDataClass>()
while (resultSet.next()) {
val item = PostDataClass(
resultSet.getInt(1),
resultSet.getString(2),
resultSet.getObject(3, java.time.LocalDateTime::class.java).toKotlinLocalDateTime(),
resultSet.getObject(4, java.time.LocalDateTime::class.java).toKotlinLocalDateTime(),
resultSet.getInt(5),
resultSet.getInt(6),
resultSet.getInt(7),
resultSet.getInt(8),
resultSet.getInt(9),
resultSet.getInt(10),
resultSet.getInt(11),
resultSet.getInt(12),
resultSet.getInt(13),
)
items.add(item)
}
}
}
}
}
}
result.awaitAll()
}
@TearDown
fun destroy() {
dataSource.close()
}
}
| 7
|
Kotlin
|
0
| 0
|
5440565fd91cf3caf0bf3e913afba3078c24c24e
| 3,231
|
kdbc
|
Apache License 2.0
|
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/MarsStrokeUp.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.rounded.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.rounded.Icons
public val Icons.Bold.MarsStrokeUp: ImageVector
get() {
if (_marsStrokeUp != null) {
return _marsStrokeUp!!
}
_marsStrokeUp = Builder(name = "MarsStrokeUp", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(13.5f, 10.166f)
verticalLineToRelative(-1.166f)
horizontalLineToRelative(1.0f)
curveToRelative(0.828f, 0.0f, 1.5f, -0.671f, 1.5f, -1.5f)
reflectiveCurveToRelative(-0.672f, -1.5f, -1.5f, -1.5f)
horizontalLineToRelative(-1.0f)
verticalLineToRelative(-1.0f)
horizontalLineToRelative(1.563f)
curveToRelative(0.863f, 0.0f, 1.295f, -1.043f, 0.685f, -1.653f)
lineTo(12.685f, 0.284f)
curveToRelative(-0.378f, -0.378f, -0.991f, -0.378f, -1.369f, 0.0f)
lineToRelative(-3.063f, 3.063f)
curveToRelative(-0.61f, 0.61f, -0.178f, 1.653f, 0.685f, 1.653f)
horizontalLineToRelative(1.563f)
verticalLineToRelative(1.0f)
horizontalLineToRelative(-1.0f)
curveToRelative(-0.828f, 0.0f, -1.5f, 0.671f, -1.5f, 1.5f)
reflectiveCurveToRelative(0.672f, 1.5f, 1.5f, 1.5f)
horizontalLineToRelative(1.0f)
verticalLineToRelative(1.166f)
curveToRelative(-3.14f, 0.689f, -5.5f, 3.49f, -5.5f, 6.834f)
curveToRelative(0.0f, 3.86f, 3.141f, 7.0f, 7.0f, 7.0f)
reflectiveCurveToRelative(7.0f, -3.14f, 7.0f, -7.0f)
curveToRelative(0.0f, -3.345f, -2.359f, -6.145f, -5.5f, -6.834f)
close()
moveTo(12.0f, 21.0f)
curveToRelative(-2.206f, 0.0f, -4.0f, -1.794f, -4.0f, -4.0f)
reflectiveCurveToRelative(1.794f, -4.0f, 4.0f, -4.0f)
reflectiveCurveToRelative(4.0f, 1.794f, 4.0f, 4.0f)
reflectiveCurveToRelative(-1.794f, 4.0f, -4.0f, 4.0f)
close()
}
}
.build()
return _marsStrokeUp!!
}
private var _marsStrokeUp: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 3,033
|
icons
|
MIT License
|
EmmaExampleApp/app/src/main/java/com/emma/emmaandroidexample/ui/home/HomeScreen.kt
|
EMMADevelopment
| 851,476,718
| false
|
{"Kotlin": 30988}
|
package com.emma.emmaandroidexample.ui.home
import android.util.Log
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import androidx.navigation.compose.rememberNavController
import com.emma.emmaandroidexample.R
import com.emma.emmaandroidexample.data.learnMoreData
import com.emma.emmaandroidexample.data.mainData
import com.emma.emmaandroidexample.ui.home.components.Header
import com.emma.emmaandroidexample.ui.home.components.LearnMoreItem
import com.emma.emmaandroidexample.ui.home.components.MainItem
import com.emma.emmaandroidexample.ui.navigation.Routes
@Composable
fun HomeScreen(
navController: NavHostController
) {
LazyColumn {
item {
Header()
}
items(mainData) {
MainItem(
title = stringResource(id = it.title),
description = it.description?.let { it1 -> stringResource(id = it1) },
statusInfo = it.statusInfo?.let { it1 -> stringResource(id = it1) },
buttons = it.buttons
) { stringId ->
manageButtonClick(stringId, navController)
}
}
item {
Footer()
}
}
}
fun manageButtonClick(stringId: Int, navController: NavHostController) {
when (stringId) {
R.string.session_button_start_session -> Log.d("SALVA", "START SESSION")
R.string.register_button_register_user -> Log.d("SALVA", "REGISTER USER")
R.string.log_button_log_in_user -> Log.d("SALVA", "LOG IN USER")
R.string.events_button_track_event -> Log.d("SALVA", "TRACK EVENT")
R.string.events_button_add_user -> Log.d("SALVA", "ADD USER TAG 'TAG'")
R.string.communication_button_show_adball -> Log.d("SALVA", "SHOW ADBALL")
R.string.communication_button_show_startview -> Log.d("SALVA", "SHOW STARTVIEW")
R.string.communication_button_show_strip -> Log.d("SALVA", "SHOW STRIP")
R.string.communication_button_show_native_ad -> {
Log.d("SALVA", "SHOW NATIVE AD -> NAVIGATING...")
navController.navigate(Routes.NativeAdScreen.route)
}
R.string.orders_button_start_order -> Log.d("SALVA", "START ORDER")
R.string.orders_button_add_order -> Log.d("SALVA", "ADD PRODUCT")
R.string.orders_button_track_order -> Log.d("SALVA", "TRACK ORDER")
R.string.orders_button_cancel_order -> Log.d("SALVA", "CANCEL ORDER")
R.string.idfa_button_request_idfa_tracking -> Log.d("SALVA", "REQUEST IDFA TRACKING")
else -> {
Log.d("SALVA", "Button not found!")
}
}
}
@Composable
fun Footer() {
Column(
modifier = Modifier
.padding(horizontal = 30.dp, vertical = 6.dp)
) {
learnMoreData.forEach {
LearnMoreItem(
title = stringResource(id = it.title),
description = stringResource(id = it.description),
link = it.link
)
}
}
}
@Preview(showSystemUi = true)
@Composable
fun TestMain_Preview() {
val navController = rememberNavController()
HomeScreen(navController)
}
| 0
|
Kotlin
|
0
| 0
|
57e0cea0ac150172c021418058ede4dd335c6188
| 3,518
|
emma-android-app
|
Apache License 2.0
|
invert-report/src/jsMain/kotlin/com/squareup/invert/common/pages/BlankReportPage.kt
|
square
| 789,061,154
| false
|
{"Kotlin": 369133, "JavaScript": 4120, "HTML": 1882, "CSS": 1113, "Shell": 878}
|
package com.squareup.invert.common.pages
import androidx.compose.runtime.Composable
import com.squareup.invert.common.InvertReportPage
import com.squareup.invert.common.navigation.NavPage
import com.squareup.invert.common.navigation.routes.BaseNavRoute
import org.jetbrains.compose.web.dom.Text
import kotlin.reflect.KClass
class BlankNavRoute : BaseNavRoute(ArtifactsReportPage.navPage)
object BlankReportPage : InvertReportPage<ArtifactsNavRoute> {
override val navPage: NavPage = null!!
override val navRouteKClass: KClass<ArtifactsNavRoute> = ArtifactsNavRoute::class
override val composableContent: @Composable (ArtifactsNavRoute) -> Unit = { navRoute ->
Text(navRoute.toString())
}
}
| 4
|
Kotlin
|
0
| 82
|
31b1859a5b9b49553068a4da6ada5de2fe9d82ac
| 721
|
invert
|
Apache License 2.0
|
generators/server/templates/spring-boot-with-kotlin/spring-boot-with-kotlin-app/src/main/kotlin/me/ely/service/UserService.kt
|
xiaochunyong
| 204,886,659
| false
|
{"JavaScript": 145201, "Kotlin": 82063, "CSS": 10974, "HTML": 514, "Dockerfile": 289}
|
package me.ely.service
import me.ely.domain.entity.User
import me.ely.domain.entity.User_
import me.ely.domain.request.UserSearchRequestModel
import me.ely.repository.jpa.UserRepository
import org.springframework.data.domain.Page
import org.springframework.data.domain.PageImpl
import org.springframework.data.domain.PageRequest
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service
import java.util.*
import javax.persistence.criteria.CriteriaBuilder
import javax.persistence.criteria.Predicate
import javax.persistence.criteria.Root
import kotlin.math.max
/**
*
*
* @author <a href="mailto:<EMAIL>">Ely</a>
* @see
* @since 2019-08-05
*/
@Service
class UserService : AbstractJpaService<User, Long, UserRepository>() {
fun search(requestModel: UserSearchRequestModel): Page<User> {
val cb = entityManager.criteriaBuilder
val dataCq = cb.createQuery(User::class.java)
val dataRoot = dataCq.from(User::class.java)
val dataPredicates = buildSearchPredicates(requestModel, cb, dataRoot)
dataCq.where(*dataPredicates)
dataCq.orderBy(cb.desc(dataRoot.get(User_.createDt)))
val typedQuery = entityManager.createQuery(dataCq)
typedQuery.firstResult = requestModel.pageSize * max(requestModel.pageIndex - 1, 0)
typedQuery.maxResults = requestModel.pageSize
val data = typedQuery.resultList
val countCq = cb.createQuery(Long::class.java)
val countRoot = countCq.from(User::class.java)
val countPredicates = buildSearchPredicates(requestModel, cb, countRoot)
countCq.select(cb.count(countRoot)).where(*countPredicates)
val count = entityManager.createQuery(countCq).singleResult
return PageImpl(data, PageRequest.of(max(requestModel.pageIndex - 1, 0), requestModel.pageSize, Sort(Sort.Direction.DESC, "id")), count)
}
private fun buildSearchPredicates(requestModel: UserSearchRequestModel, cb: CriteriaBuilder, dataRoot: Root<User>): Array<Predicate> {
val conditions = ArrayList<Predicate>()
if (!requestModel.username.isNullOrEmpty()) {
conditions.add(cb.like(dataRoot.get(User_.username), "%" + requestModel.username + "%"))
}
return conditions.toTypedArray()
}
}
| 17
|
JavaScript
|
1
| 0
|
fb8523e3d04923be45737918ca693718bc6dcf04
| 2,304
|
generator-acg
|
Apache License 2.0
|
src/main/kotlin/vm2gol_v2/util/Utils.kt
|
sonota88
| 329,389,312
| false
| null |
package vm2gol_v2.util
class Utils {
companion object {
const val DQ = "\""
const val LF = "\n"
fun puts(x: Any?) {
println(x)
}
fun puts_e(x: Any?) {
System.err.println(x)
}
fun putskv_e(k: String, v: Any?) {
val vstr = if (v == null) "null" else v.toString()
puts_e("${k} (${vstr})")
}
fun slice(
xs: List<String>, from: Int, until: Int
): List<String>
{
val size = until - from
val newXs = MutableList<String>(size) { "" }
for ( (i, x) in xs.withIndex() ) {
if (from <= i && i < until) {
newXs.set(i - from, x)
}
}
return newXs
}
fun inspect(obj: Any?): String {
if (obj == null) {
return "null"
} else {
if (obj is Int) {
return obj.toString()
} else if (obj is String) {
return inspectString(obj)
} else if (obj is Boolean) {
return obj.toString()
} else if (isList(obj)) {
return inspectList(obj)
} else {
// val className = obj::class.toString()
// throw RuntimeException("not yet impl (${className})")
return obj.toString()
}
}
}
fun inspectString(s: String): String {
return (
DQ +
s
.replace("\\", "\\\\")
.replace("\n", "\\n")
.replace("\r", "\\r")
.replace("\"", "\\\"")
.replace("\t", "\\t") +
DQ
)
}
fun isList(obj: Any): Boolean {
val className = (obj::class).toString()
return (
className == "class java.util.ArrayList" ||
className == "class java.util.Arrays\$ArrayList" ||
className == "class java.util.Collections\$SingletonList"
)
}
fun inspectList(obj: Any): String {
val xs = obj as List<Any>
var s = "["
for ( (i, x) in xs.withIndex() ) {
if (1 <= i) {
s += ", "
}
s += inspect(x)
}
return s + "]"
}
fun strEq(s1: String?, s2: String?): Boolean {
return s1 == s2
}
fun isNumber(str: String): Boolean {
return RegexWrapper().match("""^[0-9]+""", str)
}
fun readStdinAll(): String {
var s: String = ""
while (true) {
val line : String? = readLine()
if (line == null) {
break
}
s += line + LF
}
return s
}
fun panic(msg: String): RuntimeException {
return RuntimeException("PANIC " + msg)
}
fun panic(msg: String, x: Any?): RuntimeException {
return RuntimeException("PANIC " + msg + " (${ inspect(x) })")
}
}
}
| 0
|
Kotlin
|
0
| 1
|
e2ed5dfd30c25f3953740d18a290d8f0cd9d8d5a
| 3,328
|
vm2gol-v2-kotlin
|
MIT License
|
shared/src/commonMain/kotlin/com/kevinschildhorn/fotopresenter/ui/screens/common/composables/AtomikText.kt
|
KevinSchildhorn
| 522,216,678
| false
|
{"Kotlin": 299918, "Swift": 580}
|
package com.kevinschildhorn.fotopresenter.ui.screens.common.composables
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.kevinschildhorn.atomik.atomic.atoms.interfaces.TextAtom
import com.kevinschildhorn.atomik.atomic.atoms.textStyle
import com.kevinschildhorn.atomik.color.base.composeColor
@Composable
fun AtomikText(text: String, atom: TextAtom, modifier: Modifier = Modifier) {
Text(
text,
style = atom.textStyle,
color = atom.textColor.composeColor,
modifier = modifier
)
}
| 0
|
Kotlin
|
0
| 0
|
c48e2b410b4f0f347448b7fa3f9b8cca644ba71c
| 599
|
FoToPresenter
|
Apache License 2.0
|
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/eks/KubernetesManifestPropsDsl.kt
|
cloudshiftinc
| 667,063,030
| false
| null |
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.eks
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.Any
import kotlin.Boolean
import kotlin.String
import kotlin.collections.Collection
import kotlin.collections.Map
import kotlin.collections.MutableList
import software.amazon.awscdk.services.eks.AlbScheme
import software.amazon.awscdk.services.eks.ICluster
import software.amazon.awscdk.services.eks.KubernetesManifestProps
/**
* Properties for KubernetesManifest.
*
* Example:
*
* ```
* Cluster cluster;
* Map<String, String> appLabel = Map.of("app", "hello-kubernetes");
* Map<String, Object> deployment = Map.of(
* "apiVersion", "apps/v1",
* "kind", "Deployment",
* "metadata", Map.of("name", "hello-kubernetes"),
* "spec", Map.of(
* "replicas", 3,
* "selector", Map.of("matchLabels", appLabel),
* "template", Map.of(
* "metadata", Map.of("labels", appLabel),
* "spec", Map.of(
* "containers", List.of(Map.of(
* "name", "hello-kubernetes",
* "image", "paulbouwer/hello-kubernetes:1.5",
* "ports", List.of(Map.of("containerPort", 8080))))))));
* Map<String, Object> service = Map.of(
* "apiVersion", "v1",
* "kind", "Service",
* "metadata", Map.of("name", "hello-kubernetes"),
* "spec", Map.of(
* "type", "LoadBalancer",
* "ports", List.of(Map.of("port", 80, "targetPort", 8080)),
* "selector", appLabel));
* // option 1: use a construct
* // option 1: use a construct
* KubernetesManifest.Builder.create(this, "hello-kub")
* .cluster(cluster)
* .manifest(List.of(deployment, service))
* .build();
* // or, option2: use `addManifest`
* cluster.addManifest("hello-kub", service, deployment);
* ```
*/
@CdkDslMarker
public class KubernetesManifestPropsDsl {
private val cdkBuilder: KubernetesManifestProps.Builder = KubernetesManifestProps.builder()
private val _manifest: MutableList<Map<String, Any>> = mutableListOf()
/**
* @param cluster The EKS cluster to apply this manifest to.
* [disable-awslint:ref-via-interface]
*/
public fun cluster(cluster: ICluster) {
cdkBuilder.cluster(cluster)
}
/**
* @param ingressAlb Automatically detect `Ingress` resources in the manifest and annotate them so
* they are picked up by an ALB Ingress Controller.
*/
public fun ingressAlb(ingressAlb: Boolean) {
cdkBuilder.ingressAlb(ingressAlb)
}
/**
* @param ingressAlbScheme Specify the ALB scheme that should be applied to `Ingress` resources.
* Only applicable if `ingressAlb` is set to `true`.
*/
public fun ingressAlbScheme(ingressAlbScheme: AlbScheme) {
cdkBuilder.ingressAlbScheme(ingressAlbScheme)
}
/**
* @param manifest The manifest to apply.
* Consists of any number of child resources.
*
* When the resources are created/updated, this manifest will be applied to the
* cluster through `kubectl apply` and when the resources or the stack is
* deleted, the resources in the manifest will be deleted through `kubectl delete`.
*/
public fun manifest(vararg manifest: Map<String, Any>) {
_manifest.addAll(listOf(*manifest))
}
/**
* @param manifest The manifest to apply.
* Consists of any number of child resources.
*
* When the resources are created/updated, this manifest will be applied to the
* cluster through `kubectl apply` and when the resources or the stack is
* deleted, the resources in the manifest will be deleted through `kubectl delete`.
*/
public fun manifest(manifest: Collection<Map<String, Any>>) {
_manifest.addAll(manifest)
}
/**
* @param overwrite Overwrite any existing resources.
* If this is set, we will use `kubectl apply` instead of `kubectl create`
* when the resource is created. Otherwise, if there is already a resource
* in the cluster with the same name, the operation will fail.
*/
public fun overwrite(overwrite: Boolean) {
cdkBuilder.overwrite(overwrite)
}
/**
* @param prune When a resource is removed from a Kubernetes manifest, it no longer appears in the
* manifest, and there is no way to know that this resource needs to be deleted.
* To address this, `kubectl apply` has a `--prune` option which will
* query the cluster for all resources with a specific label and will remove
* all the labeld resources that are not part of the applied manifest. If this
* option is disabled and a resource is removed, it will become "orphaned" and
* will not be deleted from the cluster.
*
* When this option is enabled (default), the construct will inject a label to
* all Kubernetes resources included in this manifest which will be used to
* prune resources when the manifest changes via `kubectl apply --prune`.
*
* The label name will be `aws.cdk.eks/prune-<ADDR>` where `<ADDR>` is the
* 42-char unique address of this construct in the construct tree. Value is
* empty.
*/
public fun prune(prune: Boolean) {
cdkBuilder.prune(prune)
}
/**
* @param skipValidation A flag to signify if the manifest validation should be skipped.
*/
public fun skipValidation(skipValidation: Boolean) {
cdkBuilder.skipValidation(skipValidation)
}
public fun build(): KubernetesManifestProps {
if(_manifest.isNotEmpty()) cdkBuilder.manifest(_manifest)
return cdkBuilder.build()
}
}
| 1
|
Kotlin
|
0
| 0
|
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
| 5,486
|
awscdk-dsl-kotlin
|
Apache License 2.0
|
app/src/main/java/com/hal/kaiyan/ui/home/fragment/PreferenceSettingsFragment.kt
|
leihaogit
| 734,572,648
| false
|
{"Kotlin": 239759}
|
package com.hal.kaiyan.ui.home.fragment
import android.os.Bundle
import androidx.appcompat.app.AppCompatDelegate
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import androidx.preference.SwitchPreferenceCompat
import com.hal.kaiyan.R
import com.hal.kaiyan.ui.base.Constant
import com.hal.kaiyan.utils.AppUtils
import com.hal.kaiyan.utils.byteToMb
import com.hal.kaiyan.utils.vibrate
import com.hal.kaiyan.view.CustomDialog
import es.dmoral.toasty.Toasty
/**
* ...
* @author LeiHao
* @date 2024/1/31
* @description 偏好设置页面
*/
class PreferenceSettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
setPreferencesFromResource(R.xml.settings_preferences, rootKey)
//初始化偏好设置
initPreferences()
}
private fun initPreferences() {
/**
* 深色设置
*/
val switchFollow: SwitchPreferenceCompat = findPreference("switch_follow")!!
val switchNight: SwitchPreferenceCompat = findPreference("switch_night")!!
//初始化日夜间模式选择状态
when (AppUtils.decodeMMKV(
Constant.KEY_NIGHT_MODE, Constant.FOLLOW_MODE
)) {
//日间模式
Constant.DAY_MODE -> {
switchFollow.isChecked = false
switchNight.isChecked = false
switchNight.isEnabled = true
}
//夜间模式
Constant.NIGHT_MODE -> {
switchFollow.isChecked = false
switchNight.isChecked = true
switchNight.isEnabled = true
}
//跟随系统模式
Constant.FOLLOW_MODE -> {
switchFollow.isChecked = true
switchNight.isChecked = false
switchNight.isEnabled = false
}
}
/**
* 点击跟随系统
*/
switchFollow.let {
it.setOnPreferenceChangeListener { _, newValue ->
val isChecked = newValue as Boolean
vibrate()
if (isChecked) {
//设置为跟随系统
AppUtils.encodeMMKV(
Constant.KEY_NIGHT_MODE, Constant.FOLLOW_MODE
)
// 设置为跟随系统
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
switchNight.isChecked = false
switchNight.isEnabled = false
} else {
//设置为非跟随系统,并打开日间模式
AppUtils.encodeMMKV(
Constant.KEY_NIGHT_MODE, Constant.DAY_MODE
)
// 设置为非跟随系统,并打开日间模式
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
switchNight.isEnabled = true
}
true
}
}
/**
* 点击夜间模式
*/
switchNight.let {
it.setOnPreferenceChangeListener { _, newValue ->
val isChecked = newValue as Boolean
vibrate()
if (isChecked) {
//设置为夜间模式
AppUtils.encodeMMKV(
Constant.KEY_NIGHT_MODE, Constant.NIGHT_MODE
)
// 设置为日间模式
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
} else {
//设置为日间模式
AppUtils.encodeMMKV(
Constant.KEY_NIGHT_MODE, Constant.DAY_MODE
)
// 设置为日间模式
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
}
true
}
}
/**
* 横屏自动全屏
*/
val automaticFullScreenPlay: SwitchPreferenceCompat =
findPreference("automatic_full_screen_play")!!
//初始化自动全屏选择状态,没有选择过则默认手动
when (AppUtils.decodeMMKV(
Constant.KEY_AUTO_FULL_SCREEN, Constant.MANUAL_MODE
)) {
//自动模式
Constant.AUTO_MODE -> {
automaticFullScreenPlay.isChecked = true
}
//手动模式
else -> {
automaticFullScreenPlay.isChecked = false
}
}
automaticFullScreenPlay.let {
it.setOnPreferenceChangeListener { _, newValue ->
val isChecked = newValue as Boolean
vibrate()
if (isChecked) {
//设置为自动全屏播放
AppUtils.encodeMMKV(
Constant.KEY_AUTO_FULL_SCREEN, Constant.AUTO_MODE
)
} else {
//设置为手动全屏播放
AppUtils.encodeMMKV(
Constant.KEY_AUTO_FULL_SCREEN, Constant.MANUAL_MODE
)
}
true
}
}
/**
* 清空缓存
*/
val clearCache: Preference = findPreference("clear_cache")!!
clearCache.let {
//初始化缓存大小
val calculateDirSize =
AppUtils.calculateDirSize(requireContext().externalCacheDir) + AppUtils.calculateDirSize(
requireContext().cacheDir
)
it.summary = calculateDirSize.byteToMb()
//点击清空
it.setOnPreferenceClickListener {
vibrate()
val customDialog = CustomDialog(
requireContext(),
resources.getString(R.string.sure_to_clear_cache),
resources.getString(R.string.cancel),
resources.getString(R.string.confirm)
)
customDialog.show()
customDialog.setOnDoubleButtonClickListener(object :
CustomDialog.OnDoubleButtonClickListener {
override fun onLeftButtonClick() {
vibrate()
}
override fun onRightButtonClick() {
vibrate()
AppUtils.clearAppCache()
clearCache.summary = 0L.byteToMb()
Toasty.success(requireContext(), resources.getString(R.string.success))
.show()
}
})
true
}
}
/**
* 自动清空缓存
*/
val autoClearCache: SwitchPreferenceCompat = findPreference("auto_clear_cache")!!
//初始化自动清理缓存的选择状态,没有选择过则默认手动
when (AppUtils.decodeMMKV(
Constant.KEY_AUTO_CLEAR_CACHE, Constant.MANUAL_MODE
)) {
//自动模式
Constant.AUTO_MODE -> {
autoClearCache.isChecked = true
}
//手动模式
else -> {
autoClearCache.isChecked = false
}
}
//点击自动清理缓存按钮
autoClearCache.let {
it.setOnPreferenceChangeListener { _, newValue ->
val isChecked = newValue as Boolean
vibrate()
if (isChecked) {
//设置为自动清理
AppUtils.encodeMMKV(
Constant.KEY_AUTO_CLEAR_CACHE, Constant.AUTO_MODE
)
} else {
//设置为手动清理
AppUtils.encodeMMKV(
Constant.KEY_AUTO_CLEAR_CACHE, Constant.MANUAL_MODE
)
}
true
}
}
}
}
| 0
|
Kotlin
|
1
| 6
|
dc9cbb8035f46e35c7a2f648fc9e3bdf7a8eb7d6
| 7,686
|
kaiyan
|
Apache License 2.0
|
app/src/main/java/com/jawnnypoo/geotune/dialog/EditNameDialog.kt
|
Commit451
| 58,508,396
| false
| null |
package com.jawnnypoo.geotune.dialog
import android.content.Context
import android.support.v7.app.AppCompatDialog
import com.jawnnypoo.geotune.R
import kotlinx.android.synthetic.main.dialog_edit_name.*
class EditNameDialog(context: Context) : AppCompatDialog(context) {
private var listener: ((name: String) -> Unit)? = null
init {
setContentView(R.layout.dialog_edit_name)
textName.setOnEditorActionListener { _, _, _ ->
returnName()
true
}
done.setOnClickListener {
returnName()
}
}
fun returnName() {
listener?.invoke(textName.text.toString())
}
fun setOnEditNameListener(listener: (name: String) -> Unit) {
this.listener = listener
}
fun setName(name: String?) {
textName.append(name)
}
}
| 0
|
Kotlin
|
2
| 8
|
776e36f119efc855a76c4acd92caa9498f934392
| 836
|
GeoTune
|
Apache License 2.0
|
app/src/main/java/com/bejussi/dailyadvice/di/DataModule.kt
|
Bejussi
| 641,076,669
| false
| null |
package com.bejussi.dailyadvice.di
import android.content.Context
import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import androidx.datastore.preferences.preferencesDataStore
import androidx.room.Room
import com.bejussi.dailyadvice.data.AdviceRepositoryImpl
import com.bejussi.dailyadvice.data.SettingsDataStoreRepositoryImpl
import com.bejussi.dailyadvice.data.local.AdviceNotificationDatabase
import com.bejussi.dailyadvice.domain.AdviceRepository
import com.bejussi.dailyadvice.domain.SettingsDataStoreRepository
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "SETTINGS")
@Module
@InstallIn(SingletonComponent::class)
class DataModule {
@Provides
@Singleton
fun provideAdviceRepository(
adviceRepositoryImpl: AdviceRepositoryImpl
): AdviceRepository = adviceRepositoryImpl
@Provides
@Singleton
fun provideUserDataStorePreferences(
@ApplicationContext applicationContext: Context
): DataStore<Preferences> {
return applicationContext.dataStore
}
@Provides
@Singleton
fun provideSettingsDataStoreRepository(
dataStore: DataStore<Preferences>
): SettingsDataStoreRepository = SettingsDataStoreRepositoryImpl(
dataStore = dataStore
)
@Provides
@Singleton
fun provideAdviceNotificationDatabase(
@ApplicationContext
applicationContext: Context
) = Room.databaseBuilder(
applicationContext,
AdviceNotificationDatabase::class.java,
AdviceNotificationDatabase.DATABASE_NAME
).build()
@Provides
@Singleton
fun provideAdviceNotificationDao(adviceNotificationDatabase: AdviceNotificationDatabase) =
adviceNotificationDatabase.adviceNotificationDao()
}
| 0
|
Kotlin
|
0
| 0
|
250b1b1988c823e9a1e4afdadfc838f3b220ec87
| 2,012
|
DailyAdvice
|
MIT License
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.