path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/kotlin/com/coredocker/android/data/network/NetworkModule.kt | rolfwessels | 256,949,423 | false | null | package com.coredocker.android.data.network
import com.apollographql.apollo.ApolloClient
import com.apollographql.apollo.api.CustomTypeAdapter
import com.apollographql.apollo.api.CustomTypeValue
import com.apollographql.apollo.subscription.WebSocketSubscriptionTransport
import com.coredocker.android.data.network.category.CoreDockerApi
import com.coredocker.android.data.network.graphql.IUsersApi
import com.coredocker.android.data.network.graphql.UsersApi
import com.coredocker.android.data.repository.AuthenticationRepository
import com.coredocker.android.util.fromIsoDateString
import com.coredocker.android.util.toIsoDateTimeString
import com.coredocker.type.CustomType
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import org.koin.dsl.module.module
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
import timber.log.Timber
import java.math.BigInteger
import java.net.URL
import java.text.ParseException
import java.util.Date
import java.util.concurrent.TimeUnit
val networkModule = module {
single {
provideDefaultOkHttpClient()
}
single {
provideRetrofit(
get(),
NetworkConstants.BASE_URL
)
}
single { provideCoreDockerApiService(get()) }
single {
provideApolloClient(
buildGraphQlUrl(NetworkConstants.BASE_URL),
get()
)
}
single { provideCoreUserService(get()) }
}
fun buildGraphQlUrl(baseUrl: String) = URL(baseUrl).toURI().resolve("graphql").toString()
fun provideDefaultOkHttpClient(): OkHttpClient {
return OkHttpClient.Builder().build()
}
fun provideRetrofit(client: OkHttpClient, url: String): Retrofit {
return Retrofit.Builder()
.client(client)
.baseUrl(url)
.addConverterFactory(MoshiConverterFactory.create())
.build()
}
fun provideApolloClient(
url: String,
authenticationRepository: AuthenticationRepository
): ApolloClient {
val client = httpClientWithAuthHeader(
url,
getToken = authenticationRepository::currentToken
)
return provideApolloClientFromHttpClient(
url,
client
)
}
fun provideApolloClientFromHttpClient(
url: String,
client: OkHttpClient
): ApolloClient {
return ApolloClient.builder()
.serverUrl(url)
.addCustomTypeAdapter(CustomType.DATETIME, DateConvert())
.addCustomTypeAdapter(CustomType.LONG, LongConvert())
.okHttpClient(client)
.subscriptionTransportFactory(WebSocketSubscriptionTransport.Factory(url, client))
.build()
}
fun httpClientWithAuthHeader(
url: String,
getToken: () -> String?
): OkHttpClient {
return OkHttpClient.Builder()
.readTimeout(30, TimeUnit.SECONDS)
.addInterceptor { chain ->
val currentToken = getToken()
Timber.tag("okHttp")
.i("Request to $url with token: '${currentToken?.substring(0, 10)}...'")
if (currentToken != null) {
val original = chain.request()
val requestBuilder = original.newBuilder()
.header(
"Authorization",
"Bearer $currentToken"
) // <-- this is the important line
val request = requestBuilder.build()
chain.proceed(request)
} else {
chain.proceed(chain.request())
}
}.build()
}
private fun LoggingInterceptor(): HttpLoggingInterceptor {
val interceptor = HttpLoggingInterceptor()
interceptor.level = HttpLoggingInterceptor.Level.BODY
return interceptor
}
fun provideCoreDockerApiService(retrofit: Retrofit): CoreDockerApi =
retrofit.create(CoreDockerApi::class.java)
fun provideCoreUserService(apolloClient: ApolloClient): IUsersApi {
return UsersApi(apolloClient)
}
class DateConvert : CustomTypeAdapter<Date> {
override fun encode(value: Date): CustomTypeValue<*> {
return CustomTypeValue.GraphQLString(value.toIsoDateTimeString())
}
override fun decode(value: CustomTypeValue<*>): Date {
return try {
value.value.toString().fromIsoDateString()
} catch (e: ParseException) {
return Date(0)
}
}
}
class LongConvert : CustomTypeAdapter<BigInteger> {
override fun decode(value: CustomTypeValue<*>): BigInteger {
return BigInteger(value.value.toString())
}
override fun encode(value: BigInteger): CustomTypeValue<*> {
return CustomTypeValue.GraphQLString(value.toString())
}
} | 0 | Kotlin | 0 | 0 | 7efd0255dcc6b3de93ea65428e3fcebd2538b016 | 4,618 | coredocker-droid | MIT License |
app/src/main/kotlin/github/showang/kat/async/iterator.kt | showang | 198,557,514 | false | null | package github.showang.kat.async
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
fun <A, B> Iterable<A>.pMap(f: (A) -> B): List<B> = runBlocking {
map {
async {
f(it)
}
}.map {
it.await()
}
} | 0 | Kotlin | 1 | 0 | 4fcfc515470f96bb33dbc40232198a30df7b88d8 | 263 | Kat | MIT License |
app/src/main/java/com/cornellappdev/uplift/ui/MainNavigationWrapper.kt | cuappdev | 596,747,757 | false | null | package com.cornellappdev.uplift.ui
import androidx.compose.runtime.Composable
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.cornellappdev.uplift.ui.screens.GymDetailScreen
import com.cornellappdev.uplift.ui.viewmodels.GymDetailViewModel
import com.cornellappdev.uplift.util.PRIMARY_YELLOW
import com.google.accompanist.systemuicontroller.SystemUiController
import com.google.accompanist.systemuicontroller.rememberSystemUiController
/**
* The main navigation controller for the app.
*/
@Composable
fun MainNavigationWrapper(
gymDetailViewModel: GymDetailViewModel
) {
val navController = rememberNavController()
val systemUiController: SystemUiController = rememberSystemUiController()
systemUiController.setStatusBarColor(PRIMARY_YELLOW)
NavHost(navController = navController, startDestination = "gymDetail") {
composable(route = "gymDetail") {
GymDetailScreen(gymDetailViewModel = gymDetailViewModel)
}
}
} | 0 | Kotlin | 0 | 0 | 9b72c67c4c7ee7e56400e64496912e024912da89 | 1,078 | uplift-android | MIT License |
app/src/main/kotlin/kt/school/starlord/di/Qualifier.kt | suhocki | 174,985,255 | false | null | package kt.school.starlord.di
import org.koin.core.qualifier.named
/**
* Contains constants to describe objects of the same types for our DI.
* Qualifier - it is a name of the definition (when specified name parameter in your definition).
*/
object Qualifier {
val LOCALIZED = named("localized")
}
| 19 | Kotlin | 0 | 1 | 09a3bb151a3dfe6982adf7ca246f8b0b077e3644 | 307 | starlord | MIT License |
data/src/main/java/com/hana/data/mapper/UserEntityMapper.kt | yenaingoo992 | 875,796,488 | false | {"Kotlin": 93374} | package com.hana.data.mapper
import com.hana.data.datasource.local.entity.UserEntity
import com.hana.domain.model.UserModel
fun List<UserModel>.toEntities(): List<UserEntity> = map { user ->
UserEntity(
id = user.id,
name = user.name,
email = user.email
)
}
fun List<UserEntity>.toDomain(): List<UserModel> = map { user ->
UserModel(
id = user.id,
name = user.name,
email = user.email
)
} | 0 | Kotlin | 0 | 0 | 268ba3381dd0c57d335836c39ab971235efb9526 | 455 | HanaCodeTest | MIT License |
app/src/main/java/arira/co/id/mesinatrian/adapter/holder/RiwayatHolder.kt | ramcona | 295,104,924 | false | null | package arira.co.id.mesinatrian.adapter.holder
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import arira.co.id.mesinatrian.R
import arira.co.id.mesinatrian.helper.Helper
import arira.co.id.mesinatrian.helper.Helper.log
import arira.co.id.mesinatrian.model.RiwayatModel
class RiwayatHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
val tvAntrian :TextView = itemView.findViewById(R.id.iRiwayat_tv_antrian)
val tvWatktu :TextView = itemView.findViewById(R.id.iRiwayat_tv_waktu)
val tvTempat :TextView = itemView.findViewById(R.id.iRiwayat_tv_lokasi)
val tvLoket :TextView = itemView.findViewById(R.id.iRiwayat_tv_loket)
fun setData(model: RiwayatModel){
tvAntrian.text = model.nomorantri
tvLoket.text = itemView.context.getString(R.string.loket_, model.loket)
tvTempat.text = """${model.admin} - ${model.tempat}"""
tvWatktu.text = model.waktu
}
} | 0 | Kotlin | 0 | 0 | ed95c8b13f6e2aa2a64087b08719ca16b7cdb08c | 977 | mesin-antrian | Apache License 2.0 |
emoji/src/androidMain/kotlin/com/vanniktech/emoji/EmojiTheming.kt | vfishv | 215,065,261 | true | {"Kotlin": 2339499, "JavaScript": 18682, "Ruby": 10874} | /*
* Copyright (C) 2016 - <NAME>, <NAME>, <NAME> and contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:JvmName("EmojiThemings")
package com.vanniktech.emoji
import androidx.annotation.ColorInt
/** Control the colors of all Emoji UI components. */
@Parcelize data class EmojiTheming @JvmOverloads constructor(
/**
* If set, it will be taken.
* Otherwise it'll look for a theme attribute called emojiBackgroundColor.
* If that isn't found, the library has a default.
*/
@ColorInt @JvmField val backgroundColor: Int? = null,
/**
* If set, it will be taken.
* Otherwise it'll take the color from your theme.
*/
@ColorInt @JvmField val primaryColor: Int? = null,
/**
* If set, it will be taken.
* Otherwise it'll take the color from your theme.
*/
@ColorInt @JvmField val secondaryColor: Int? = null,
/**
* If set, it will be taken.
* Otherwise it'll look for a theme attribute called emojiDividerColor.
* If that isn't found, the library has a default.
*/
@ColorInt @JvmField val dividerColor: Int? = null,
/**
* If set, it will be taken.
* Otherwise it'll look for a theme attribute called emojiTextColor.
* If that isn't found, the library has a default.
*/
@ColorInt @JvmField val textColor: Int? = null,
/**
* If set, it will be taken.
* Otherwise it'll look for a theme attribute called emojiTextSecondaryColor.
* If that isn't found, the library has a default.
*/
@ColorInt @JvmField val textSecondaryColor: Int? = null,
) : Parcelable
| 2 | Kotlin | 0 | 0 | 785effa190b8da7f2cebaab23266b4b31b4147fc | 2,064 | Emoji | Apache License 2.0 |
app/src/main/java/com/example/flashcards/ui/viewmodels/TopicCreateViewModel.kt | nomionz | 726,944,886 | false | {"Kotlin": 46754} | package com.example.flashcards.ui.viewmodels
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.flashcards.DbSingleton
import com.example.flashcards.data.room.models.Card
import com.example.flashcards.data.room.models.Topic
import com.example.flashcards.data.room.models.TopicWithCards
import com.example.flashcards.ui.repository.FlashCardsRepository
import kotlinx.coroutines.launch
data class TopicCreateState(
val topicName: String = "",
val cardQuestion: String = "",
val cardDescription: String = "",
)
// TopicCreateViewModel is a ViewModel class that provides data to the AddScreen composable.
class TopicCreateViewModel(
private val repository: FlashCardsRepository = DbSingleton.repository
) : ViewModel() {
var state = mutableStateOf(TopicCreateState())
private set
private val cards = mutableListOf<Card>()
fun isCardsEmpty() = cards.isEmpty()
// saveTopic saves the topic and its cards to the database.
fun saveTopic() {
if (cards.isEmpty()) return
viewModelScope.launch {
val topic = TopicWithCards(
topic = Topic(name = state.value.topicName),
cards = cards
)
repository.insertWithCards(topic)
}
}
fun addCard() {
if (state.value.cardQuestion.isEmpty() ||
state.value.cardDescription.isEmpty()
) return
val card = Card(
content = state.value.cardQuestion,
description = state.value.cardDescription
)
cards.add(card)
}
fun onTopicNameChange(topicName: String) {
state.value = state.value.copy(topicName = topicName)
}
fun onCardQuestionChange(cardQuestion: String) {
state.value = state.value.copy(cardQuestion = cardQuestion)
}
fun onCardDescriptionChange(cardDescription: String) {
state.value = state.value.copy(cardDescription = cardDescription)
}
} | 0 | Kotlin | 0 | 0 | 818daab25e7778c0c8ed2f5ab61664e7e47019fe | 2,045 | flashcards | Apache License 2.0 |
src/main/kotlin/org/snd/metadata/model/metadata/ProviderBookMetadata.kt | Snd-R | 463,859,568 | false | null | package org.snd.metadata.model.metadata
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class ProviderBookMetadata(
val id: ProviderBookId? = null,
val seriesId: ProviderSeriesId? = null,
val metadata: BookMetadata,
)
| 11 | Kotlin | 9 | 99 | 0584078f460c5d8c7b740bbe77905fab1c0ad105 | 261 | komf | MIT License |
app/src/main/java/com/example/r2devprosproject/MainActivity.kt | chdsz123 | 491,357,055 | false | null | package com.example.r2devprosproject
import android.content.Intent
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.os.PersistableBundle
import android.provider.MediaStore
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.net.toUri
import com.example.r2devprosproject.databinding.ActivityMainBinding
import timber.log.Timber
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private var image = ""
override fun onCreate(savedInstanceState: Bundle?) {
Timber.d("MainActivity_TAG: onCreate: ")
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
bindViews()
}
override fun onConfigurationChanged(newConfig: Configuration) {
Timber.d("MainActivity_TAG: onConfigurationChanged: ")
super.onConfigurationChanged(newConfig)
Toast.makeText(this, "Image: $image", Toast.LENGTH_SHORT).show()
loadImage()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
Timber.d("MainActivity_TAG: onActivityResult: requestCode: $requestCode")
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == RESULT_CANCELED) {
Timber.d("MainActivity_TAG: No image loaded: ")
// action cancelled
}
if (resultCode == RESULT_OK) {
Timber.d("MainActivity_TAG: onActivityResult: IMAGE: $image")
image = data?.data.toString()
loadImage()
}
}
private fun bindViews() {
binding.btnUpload.setOnClickListener {
Timber.d("MainActivity_TAG: bindViews: Upload Image")
val gallery = Intent()
gallery.type = "image/*"
gallery.action = Intent.ACTION_GET_CONTENT
startActivityForResult(Intent.createChooser(gallery, getString(R.string.upload_button)), PICK_IMAGE)
}
binding.btnAddress.setOnClickListener {
Timber.d("MainActivity_TAG: Go to Address: ")
val intent = Intent(this@MainActivity, UserAddressLayoutActivity::class.java).apply {
putExtras(Bundle().apply {
putString(CONTACT_PHOTO, image)
putString(CONTACT_NAME, "${binding.etName.text} ${binding.etLastName.text}")
})
}
startActivity(intent)
}
}
private fun loadImage() {
Timber.d("MainActivity_TAG: loadInfo: ")
if (image.isNotEmpty()) {
binding.ivAvatar.setImageBitmap(MediaStore.Images.Media.getBitmap(this.contentResolver, image.toUri()))
}
}
} | 0 | Kotlin | 0 | 0 | f3d153819fc1d3b7bc5da92ab74824cfa9403ca0 | 2,862 | AndroidProjects | Blue Oak Model License 1.0.0 |
app/src/main/java/com/zipdabang/zipdabang_android/module/detail/recipe/use_case/CancelBlockUseCase.kt | zipdabang | 666,457,004 | false | {"Kotlin": 1882109} | package com.zipdabang.zipdabang_android.module.detail.recipe.use_case
import android.util.Log
import androidx.datastore.core.DataStore
import com.zipdabang.zipdabang_android.common.Resource
import com.zipdabang.zipdabang_android.common.ResponseCode
import com.zipdabang.zipdabang_android.common.getErrorCode
import com.zipdabang.zipdabang_android.core.data_store.proto.Token
import com.zipdabang.zipdabang_android.module.comment.domain.UserBlockResult
import com.zipdabang.zipdabang_android.module.comment.use_case.BlockUserUseCase
import com.zipdabang.zipdabang_android.module.comment.util.toUserBlockResult
import com.zipdabang.zipdabang_android.module.detail.recipe.domain.RecipeDetailRepository
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import retrofit2.HttpException
import java.io.IOException
import javax.inject.Inject
import kotlin.coroutines.cancellation.CancellationException
class CancelBlockUseCase @Inject constructor(
private val tokenDataStore: DataStore<Token>,
private val repository: RecipeDetailRepository
) {
operator fun invoke(userId: Int): Flow<Resource<UserBlockResult>> = flow {
try {
val accessToken = "Bearer ${tokenDataStore.data.first().accessToken}"
val result = repository.cancelUserBlock(accessToken, userId).toUserBlockResult()
when (result.code) {
ResponseCode.RESPONSE_DEFAULT.code -> {
emit(Resource.Success(
data = result,
code = result.code,
message = result.message
))
}
else -> {
emit(Resource.Error(message = result.message))
}
}
} catch (e: HttpException) {
val errorBody = e.response()?.errorBody()
val errorCode = errorBody?.getErrorCode()
errorCode?.let {
emit(Resource.Error(message = ResponseCode.getMessageByCode(errorCode)))
return@flow
}
emit(Resource.Error(message = e.message ?: "unexpected http exception"))
} catch (e: IOException) {
emit(Resource.Error(message = e.message ?: "unexpected io exception"))
} catch (e: Exception) {
if (e is CancellationException) {
throw e
}
emit(Resource.Error(message = e.message ?: "unexpected exception"))
}
}
} | 8 | Kotlin | 1 | 2 | c883a072e1d60ea6e00cc3ea87c67d23b882f2fc | 2,531 | android | The Unlicense |
core/src/jvmMain/kotlin/zakadabar/stack/backend/util/uuid.kt | kondorj | 355,137,640 | true | {"Kotlin": 577495, "HTML": 828, "JavaScript": 820, "Shell": 253} | /*
* Copyright © 2020, <NAME> and contributors. Use of this source code is governed by the Apache 2.0 license.
*/
package zakadabar.stack.backend.util
import zakadabar.stack.util.UUID
fun UUID.native() = java.util.UUID(msb, lsb) | 0 | null | 0 | 0 | 2379c0fb031f04a230e753a9afad6bd260f6a0b2 | 232 | zakadabar-stack | Apache License 2.0 |
Chat-Microservice/chat-server-grpc/src/main/kotlin/io/grpc/kotlin/generator/services/chatroom/spring/ChatRoomService.kt | GeoGrind | 703,185,030 | false | {"Kotlin": 355636, "Shell": 2624, "HTML": 1687, "Dockerfile": 488, "Java": 302} | package io.grpc.kotlin.generator.services.chatroom.spring
import io.grpc.kotlin.generator.dto.chatroom.CreateChatRoomDto
import io.grpc.kotlin.generator.dto.chatroom.DeleteChatRoomByIdDto
import io.grpc.kotlin.generator.dto.chatroom.GetChatRoomByIdDto
import io.grpc.kotlin.generator.dto.chatroom.UpdateChatRoomByIdDto
import io.grpc.kotlin.generator.models.chatroom.ChatRoom
import jakarta.validation.Valid
import org.springframework.stereotype.Service
@Service
interface ChatRoomService {
suspend fun getAllChatRooms(): List<ChatRoom>
suspend fun getChatRoomById(
@Valid requestDto: GetChatRoomByIdDto
): ChatRoom
suspend fun createChatRoom(
@Valid requestDto: CreateChatRoomDto
): ChatRoom
suspend fun updateChatRoomById(
@Valid requestDto: UpdateChatRoomByIdDto
): ChatRoom
suspend fun deleteChatRoomById(
@Valid requestDto: DeleteChatRoomByIdDto
)
} | 13 | Kotlin | 0 | 2 | b1d44aac6e304f5c97ba233882c0dca42eddf3f7 | 924 | GeoGrind-Backend | Apache License 2.0 |
@ddd/event-storage-adapter-cassandra-db/src/test/kotlin/com/mz/ddd/common/eventsourcing/event/storage/adapter/cassandra/persistence/SnapshotRepositoryTest.kt | michalzeman | 519,548,115 | false | {"Kotlin": 323513, "Shell": 799, "Dockerfile": 531} | package com.mz.ddd.common.eventsourcing.event.storage.adapter.cassandra.persistence
import com.mz.ddd.common.eventsourcing.event.storage.adapter.cassandra.wiring.EventStorageAdapterCassandraConfiguration
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.ActiveProfiles
import reactor.test.StepVerifier
import java.nio.ByteBuffer
import java.time.Instant
@SpringBootTest(classes = [EventStorageAdapterCassandraConfiguration::class])
@ActiveProfiles("test")
class SnapshotRepositoryTest {
@Autowired
internal lateinit var repository: SnapshotRepository
// beforeEach method that generate and store testing data
@BeforeEach
fun setUp() {
// create 3 instances of EvenJournalEntity with respecting sequenceNr and store it into the DB
repository.saveAll(
listOf(
SnapshotEntity().apply {
aggregateId = "1"
sequenceNr = 1
createdAt = Instant.now()
tag = "TestingAggregate"
payload = ByteBuffer.wrap(byteArrayOf(1))
payloadType = "string"
},
SnapshotEntity().apply {
aggregateId = "1"
sequenceNr = 2
createdAt = Instant.now()
tag = "TestingAggregate"
payload = ByteBuffer.wrap(byteArrayOf(2))
payloadType = "string"
},
SnapshotEntity().apply {
aggregateId = "1"
sequenceNr = 3
createdAt = Instant.now()
tag = "TestingAggregate"
payload = ByteBuffer.wrap(byteArrayOf(3))
payloadType = "string"
}
)
).log()
.then()
.block()
}
@AfterEach
fun tearDown() {
repository.deleteAll().block()
}
@Test
fun `find by aggregate id`() {
StepVerifier.create(repository.findByAggregateId("1"))
.expectNextCount(3)
.verifyComplete()
}
@Test
fun `find by aggregateId and started with sequenceNr`() {
StepVerifier.create(repository.findByAggregateIdAndSequenceNrGreaterThanEqual("1", 2))
.expectNextCount(2)
.verifyComplete()
}
} | 0 | Kotlin | 0 | 2 | a726878fe9393c29c864b612e85eff5d3c21f268 | 2,596 | cqrs-reservation-reactive-system | Creative Commons Attribution 4.0 International |
server/src/main/kotlin/net/eiradir/server/network/entity/ClientComponent.kt | Eiradir | 635,460,745 | false | {"Kotlin": 646160, "Dockerfile": 470} | package net.eiradir.server.network.entity
import com.badlogic.ashley.core.Component
import net.eiradir.server.network.ConnectionStatus
import net.eiradir.server.network.ServerNetworkContext
data class ClientComponent(val client: ServerNetworkContext) : Component {
var status: ConnectionStatus = ConnectionStatus.PRE_AUTH
} | 11 | Kotlin | 0 | 0 | edca8986ef06fd5a75fd2a4dc53dfe75dbfbbaae | 329 | eiradir-server | MIT License |
src/test/trees/TreeTest.kt | dremme | 162,006,465 | false | null | package trees
import kotlin.test.assertEquals
fun main() {
val numbers = 1..31
val randomNumbers = numbers.shuffled()
val sortedNumbers = numbers.toList()
/*
* Adding values
*/
val tree1 = randomNumbers.toTree { insert(it) }
assertEquals(randomNumbers.first(), tree1.root!!.value)
assertEquals(sortedNumbers, tree1.toList())
}
private fun <T : Comparable<T>> List<T>.toTree(insertMethod: BinaryTree<T>.(T) -> Unit): BinaryTree<T> {
val tree = BinaryTree<T>()
forEach { tree.insertMethod(it) }
return tree
}
| 0 | Kotlin | 0 | 0 | 1bdd6639502e3a5317a76bb5c0c116f04123f047 | 562 | coding-kotlin | MIT License |
app/src/main/java/com/kekulta/events/presentation/formatters/CommunityItemFormatter.kt | kekulta | 817,411,794 | false | {"Kotlin": 317565} | package com.kekulta.events.presentation.formatters
import com.kekulta.events.domain.models.base.CommunityModel
import com.kekulta.events.presentation.ui.models.CommunityItemVo
class CommunityItemFormatter() {
fun format(models: List<CommunityModel>, membersCount: List<Int>): List<CommunityItemVo> {
return models.mapIndexed { index, model ->
CommunityItemVo(
id = model.id,
name = model.name,
avatar = model.avatar,
membersCount = membersCount.getOrElse(index) { 0 },
)
}
}
} | 0 | Kotlin | 0 | 7 | b2b08eb781e27927354109d638d89c76ffe024be | 590 | Events | MIT License |
actions-kotlin/src/jsMain/kotlin/actions/artifact/FindOptions.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6272741} | // Automatically generated - do not modify!
package actions.artifact
import kotlinx.js.JsPlainObject
@JsPlainObject
external interface FindOptions {
/**
* The criteria for finding Artifact(s) out of the scope of the current run.
*/
val findBy: FindBy?
@JsPlainObject
interface FindBy {
/**
* Token with actions:read permissions
*/
val token: String
/**
* WorkflowRun of the artifact(s) to lookup
*/
val workflowRunId: Number
/**
* Repository owner (eg. 'actions')
*/
val repositoryOwner: String
/**
* Repository owner (eg. 'toolkit')
*/
val repositoryName: String
}
}
| 0 | Kotlin | 8 | 36 | 95b065622a9445caf058ad2581f4c91f9e2b0d91 | 741 | types-kotlin | Apache License 2.0 |
phone/src/main/java/dev/synople/glassecho/phone/fragments/SettingsFragment.kt | tujson | 243,186,393 | false | {"Kotlin": 93812} | package dev.synople.glassecho.phone.fragments
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import dev.synople.glassecho.phone.R
import dev.synople.glassecho.phone.databinding.FragmentSettingsBinding
class SettingsFragment : Fragment(R.layout.fragment_settings) {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
FragmentSettingsBinding.bind(view)
}
} | 5 | Kotlin | 6 | 39 | f0bef4722f5af407d8a42157103d7ddc9be36786 | 553 | GlassEcho | MIT License |
src/main/kotlin/io/github/breninsul/javatimerscheduler/timer/VirtualWaitTimerTask.kt | BreninSul | 758,868,058 | false | {"Kotlin": 53083} | /*
* MIT License
*
* Copyright (c) 2024 BreninSul
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package io.github.breninsul.javatimerscheduler.timer
import java.util.concurrent.atomic.AtomicLong
import java.util.logging.Level
import kotlin.reflect.KClass
/**
* Class that represents a new virtual any run timer task.
*
* @param name The name of the task.
* @param counter An AtomicLong used for incrementing a count.
* @param loggerClass A class reference used for retrieving a logger.
* @param loggingLevel The level at which the logger should log.
* @param runnable The actual task to be run.
*/
open class VirtualNoWaitTimerTask(
name: String,
counter: AtomicLong = AtomicLong(0),
loggerClass: KClass<*> = VirtualNoWaitTimerTask::class,
loggingLevel: Level = Level.FINEST,
runnable: Runnable,
) : VirtualTimerTask(name, counter, loggerClass, loggingLevel, runnable) {
override fun runInternal(currentThread: Thread) {
addThread(currentThread)
runnable.run()
removeThread(currentThread)
}
}
| 0 | Kotlin | 0 | 0 | 556f1e6d6015ab2198ad2252f0661a53e5c1c3d2 | 2,092 | java-timer-scheduler-starter | MIT License |
core/src/main/java/com/reift/core/domain/usecase/detail/movie/MovieDetailUseCase.kt | ReihanFatilla | 523,763,069 | false | null | package com.reift.core.domain.repository.detail.movie
import com.reift.core.domain.model.Resource
import com.reift.core.domain.model.detail.*
import com.reift.core.domain.model.movie.Movie
import com.reift.core.domain.model.movie.MovieResult
import com.reift.core.domain.model.tv.Tv
import io.reactivex.rxjava3.core.Flowable
import kotlinx.coroutines.flow.Flow
interface MovieDetailRepository {
fun getMovieDetail(id: String): Flowable<Resource<MovieDetail>>
fun getMovieReviews(id: String): Flowable<Resource<List<Review>>>
fun getMovieWallpapers(id: String): Flowable<Resource<Wallpaper>>
fun getMovieActors(id: String): Flowable<Resource<List<Actor>>>
fun getMovieVideos(id: String): Flowable<Resource<List<Video>>>
fun isFollowed(id: String): Flow<Boolean>
fun insertFavoriteMovie(movie: Movie)
fun deleteFavoriteMovie(movie: Movie)
fun getRecommendationsMovies(id: String): Flowable<Resource<MovieResult>>
fun getSimilarMovies(id: String): Flowable<Resource<MovieResult>>
} | 0 | Kotlin | 2 | 4 | 6558f6ba3ed176dcc6f23e2f1bc9ed2e8699d079 | 1,023 | Movo | MIT License |
utbot-framework/src/main/kotlin/org/utbot/engine/StreamWrappers.kt | UnitTestBot | 480,810,501 | false | null | package org.utbot.engine
import org.utbot.engine.overrides.stream.UtDoubleStream
import org.utbot.engine.overrides.stream.UtIntStream
import org.utbot.engine.overrides.stream.UtLongStream
import org.utbot.engine.overrides.stream.UtStream
import org.utbot.framework.plugin.api.ClassId
import org.utbot.framework.plugin.api.FieldId
import org.utbot.framework.plugin.api.MethodId
import org.utbot.framework.plugin.api.UtArrayModel
import org.utbot.framework.plugin.api.UtAssembleModel
import org.utbot.framework.plugin.api.UtExecutableCallModel
import org.utbot.framework.plugin.api.UtModel
import org.utbot.framework.plugin.api.UtNullModel
import org.utbot.framework.plugin.api.UtPrimitiveModel
import org.utbot.framework.plugin.api.classId
import org.utbot.framework.plugin.api.util.defaultValueModel
import org.utbot.framework.plugin.api.util.doubleArrayClassId
import org.utbot.framework.plugin.api.util.doubleClassId
import org.utbot.framework.plugin.api.util.doubleStreamClassId
import org.utbot.framework.plugin.api.util.intArrayClassId
import org.utbot.framework.plugin.api.util.intClassId
import org.utbot.framework.plugin.api.util.intStreamClassId
import org.utbot.framework.plugin.api.util.isArray
import org.utbot.framework.plugin.api.util.isPrimitiveWrapper
import org.utbot.framework.plugin.api.util.longArrayClassId
import org.utbot.framework.plugin.api.util.longClassId
import org.utbot.framework.plugin.api.util.longStreamClassId
import org.utbot.framework.plugin.api.util.methodId
import org.utbot.framework.plugin.api.util.objectArrayClassId
import org.utbot.framework.plugin.api.util.objectClassId
import org.utbot.framework.plugin.api.util.streamClassId
import org.utbot.framework.util.nextModelName
/**
* Auxiliary enum class for specifying an implementation for [StreamWrapper], that it will use.
*/
// TODO introduce a base interface for all such enums after https://github.com/UnitTestBot/UTBotJava/issues/146?
enum class UtStreamClass {
UT_STREAM,
UT_INT_STREAM,
UT_LONG_STREAM,
UT_DOUBLE_STREAM;
val className: String
get() = when (this) {
UT_STREAM -> UtStream::class.java.canonicalName
UT_INT_STREAM -> UtIntStream::class.java.canonicalName
UT_LONG_STREAM -> UtLongStream::class.java.canonicalName
UT_DOUBLE_STREAM -> UtDoubleStream::class.java.canonicalName
}
val elementClassId: ClassId
get() = when (this) {
UT_STREAM -> objectClassId
UT_INT_STREAM -> intClassId
UT_LONG_STREAM -> longClassId
UT_DOUBLE_STREAM -> doubleClassId
}
val overriddenStreamClassId: ClassId
get() = when (this) {
UT_STREAM -> streamClassId
UT_INT_STREAM -> intStreamClassId
UT_LONG_STREAM -> longStreamClassId
UT_DOUBLE_STREAM -> doubleStreamClassId
}
}
abstract class StreamWrapper(
utStreamClass: UtStreamClass, protected val elementsClassId: ClassId
) : BaseGenericStorageBasedContainerWrapper(utStreamClass.className) {
protected val streamClassId = utStreamClass.overriddenStreamClassId
override fun value(resolver: Resolver, wrapper: ObjectValue): UtAssembleModel = resolver.run {
val addr = holder.concreteAddr(wrapper.addr)
val modelName = nextModelName(baseModelName)
val parametersArrayModel = resolveElementsAsArrayModel(wrapper)?.transformElementsModel()
val (builder, params) = if (parametersArrayModel == null || parametersArrayModel.length == 0) {
streamEmptyMethodId to emptyList()
} else {
streamOfMethodId to listOf(parametersArrayModel)
}
val instantiationCall = UtExecutableCallModel(
instance = null,
executable = builder,
params = params
)
UtAssembleModel(addr, streamClassId, modelName, instantiationCall)
}
override fun chooseClassIdWithConstructor(classId: ClassId): ClassId = error("No constructor for Stream")
override val modificationMethodId: MethodId
get() = error("No modification method for Stream")
private fun Resolver.resolveElementsAsArrayModel(wrapper: ObjectValue): UtArrayModel? {
val elementDataFieldId = FieldId(overriddenClass.type.classId, "elementData")
return collectFieldModels(wrapper.addr, overriddenClass.type)[elementDataFieldId] as? UtArrayModel
}
open fun UtArrayModel.transformElementsModel(): UtArrayModel = this
private val streamOfMethodId: MethodId
get() = methodId(
classId = streamClassId,
name = "of",
returnType = streamClassId,
arguments = arrayOf(elementsClassId) // vararg
)
private val streamEmptyMethodId: MethodId = methodId(
classId = streamClassId,
name = "empty",
returnType = streamClassId,
arguments = emptyArray()
)
}
class CommonStreamWrapper : StreamWrapper(UtStreamClass.UT_STREAM, objectArrayClassId) {
override val baseModelName: String = "stream"
}
abstract class PrimitiveStreamWrapper(
utStreamClass: UtStreamClass,
elementsClassId: ClassId
) : StreamWrapper(utStreamClass, elementsClassId) {
init {
require(elementsClassId.isArray) {
"Elements $$elementsClassId of primitive Stream wrapper for $streamClassId are not arrays"
}
}
/**
* Transforms a model for an array of wrappers (Integer, Long, etc) to an array of corresponding primitives.
*/
override fun UtArrayModel.transformElementsModel(): UtArrayModel {
val primitiveConstModel = if (constModel is UtNullModel) {
// UtNullModel is not allowed for primitive arrays
elementsClassId.elementClassId!!.defaultValueModel()
} else {
constModel.wrapperModelToPrimitiveModel()
}
return copy(
classId = elementsClassId,
constModel = primitiveConstModel,
stores = stores.mapValuesTo(mutableMapOf()) { it.value.wrapperModelToPrimitiveModel() }
)
}
/**
* Transforms [this] to [UtPrimitiveModel] if it is an [UtAssembleModel] for the corresponding wrapper
* (primitive int and wrapper Integer, etc.), and throws an error otherwise.
*/
private fun UtModel.wrapperModelToPrimitiveModel(): UtModel {
require(this !is UtNullModel) {
"Unexpected null value in wrapper for primitive stream ${[email protected]}"
}
require(classId.isPrimitiveWrapper && this is UtAssembleModel) {
"Unexpected not wrapper assemble model $this for value in wrapper " +
"for primitive stream ${[email protected]}"
}
return (instantiationCall.params.firstOrNull() as? UtPrimitiveModel)
?: error("No primitive value parameter for wrapper constructor $instantiationCall in model $this " +
"in wrapper for primitive stream ${[email protected]}")
}
}
class IntStreamWrapper : PrimitiveStreamWrapper(UtStreamClass.UT_INT_STREAM, intArrayClassId) {
override val baseModelName: String = "intStream"
}
class LongStreamWrapper : PrimitiveStreamWrapper(UtStreamClass.UT_LONG_STREAM, longArrayClassId) {
override val baseModelName: String = "longStream"
}
class DoubleStreamWrapper : PrimitiveStreamWrapper(UtStreamClass.UT_DOUBLE_STREAM, doubleArrayClassId) {
override val baseModelName: String = "doubleStream"
}
| 398 | Kotlin | 32 | 91 | abb62682c70d7d2ecc4ad610851d304f7ad716e4 | 7,563 | UTBotJava | Apache License 2.0 |
ui-main/src/main/java/pl/kamilszustak/read/ui/main/quotes/QuotesFragment.kt | swistak7171 | 289,985,013 | false | null | package pl.kamilszustak.read.ui.main.quotes
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.RecyclerView
import com.mikepenz.fastadapter.FastAdapter
import com.mikepenz.fastadapter.adapters.ModelAdapter
import com.mikepenz.fastadapter.listeners.LongClickEventHook
import jp.wasabeef.recyclerview.animators.FadeInAnimator
import pl.kamilszustak.model.common.id.QuoteId
import pl.kamilszustak.read.model.domain.Quote
import pl.kamilszustak.read.ui.base.util.*
import pl.kamilszustak.read.ui.main.MainDataBindingFragment
import pl.kamilszustak.read.ui.main.R
import pl.kamilszustak.read.ui.main.databinding.FragmentQuotesBinding
import javax.inject.Inject
class QuotesFragment @Inject constructor(
viewModelFactory: ViewModelProvider.Factory,
) : MainDataBindingFragment<FragmentQuotesBinding, QuotesViewModel>(R.layout.fragment_quotes) {
override val viewModel: QuotesViewModel by viewModels(viewModelFactory)
private val navigator: Navigator = Navigator()
private val modelAdapter: ModelAdapter<Quote, QuoteItem> by lazy {
ModelAdapter { QuoteItem(it) }
}
override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
inflater.inflate(R.menu.menu_quotes_fragment, menu)
super.onCreateOptionsMenu(menu, inflater)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.addQuoteItem -> {
viewModel.dispatch(QuotesEvent.OnAddQuoteButtonClicked)
true
}
else -> {
super.onOptionsItemSelected(item)
}
}
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setHasOptionsMenu(true)
}
override fun initializeRecyclerView() {
val fastAdapter = FastAdapter.with(modelAdapter).apply {
addEventHook(object : LongClickEventHook<QuoteItem>() {
override fun onBind(viewHolder: RecyclerView.ViewHolder): View? {
return if (viewHolder is QuoteItem.ViewHolder) {
viewHolder.binding.root
} else {
null
}
}
override fun onLongClick(
v: View,
position: Int,
fastAdapter: FastAdapter<QuoteItem>,
item: QuoteItem
): Boolean {
openQuoteItemPopupMenu(v, item.model)
return true
}
})
}
binding.quotesRecyclerView.apply {
itemAnimator = FadeInAnimator()
adapter = fastAdapter
}
}
override fun observeViewModel() {
viewModel.action.observe(viewLifecycleOwner) { action ->
when (action) {
is QuotesAction.ShareQuote -> {
val title = getString(action.titleResourceId)
val chooserIntent = Intent.createChooser(action.intent, title)
requireActivity().startActivity(chooserIntent)
}
is QuotesAction.NavigateToQuoteEditFragment -> {
navigator.navigateToQuoteEditFragment(action.quoteId)
}
is QuotesAction.QuoteDeleted -> {
successToast(R.string.quote_deleted)
}
is QuotesAction.Error -> {
errorToast(action.messageResourceId)
}
}
}
viewModel.quotes.observe(viewLifecycleOwner) { quotes ->
binding.quotesRecyclerView.isVisible = quotes.isNotEmpty()
binding.emptyQuotesListLayout.root.isVisible = quotes.isEmpty()
modelAdapter.updateModels(quotes)
}
}
private fun openQuoteItemPopupMenu(view: View, quote: Quote) {
popupMenu(view, R.menu.popup_menu_quote_item) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
setForceShowIcon(true)
}
setOnMenuItemClickListener { menuItem ->
when (menuItem.itemId) {
R.id.shareQuoteItem -> {
val event = QuotesEvent.OnShareQuoteButtonClicked(quote.id)
viewModel.dispatch(event)
true
}
R.id.editQuoteItem -> {
val event = QuotesEvent.OnEditQuoteButtonClicked(quote.id)
viewModel.dispatch(event)
true
}
R.id.deleteQuoteItem -> {
dialog {
title(R.string.delete_quote_dialog_title)
message(R.string.delete_quote_dialog_message)
positiveButton(R.string.yes) {
val event = QuotesEvent.OnDeleteQuoteButtonClicked(quote.id)
viewModel.dispatch(event)
}
negativeButton(R.string.no) { dialog ->
dialog.dismiss()
}
}
true
}
else -> {
false
}
}
}
}
}
private inner class Navigator {
fun navigateToQuoteEditFragment(quoteId: QuoteId? = null) {
val direction = QuotesFragmentDirections.actionQuotesFragmentToNavigationQuoteEdit(
quoteId = quoteId?.value
)
navigate(direction)
}
}
} | 2 | Kotlin | 0 | 1 | 70d7be58042410bdb969035413b726126426e3d3 | 6,066 | read | Apache License 2.0 |
lib/src/main/kotlin/io/github/newagewriter/template/keywords/Keyword.kt | newagewriter | 681,180,371 | false | {"Kotlin": 7376, "Shell": 1398, "Java": 159} | package io.github.newagewriter.template.keywords
abstract class Keyword {
abstract fun find(content: String): MatchResult?
} | 1 | Kotlin | 0 | 0 | 208553da1d89189d1ad5fdeaaedcdbc7804f5641 | 129 | kt-generator | MIT License |
mercado-livro/src/main/kotlin/com/mercadolivro/repository/BookRepository.kt | juliocarvalho2019 | 633,990,981 | false | null | package com.mercadolivro.repository
import com.mercadolivro.enums.BookStatus
import com.mercadolivro.model.BookModel
import com.mercadolivro.model.CustomerModel
import org.springframework.data.domain.Page
import org.springframework.data.domain.Pageable
import org.springframework.data.jpa.repository.JpaRepository
import org.springframework.data.repository.CrudRepository
interface BookRepository : JpaRepository<BookModel, Int> {
fun findByStatus(status: BookStatus, pageable: Pageable): Page<BookModel>
fun findByCustomer(customer: CustomerModel): List<BookModel>
// fun findAll(pageable: Pageable): Page<BookModel>
} | 0 | null | 0 | 1 | a554bb1eeae0850d39e1e95c0ea3aa7cccdef71c | 635 | Mercado-livro | Apache License 2.0 |
bgw-gui/src/main/kotlin/tools/aqua/bgw/util/GridIteratorElement.kt | tudo-aqua | 377,420,862 | false | null | /*
* Copyright 2021-2023 The BoardGameWork Authors
* SPDX-License-Identifier: Apache-2.0
*
* 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 tools.aqua.bgw.util
import tools.aqua.bgw.util.ComponentViewGrid.GridIterator
/**
* Data class containing meta info about current grid element returned by its [GridIterator].
*
* @constructor Creates a [GridIteratorElement].
*
* @param T Type of boxed [component].
* @property columnIndex Current column index.
* @property rowIndex Current row index.
* @property component Current component or `null` if there is no component present in this cell.
*/
data class GridIteratorElement<T>(val columnIndex: Int, val rowIndex: Int, val component: T?)
| 31 | null | 16 | 24 | 266db439e4443d10bc1ec7eb7d9032f29daf6981 | 1,218 | bgw | Apache License 2.0 |
src/main/java/com/dzen/campfire/api/models/publications/history/History.kt | ZeonXX | 381,983,751 | false | {"Kotlin": 1087578} | package com.dzen.campfire.api.models.publications.history
import com.dzen.campfire.api.API
import com.sup.dev.java.libs.json.Json
import com.sup.dev.java.libs.json.JsonParsable
abstract class History : JsonParsable {
var userId = 0L
var userImageId = 0L
var userName = ""
var comment = ""
constructor(){
}
constructor(userId:Long,
userImageId:Long,
userName:String,
comment:String
){
this.userId = userId
this.userImageId = userImageId
this.userName = userName
this.comment = comment
}
abstract fun getType():Long
override fun json(inp: Boolean, json: Json): Json {
userId = json.m(inp, "userId", userId)
userImageId = json.m(inp, "userImageId", userImageId)
userName = json.m(inp, "userName", userName)
comment = json.m(inp, "comment", comment)
json.m(inp, "type", getType())
return json
}
companion object {
fun instance(json: Json): History {
val history = when (json.get<Long>("type")!!) {
API.HISTORY_PUBLICATION_TYPE_CREATED -> HistoryCreate()
API.HISTORY_PUBLICATION_TYPE_ADMIN_BACK_DRAFT -> HistoryAdminBackDraft()
API.HISTORY_PUBLICATION_TYPE_ADMIN_BLOCK -> HistoryAdminBlock()
API.HISTORY_PUBLICATION_TYPE_ADMIN_CHANGE_FANDOM -> HistoryAdminChangeFandom()
API.HISTORY_PUBLICATION_TYPE_ADMIN_CLEAR_REPORTS -> HistoryAdminClearReports()
API.HISTORY_PUBLICATION_TYPE_ADMIN_DEEP_BLOCK -> HistoryAdminDeepBlock()
API.HISTORY_PUBLICATION_TYPE_ADMIN_NOT_BLOCK -> HistoryAdminNotBlock()
API.HISTORY_PUBLICATION_TYPE_ADMIN_NOT_MULTILINGUAL -> HistoryAdminNotMultilingual()
API.HISTORY_PUBLICATION_TYPE_BACK_DRAFT -> HistoryBackDraft()
API.HISTORY_PUBLICATION_TYPE_CHANGE_FANDOM -> HistoryChangeFandom()
API.HISTORY_PUBLICATION_TYPE_EDIT_PUBLIC -> HistoryEditPublic()
API.HISTORY_PUBLICATION_TYPE_MULTILINGUAL -> HistoryMultilingual()
API.HISTORY_PUBLICATION_TYPE_NOT_MULTILINGUAL -> HistoryNotMultolingual()
API.HISTORY_PUBLICATION_TYPE_PUBLISH -> HistoryPublish()
API.HISTORY_PUBLICATION_TYPE_ADMIN_CHANGE_TAGS -> HistoryAdminChangeTags()
API.HISTORY_PUBLICATION_TYPE_ADMIN_IMPORTANT -> HistoryAdminImportant()
API.HISTORY_PUBLICATION_TYPE_ADMIN_NOT_IMPORTANT -> HistoryAdminNotImportant()
API.HISTORY_PUBLICATION_TYPE_ADMIN_PIN_FANDOM -> HistoryAdminPinFandom()
API.HISTORY_PUBLICATION_TYPE_ADMIN_UNPIN_FANDOM -> HistoryAdminUnpinFandom()
API.HISTORY_PUBLICATION_TYPE_CHANGE_TAGS -> HistoryChangeTags()
API.HISTORY_PUBLICATION_TYPE_PIN_PROFILE -> HistoryPinProfile()
API.HISTORY_PUBLICATION_TYPE_UNPIN_PROFILE -> HistoryUnpinProfile()
API.HISTORY_PUBLICATION_TYPE_ADMIN_NOT_DEEP_BLOCK -> HistoryAdminNotDeepBlock()
API.HISTORY_PUBLICATION_TYPE_CLOSE -> HistoryClose()
API.HISTORY_PUBLICATION_TYPE_ADMIN_CLOSE -> HistoryAdminClose()
API.HISTORY_PUBLICATION_TYPE_CLOSE_NO -> HistoryCloseNo()
API.HISTORY_PUBLICATION_TYPE_ADMIN_CLOSE_NO -> HistoryAdminCloseNo()
API.HISTORY_PUBLICATION_TYPE_ADMIN_REMOVE_MEDIA -> HistoryAdminRemoveMedia()
else -> HistoryUnknown()
}
history.json(false, json)
return history
}
}
} | 0 | Kotlin | 2 | 5 | 6f3b371624fb66a065bcbaa6302830c574c55e9f | 3,639 | CampfireApi | Apache License 2.0 |
customer-kotlin-webflux/src/main/kotlin/com/prez/ws/model/CustomerWSModel.kt | jaguiar | 317,158,906 | false | null | package com.prez.ws.model
import com.fasterxml.jackson.annotation.JsonProperty
import org.apache.commons.lang3.StringUtils.isNotBlank
data class GetCustomerWSResponse(
val id: String,
val personalInformation: PersonalInformation?,
val personalDetails: PersonalDetails?,
val cards: Cards = Cards(listOf()),
val services: Services? = null,
val photos: Photos? = null,
val misc: List<Misc> = listOf()
)
data class NestedValue(
val value: String
)
data class PersonalInformation(
val civility: NestedValue?,
val lastName: String?,
val firstName: String?,
val birthdate: String?,
val alive: Boolean?
)
data class PersonalDetails(
val email: Email?,
val cell: Cell?
)
data class Email(
val address: String?,
val default: Boolean = false,
val confirmed: NestedValue? = null
)
data class Cell(
val number: String?
)
data class Cards(
@JsonProperty("records")
val cards: List<Card> = listOf()
)
data class Card(
val number: String?,
val type: NestedValue?,
val ticketless: Boolean,
val disableStatus: NestedValue?
)
data class Services(
val list: List<Service> = listOf()
)
data class Service(
val name: NestedValue?,
val status: NestedValue?,
val updatedTime: String?
)
data class Photos(
val file: File?
)
data class File(
@JsonProperty("@id")
val id: String
)
data class Misc(
val type: NestedValue?,
val count: Int,
val hasMore: Boolean,
val records: List<Record> = listOf()
)
data class Record(
@JsonProperty("otherId")
val otherId: String?,
val type: NestedValue?,
@JsonProperty("fields") // ici en java on avait mis un ListOfObjectsToMapDeserializer
private val map: List<Map<String, String>> = listOf()
) {
val mapAsRealMap: Map<String, String> by lazy { //by lazy is not mandatory, could be useful for perfs
//something more usable for mapping misc properties
map
.filter { isNotBlank(it["key"]) && isNotBlank(it["value"]) }
.map { it.getValue("key") to it.getValue("value") }
.toMap()
}
fun getValue(key: String): String = mapAsRealMap.getValue(key)
fun getMaybeValue(key: String): String? = mapAsRealMap[key]
} | 12 | Kotlin | 0 | 2 | 141c553ae6a5f29a683d35670cc0f64572c97800 | 2,437 | customer-api | Apache License 2.0 |
app/src/main/java/com/we2dx/hodop/ui/share/ShareFragment.kt | ashishkharcheiuforks | 245,642,964 | true | {"Kotlin": 103440, "Java": 9633} | package com.we2dx.hodop.ui.share
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.widget.AppCompatButton
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.we2dx.hodop.R
class ShareFragment : Fragment() {
private lateinit var shareViewModel: ShareViewModel
private lateinit var mReferFriendButton : AppCompatButton
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
shareViewModel =
ViewModelProviders.of(this).get(ShareViewModel::class.java)
val root = inflater.inflate(R.layout.fragment_share, container, false)
mReferFriendButton = root.findViewById(R.id.refer_a_friend)
shareViewModel.text.observe(this, Observer {
})
return root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
mReferFriendButton.setOnClickListener { shareWithFriend() }
}
fun shareWithFriend() {
val sendIntent: Intent = Intent().apply {
action = Intent.ACTION_SEND
putExtra(Intent.EXTRA_TEXT, "Get more ahead with better traffic update to navigate around\n Download Hodop app on Google playstore")
type = "text/plain"
}
val shareIntent = Intent.createChooser(sendIntent, null)
startActivity(shareIntent)
}
} | 0 | null | 0 | 0 | c973721d0b8780104a629e2fad911f908d7903a4 | 1,653 | Hodop | MIT License |
presentation/detail_screen/src/main/java/com/zekierciyas/detail_screen/view_model/DetailScreenViewModel.kt | zekierciyas | 603,181,275 | false | null | package com.zekierciyas.detail_screen.view_model
import androidx.lifecycle.ViewModel
import com.zekierciyas.cache.model.position.Position
import com.zekierciyas.cache.model.position.Positions
import com.zekierciyas.cache.repository.SatellitePositionsRepository
import com.zekierciyas.cache.repository.satellite_detail.SatelliteDetailRepository
import com.zekierciyas.navigation.SatelliteListArgModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import javax.inject.Inject
@HiltViewModel
class DetailScreenViewModel @Inject constructor(
private val positionsRepository: SatellitePositionsRepository,
private val detailRepository: SatelliteDetailRepository
): ViewModel() {
private val viewModelJob = SupervisorJob()
private val viewModelScope = CoroutineScope(viewModelJob + Dispatchers.IO)
private val _uiState = MutableStateFlow<DetailScreenUiState>(DetailScreenUiState.Loading)
val uiState: StateFlow<DetailScreenUiState> = _uiState
private val _positions = MutableStateFlow<Position?>(null)
val positions: StateFlow<Position?> = _positions
private var selectedID = 0
private var arg: SatelliteListArgModel? = null
companion object {
const val POSITION_CHANGE_DELAY : Long = 3000
}
init {
viewModelScope.launch {
positionsRepository.getPositions(
onComplete = {
changePositionRandomly(it)
},
onError = {
_uiState.value = DetailScreenUiState.Error()
}
)
detailRepository.getDetails(
onComplete = {
_uiState.value = DetailScreenUiState.Loaded(it[selectedID], arg!!.name)
},
onError = {
_uiState.value = DetailScreenUiState.Error()
}
)
}
}
private fun changePositionRandomly(positions: Positions) {
val scope = CoroutineScope(Dispatchers.Main)
scope.launch {
var counter = 1
while (true) {
positions.list[selectedID].positions.random().also {
_positions.value = Position(it.posX,it.posY)
}
delay(POSITION_CHANGE_DELAY) // wait for 3 seconds
counter++
}
}
}
fun setData(arg: SatelliteListArgModel) {
selectedID = arg.id - 1
this.arg = arg
}
override fun onCleared() {
super.onCleared()
viewModelJob.cancel()
}
} | 0 | Kotlin | 0 | 1 | 79ffb9baef4d7e4c7216edf50035296e8c0654f6 | 2,681 | SatelliteList | MIT License |
hex-ai/src/test/kotlin/alfabeta/evaluator/TestExtensions.kt | krasnoludkolo | 265,339,358 | false | null | package alfabeta.evaluator
import hex.*
import hex.engine.HexGame
import io.vavr.collection.List
import io.vavr.kotlin.getOrNull
fun switch() = SwitchMove
fun blue(x: Int, y: Int) = NormalMove.blue(Point(x, y))
fun red(x: Int, y: Int) = NormalMove.red(Point(x, y))
fun Board.getPieceAt(point: Point) = piecesMap.getOrNull(point)
fun HexGame.makeMoves(vararg moves: Move) =
List.ofAll(moves.toList()).fold(this) { board, move -> (board.makeMove(move) as Success).hexGame } | 0 | Kotlin | 0 | 0 | 97e136262f79c78aea0aabf4c7132b18da6f70bf | 479 | hex | MIT License |
app/src/main/java/com/zhou/speech/common/FileAdapter.kt | maxiaozhou1234 | 166,927,557 | false | null | package com.zhou.speech.common
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
class FileAdapter : RecyclerView.Adapter<FileAdapter.FileViewHolder> {
var data: ArrayList<String>
var inflater: LayoutInflater
constructor(context: Context, data: ArrayList<String>) {
inflater = LayoutInflater.from(context)
[email protected] = data
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FileViewHolder {
return FileViewHolder(inflater.inflate(android.R.layout.simple_list_item_1, parent, false))
}
override fun getItemCount(): Int {
return data.size
}
override fun onBindViewHolder(holder: FileViewHolder, position: Int) {
holder.file.text = data[position]
holder.file.setOnClickListener {
// listener?.onItemClick(data[position], position)
listener?.invoke(data[position], position)
}
}
class FileViewHolder : RecyclerView.ViewHolder {
var file: TextView
constructor(view: View) : super(view) {
file = view.findViewById(android.R.id.text1)
}
}
private var listener: ((name: String, pos: Int) -> Unit)? = null
interface OnItemClickListener {
fun onItemClick(file: String, position: Int)
}
fun setOnItemClickListener(listener: (name: String, pos: Int) -> Unit) {
[email protected] = listener
}
} | 0 | Kotlin | 0 | 0 | aebc565a885a456d804e56817bbc45142598adc3 | 1,592 | Text2Speech | MIT License |
composeApp/src/desktopMain/kotlin/com/rwmobi/kunigami/ui/extensions/GenerateRandomLong.desktop.kt | ryanw-mobile | 794,752,204 | false | {"Kotlin": 1112930, "Ruby": 2466, "Swift": 693} | /*
* Copyright (c) 2024. <NAME>
* https://github.com/ryanw-mobile
* Sponsored by RW MobiMedia UK Limited
*
*/
package com.rwmobi.kunigami.ui.extensions
import java.util.UUID
actual fun generateRandomLong(): Long {
return UUID.randomUUID().mostSignificantBits
}
| 20 | Kotlin | 10 | 98 | e1e73f5b44baaef5ab87fd10db21775d442a3172 | 273 | OctoMeter | Apache License 2.0 |
src/main/java/com/denisbelobrotski/eye_tracking_library/abstraction/IClearable.kt | DenisBelobrotski | 354,017,403 | false | null | package com.denisbelobrotski.eye_tracking_library.abstraction
interface IClearable {
fun clear()
}
| 0 | Kotlin | 0 | 1 | 7f7654914023a0f572abb79274081475edb724c5 | 104 | eye-tracking-library | MIT License |
lightspark-sdk/src/commonMain/kotlin/com/lightspark/sdk/model/InvoiceData.kt | lightsparkdev | 590,703,408 | false | {"Kotlin": 1689958, "Java": 34937, "Dockerfile": 1719, "Shell": 490} | // Copyright ©, 2023-present, Lightspark Group, Inc. - All Rights Reserved
@file:Suppress("ktlint:standard:max-line-length")
package com.lightspark.sdk.model
import kotlinx.datetime.Instant
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
/**
* This object represents the data associated with a BOLT #11 invoice. You can retrieve this object to receive the relevant data associated with a specific invoice.
* @param paymentHash The payment hash of this invoice.
* @param amount The requested amount in this invoice. If it is equal to 0, the sender should choose the amount to send.
* @param createdAt The date and time when this invoice was created.
* @param expiresAt The date and time when this invoice will expire.
* @param destination The lightning node that will be paid when fulfilling this invoice.
* @param memo A short, UTF-8 encoded, description of the purpose of this invoice.
*/
@Serializable
@SerialName("InvoiceData")
data class InvoiceData(
@SerialName("invoice_data_encoded_payment_request")
override val encodedPaymentRequest: String,
@SerialName("invoice_data_bitcoin_network")
override val bitcoinNetwork: BitcoinNetwork,
@SerialName("invoice_data_payment_hash")
val paymentHash: String,
@SerialName("invoice_data_amount")
val amount: CurrencyAmount,
@SerialName("invoice_data_created_at")
val createdAt: Instant,
@SerialName("invoice_data_expires_at")
val expiresAt: Instant,
@SerialName("invoice_data_destination")
val destination: Node,
@SerialName("invoice_data_memo")
val memo: String? = null,
) : PaymentRequestData {
companion object {
const val FRAGMENT = """
fragment InvoiceDataFragment on InvoiceData {
type: __typename
invoice_data_encoded_payment_request: encoded_payment_request
invoice_data_bitcoin_network: bitcoin_network
invoice_data_payment_hash: payment_hash
invoice_data_amount: amount {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
invoice_data_created_at: created_at
invoice_data_expires_at: expires_at
invoice_data_memo: memo
invoice_data_destination: destination {
type: __typename
... on GraphNode {
type: __typename
graph_node_id: id
graph_node_created_at: created_at
graph_node_updated_at: updated_at
graph_node_alias: alias
graph_node_bitcoin_network: bitcoin_network
graph_node_color: color
graph_node_conductivity: conductivity
graph_node_display_name: display_name
graph_node_public_key: public_key
}
... on LightsparkNodeWithOSK {
type: __typename
lightspark_node_with_o_s_k_id: id
lightspark_node_with_o_s_k_created_at: created_at
lightspark_node_with_o_s_k_updated_at: updated_at
lightspark_node_with_o_s_k_alias: alias
lightspark_node_with_o_s_k_bitcoin_network: bitcoin_network
lightspark_node_with_o_s_k_color: color
lightspark_node_with_o_s_k_conductivity: conductivity
lightspark_node_with_o_s_k_display_name: display_name
lightspark_node_with_o_s_k_public_key: public_key
lightspark_node_with_o_s_k_owner: owner {
id
}
lightspark_node_with_o_s_k_status: status
lightspark_node_with_o_s_k_total_balance: total_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
lightspark_node_with_o_s_k_total_local_balance: total_local_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
lightspark_node_with_o_s_k_local_balance: local_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
lightspark_node_with_o_s_k_remote_balance: remote_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
lightspark_node_with_o_s_k_blockchain_balance: blockchain_balance {
type: __typename
blockchain_balance_total_balance: total_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
blockchain_balance_confirmed_balance: confirmed_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
blockchain_balance_unconfirmed_balance: unconfirmed_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
blockchain_balance_locked_balance: locked_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
blockchain_balance_required_reserve: required_reserve {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
blockchain_balance_available_balance: available_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
}
lightspark_node_with_o_s_k_uma_prescreening_utxos: uma_prescreening_utxos
lightspark_node_with_o_s_k_encrypted_signing_private_key: encrypted_signing_private_key {
type: __typename
secret_encrypted_value: encrypted_value
secret_cipher: cipher
}
}
... on LightsparkNodeWithRemoteSigning {
type: __typename
lightspark_node_with_remote_signing_id: id
lightspark_node_with_remote_signing_created_at: created_at
lightspark_node_with_remote_signing_updated_at: updated_at
lightspark_node_with_remote_signing_alias: alias
lightspark_node_with_remote_signing_bitcoin_network: bitcoin_network
lightspark_node_with_remote_signing_color: color
lightspark_node_with_remote_signing_conductivity: conductivity
lightspark_node_with_remote_signing_display_name: display_name
lightspark_node_with_remote_signing_public_key: public_key
lightspark_node_with_remote_signing_owner: owner {
id
}
lightspark_node_with_remote_signing_status: status
lightspark_node_with_remote_signing_total_balance: total_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
lightspark_node_with_remote_signing_total_local_balance: total_local_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
lightspark_node_with_remote_signing_local_balance: local_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
lightspark_node_with_remote_signing_remote_balance: remote_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
lightspark_node_with_remote_signing_blockchain_balance: blockchain_balance {
type: __typename
blockchain_balance_total_balance: total_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
blockchain_balance_confirmed_balance: confirmed_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
blockchain_balance_unconfirmed_balance: unconfirmed_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
blockchain_balance_locked_balance: locked_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
blockchain_balance_required_reserve: required_reserve {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
blockchain_balance_available_balance: available_balance {
type: __typename
currency_amount_original_value: original_value
currency_amount_original_unit: original_unit
currency_amount_preferred_currency_unit: preferred_currency_unit
currency_amount_preferred_currency_value_rounded: preferred_currency_value_rounded
currency_amount_preferred_currency_value_approx: preferred_currency_value_approx
}
}
lightspark_node_with_remote_signing_uma_prescreening_utxos: uma_prescreening_utxos
}
}
}"""
}
}
| 1 | Kotlin | 1 | 4 | b966c6681e77906e6b3b659c01a9bce05b55fdf9 | 16,116 | kotlin-sdk | Apache License 2.0 |
src/main/kotlin/org/treeWare/metaModel/encoder/kotlin/EncodeKotlin.kt | tree-ware | 677,942,297 | false | {"Kotlin": 41831} | package org.treeWare.metaModel.encoder.kotlin
import org.treeWare.metaModel.traversal.metaModelForEach
import org.treeWare.model.core.MainModel
fun encodeKotlin(metaModelFilePaths: List<String>, mainMeta: MainModel, kotlinDirectoryPath: String) {
val encodeVisitor = EncodeKotlinMetaModelVisitor(metaModelFilePaths, kotlinDirectoryPath)
metaModelForEach(mainMeta, encodeVisitor)
} | 3 | Kotlin | 0 | 0 | 091d757967e26f56bc59c40c5e4a93db8a8914fb | 390 | tree-ware-gradle-core-plugin | Apache License 2.0 |
app/src/main/java/com/rain/currency/ui/converter/ConverterViewModel.kt | nongdenchet | 128,639,036 | false | null | package com.rain.currency.ui.converter
import android.view.View
import com.jakewharton.rxrelay2.BehaviorRelay
import com.rain.currency.data.model.CurrencyInfo
import com.rain.currency.domain.ConverterData
import com.rain.currency.domain.ConverterInteractor
import com.rain.currency.data.mapper.CurrencyMapper
import com.rain.currency.ui.converter.reducer.ConverterCommand
import com.rain.currency.ui.converter.reducer.ConverterReducer
import com.rain.currency.ui.converter.reducer.ConverterState
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.BiFunction
import io.reactivex.schedulers.Schedulers
import timber.log.Timber
class ConverterViewModel(
private val reducer: ConverterReducer,
private val interactor: ConverterInteractor,
private val mapper: CurrencyMapper
) {
private val state = BehaviorRelay.createDefault(ConverterState.INIT_STATE)
private var disposable: Disposable? = null
class Input(
val retryClicks: Observable<Any>,
val moneyClicks: Observable<Any>,
val baseChange: Observable<String>,
val targetChange: Observable<String>,
val baseUnitChange: Observable<String>,
val targetUnitChange: Observable<String>,
val backClicks: Observable<Any>
)
class Output(
val baseResult: Observable<String>,
val targetResult: Observable<String>,
val baseCurrency: Observable<CurrencyInfo>,
val targetCurrency: Observable<CurrencyInfo>,
val loadingVisibility: Observable<Int>,
val showContent: Observable<Boolean>,
val errorVisibility: Observable<Int>,
val expand: Observable<Boolean>
)
fun bind(input: Input): Output {
val moneyClicks = input.moneyClicks.share()
val expandChange = Observable.merge(
moneyClicks.map { true },
input.backClicks.withLatestFrom(state.filter { it.expand },
BiFunction { _, _ -> false })
).map { ConverterCommand.ChangeExpand(it) }
val loadTrigger = Observable.merge(input.retryClicks, moneyClicks)
.startWith(0)
.switchMap { interactor.fetchCurrency() }
val baseChange = combine(input.baseChange)
.switchMapSingle { interactor.convertBaseValue(it.first, it.second) }
val baseUnitChange = combine(input.baseUnitChange)
.switchMapSingle { interactor.convertBaseUnit(it.first, it.second) }
val targetChange = combine(input.targetChange)
.switchMapSingle { interactor.convertTargetValue(it.first, it.second) }
val targetUnitChange = combine(input.targetUnitChange)
.switchMapSingle { interactor.convertTargetUnit(it.first, it.second) }
val commands = Observable.merge(
listOf(
expandChange, loadTrigger,
baseChange, baseUnitChange,
targetChange, targetUnitChange
)
)
disposable = commands.scan(ConverterState.INIT_STATE, reducer)
.subscribeOn(Schedulers.computation())
.observeOn(AndroidSchedulers.mainThread())
.subscribe({ state.accept(it) }, Timber::e)
return configureOutput()
}
private fun combine(observable: Observable<String>): Observable<Pair<String, ConverterData>> {
return observable.withLatestFrom(
getData(),
BiFunction<String, ConverterData, Pair<String, ConverterData>> { value, data ->
Pair(value, data)
})
}
private fun configureOutput(): Output {
val baseResult = getData()
.map { it.currency.base }
.distinctUntilChanged()
val targetResult = getData()
.map { it.currency.target }
.distinctUntilChanged()
val baseCurrency = getData()
.map { it.currency.baseUnit }
.map { mapper.toInfo(it) }
.distinctUntilChanged()
val targetCurrency = getData()
.map { it.currency.targetUnit }
.map { mapper.toInfo(it) }
.distinctUntilChanged()
val loadingVisibility = state.filter { it.expand }
.map { it.loading }
.map { if (it) View.VISIBLE else View.GONE }
.distinctUntilChanged()
val showContent = state.filter { it.expand }
.map { it.data != null && !it.loading }
.distinctUntilChanged()
val errorVisibility = state.filter { it.expand }
.map { it.data == null && !it.loading }
.map { if (it) View.VISIBLE else View.GONE }
.distinctUntilChanged()
val expand = state
.map { it.expand }
.distinctUntilChanged()
return Output(
baseResult, targetResult, baseCurrency, targetCurrency,
loadingVisibility, showContent, errorVisibility, expand
)
}
private fun getData(): Observable<ConverterData> {
return state.filter { it.data != null }
.map { it.data!! }
}
fun unbind() {
disposable?.dispose()
disposable = null
}
}
| 1 | null | 1 | 4 | a9b9d4741d0fb315cafa6297ee905fbba89fd177 | 5,223 | Kurrency | MIT License |
verik-importer/src/main/kotlin/io/verik/importer/normalize/ElementAliasChecker.kt | frwang96 | 269,980,078 | false | null | /*
* Copyright (c) 2022 Francis Wang
*
* 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.verik.importer.normalize
import io.verik.importer.ast.element.common.EElement
import io.verik.importer.common.TreeVisitor
import io.verik.importer.main.ProjectContext
import io.verik.importer.main.ProjectStage
import io.verik.importer.message.Messages
object ElementAliasChecker : NormalizationChecker {
override fun check(projectContext: ProjectContext, projectStage: ProjectStage) {
val elementAliasVisitor = ElementAliasVisitor(projectStage)
projectContext.project.accept(elementAliasVisitor)
}
private class ElementAliasVisitor(
private val projectStage: ProjectStage
) : TreeVisitor() {
private val elementSet = HashSet<EElement>()
override fun visitElement(element: EElement) {
super.visitElement(element)
if (element in elementSet)
Messages.NORMALIZATION_ERROR.on(element, projectStage, "Unexpected element aliasing: $element")
elementSet.add(element)
}
}
}
| 0 | Kotlin | 1 | 7 | a40d6195f3b57bebac813b3e5be59d17183433c7 | 1,604 | verik | Apache License 2.0 |
src/test/kotlin/com/gregwoodfill/concordlunch/LunchServiceTest.kt | gregwoodfill | 166,568,532 | false | null | package com.gregwoodfill.concordlunch
import org.junit.jupiter.api.Assertions.*
import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.time.LocalDateTime
internal class LunchServiceTest {
@Test
fun `get lunches`() {
val response = LunchService().getEntrees(LocalDate.now())
response
}
} | 0 | Kotlin | 0 | 1 | 2af83f7889c868a16c8d6d7880fb07bd73c32a94 | 336 | SchoolLunch | MIT License |
smtp/src/main/kotlin/mailer/SmtpMailerConfig.kt | picortex | 546,065,516 | false | {"Kotlin": 25081} | package mailer
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import java.io.InputStream
import java.lang.IllegalArgumentException
import java.util.*
interface SmtpMailerConfig {
val host: String
val port: Int
val user: String?
val password: String?
val auth: Boolean
val startTls: Boolean
val debug: Boolean
val socketFactory: SocketFactoryConfig
val scope: CoroutineScope
companion object {
@JvmField
val HOST = Property<String?>("mail.smtp.host", null)
@JvmField
val PORT = Property("mail.smtp.port", 465)
@JvmField
val USER = Property<String?>("mail.smtp.user", null)
@JvmField
val PASSWORD = Property<String?>("mail.smtp.password", null)
@JvmField
val AUTH = Property("mail.smtp.auth", true)
@JvmField
val START_TLS = Property("mail.smtp.starttls.enable", true)
@JvmField
val DEBUG = Property("mail.smtp.debug", true)
@JvmField
val DEFAULT_SCOPE = CoroutineScope(SupervisorJob() + Dispatchers.IO)
@JvmSynthetic
operator fun invoke(
host: String,
port: Int = PORT.default,
auth: Boolean = AUTH.default,
user: String? = USER.default,
password: String? = <PASSWORD>.default,
startTls: Boolean = START_TLS.default,
debug: Boolean = DEBUG.default,
socketFactory: SocketFactoryConfig = SocketFactoryConfig(),
scope: CoroutineScope = DEFAULT_SCOPE
) = object : SmtpMailerConfig {
init {
if (auth && user == null) {
throw IllegalArgumentException("User must not be null when auth is set to true (which is the default behaviour)")
}
}
override val host: String = host
override val port: Int = port
override val user: String? = user
override val password: String? = <PASSWORD>
override val auth: Boolean = auth
override val startTls: Boolean = startTls
override val debug: Boolean = debug
override val socketFactory: SocketFactoryConfig = socketFactory
override val scope: CoroutineScope = scope
}
@JvmSynthetic
operator fun invoke(
properties: Properties,
scope: CoroutineScope = DEFAULT_SCOPE
) = invoke(
host = properties[HOST.KEY]?.toString() ?: error("Key ${HOST.KEY} is not available in properties"),
port = properties[PORT.KEY]?.toString()?.toIntOrNull() ?: PORT.default,
auth = properties[AUTH.KEY]?.toString()?.toBooleanStrict() ?: AUTH.default,
user = properties[USER.KEY]?.toString() ?: USER.default,
password = properties[PASSWORD.KEY]?.toString() ?: PASSWORD.default,
startTls = properties[START_TLS]?.toString()?.toBooleanStrict() ?: START_TLS.default,
debug = properties[DEBUG.KEY]?.toString()?.toBooleanStrict() ?: DEBUG.default,
socketFactory = SocketFactoryConfig(properties),
scope = scope
)
@JvmStatic
@JvmOverloads
fun create(
host: String,
port: Int = PORT.default,
auth: Boolean = AUTH.default,
user: String? = USER.default,
password: String? = <PASSWORD>,
startTls: Boolean = START_TLS.default,
debug: Boolean = DEBUG.default,
socketFactory: SocketFactoryConfig = SocketFactoryConfig(),
scope: CoroutineScope = DEFAULT_SCOPE
) = invoke(host, port, auth, user, password, startTls, debug, socketFactory, scope)
@JvmStatic
@JvmOverloads
fun create(
properties: Properties,
scope: CoroutineScope = DEFAULT_SCOPE
) = invoke(properties, scope)
fun from(stream: InputStream): SmtpMailerConfig {
val props = Properties().apply { load(stream) }
return invoke(props)
}
}
fun toProperties(): Properties {
val props = Properties()
props[HOST.KEY] = host
props[PORT.KEY] = port
props[USER.KEY] = user
props[PASSWORD.KEY] = <PASSWORD>
props[AUTH.KEY] = auth
props[START_TLS.KEY] = startTls
props[DEBUG.KEY] = debug
props[SocketFactoryConfig.PORT.KEY] = socketFactory.port
props[SocketFactoryConfig.CLASS.KEY] = socketFactory.clazz
props[SocketFactoryConfig.FALLBACK.KEY] = socketFactory.fallback
return props
}
} | 0 | Kotlin | 0 | 2 | acc4b32467881fb28c32a849cf38c4780349792e | 4,706 | mailer | MIT License |
src/main/kotlin/tlint/cli/TLint.kt | tighten | 128,395,274 | false | null | package tlint.cli
import com.google.gson.GsonBuilder
import com.google.gson.JsonSyntaxException
import java.util.ArrayList
class TLint {
var file = File()
class File {
var errors: List<Issue> = ArrayList()
}
class Issue {
var source: String? = null
var line: Int = 0
var message: String? = null
}
companion object {
internal fun read(json: String): TLint {
val lint = TLint()
try {
val builder = GsonBuilder()
val gson = builder.create()
lint.file = gson.fromJson(json, File::class.java)
} catch (e: JsonSyntaxException) {
//
} catch (e: java.lang.IllegalStateException) {
//
}
return lint
}
}
} | 3 | Kotlin | 4 | 3 | e3ade42c45081243c4867070ed15faaee42d0da4 | 831 | tlint-plugin | MIT License |
src/test/kotlin/com/shopify/promises/MockScheduledThreadPoolExecutor.kt | Shopify | 97,160,262 | false | null | package com.shopify.promises
import java.util.concurrent.Delayed
import java.util.concurrent.ScheduledFuture
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.TimeUnit
class MockScheduledThreadPoolExecutor(val taskDelayAssert: (Long, TimeUnit) -> Unit = { _, _ -> }) : ScheduledThreadPoolExecutor(1) {
var lastScheduledFuture: MockScheduledFuture? = null
override fun schedule(command: Runnable?, delay: Long, timeUnit: TimeUnit?): ScheduledFuture<*> {
taskDelayAssert(delay, timeUnit!!)
command?.run()
return MockScheduledFuture()
}
class MockScheduledFuture : ScheduledFuture<Any> {
override fun get(timeout: Long, unit: TimeUnit?): Any {
TODO("not implemented")
}
override fun get(): Any {
TODO("not implemented")
}
override fun cancel(mayInterruptIfRunning: Boolean): Boolean = true
override fun isDone(): Boolean = true
override fun getDelay(unit: TimeUnit?): Long = 0
override fun compareTo(other: Delayed?): Int = 0
override fun isCancelled(): Boolean = false
}
} | 1 | Kotlin | 15 | 81 | 14c370fd812d5d1a789db13baadcbe755e46c007 | 1,084 | promise-kotlin | MIT License |
recommend-sdk/src/main/java/com/recommend/sdk/device/data/model/activity/data/DeviceCartUpdateActivityData.kt | recommend-pro | 609,114,602 | false | null | package com.recommend.sdk.device.data.model.activity.data
import com.google.gson.annotations.SerializedName
/**
* Cart update event data
*
* @property cartHash Hashed cart identifier SHA256
* @property requestId Backend API request identifier linked with activity. Request_id can be omitted.
* This field is needed in case the api does not work correctly for some reason (for example, there is too much delay between sending requests to update orders / wishlists / carts).
* @constructor Create Cart update event data
*/
data class DeviceCartUpdateActivityData(
@SerializedName("cart_hash") val cartHash: String,
@SerializedName("request_id") val requestId: String? = null
)
| 0 | Kotlin | 0 | 2 | 9f215b7c549d7935a6bc12905cf16be0c2d30aef | 692 | recommend-android-sdk | MIT License |
app/src/main/java/com/example/breeze/ui/factory/EventViewModelFactory.kt | bangkit-breeze | 724,188,087 | false | {"Kotlin": 226903} | package com.example.breeze.ui.factory
import android.app.Application
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.example.breeze.data.repository.EventRepository
import com.example.breeze.data.repository.UserRepository
import com.example.breeze.di.Injection
import com.example.breeze.ui.viewmodel.DetailEventViewModel
import com.example.breeze.ui.viewmodel.FormEventViewModel
import com.example.breeze.ui.viewmodel.EventViewModel
class EventViewModelFactory private constructor(
private val userRepository: UserRepository,
private val eventRepository: EventRepository
) :
ViewModelProvider.NewInstanceFactory() {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>):T =
when {
modelClass.isAssignableFrom(EventViewModel::class.java) ->
EventViewModel(userRepository, eventRepository) as T
modelClass.isAssignableFrom(DetailEventViewModel::class.java) ->
DetailEventViewModel(userRepository, eventRepository) as T
modelClass.isAssignableFrom(FormEventViewModel::class.java) ->
FormEventViewModel(userRepository, eventRepository) as T
else -> throw IllegalArgumentException("Unknown ViewModel class: ${modelClass.name}")
}
companion object {
@Volatile
private var instance: EventViewModelFactory? = null
fun getInstance(application: Application): EventViewModelFactory =
instance ?: synchronized(this) {
instance ?: EventViewModelFactory(
Injection.provideUserRepository(application),
Injection.provideEventRepository(application))
}.also { instance = it }
}
} | 0 | Kotlin | 0 | 0 | 52bd1da7ce3e869d9ccb8baf2cea44853569ab58 | 1,783 | breeze-android-development | Open Market License |
feature.main/src/main/java/lac/feature/main/app/data/model/DataCity.kt | bandysik | 143,031,693 | false | null | package lac.feature.main.app.data.model
data class DataCity(val id: String, val content: String) | 0 | Kotlin | 0 | 1 | c2e0478c93eb5eaf7ec1632d2257427a9174443e | 97 | LAC | Apache License 2.0 |
12_NatureCollection/app/src/main/java/com/mboultoureau/naturecollection/adapter/PlantAdapter.kt | mboultoureau | 125,827,712 | false | {"JavaScript": 40939, "C": 19603, "Kotlin": 18454, "CSS": 12216, "C++": 11301, "HTML": 6700, "Java": 5779, "Vue": 3855, "SCSS": 3279, "Objective-C++": 1882, "Makefile": 164} | package com.mboultoureau.naturecollection.adapter
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.mboultoureau.naturecollection.*
class PlantAdapter(
val context: MainActivity,
private val plantList: List<PlantModel>,
private val layoutId: Int
) : RecyclerView.Adapter<PlantAdapter.ViewHolder>() {
// Boite à composants
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val plantImage = view.findViewById<ImageView>(R.id.image_item)
val plantName:TextView? = view.findViewById(R.id.name_item)
val plantDescription:TextView? = view.findViewById(R.id.description_item)
val starIcon = view.findViewById<ImageView>(R.id.star_icon)
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater
.from(parent.context)
.inflate(layoutId, parent, false)
return ViewHolder(view)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
// Récupérer les informations de la plante
val currentPlant = plantList[position]
// Récupérer repository
val repo = PlantRepository()
// Glide : récupérer image à partir du lien
Glide.with(context).load(Uri.parse(currentPlant.imageUrl)).into(holder.plantImage)
// Mise à jour nom & description
holder.plantName?.text = currentPlant.name
holder.plantDescription?.text = currentPlant.description
// Like
if (currentPlant.liked) {
holder.starIcon.setImageResource(R.drawable.ic_star)
} else {
holder.starIcon.setImageResource(R.drawable.ic_unstar)
}
// Interaction du like
holder.starIcon.setOnClickListener {
// Inverser le button
currentPlant.liked = !currentPlant.liked
// Mise à jour de la plante
repo.updatePlant(currentPlant)
}
// Interaction clic sur une plante
holder.itemView.setOnClickListener {
// Afficher la popup
PlantPopup(this, currentPlant).show()
}
}
override fun getItemCount(): Int = plantList.size
} | 23 | JavaScript | 0 | 0 | b93f732d23e45aecc71189f42194f8be3210fb13 | 2,426 | coding-challenges | MIT License |
src/test/kotlin/dev/ise/ApplicationTest.kt | GalievDev | 831,853,525 | false | {"Kotlin": 50942} | package dev.ise
//const val TEST_IMAGE_BYTE_CODE = "<KEY>AAB9+SUR<KEY>AAAAwaielBwAAAADeTuADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAAAhD4AAAAEIDABwAAgAAEPgAAAAQg8AEAACAAgQ8AAAABCHwAAAAIQOADAABAAAIfAAAA<KEY>3<KEY>Ip/BMvl0ucZYAQEPgBHc39/X3qEwVqtVq7Oe6Xr6+vSI4Tn3XuAcXhXegAApqFpmtT3fekxBqvv+7RardKHDx+KzdC2beq67l8PGhaLRZrP54M9PX02m6WLiwu3EhzI5eWld+8BRkLgA3AUU773/rl2u11qmuao7zo/Xln4o2sLH89NODs7SxcXF4Pcqn15eZm+fv3qIdKezWYzq/cAIyLwATi4zWYjvJ5pvV6nxWJx8BXTnHO6u7t70bv/u90u7Xa7dHZ2lq6vrwe1on9ycpKur6/T7e1t6VFC8foDwLgM5zczACHlnNN2uy09xmjknNOXL18O+md0XZc+ffr06oP9drtd+vTpU+q6bs+Tvc1isUgXFxelxwjj8vJykLs1APg+gQ/AQdV17fC4F+q67mCvNLRtm25vb9/8Nck5p9vb28FF/tXVVZrP56XHGL3FYmFrPsAICXwADsbq/etVVbX3q/OaptlL3D/KOafVarWXj7VPHz58GNTrA2NzcnKS/vvf/5YeA4BX8NsPgIOpqsrq/Rvs8+q8pmkOEuOH3G3wWrPZTKC+0snJSbq5ufGABGCk/PQG4CD6vndt2Rs9Xp33VoeK+0fb7XZwD3IWi4UD4l7BKw4A4ybwATiIoa3qjtXjyfWvVdf1wbfR55wH+TBnuVyK/Be4vr4+6hWNAOyfwAdg7/q+/+G96rzMarV61TWDq9UqrdfrA0z0b9vtdpBXIYr85xH3ADEIfAD2bogHr43Zaw6zW61WR33IknMe7K4Nkf9j4h4gDoEPwF61bbv309/5/fP63IA+dtw/appmkKv4KYn8p5ycnKQPHz6Ie4BABD4Ae1VVVekRwqqq6of3zj+u9Jd8PWKoq/gp/R75Hz9+dEJ8+v2mgZubm3R2dlZ6FAD2yG84APbG6v3hffny5ckT63PO6fb2tvjZB03TDPp7YD6fp48fP076pPjFYjH5zwFAVAIfgL051oFuU9b3/b8+z49x/6PV/WMa+i6O2WyWPn78mC4uLkqPcnSXl5fuuQcIzE93APaiaZrBBGZ0TdP8eXXe0OI+pfHs5Li6uko3NzdpNpuVHuXgHncuvH//vvQoAByQwAdgL4b87nVEq9UqdV03uLh/NPRV/EeP29Ujr+ZfXl7akg8wEe9KDwDA+A359PSocs7p8+fPpcf4rrZt0263G8UhbicnJ+nq6iotl8u0Xq9HsfvgOc7OztJ//vOfSexQAOB3VvABeJOcs3fvedL9/X3pEV5kPp+nm5ubdHNzkxaLRelxXm2xWKSbm5v04cMHcQ8wMVbwAXiTuq6fPNUd+r5PTdOM7p71xWKRFotFats2VVU1mhX9s7OzdHFxMeqHEwC8jcAH4NVyzmm73ZYegwHbbDajC/xHj6Hf932q6zo1TTO4h1mz2Swtl8v066+/Wq0HQOAD8HpW7/mZvu/TZrMZ9ents9ksXV1dpaurq7Tb7dLXr1/Tbrcr9r1/cnKSzs7O0vn5+SjOOADgeAQ+AK/S973Ve55lu92mi4uLEHevn52d/RnVj9cBPjw8HHwb/2KxSKenp+n8/Nxp+AB8l8AH4FU2m43Ve54l55zquh71Kv5THrfwP+q6LnVdl759+5YeHh5SSunF4f/48U5PT9O7d+/SfD4X9AA8m8AH4MUeD0+D54q0iv89P4vx78W+Q/EA2BeBD8CLbTab0iMwMjnnVFVVurq6Kj1KMUIegEOL+xgdgINo29bqPa9S13Xq+770GAAQlsAH4EWqqio9AiNm9wcAHI7AB+DZHk8Nh9dqmsYqPgAciMAH4Nms3rMPq9Wq9AgAEJLAB+BZdrud1Xv2wk4QADgMgQ/As9zf35cegUDsBgGA/RP4APyU96bZN6v4ALB/Ah+An3LyOYewXq9LjwAAoQh8AH5os9lYvecguq5LTdOUHgMAwhD4AHxXzjltt9vSYxCY3SEAsD8CH4Dvqus65ZxLj0Fgfd9bxQeAPRH4ADzJ6j3HstlsPEgCgD0Q+AA8qaoq0cVR9H2f6rouPQYAjJ7AB+BfBBfHtt1uPVACgDcS+AD8i4PPOLacs4dKAPBGAh+Av3HoGaVst1tXMgLAGwh8AP5mtVqVHoGJyjnbPQIAbyDwAfhT27apbdvSYzBhTdNYx<KEY>Am<KEY>ACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAIQ+AAAABCAwAcAAIAABD4AAAAEIPABAAAgAIEPAAAAAQh8AAAACEDgAwAAQAACHwAAAAL4P5r8eli1KhNuAAAAAElFTkSuQmCC"
class ApplicationTest {
/* @Test
fun testClothesGetAll() = testApplication {
application {
install(ContentNegotiation) {
json(
contentType = ContentType.Application.Json,
json = Json {
prettyPrint = true
ignoreUnknownKeys = true
}
)
}
configureRouting()
}
client.get("/api/v1/clothes").apply {
println(status)
assertEquals(HttpStatusCode.OK, status)
}
}
@Test
fun testClothesGetById() = testApplication {
application {
install(ContentNegotiation) {
json(
contentType = ContentType.Application.Json,
json = Json {
prettyPrint = true
ignoreUnknownKeys = true
}
)
}
configureRouting()
}
client.get("/api/v1/clothes/1").apply {
assertEquals(HttpStatusCode.OK, status)
}
}
@Test
fun testClothesPost() = testApplication {
application {
install(ContentNegotiation) {
json(
contentType = ContentType.Application.Json,
json = Json {
prettyPrint = true
ignoreUnknownKeys = true
}
)
}
configureRouting()
}
createClient {
install(ClientContentNegotiation) {
json(
contentType = ContentType.Application.Json,
json = Json {
prettyPrint = true
ignoreUnknownKeys = true
}
)
}
}.post("/api/v1/clothes") {
contentType(ContentType.Application.Json)
setBody(
ClothRequest("TEST_CLOTH", "TEST_LINK", "TEST_DESCRIPTION",
ClothType.TOP, TEST_IMAGE_BYTE_CODE)
)
}.apply {
assertEquals(HttpStatusCode.OK, status)
}
}
// @Test
// fun testClothesDeleteById() {
// TODO("Lack of backend functionality")
//
// }
@Test
fun testOutfitsGetAll() = testApplication {
application {
install(ContentNegotiation) {
json(
contentType = ContentType.Application.Json,
json = Json {
prettyPrint = true
ignoreUnknownKeys = true
}
)
}
configureRouting()
}
client.get("/api/v1/outfits").apply {
assertEquals(HttpStatusCode.OK, status)
}
}
@Test
fun testOutfitsGetById() = testApplication {
application {
install(ContentNegotiation) {
json(
contentType = ContentType.Application.Json,
json = Json {
prettyPrint = true
ignoreUnknownKeys = true
}
)
}
configureRouting()
}
client.get("/api/v1/outfits/1").apply {
assertEquals(HttpStatusCode.OK, status)
}
}
@Test
fun testOutfitsPost() = testApplication {
application {
install(ContentNegotiation) {
json(
contentType = ContentType.Application.Json,
json = Json {
prettyPrint = true
ignoreUnknownKeys = true
}
)
}
configureRouting()
}
createClient {
install(ClientContentNegotiation) {
json(
contentType = ContentType.Application.Json,
json = Json {
prettyPrint = true
ignoreUnknownKeys = true
}
)
}
}.post("/api/v1/outfits") {
contentType(ContentType.Application.Json)
setBody(
Outfit(name = "TEST_OUTFIT", description = "TEST_DESCRIPTION", image_id = 1, clothes = listOf(2, 3))
)
}.apply {
assertEquals(HttpStatusCode.OK, status)
}
}
// @Test
// fun testOutfitsDeleteDyId() {
// TODO("Lack of backend functionality")
// }
@Test
fun testCapsulesGetAll() = testApplication {
application {
install(ContentNegotiation) {
json(
contentType = ContentType.Application.Json,
json = Json {
prettyPrint = true
ignoreUnknownKeys = true
}
)
}
configureRouting()
}
client.get("/api/v1/capsules").apply {
assertEquals(HttpStatusCode.OK, status)
}
}
@Test
fun testCapsulesGetById() = testApplication {
application {
install(ContentNegotiation) {
json(
contentType = ContentType.Application.Json,
json = Json {
prettyPrint = true
ignoreUnknownKeys = true
}
)
}
configureRouting()
}
client.get("/api/v1/capsules/1").apply {
assertEquals(HttpStatusCode.OK, status)
}
}
@Test
fun testCapsulesPost() = testApplication {
application {
install(ContentNegotiation) {
json(
contentType = ContentType.Application.Json,
json = Json {
prettyPrint = true
ignoreUnknownKeys = true
}
)
}
configureRouting()
}
createClient {
install(ClientContentNegotiation) {
json(
contentType = ContentType.Application.Json,
json = Json {
prettyPrint = true
ignoreUnknownKeys = true
}
)
}
}.post("/api/v1/capsules") {
contentType(ContentType.Application.Json)
setBody(
Capsule(name = "TEST_CAPSULE", description = "TEST_DESCRIPTION", image_id = 1, outfits = listOf(1))
)
}.apply {
assertEquals(HttpStatusCode.OK, status)
}
}
// @Test
// fun testCapsulesDeleteById() {
// TODO("Lack of backend functionality")
// }*/
}
| 0 | Kotlin | 0 | 0 | 8317d6183f5fc2fba8b371f2bca87298707fe233 | 12,932 | shopping-map-backend | MIT License |
muslim_prayer/src/main/java/cc/fastcv/muslim_prayer/convention/ConstantConvention.kt | fastcv-cc | 721,493,786 | false | {"Kotlin": 110182, "Java": 30156} | package cc.fastcv.muslim_prayer.convention
import android.content.Context
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import java.io.BufferedReader
import java.io.InputStreamReader
import java.util.Calendar
/**
* 固定惯例模型
*/
class ConstantConvention(
name: String,
desc: String, private val jsonFileName: String
) : AbsConvention(name, desc) {
override val type: ConventionType = ConventionType.CONSTANT
//新增固定惯例
private val format = object : TypeToken<Map<String, MutableList<String>>>() {}.type
//新增固定惯例
private lateinit var data: Map<String, MutableList<String>>
fun initConventionInfo(context: Context) {
data = Gson().fromJson(loadJsonStr(context), format)
}
/**
* 解析固定惯例数据
*/
private fun loadJsonStr(context: Context): String {
val stringBuffer = StringBuffer()
val bufferedReader = BufferedReader(InputStreamReader(context.assets.open(jsonFileName)))
var line: String?
while (bufferedReader.readLine().also { line = it } != null) {
stringBuffer.append(line)
}
return stringBuffer.toString()
}
fun getPrayerTimeList(date: Calendar): List<String>? {
val day = date[Calendar.DAY_OF_MONTH]
val month = date[Calendar.MONTH] + 1
return data["$month-$day"]
}
} | 0 | Kotlin | 0 | 0 | 6d13279200d3bf69c15228fc8ad2b50b3cb6fadd | 1,350 | AndroidLibs | Apache License 2.0 |
app/src/main/java/com/lnight/videochat/connect/ConnectScreen.kt | EvgenyPlaksin | 845,218,731 | false | {"Kotlin": 19152} | package com.lnight.videochat.connect
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
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.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.lnight.videochat.ui.theme.VideoChatTheme
@Composable
fun ConnectScreen(
state: ConnectState,
onAction: (ConnectAction) -> Unit
) {
Column(
modifier = Modifier
.fillMaxSize()
.padding(16.dp)
) {
Text(
text = "Choose a name",
fontSize = 18.sp
)
Spacer(modifier = Modifier.height(16.dp))
TextField(
value = state.name,
onValueChange = {
onAction(ConnectAction.OnNameChange(it))
},
placeholder = {
Text(text = "Name")
},
modifier = Modifier
.fillMaxWidth()
)
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = {
onAction(ConnectAction.OnConnectClick)
},
modifier = Modifier.align(Alignment.End)
) {
Text(text = "Connect")
}
Spacer(modifier = Modifier.height(16.dp))
if(state.errorMessage != null) {
Text(
text = state.errorMessage,
color = MaterialTheme.colorScheme.error
)
}
}
}
@Preview(showBackground = true)
@Composable
private fun ConnectScreenPreview() {
VideoChatTheme {
ConnectScreen(
state = ConnectState(
errorMessage = "Hello world"
),
onAction = {}
)
}
} | 0 | Kotlin | 0 | 0 | f7e8ce3b2d5b3189d3be173fe66bf6bb9c81fb5d | 2,225 | VideoChat | MIT License |
app/src/main/java/com/dede/nativetools/netspeed/NetSpeedPreferences.kt | hushenghao | 242,718,110 | false | null | package com.dede.nativetools.netspeed
import android.graphics.Typeface
import com.dede.nativetools.netspeed.NetSpeedConfiguration.Companion.defaultConfiguration
import com.dede.nativetools.netspeed.typeface.TypefaceGetter
import com.dede.nativetools.util.get
import com.dede.nativetools.util.globalPreferences
import com.dede.nativetools.util.set
/**
* NetSpeed配置
*
* @author hsh
* @since 2021/8/10 2:15 下午
*/
object NetSpeedPreferences {
const val KEY_NET_SPEED_STATUS = "net_speed_status"
const val KEY_NET_SPEED_INTERVAL = "net_speed_interval"
const val KEY_NET_SPEED_NOTIFY_CLICKABLE = "net_speed_notify_clickable"
const val KEY_NET_SPEED_MODE = "net_speed_mode_1"
const val KEY_NET_SPEED_QUICK_CLOSEABLE = "net_speed_notify_quick_closeable"
const val KEY_NET_SPEED_USAGE = "net_speed_usage"
const val KEY_NET_SPEED_USAGE_JUST_MOBILE = "net_speed_usage_just_mobile"
const val KEY_NET_SPEED_HIDE_LOCK_NOTIFICATION = "net_speed_locked_hide"
const val KEY_NET_SPEED_HIDE_NOTIFICATION = "net_speed_hide_notification"
const val KEY_NET_SPEED_HIDE_THRESHOLD = "net_speed_hide_threshold"
const val KEY_NET_SPEED_TEXT_STYLE = "net_speed_text_style"
const val KEY_NET_SPEED_FONT = "net_speed_font"
const val KEY_NET_SPEED_VERTICAL_OFFSET = "net_speed_vertical_offset"
const val KEY_NET_SPEED_HORIZONTAL_OFFSET = "net_speed_horizontal_offset"
const val KEY_NET_SPEED_RELATIVE_RATIO = "net_speed_relative_ratio"
const val KEY_NET_SPEED_RELATIVE_DISTANCE = "net_speed_relative_distance"
const val KEY_NET_SPEED_TEXT_SCALE = "net_speed_text_scale"
const val KEY_NET_SPEED_HORIZONTAL_SCALE = "net_speed_horizontal_scale"
private const val KEY_NET_SPEED_AUTO_START = "net_speed_auto_start"
private const val KEY_NOTIFICATION_DONT_ASK = "notification_dont_ask"
const val DEFAULT_INTERVAL = 1000
const val DEFAULT_TEXT_STYLE = Typeface.BOLD
const val DEFAULT_FONT = TypefaceGetter.FONT_NORMAL
var status: Boolean
get() = globalPreferences.get(KEY_NET_SPEED_STATUS, false)
set(value) = globalPreferences.set(KEY_NET_SPEED_STATUS, value)
val textStyle: Int
get() = globalPreferences.get(KEY_NET_SPEED_TEXT_STYLE, DEFAULT_TEXT_STYLE.toString())
.toIntOrNull() ?: defaultConfiguration.textStyle
val font: String
get() = globalPreferences.get(KEY_NET_SPEED_FONT, defaultConfiguration.font)
val verticalOffset: Float
get() = globalPreferences.get(
KEY_NET_SPEED_VERTICAL_OFFSET,
defaultConfiguration.verticalOffset
)
val horizontalOffset: Float
get() = globalPreferences.get(
KEY_NET_SPEED_HORIZONTAL_OFFSET,
defaultConfiguration.horizontalOffset
)
val horizontalScale: Float
get() = globalPreferences.get(
KEY_NET_SPEED_HORIZONTAL_SCALE,
defaultConfiguration.horizontalScale
)
val relativeRatio: Float
get() = globalPreferences.get(
KEY_NET_SPEED_RELATIVE_RATIO,
defaultConfiguration.relativeRatio
)
val relativeDistance: Float
get() = globalPreferences.get(
KEY_NET_SPEED_RELATIVE_DISTANCE,
defaultConfiguration.relativeDistance
)
val textScale: Float
get() = globalPreferences.get(KEY_NET_SPEED_TEXT_SCALE, defaultConfiguration.textScale)
val autoStart: Boolean
get() = globalPreferences.get(KEY_NET_SPEED_AUTO_START, false)
var dontAskNotify: Boolean
get() = globalPreferences.get(KEY_NOTIFICATION_DONT_ASK, false)
set(value) = globalPreferences.set(KEY_NOTIFICATION_DONT_ASK, value)
val interval: Int
get() = globalPreferences.get(
KEY_NET_SPEED_INTERVAL,
DEFAULT_INTERVAL.toString()
).toIntOrNull() ?: defaultConfiguration.interval
val mode: String
get() = globalPreferences.get(KEY_NET_SPEED_MODE, defaultConfiguration.mode)
val notifyClickable: Boolean
get() = globalPreferences.get(
KEY_NET_SPEED_NOTIFY_CLICKABLE,
defaultConfiguration.notifyClickable
)
val hideThreshold: Long
get() = globalPreferences.get(
KEY_NET_SPEED_HIDE_THRESHOLD,
defaultConfiguration.hideThreshold.toString()
).toLongOrNull() ?: defaultConfiguration.hideThreshold
val quickCloseable: Boolean
get() = globalPreferences.get(
KEY_NET_SPEED_QUICK_CLOSEABLE,
defaultConfiguration.quickCloseable
)
val usage: Boolean
get() = globalPreferences.get(KEY_NET_SPEED_USAGE, defaultConfiguration.usage)
val justMobileUsage: Boolean
get() = globalPreferences.get(
KEY_NET_SPEED_USAGE_JUST_MOBILE,
defaultConfiguration.justMobileUsage
)
val hideNotification: Boolean
get() = globalPreferences.get(
KEY_NET_SPEED_HIDE_NOTIFICATION,
defaultConfiguration.hideNotification
)
val hideLockNotification: Boolean
get() = globalPreferences.get(
KEY_NET_SPEED_HIDE_LOCK_NOTIFICATION,
defaultConfiguration.hideLockNotification
)
} | 0 | Kotlin | 1 | 5 | f7550e37d20efe555914c0c2428a048b131a89aa | 5,246 | NativeTools | Apache License 2.0 |
src/test/kotlin/com/javax0/axsessgard/util/JwtTestUtil.kt | serverless-u | 830,570,227 | false | {"Kotlin": 52922, "HTML": 3863, "Shell": 407} | package com.javax0.axsessgard.util
import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.javax0.axsessgard.utils.AXSG_CONFIG_DIR
import com.javax0.axsessgard.utils.AXSG_INIT_DATA
import com.javax0.axsessgard.utils.AlgorithmFactory
import java.security.KeyFactory
import java.security.spec.PKCS8EncodedKeySpec
import java.security.spec.X509EncodedKeySpec
import java.time.Instant
import java.util.*
class JwtTestUtil {
companion object {
private lateinit var algorithm: Algorithm
private lateinit var issuer1Algorithm: Algorithm
private lateinit var issuer2Algorithm: Algorithm
fun setup() {
val publicKeyPem =
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEzsLb427Ewa4dWp51L6ZcVrPpEYBzT6vcQaCmmR6BhmN1EoFxzFo3NiLmTh9CyonldHgI05ns8D54sn4jPnRJew=="
val privateKeyPem =
"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgncREArQ4aGEbETfG4Xnco73k3Z7nCYhDzfPUrpa5uJahRANCAATOwtvjbsTBrh1annUvplxWs+kRgHNPq9xBoKaZHoGGY3USgXHMWjc2IuZOH0LKieV0eAjTmezwPniyfiM+dEl7"
val keyFactory = KeyFactory.getInstance("EC")
val publicKey = keyFactory.generatePublic(X509EncodedKeySpec(Base64.getDecoder().decode(publicKeyPem)))
val privateKey = keyFactory.generatePrivate(PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKeyPem)))
algorithm = AlgorithmFactory.createAlgorithm("ECDSA256", publicKey, privateKey)
// set the environment variables (well, system properties)
System.setProperty("AXSG_PUBLIC_KEY", publicKeyPem)
System.setProperty("AXSG_PRIVATE_KEY", privateKeyPem)
System.setProperty("AXSG_ALGO_TYPE", "EC")
System.setProperty("AXSG_ALGO", "ECDSA256")
System.setProperty(AXSG_CONFIG_DIR, "src/test/resources/config")
System.setProperty(AXSG_INIT_DATA, "src/test/resources/sample_data.txt")
val issuer1PublicKeyPem =
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEo2SGwd5psDsfx1gwirzZP+udK1FlWl7t3Ho7tnZqJ+96oOgW/w3nKrXGU/SYbqOgdpB8D8A+Y4MqfCjmstOLFg=="
val issuer1PrivateKeyPem =
"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQg9UPbdfQc/poGRgcgq6tyTsEEDmwP7SpCtQjcNFi2QXShRANCAASjZIbB3mmwOx/HWDCKvNk/650rUWVaXu3ceju2dmon73qg6Bb/DecqtcZT9Jhuo6B2kHwPwD5jgyp8KOay04sW"
val issues1PublicKey =
keyFactory.generatePublic(X509EncodedKeySpec(Base64.getDecoder().decode(issuer1PublicKeyPem)))
val issuer1PrivateKey =
keyFactory.generatePrivate(PKCS8EncodedKeySpec(Base64.getDecoder().decode(issuer1PrivateKeyPem)))
issuer1Algorithm = AlgorithmFactory.createAlgorithm("ECDSA256", issues1PublicKey, issuer1PrivateKey)
val issuer2PublicKeyPem =
"MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEo2SGwd5psDsfx1gwirzZP+udK1FlWl7t3Ho7tnZqJ+96oOgW/w3nKrXGU/SYbqOgdpB8D8A+Y4MqfCjmstOLFg=="
val issuer2PrivateKeyPem =
"MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgbszCZsYgvbsn03t/T1vvyxQrJBo5ikxBghTTrkKT8BehRANCAAQsbsP0zG0dVd9U/8L9GsJ1V0+uqI6JCi+BwuDPI1sdkGxfF/IUmFhNY1IefuoIXV6ets9HXh7GFiHUGFc9UpbE"
val issues2PublicKey =
keyFactory.generatePublic(X509EncodedKeySpec(Base64.getDecoder().decode(issuer2PublicKeyPem)))
val issuer2PrivateKey =
keyFactory.generatePrivate(PKCS8EncodedKeySpec(Base64.getDecoder().decode(issuer2PrivateKeyPem)))
issuer2Algorithm = AlgorithmFactory.createAlgorithm("ECDSA256", issues2PublicKey, issuer2PrivateKey)
}
fun createTestToken(issuer: String, subject: String, policy: String, roles: List<String>): String {
if( issuer == "issuer1" ){
return JWT.create()
.withIssuer(issuer)
.withSubject(subject)
.withClaim("policy", policy)
.withClaim("roles", roles)
.withIssuedAt(Instant.now())
.withExpiresAt(Instant.now().plusSeconds(3600))
.sign(issuer1Algorithm)
} else {
return JWT.create()
.withIssuer(issuer)
.withSubject(subject)
.withClaim("policy", policy)
.withClaim("roles", roles)
.withIssuedAt(Instant.now())
.withExpiresAt(Instant.now().plusSeconds(3600))
.sign(issuer2Algorithm)
}
}
}
} | 0 | Kotlin | 0 | 0 | 9806c0f2ed4f2d8eab019d876a7e3bcd71806bf1 | 4,525 | AxsessGard | Apache License 2.0 |
androidwalletdemo/src/main/java/com/lightspark/androidwalletdemo/di/StorageModule.kt | lightsparkdev | 590,703,408 | false | {"Kotlin": 1660352, "Java": 34937, "Dockerfile": 1719, "Shell": 490} | package com.lightspark.androidwalletdemo.di
import android.content.Context
import com.lightspark.androidwalletdemo.auth.CredentialsStore
import com.lightspark.androidwalletdemo.settings.DefaultPrefsStore
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
@Module
@InstallIn(SingletonComponent::class)
class StorageModule {
@Provides
@Singleton
fun providePrefsStore(@ApplicationContext appContext: Context): DefaultPrefsStore =
DefaultPrefsStore(appContext)
@Provides
@Singleton
fun provideCredentialsStore(@ApplicationContext appContext: Context): CredentialsStore =
CredentialsStore(appContext)
}
| 0 | Kotlin | 1 | 4 | 9a954d479d28fc69a9f4a49aa52af1bd14cdd630 | 800 | kotlin-sdk | Apache License 2.0 |
platform/backend/core/src/main/kotlin/io/hamal/core/req/handler/func/CreateFuncHandler.kt | hamal-io | 622,870,037 | false | {"Kotlin": 1678862, "C": 1398401, "TypeScript": 47224, "Lua": 41508, "C++": 40651, "Makefile": 11728, "Java": 7564, "CMake": 2881, "JavaScript": 1532, "HTML": 694, "Shell": 449, "CSS": 118} | package io.hamal.core.req.handler.func
import io.hamal.core.event.PlatformEventEmitter
import io.hamal.core.req.ReqHandler
import io.hamal.core.req.handler.cmdId
import io.hamal.lib.common.domain.CmdId
import io.hamal.lib.domain.vo.NamespaceName
import io.hamal.repository.api.CodeCmdRepository
import io.hamal.repository.api.Func
import io.hamal.repository.api.FuncCmdRepository
import io.hamal.repository.api.FuncCmdRepository.CreateCmd
import io.hamal.repository.api.NamespaceQueryRepository
import io.hamal.repository.api.event.FuncCreatedEvent
import io.hamal.repository.api.submitted_req.SubmittedCreateFuncReq
import org.springframework.stereotype.Component
@Component
class CreateFuncHandler(
val codeCmdRepository: CodeCmdRepository,
val funcCmdRepository: FuncCmdRepository,
val eventEmitter: PlatformEventEmitter,
val namespaceQueryRepository: NamespaceQueryRepository
) : ReqHandler<SubmittedCreateFuncReq>(SubmittedCreateFuncReq::class) {
override fun invoke(req: SubmittedCreateFuncReq) {
createFunc(req).also { emitEvent(req.cmdId(), it) }
}
}
private fun CreateFuncHandler.createFunc(req: SubmittedCreateFuncReq): Func {
val code = codeCmdRepository.create(
CodeCmdRepository.CreateCmd(
id = req.cmdId(),
codeId = req.codeId,
groupId = req.groupId,
value = req.code
)
)
return funcCmdRepository.create(
CreateCmd(
id = req.cmdId(),
funcId = req.id,
groupId = req.groupId,
namespaceId = req.namespaceId ?: namespaceQueryRepository.get(NamespaceName("hamal")).id,
name = req.name,
inputs = req.inputs,
codeId = code.id,
codeVersion = code.version
)
)
}
private fun CreateFuncHandler.emitEvent(cmdId: CmdId, func: Func) {
eventEmitter.emit(cmdId, FuncCreatedEvent(func))
}
| 6 | Kotlin | 0 | 0 | fd06bf799f18db2d425b7084abf15b741fa9878e | 1,918 | hamal | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/sublimetech/supervisor/data/model/youtAndWoman/StudentDto.kt | Xget7 | 675,440,130 | false | null | package com.sublimetech.supervisor.data.model.youtAndWoman
data class StudentDto(
val id: String? = null,
val groupId: String? = null,
val name: String = "",
val documentId: String = "",
val age: Int? = null,
val gender: String = ""
) {
fun toMap(): HashMap<String, Any> {
val map = HashMap<String, Any>()
map["id"] = id.orEmpty()
map["groupId"] = groupId.orEmpty()
map["name"] = name
map["documentId"] = documentId
map["age"] = age ?: -1
map["gender"] = gender
return map
}
}
| 0 | Kotlin | 0 | 0 | b86ee2e9a33ec8ee6551c4284b0c0c03c80f0038 | 574 | Data-Collector | MIT License |
app/src/main/java/io/github/akiomik/seiun/repository/TimelineRepository.kt | akiomik | 609,540,386 | false | null | package io.github.akiomik.seiun.repository
import android.util.Log
import com.slack.eithernet.ApiResult
import com.slack.eithernet.response
import io.github.akiomik.seiun.SeiunApplication
import io.github.akiomik.seiun.model.ISession
import io.github.akiomik.seiun.model.app.bsky.blob.UploadBlobOutput
import io.github.akiomik.seiun.model.app.bsky.embed.Image
import io.github.akiomik.seiun.model.type.Image as ImageType
import io.github.akiomik.seiun.model.app.bsky.feed.*
import io.github.akiomik.seiun.model.com.atproto.repo.CreateRecordInput
import io.github.akiomik.seiun.model.com.atproto.repo.CreateRecordOutput
import io.github.akiomik.seiun.model.com.atproto.repo.DeleteRecordInput
import io.github.akiomik.seiun.model.com.atproto.repo.StrongRef
import io.github.akiomik.seiun.service.AtpService
import io.github.akiomik.seiun.service.UnauthorizedException
import okhttp3.RequestBody.Companion.toRequestBody
import retrofit2.HttpException
import java.time.Instant
class TimelineRepository(private val atpService: AtpService) {
suspend fun getTimeline(session: ISession, before: String? = null): Timeline {
Log.d(SeiunApplication.TAG, "Get timeline: before = $before")
return when (val result =
atpService.getTimeline("Bearer ${session.accessJwt}", before = before)) {
is ApiResult.Success -> result.value
is ApiResult.Failure -> when (result) {
is ApiResult.Failure.HttpFailure -> {
if (result.code == 401) {
throw UnauthorizedException("Unauthorized: ${result.code} (${result.error})")
} else {
throw IllegalStateException("HttpError: ${result.code} (${result.error})")
}
}
else -> throw IllegalStateException("ApiResult.Failure: ${result.response()}")
}
}
}
suspend fun upvote(session: ISession, subject: StrongRef): SetVoteOutput {
Log.d(SeiunApplication.TAG, "Upvote post: uri = ${subject.uri}, cid = ${subject.cid}")
val body = SetVoteInput(subject = subject, direction = VoteDirection.up)
when (val result =
atpService.setVote(authorization = "Bearer ${session.accessJwt}", body = body)) {
is ApiResult.Success -> return result.value
is ApiResult.Failure -> when (result) {
is ApiResult.Failure.HttpFailure -> {
if (result.code == 401) {
throw UnauthorizedException("Unauthorized: ${result.code} (${result.error})")
} else {
throw IllegalStateException("HttpError: ${result.code} (${result.error})")
}
}
else -> throw IllegalStateException("ApiResult.Failure: ${result.response()}")
}
}
}
suspend fun cancelVote(session: ISession, subject: StrongRef) {
Log.d(SeiunApplication.TAG, "Cancel vote post: uri = ${subject.uri}, cid = ${subject.cid}")
val body = SetVoteInput(subject = subject, direction = VoteDirection.none)
when (val result =
atpService.setVote(authorization = "Bearer ${session.accessJwt}", body = body)) {
is ApiResult.Success -> {}
is ApiResult.Failure -> when (result) {
is ApiResult.Failure.HttpFailure -> {
if (result.code == 401) {
throw UnauthorizedException("Unauthorized: ${result.code} (${result.error})")
} else {
throw IllegalStateException("HttpError: ${result.code} (${result.error})")
}
}
else -> throw IllegalStateException("ApiResult.Failure: ${result.response()}")
}
}
}
suspend fun repost(session: ISession, subject: StrongRef): CreateRecordOutput {
Log.d(SeiunApplication.TAG, "Cancel repost: uri = ${subject.uri}, cid = ${subject.cid}")
val createdAt = Instant.now().toString()
val record = Repost(subject = subject, createdAt)
val body = CreateRecordInput(
did = session.did,
record = record,
collection = "app.bsky.feed.repost"
)
when (val result =
atpService.repost(authorization = "Bearer ${session.accessJwt}", body = body)) {
is ApiResult.Success -> return result.value
is ApiResult.Failure -> when (result) {
is ApiResult.Failure.HttpFailure -> {
if (result.code == 401) {
throw UnauthorizedException("Unauthorized: ${result.code} (${result.error})")
} else {
throw IllegalStateException("HttpError: ${result.code} (${result.error})")
}
}
else -> throw IllegalStateException("ApiResult.Failure: ${result.response()}")
}
}
}
suspend fun cancelRepost(session: ISession, uri: String) {
Log.d(SeiunApplication.TAG, "Cancel repost: $uri")
val rkey = uri.split('/').last()
val body =
DeleteRecordInput(did = session.did, rkey = rkey, collection = "app.bsky.feed.repost")
try {
atpService.deleteRecord(authorization = "Bearer ${session.accessJwt}", body = body)
} catch (e: HttpException) {
if (e.code() == 401) {
throw UnauthorizedException("Unauthorized: ${e.code()} (${e.message()})")
} else {
throw IllegalStateException("HttpError: ${e.code()} (${e.message()})")
}
}
}
suspend fun createPost(
session: ISession,
content: String,
imageCid: String?,
imageMimeType: String?
) {
Log.d(SeiunApplication.TAG, "Create a post: content = $content")
val createdAt = Instant.now().toString()
val embed = if (imageCid != null && imageMimeType != null) {
val image = Image(image = ImageType(imageCid, imageMimeType), alt = "")
ImagesOrExternal(images = listOf(image), type = "app.bsky.embed.images")
} else {
null
}
val record = Post(text = content, createdAt = createdAt, embed = embed)
val body =
CreateRecordInput(did = session.did, record = record, collection = "app.bsky.feed.post")
when (val result =
atpService.createPost(authorization = "Bearer ${session.accessJwt}", body = body)) {
is ApiResult.Success -> {}
is ApiResult.Failure -> when (result) {
is ApiResult.Failure.HttpFailure -> {
if (result.code == 401) {
throw UnauthorizedException("Unauthorized: ${result.code} (${result.error})")
} else {
throw IllegalStateException("HttpError: ${result.code} (${result.error})")
}
}
else -> throw IllegalStateException("ApiResult.Failure: ${result.response()}")
}
}
}
suspend fun createReply(
session: ISession,
content: String,
to: PostReplyRef,
imageCid: String?,
imageMimeType: String?
) {
Log.d(SeiunApplication.TAG, "Create a reply: content = $content, to = $to")
val createdAt = Instant.now().toString()
val embed = if (imageCid != null && imageMimeType != null) {
val image = Image(image = ImageType(imageCid, imageMimeType), alt = "app.bsky.feed.post")
ImagesOrExternal(images = listOf(image), type = "app.bsky.embed.images")
} else {
null
}
val record = Post(text = content, createdAt = createdAt, reply = to, embed = embed)
val body = CreateRecordInput(did = session.did, record = record, collection = "")
when (val result =
atpService.createPost(authorization = "Bearer ${session.accessJwt}", body = body)) {
is ApiResult.Success -> {}
is ApiResult.Failure -> when (result) {
is ApiResult.Failure.HttpFailure -> {
if (result.code == 401) {
throw UnauthorizedException("Unauthorized: ${result.code} (${result.error})")
} else {
throw IllegalStateException("HttpError: ${result.code} (${result.error})")
}
}
else -> throw IllegalStateException("ApiResult.Failure: ${result.response()}")
}
}
}
suspend fun deletePost(session: ISession, feedViewPost: FeedViewPost) {
Log.d(SeiunApplication.TAG, "Delete post: uri = ${feedViewPost.post.uri}")
val rkey = feedViewPost.post.uri.split('/').last()
val body =
DeleteRecordInput(did = session.did, collection = "app.bsky.feed.post", rkey = rkey)
try {
atpService.deleteRecord("Bearer ${session.accessJwt}", body)
} catch (e: HttpException) {
if (e.code() == 401) {
throw UnauthorizedException("Unauthorized: ${e.code()} (${e.message()})")
} else {
throw IllegalStateException("HttpError: ${e.code()} (${e.message()})")
}
}
}
suspend fun uploadImage(
session: ISession,
image: ByteArray,
mimeType: String,
): UploadBlobOutput {
when (val result =
atpService.uploadBlob(
authorization = "Bearer ${session.accessJwt}",
contentType = mimeType,
body = image.toRequestBody(),
)) {
is ApiResult.Success -> return result.value
is ApiResult.Failure -> when (result) {
is ApiResult.Failure.HttpFailure -> {
if (result.code == 401) {
throw UnauthorizedException("Unauthorized: ${result.code} (${result.error})")
} else {
throw IllegalStateException("HttpError: ${result.code} (${result.error})")
}
}
else -> throw IllegalStateException("ApiResult.Failure: ${result.response()}")
}
}
}
} | 3 | Kotlin | 3 | 17 | 40656537252ef5208638329349c3428d751139ea | 10,367 | seiun | Apache License 2.0 |
cache/src/main/java/com/zlagi/cache/database/account/AccountDao.kt | Zlagi | 475,379,557 | false | {"Kotlin": 496613} | package com.zlagi.cache.database.account
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import com.zlagi.cache.model.AccountCacheModel
import kotlinx.coroutines.flow.Flow
@Dao
interface AccountDao {
@Query(
"""
SELECT * FROM account
"""
)
fun fetchAccount(): Flow<AccountCacheModel>
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun storeAccount(accountCacheModel: AccountCacheModel)
@Query(
"""
DELETE FROM account
"""
)
suspend fun deleteAccount()
}
| 0 | Kotlin | 12 | 63 | dffd07e8533c285bb5ca9de4e9676985aa0e87cc | 618 | Blogfy | Apache License 2.0 |
app/src/main/kotlin/com/github/jonathanmerritt/rxassetmanager/extensions/View.kt | JonathanMerritt | 122,155,124 | false | null | /*
* Copyright 2018 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.github.jonathanmerritt.rxassetmanager.extensions
import android.view.View
internal infix fun View.click(action: () -> Boolean) = setOnClickListener { action() }
| 0 | Kotlin | 4 | 54 | bb5d952f6a168b55e63399a17297173d6a725c06 | 805 | RxAssetManager | Apache License 2.0 |
app/src/main/java/com/sf/architecture/app/RootActivity.kt | seanfreiburg | 350,099,209 | false | null | package com.sf.architecture.app
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.ui.Modifier
import app.cash.molecule.AndroidUiDispatcher
import app.cash.molecule.launchMolecule
import com.sf.architecture.app.ui.theme.AppTheme
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.cancel
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
class RootActivity : ComponentActivity() {
private val scope = CoroutineScope(AndroidUiDispatcher.Main)
@OptIn(InternalCoroutinesApi::class)
override fun onCreate(savedInstanceState: Bundle?) {
(applicationContext as RootApplication).appComponent.inject(this)
super.onCreate(savedInstanceState)
val navigator = RealNavigator(SplashScreen)
scope.launch {
navigator.screensFlow.collect {
val events = MutableSharedFlow<ViewEvent>(0, 50)
val view = it.first as MoleculeView<ViewEvent, ViewModel>
val presenter = it.second as MoleculePresenter<ViewEvent, ViewModel>
view.setEventReceiver(events)
launch {
val models = launchMolecule {
presenter.viewModel(events = events)
}
models.collect { model ->
setContent {
AppTheme {
// A surface container using the 'background' color from the theme
Surface(modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background) {
view.Render(model)
}
}
}
}
}
}
}
}
override fun onDestroy() {
super.onDestroy()
scope.cancel()
}
}
| 0 | Kotlin | 0 | 1 | 23fe06604e276505e60277f700998fc1d20e7987 | 2,226 | androidArchitechture | MIT License |
examples/audio_classification/android/app/src/main/java/com/google/aiedge/examples/audio_classification/MainActivity.kt | google-ai-edge | 800,245,798 | false | null | /*
* Copyright 2024 The Google AI Edge Authors. All Rights Reserved.
*
* 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.aiedge.examples.audio_classification
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
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.PaddingValues
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.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material3.BottomSheetScaffold
import androidx.compose.material3.Button
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.RadioButton
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.integerArrayResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.core.content.ContextCompat
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import com.google.aiedge.examples.audio_classification.ui.ApplicationTheme
import java.util.Locale
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AudioClassificationScreen()
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AudioClassificationScreen(
viewModel: MainViewModel = viewModel(
factory = MainViewModel.getFactory(LocalContext.current.applicationContext)
)
) {
val context = LocalContext.current
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
val launcher = rememberLauncherForActivityResult(
ActivityResultContracts.RequestPermission()
) { isGranted: Boolean ->
if (isGranted) {
viewModel.startAudioClassification()
} else {
// Permission Denied
Toast.makeText(context, "Audio permission is denied", Toast.LENGTH_SHORT).show()
}
}
LaunchedEffect(key1 = uiState.errorMessage) {
if (uiState.errorMessage != null) {
Toast.makeText(
context, "${uiState.errorMessage}", Toast.LENGTH_SHORT
).show()
viewModel.errorMessageShown()
}
}
DisposableEffect(Unit) {
if (ContextCompat.checkSelfPermission(
context, android.Manifest.permission.RECORD_AUDIO
) == PackageManager.PERMISSION_GRANTED
) {
viewModel.startAudioClassification()
} else {
launcher.launch(android.Manifest.permission.RECORD_AUDIO)
}
onDispose {
viewModel.stopClassifier()
}
}
ApplicationTheme {
BottomSheetScaffold(
sheetDragHandle = {
Image(
modifier = Modifier
.size(40.dp)
.padding(top = 2.dp, bottom = 5.dp),
painter = painterResource(id = R.drawable.ic_chevron_up),
colorFilter = ColorFilter.tint(MaterialTheme.colorScheme.secondary),
contentDescription = ""
)
},
sheetPeekHeight = 70.dp,
sheetContent = {
BottomSheet(
uiState = uiState,
onModelSelected = {
viewModel.setModel(it)
},
onDelegateSelected = {
if (it == AudioClassificationHelper.Delegate.NNAPI) {
viewModel.throwError(IllegalArgumentException("Cannot use NNAPI"))
} else {
viewModel.setDelegate(it)
}
},
onMaxResultSet = {
viewModel.setMaxResults(it)
},
onThresholdSet = {
viewModel.setThreshold(it)
},
onThreadsCountSet = {
viewModel.setThreadCount(it)
},
)
}) {
ClassificationBody(uiState = uiState)
}
}
}
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Header() {
TopAppBar(
colors = TopAppBarDefaults.topAppBarColors(
containerColor = MaterialTheme.colorScheme.secondary,
),
title = {
Image(
modifier = Modifier.size(120.dp),
alignment = Alignment.CenterStart,
painter = painterResource(id = R.drawable.logo),
contentDescription = null,
)
},
)
}
@Composable
fun BottomSheet(
uiState: UiState,
modifier: Modifier = Modifier,
onModelSelected: (AudioClassificationHelper.TFLiteModel) -> Unit,
onDelegateSelected: (option: AudioClassificationHelper.Delegate) -> Unit,
onMaxResultSet: (value: Int) -> Unit,
onThresholdSet: (value: Float) -> Unit,
onThreadsCountSet: (value: Int) -> Unit,
) {
val maxResults = uiState.setting.resultCount
val threshold = uiState.setting.threshold
val threadCount = uiState.setting.threadCount
val model = uiState.setting.model
val delegate = uiState.setting.delegate
Column(modifier = modifier.padding(horizontal = 20.dp, vertical = 5.dp)) {
Row {
Text(
modifier = Modifier.weight(0.5f),
text = stringResource(id = R.string.inference_title)
)
Text(
text = stringResource(
id = R.string.inference_value,
uiState.setting.inferenceTime
)
)
}
Spacer(modifier = Modifier.height(20.dp))
ModelSelection(
model = model,
onModelSelected = onModelSelected,
)
OptionMenu(label = stringResource(id = R.string.delegate),
options = AudioClassificationHelper.Delegate.entries.map { it.name }.toList(),
currentOption = delegate.name,
onOptionSelected = {
onDelegateSelected(AudioClassificationHelper.Delegate.valueOf(it))
})
Spacer(modifier = Modifier.height(20.dp))
Spacer(modifier = Modifier.height(10.dp))
AdjustItem(
name = stringResource(id = R.string.max_result_),
value = maxResults,
onMinusClicked = {
if (maxResults > 1) {
val max = maxResults - 1
onMaxResultSet(max)
}
},
onPlusClicked = {
if (maxResults < 5) {
val max = maxResults + 1
onMaxResultSet(max)
}
},
)
AdjustItem(
name = stringResource(id = R.string.thresh_hold),
value = threshold,
onMinusClicked = {
if (threshold > 0.3f) {
val newThreshold = (threshold - 0.1f).coerceAtLeast(0.3f)
onThresholdSet(newThreshold)
}
},
onPlusClicked = {
if (threshold < 0.8f) {
val newThreshold = threshold + 0.1f.coerceAtMost(0.8f)
onThresholdSet(newThreshold)
}
},
)
AdjustItem(
name = stringResource(id = R.string.threads),
value = threadCount,
onMinusClicked = {
if (threadCount >= 2) {
val count = threadCount - 1
onThreadsCountSet(count)
}
},
onPlusClicked = {
if (threadCount < 5) {
val count = threadCount + 1
onThreadsCountSet(count)
}
},
)
}
}
@Composable
fun ClassificationBody(uiState: UiState, modifier: Modifier = Modifier) {
val primaryProgressColorList = integerArrayResource(id = R.array.colors_progress_primary)
val backgroundProgressColorList = integerArrayResource(id = R.array.colors_progress_background)
Column(modifier = modifier) {
Header()
LazyColumn(
contentPadding = PaddingValues(10.dp),
verticalArrangement = Arrangement.spacedBy(10.dp),
) {
val categories = uiState.classifications
items(count = categories.size) { index ->
val category = categories[index]
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
modifier = Modifier.weight(0.4f),
text = category.label,
fontSize = 15.sp,
fontWeight = FontWeight.Bold
)
LinearProgressIndicator(
modifier = Modifier
.weight(0.6f)
.height(25.dp)
.clip(RoundedCornerShape(7.dp)),
progress = category.score,
trackColor = Color(
backgroundProgressColorList[index % backgroundProgressColorList.size]
),
color = Color(
primaryProgressColorList[index % backgroundProgressColorList.size]
),
)
}
}
}
}
}
@Composable
fun OptionMenu(
label: String,
options: List<String>,
currentOption: String,
modifier: Modifier = Modifier,
onOptionSelected: (option: String) -> Unit,
) {
var expanded by remember { mutableStateOf(false) }
Row(
modifier = modifier, verticalAlignment = Alignment.CenterVertically
) {
Text(modifier = Modifier.weight(0.5f), text = label, fontSize = 15.sp)
Box {
Row(
modifier = Modifier.clickable {
expanded = true
}, verticalAlignment = Alignment.CenterVertically
) {
Text(text = currentOption, fontSize = 15.sp)
Spacer(modifier = Modifier.width(5.dp))
Icon(
imageVector = Icons.Default.ArrowDropDown,
contentDescription = "Localized description"
)
}
DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) {
options.forEach {
DropdownMenuItem(text = {
Text(it, fontSize = 15.sp)
}, onClick = {
onOptionSelected(it)
expanded = false
})
}
}
}
}
}
@Composable
fun ModelSelection(
model: AudioClassificationHelper.TFLiteModel,
modifier: Modifier = Modifier,
onModelSelected: (AudioClassificationHelper.TFLiteModel) -> Unit,
) {
val radioOptions = AudioClassificationHelper.TFLiteModel.entries
Column(modifier = modifier) {
radioOptions.forEach { option ->
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
RadioButton(
selected = (option == model),
onClick = {
if (option == model) return@RadioButton
onModelSelected(option)
}, // Recommended for accessibility with screen readers
)
Text(
modifier = Modifier.padding(start = 16.dp), text = option.name, fontSize = 15.sp
)
}
}
}
}
@Composable
fun AdjustItem(
name: String,
value: Number,
modifier: Modifier = Modifier,
onMinusClicked: () -> Unit,
onPlusClicked: () -> Unit,
) {
Row(
modifier = modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
Text(
modifier = Modifier.weight(0.5f),
text = name,
fontSize = 15.sp,
)
Row(
verticalAlignment = Alignment.CenterVertically,
) {
Button(
onClick = {
onMinusClicked()
}) {
Text(text = "-", fontSize = 15.sp)
}
Spacer(modifier = Modifier.width(10.dp))
Text(
modifier = Modifier.width(30.dp),
textAlign = TextAlign.Center,
text = if (value is Float) String.format(
Locale.US, "%.1f", value
) else value.toString(),
fontSize = 15.sp,
)
Spacer(modifier = Modifier.width(10.dp))
Button(
onClick = {
onPlusClicked()
}) {
Text(text = "+", fontSize = 15.sp)
}
}
}
}
| 6 | null | 8 | 35 | 3822c37565b0d7ff4853b54a11e82e1782646866 | 15,650 | litert-samples | Apache License 2.0 |
clients/kotlin-spring/generated/src/main/kotlin/org/openapitools/model/CatalogsFeedValidationDetails.kt | oapicf | 489,369,143 | false | {"Markdown": 13009, "YAML": 64, "Text": 6, "Ignore List": 43, "JSON": 688, "Makefile": 2, "JavaScript": 2261, "F#": 1305, "XML": 1120, "Shell": 44, "Batchfile": 10, "Scala": 4677, "INI": 23, "Dockerfile": 14, "Maven POM": 22, "Java": 13384, "Emacs Lisp": 1, "Haskell": 75, "Swift": 551, "Ruby": 1149, "Cabal Config": 2, "OASv3-yaml": 16, "Go": 2224, "Go Checksums": 1, "Go Module": 4, "CMake": 9, "C++": 6688, "TOML": 3, "Rust": 556, "Nim": 541, "Perl": 540, "Microsoft Visual Studio Solution": 2, "C#": 1645, "HTML": 545, "Xojo": 1083, "Gradle": 20, "R": 1079, "JSON with Comments": 8, "QMake": 1, "Kotlin": 3280, "Python": 1, "Crystal": 1060, "ApacheConf": 2, "PHP": 3940, "Gradle Kotlin DSL": 1, "Protocol Buffer": 538, "C": 1598, "Ada": 16, "Objective-C": 1098, "Java Properties": 2, "Erlang": 1097, "PlantUML": 1, "robots.txt": 1, "HTML+ERB": 2, "Lua": 1077, "SQL": 512, "AsciiDoc": 1, "CSS": 3, "PowerShell": 1083, "Elixir": 5, "Apex": 1054, "Visual Basic 6.0": 3, "TeX": 1, "ObjectScript": 1, "OpenEdge ABL": 1, "Option List": 2, "Eiffel": 583, "Gherkin": 1, "Dart": 538, "Groovy": 539, "Elm": 31} | package org.openapitools.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import org.openapitools.model.CatalogsFeedValidationErrors
import org.openapitools.model.CatalogsFeedValidationWarnings
import javax.validation.constraints.DecimalMax
import javax.validation.constraints.DecimalMin
import javax.validation.constraints.Email
import javax.validation.constraints.Max
import javax.validation.constraints.Min
import javax.validation.constraints.NotNull
import javax.validation.constraints.Pattern
import javax.validation.constraints.Size
import javax.validation.Valid
import io.swagger.v3.oas.annotations.media.Schema
/**
*
* @param errors
* @param warnings
*/
data class CatalogsFeedValidationDetails(
@field:Valid
@Schema(example = "null", required = true, description = "")
@get:JsonProperty("errors", required = true) val errors: CatalogsFeedValidationErrors,
@field:Valid
@Schema(example = "null", required = true, description = "")
@get:JsonProperty("warnings", required = true) val warnings: CatalogsFeedValidationWarnings
) {
}
| 0 | Java | 0 | 2 | dcd328f1e62119774fd8ddbb6e4bad6d7878e898 | 1,109 | pinterest-sdk | MIT License |
app/src/main/java/com/project/monopad/network/remote/datasource/MovieRemoteDataSource.kt | 4z7l | 298,148,434 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 37, "XML": 23, "Java": 1} | package com.project.monopad.network.remote.datasource
import com.project.monopad.model.network.MovieInfoResponse
import com.project.monopad.model.network.OtherMovieInfoResponse
import io.reactivex.Single
interface MovieRemoteDataSource {
fun getNowPlayMovie(apikey : String, language : String, page: Int) : Single<MovieInfoResponse>
fun getUpComingMovie(apikey : String, language : String, page: Int) : Single<MovieInfoResponse>
fun getPopularMovie(apikey : String, language : String, page: Int, region : String) : Single<MovieInfoResponse>
fun getTopRatedMovie(apikey : String, language : String, page: Int, region : String) : Single<MovieInfoResponse>
fun getLatestMovie(apikey : String, language : String) : Single<MovieInfoResponse>
fun getSimilarMovie(movie_id : Int, apikey: String, language: String, page: Int) : Single<OtherMovieInfoResponse>
fun getRecommendationsMovie(movie_id : Int, apikey: String, language: String, page: Int) : Single<OtherMovieInfoResponse>
fun getSearch(apikey : String, language : String, query : String, page: Int) : Single<OtherMovieInfoResponse>
} | 1 | null | 1 | 1 | ca59e3cacae187acbb4a07be85b6fc3e73c32f17 | 1,120 | MonoPad | Apache License 2.0 |
packages/SystemUI/src/com/android/systemui/statusbar/BlurUtils.kt | liu-wanshun | 595,904,109 | true | null | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.statusbar
import android.app.ActivityManager
import android.content.res.Resources
import android.os.SystemProperties
import android.util.IndentingPrintWriter
import android.util.MathUtils
import android.view.CrossWindowBlurListeners
import android.view.CrossWindowBlurListeners.CROSS_WINDOW_BLUR_SUPPORTED
import android.view.SurfaceControl
import android.view.ViewRootImpl
import androidx.annotation.VisibleForTesting
import com.android.systemui.Dumpable
import com.android.systemui.R
import com.android.systemui.dagger.SysUISingleton
import com.android.systemui.dagger.qualifiers.Main
import com.android.systemui.dump.DumpManager
import java.io.PrintWriter
import javax.inject.Inject
@SysUISingleton
open class BlurUtils @Inject constructor(
@Main private val resources: Resources,
private val crossWindowBlurListeners: CrossWindowBlurListeners,
dumpManager: DumpManager
) : Dumpable {
val minBlurRadius = resources.getDimensionPixelSize(R.dimen.min_window_blur_radius)
val maxBlurRadius = resources.getDimensionPixelSize(R.dimen.max_window_blur_radius)
private var lastAppliedBlur = 0
init {
dumpManager.registerDumpable(javaClass.name, this)
}
/**
* Translates a ratio from 0 to 1 to a blur radius in pixels.
*/
fun blurRadiusOfRatio(ratio: Float): Float {
if (ratio == 0f) {
return 0f
}
return MathUtils.lerp(minBlurRadius.toFloat(), maxBlurRadius.toFloat(), ratio)
}
/**
* Translates a blur radius in pixels to a ratio between 0 to 1.
*/
fun ratioOfBlurRadius(blur: Float): Float {
if (blur == 0f) {
return 0f
}
return MathUtils.map(minBlurRadius.toFloat(), maxBlurRadius.toFloat(),
0f /* maxStart */, 1f /* maxStop */, blur)
}
/**
* Applies background blurs to a {@link ViewRootImpl}.
*
* @param viewRootImpl The window root.
* @param radius blur radius in pixels.
* @param opaque if surface is opaque, regardless or having blurs or no.
*/
fun applyBlur(viewRootImpl: ViewRootImpl?, radius: Int, opaque: Boolean) {
if (viewRootImpl == null || !viewRootImpl.surfaceControl.isValid) {
return
}
createTransaction().use {
if (supportsBlursOnWindows()) {
it.setBackgroundBlurRadius(viewRootImpl.surfaceControl, radius)
if (lastAppliedBlur == 0 && radius != 0) {
it.setEarlyWakeupStart()
}
if (lastAppliedBlur != 0 && radius == 0) {
it.setEarlyWakeupEnd()
}
lastAppliedBlur = radius
}
it.setOpaque(viewRootImpl.surfaceControl, opaque)
it.apply()
}
}
@VisibleForTesting
open fun createTransaction(): SurfaceControl.Transaction {
return SurfaceControl.Transaction()
}
/**
* If this device can render blurs.
*
* @see android.view.SurfaceControl.Transaction#setBackgroundBlurRadius(SurfaceControl, int)
* @return {@code true} when supported.
*/
open fun supportsBlursOnWindows(): Boolean {
return CROSS_WINDOW_BLUR_SUPPORTED && ActivityManager.isHighEndGfx() &&
crossWindowBlurListeners.isCrossWindowBlurEnabled() &&
!SystemProperties.getBoolean("persist.sysui.disableBlur", false)
}
override fun dump(pw: PrintWriter, args: Array<out String>) {
IndentingPrintWriter(pw, " ").let {
it.println("BlurUtils:")
it.increaseIndent()
it.println("minBlurRadius: $minBlurRadius")
it.println("maxBlurRadius: $maxBlurRadius")
it.println("supportsBlursOnWindows: ${supportsBlursOnWindows()}")
it.println("CROSS_WINDOW_BLUR_SUPPORTED: $CROSS_WINDOW_BLUR_SUPPORTED")
it.println("isHighEndGfx: ${ActivityManager.isHighEndGfx()}")
}
}
}
| 0 | Java | 1 | 2 | e99201cd9b6a123b16c30cce427a2dc31bb2f501 | 4,626 | platform_frameworks_base | Apache License 2.0 |
app/src/main/kotlin/com/foreverht/workplus/notification/UpsManager.kt | AoEiuV020 | 421,650,297 | false | {"Java": 8618305, "Kotlin": 1733509, "JavaScript": 719597, "CSS": 277438, "HTML": 111559} | package com.foreverht.workplus.notification
import android.app.Application
import android.text.TextUtils
import android.util.Log
import com.foreveross.atwork.AtworkApplicationLike
import com.foreveross.atwork.infrastructure.BaseApplicationLike
import com.foreveross.atwork.infrastructure.shared.CommonShareInfo
import com.foreveross.atwork.infrastructure.support.AtworkConfig
import com.foreveross.atwork.infrastructure.utils.rom.RomUtil
import com.heytap.mcssdk.callback.PushCallback
import com.heytap.mcssdk.mode.SubscribeResult
import com.huawei.hms.push.HmsMessaging
import com.meizu.cloud.pushsdk.PushManager
import com.meizu.cloud.pushsdk.util.MzSystemUtils
import com.vivo.push.PushClient
import com.xiaomi.mipush.sdk.MiPushClient
class UpsManager {
companion object UpsInstance{
var instance : UpsManager = UpsManager()
}
fun startUpsPush(application: Application) {
startHMSPush(application)
startXMPush(application)
startMzPush(application)
startVivoPush(application)
startOppoPush(application)
}
private fun startHMSPush(application: Application) {
if (!RomUtil.isHuawei()) {
return;
}
HmsMessaging.getInstance(application).isAutoInitEnabled = true
}
private fun startVivoPush(application: Application) {
val pushClient = PushClient.getInstance(application.applicationContext)
if (pushClient.isSupport) {
pushClient.initialize ();
pushClient.checkManifest()
pushClient.turnOnPush {
Log.e("vivo", "push regId = " + pushClient.regId )
if (!TextUtils.isEmpty(pushClient.regId)) {
CommonShareInfo.setVIVOPushToken(AtworkApplicationLike.baseContext, pushClient.regId)
}
}
}
}
private fun startXMPush(application: Application) {
if (!RomUtil.isXiaomi()) {
return
}
MiPushClient.registerPush(application, AtworkConfig.XIAOMI_PUSH_APP_ID, AtworkConfig.XIAOMI_PUSH_APP_KEY)
}
private fun startMzPush(application: Application) {
if (!MzSystemUtils.isBrandMeizu(application)) {
return
}
PushManager.register(application, AtworkConfig.MEIZU_PUSH_APP_ID, AtworkConfig.MEIZU_PUSH_APP_KEY)
}
private fun startOppoPush(application: Application) {
if (!com.heytap.mcssdk.PushManager.isSupportPush(application)) {
return
}
com.heytap.mcssdk.PushManager.getInstance().register(application, AtworkConfig.OPPO_PUSH_APP_ID, AtworkConfig.OPPO_PUSH_APP_KEY, object: PushCallback{
override fun onGetPushStatus(p0: Int, p1: Int) {
}
override fun onSetPushTime(p0: Int, p1: String?) {
}
override fun onGetNotificationStatus(p0: Int, p1: Int) {
}
override fun onSetAliases(p0: Int, p1: MutableList<SubscribeResult>?) {
}
override fun onUnsetAliases(p0: Int, p1: MutableList<SubscribeResult>?) {
}
override fun onUnsetUserAccounts(p0: Int, p1: MutableList<SubscribeResult>?) {
}
override fun onGetAliases(p0: Int, p1: MutableList<SubscribeResult>?) {
}
override fun onUnsetTags(p0: Int, p1: MutableList<SubscribeResult>?) {
}
override fun onRegister(p0: Int, regId: String?) {
if (TextUtils.isEmpty(regId)) {
return
}
CommonShareInfo.setOPPOPushToken(BaseApplicationLike.baseContext, regId)
}
override fun onSetUserAccounts(p0: Int, p1: MutableList<SubscribeResult>?) {
}
override fun onSetTags(p0: Int, p1: MutableList<SubscribeResult>?) {
}
override fun onGetUserAccounts(p0: Int, p1: MutableList<SubscribeResult>?) {
}
override fun onGetTags(p0: Int, p1: MutableList<SubscribeResult>?) {
}
override fun onUnRegister(p0: Int) {
}
})
}
} | 1 | null | 1 | 1 | 1c4ca5bdaea6d5230d851fb008cf2578a23b2ce5 | 4,149 | w6s_lite_android | MIT License |
2015/11/kotlin/a.kt | shrivatsas | 583,681,989 | false | {"Kotlin": 17998, "Python": 9402, "Racket": 4669, "Clojure": 2953} | fun nextPassword(current: String): String {
var password = incrementPassword(current)
while (!isValidPassword(password)) {
password = incrementPassword(password)
}
return password
}
fun incrementPassword(password: String): String {
var chars = password.toCharArray()
var carry = 1
for (i in chars.size - 1 downTo 0) {
var c = chars[i]
if (c == 'z') {
chars[i] = 'a'
carry = 1
} else {
chars[i] = c + carry
carry = 0
break
}
}
return String(chars)
}
fun isValidPassword(password: String): Boolean {
return hasStraight(password) && hasNoConfusingLetters(password) && hasTwoPairs(password)
}
fun hasStraight(password: String): Boolean {
for (i in 0..password.length - 3) {
if (password[i] + 1 == password[i + 1] && password[i + 1] + 1 == password[i + 2]) {
return true
}
}
return false
}
fun hasNoConfusingLetters(password: String): Boolean {
val regex = "[iol]".toRegex()
return !regex.containsMatchIn(password)
}
fun hasTwoPairs(password: String): Boolean {
var pairs = 0
var skip = true
for (i in 0..password.length - 2) {
if (skip) {
skip = false
continue
}
if (password[i] == password[i + 1]) {
pairs++
skip = true
}
}
return pairs >= 2
}
fun main() {
val current = "hxbxwxba"
println("Next password: ${nextPassword(current)}")
println("Next password: ${nextPassword(nextPassword(current))}")
} | 0 | Kotlin | 0 | 1 | 529a72ff55f1d90af97f8e83b6c93a05afccb44c | 1,602 | AoC | MIT License |
app/src/main/java/com/einvopos/ratemevrmuseum/ui/profile/ProfileViewModel.kt | juanfec | 206,160,518 | false | null | package com.einvopos.ratemevrmuseum.ui.profile
import androidx.lifecycle.ViewModel;
import com.einvopos.ratemevrmuseum.data.AppDatabase
/**
* viwemodel that takes care of retrieving data for the view and saving it
*/
class ProfileViewModel(val appDatabase: AppDatabase) : ViewModel() {
}
| 0 | Kotlin | 0 | 0 | 8f804d49ab45a6c66fa9471907c123f595d474f9 | 293 | RateMeVRMuseum | Apache License 2.0 |
common/src/main/kotlin/tech/sethi/pebbles/cobbledhunters/config/screenhandler/PersonalStatsScreenConfig.kt | navneetset | 770,120,520 | false | {"Kotlin": 258561} | package tech.sethi.pebbles.cobbledhunters.config.screenhandler
import tech.sethi.pebbles.cobbledhunters.config.ConfigHandler
import tech.sethi.pebbles.cobbledhunters.util.ConfigFileHandler
import java.io.File
object PersonalStatsScreenConfig {
val gson = ConfigHandler.gson
val personalHuntScreenConfigFile = File("config/pebbles-cobbledhunters/screens/personal-stats-screen.json")
var config = PersonalStatsScreen()
val personalStatsFileHandler =
ConfigFileHandler(PersonalStatsScreen::class.java, personalHuntScreenConfigFile, gson)
init {
reload()
}
fun reload() {
personalStatsFileHandler.reload()
config = personalStatsFileHandler.config
}
data class PersonalStatsScreen(
val title: String = "<blue>Personal Stats",
val playerHeadSlot: Int = 12,
val levelSlots: List<Int> = listOf(14),
val levelSlotStack: ConfigHandler.SerializedItemStack = ConfigHandler.SerializedItemStack(
displayName = "<gray>Level",
material = "minecraft:experience_bottle",
amount = 1,
nbt = null,
lore = mutableListOf(
"<gray>Level: <yellow>{level}",
"<gray>Experience: <light_purple>{exp}",
)
),
val backSlots: List<Int> = listOf(18),
val backSlotStack: ConfigHandler.SerializedItemStack = ConfigHandler.SerializedItemStack(
displayName = "<gray>Back", material = "minecraft:gray_wool", amount = 1, nbt = null, lore = mutableListOf(
"Click to go back!"
)
),
val emptySlots: List<Int> = listOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 17, 19, 20, 21, 22, 23, 24, 25, 26),
val emptySlotStack: ConfigHandler.SerializedItemStack = ConfigHandler.SerializedItemStack(
displayName = "<gray>",
material = "minecraft:blue_stained_glass_pane",
amount = 1,
nbt = null,
lore = mutableListOf(
" "
)
)
)
} | 0 | Kotlin | 0 | 0 | 8fb73002a081807a1fde72be877f0e6dec001fce | 2,060 | pebbles-cobbledhunters-multiplatform | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/github/studydistractor/sdp/eventChat/EventChatMiddlewareOffline.kt | StudyDistractor | 606,005,189 | false | null | package com.github.studydistractor.sdp.eventChat
import android.net.ConnectivityManager
import android.os.AsyncTask
import com.github.studydistractor.sdp.data.Message
import com.github.studydistractor.sdp.roomdb.RoomDatabase
import com.github.studydistractor.sdp.utils.OnlineStatus
import com.google.android.gms.tasks.Task
import com.google.android.gms.tasks.Tasks
class EventChatMiddlewareOffline constructor(
private val database: RoomDatabase,
private val service: EventChatModel,
private val connectivityManager : ConnectivityManager
): EventChatModel {
private val messages: MutableList<Message> = mutableListOf()
private var eventId: String = ""
private var onMessagesChange: (List<Message>) -> Unit = {}
override fun observeMessages(onChange: (List<Message>) -> Unit) {
this.onMessagesChange = onChange
// If we were always offline, we added the data to `messages` in `changeCurrentChat`
// but it might not have been given to the viewModel. We give it (maybe again) here.
service.observeMessages {
AsyncTask.execute {
messages.clear()
messages.addAll(it)
for(i in messages){
database.eventChatDao().insert(i)
}
}
onChange(it)
}
}
override fun postMessage(message: String): Task<Void> {
if(!OnlineStatus().isOnline(connectivityManager)) return Tasks.forException(Exception())
return service.postMessage(message)
}
override fun changeCurrentChat(eventId: String): Task<Void> {
this.eventId = eventId
AsyncTask.execute{
val cachedMessages = database.eventChatDao().getAllMessages(eventId)
this.messages.clear()
messages.addAll(cachedMessages)
onMessagesChange(messages)
}
return service.changeCurrentChat(eventId)
}
fun deleteCache(){
database.eventChatDao().delete()
}
} | 27 | Kotlin | 1 | 3 | 79dfd84edd3c18c462a65226d99d94564105e2e4 | 2,001 | sdp | The Unlicense |
app/src/main/java/com/example/chat_bot/Activities/acivity/TruefalseActivity.kt | SEEDS-learning-apps | 536,944,125 | false | null | package com.example.chat_bot.Activities.acivity
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import com.example.chat_bot.R
import com.example.chat_bot.data.Data
import com.example.chat_bot.data.Mcqss
import com.example.chat_bot.data.Topics
import com.example.chat_bot.databinding.ActivityTruefalseBinding
import com.example.chat_bot.networking.Retrofit.Seeds_api.api.SEEDSRepository
import com.example.chat_bot.networking.Retrofit.Seeds_api.api.SEEDSViewModel
import com.example.chat_bot.networking.Retrofit.Seeds_api.api.SEEDSViewModelFact
import com.example.chat_bot.networking.Retrofit.Seeds_api.api.SEEDSApi
import com.example.chat_bot.ui.Tfadapter
import com.example.chat_bot.utils.SessionManager
class TruefalseActivity : AppCompatActivity() {
private val TAG = "TFActivity"
private val SPLASH_TIME: Long = 2000
lateinit var session: SessionManager
val handler = Handler(Looper.getMainLooper())
lateinit var viewModel: SEEDSViewModel
private lateinit var binding: ActivityTruefalseBinding
private var correct_answers: Int = 0
lateinit var q_mcqs: ArrayList <Mcqss>
var TFlist: ArrayList<Data> = arrayListOf()
var filterd_topiclist: ArrayList<Topics> = arrayListOf()
var filterd_trufalses: ArrayList<Data> = arrayListOf()
private var totale_mcq : Int = 0
private val retrofitService = SEEDSApi.getInstance()
lateinit var topic_id: String
lateinit var user_id: String
val adapter = Tfadapter(this)
@RequiresApi(Build.VERSION_CODES.N)
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_truefalse)
binding = ActivityTruefalseBinding.inflate(layoutInflater)
setContentView(binding.root)
hideActionBar()
viewModel = ViewModelProvider(this, SEEDSViewModelFact(SEEDSRepository(retrofitService))).get(SEEDSViewModel::class.java)
session = SessionManager(applicationContext)
filterd_trufalses = intent.getSerializableExtra("filterd_trufalses") as ArrayList<Data>
correct_answers = intent.getIntExtra("scores", correct_answers)
totale_mcq = intent.getIntExtra("total_mcqs", totale_mcq)
var country: String = ""
country= session.pref.getString("country", country).toString()
Log.d("OnCreate", country)
binding.tfRv.layoutManager
binding.tfRv.adapter = adapter
binding.loadingProgress.visibility = View.VISIBLE
// val sharedPreferences: SharedPreferences = this.getSharedPreferences(Context.MODE_PRIVATE.toString())
//val dev = sharedPreferences.getString("dev_id", "")
//LocalBroadcastManager.getInstance(this).registerReceiver(mFlagReciever, IntentFilter("Answer_flag"))
//
// viewModel.tfList.observe(this, Observer {
// Log.d(TAG, "OnCreate: $it")
// var datasize = it.size
//
//
//
// var mil: MutableList<String> = arrayListOf()
//
// // for (item in it)
// // {
// for (item in filterd_topiclist)
// {
// topic_id = item._id
// user_id = item.userId
//
// TFlist = item.filter { it.topicId == topic_id && it.userId == user_id } as ArrayList<trufalses>
//
// TFlist = item.filter { it.topicId == topic_id && it.userId == user_id} as ArrayList<trufalses>
//
// }
adapter.setMcqList(filterd_trufalses, correct_answers, totale_mcq)
//
// Log.d("MAA", TFlist.toString())
// // }
//
// })
viewModel.errorMessage.observe(this, Observer {
Toast.makeText(this, "Error went", Toast.LENGTH_SHORT).show()
binding.loadingProgress.visibility = View.GONE
})
handler.postDelayed({
viewModel.getAllTF()
binding.loadingProgress.visibility = View.GONE
},SPLASH_TIME)
}
private fun fill_tf() {
viewModel.tfList.observe(this, Observer {
Log.d(TAG, "OnCreate: $it")
// var datasize = it.
var mil: MutableList<String> = arrayListOf()
// for (item in it)
// {
for (item in filterd_topiclist) {
topic_id = item._id
user_id = item.userId
TFlist =
it.data.filter { it.topicId == topic_id && it.userId == user_id } as ArrayList<Data>
if (TFlist.isNotEmpty())
{
adapter.setMcqList(TFlist,correct_answers,totale_mcq)
}
}
// adapter.setMcqList(mcqlist)
Log.d("OnCreate", TFlist.toString())
// }
})
viewModel.errorMessage.observe(this, Observer {
Toast.makeText(this, "NO TF found", Toast.LENGTH_SHORT).show()
})
viewModel.getAllTF()
}
override fun onBackPressed() {
super.onBackPressed()
finish()
}
private fun hideActionBar() {
supportActionBar?.hide()
}
} | 0 | Kotlin | 2 | 0 | f8245e8c608460bc95f00f7705a72bba5aa49a6f | 5,415 | learning-MobileApp | Educational Community License v2.0 |
src/main/kotlin/uk/co/lucystevens/wildcert/cli/ListArgType.kt | lucystevens | 491,272,328 | false | {"Kotlin": 14040} | package uk.co.lucystevens.wildcert.cli
import kotlinx.cli.ArgType
class ListArgType:
ArgType<List<String>>(true) {
override val description: kotlin.String
get() = "{ Comma-separated list }"
override fun convert(value: kotlin.String, name: kotlin.String): List<kotlin.String> =
value.split(",")
} | 0 | Kotlin | 0 | 0 | 025ff33c31f2d36a225052f2830b1cb0a20ba8fc | 327 | wildcert | MIT License |
library/src/main/kotlin/ru/kontur/kinfra/kfixture/generators/dates/OffsetTimeDateCreator.kt | skbkontur | 212,616,062 | false | null | package ru.kontur.kinfra.kfixture.generators.dates
import java.time.OffsetTime
class OffsetTimeDateCreator : DateCreator<OffsetTime> {
override fun create(interval: TimeInterval): OffsetTime {
return when (interval) {
TimeInterval.PAST -> OffsetTime.now().minusHours(HOURS_TO_SUB)
TimeInterval.NOW -> OffsetTime.now()
TimeInterval.FUTURE -> OffsetTime.now().plusHours(HOURS_TO_ADD)
}
}
private companion object {
const val HOURS_TO_SUB = 1L
const val HOURS_TO_ADD = 1L
}
} | 7 | Kotlin | 1 | 1 | e1845e8c9737c66b63cfa49925ad3bb9c589fbd1 | 559 | KFixture | MIT License |
src/main/kotlin/com/maltaisn/mazegen/generator/KruskalGenerator.kt | maltaisn | 162,623,644 | false | null | /*
* Copyright (c) 2019 Nicolas Maltais
*
* Permission is hereby granted, free of charge,
* to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to
* deal in the Software without restriction, including
* without limitation the rights to use, copy, modify,
* merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom
* the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice
* shall be included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.maltaisn.mazegen.generator
import com.maltaisn.mazegen.maze.Cell
import com.maltaisn.mazegen.maze.Maze
import com.maltaisn.mazegen.maze.WeaveOrthogonalMaze
import com.maltaisn.mazegen.maze.ZetaMaze
import java.util.*
import kotlin.collections.HashMap
import kotlin.collections.LinkedHashSet
/**
* Implementation of Kruskal's algorithm as described
* [here](http://weblog.jamisbuck.org/2011/1/3/maze-generation-kruskal-s-algorithm).
*
* 1. Initialize a list with all edges and create an empty tree node for each cell.
* 2. Pop a random edge from the list and if the trees of its cells are not connected,
* connect them and connect their trees' root
* 3. Repeat step 2 until there are no more edges in the list.
*
* Kruskal's can't generate zeta and weave orthogonal mazes correctly. This is because
* the neighbors of the cells change depending on how neighbors are connected together
* but the implementation of the algorithm checks neighbors only at the beginning.
*
* Runtime complexity is O(n) and memory space is O(n).
*/
class KruskalGenerator : Generator() {
override fun generate(maze: Maze) {
super.generate(maze)
maze.fillAll()
// Get all edges and create a tree node for every cell
val edgesSet = LinkedHashSet<Edge>()
val nodesMap = HashMap<Cell, Node>()
for (cell in maze.getAllCells()) {
for (neighbor in cell.neighbors) {
edgesSet.add(Edge(cell, neighbor))
}
nodesMap[cell] = Node()
}
val edges = edgesSet.toMutableList()
edges.shuffle()
while (edges.isNotEmpty()) {
val edge = edges.removeAt(edges.size - 1)
val node1 = nodesMap[edge.cell1]!!
val node2 = nodesMap[edge.cell2]!!
if (!node1.connectedTo(node2)) {
node1.connect(node2)
edge.cell1.connectWith(edge.cell2)
}
}
}
override fun isMazeSupported(maze: Maze) = maze !is ZetaMaze && maze !is WeaveOrthogonalMaze
/**
* A edge for a maze, between two cells, [cell1] and [cell2].
* Edges are equal to each other if they have the two same cells.
*/
private class Edge(val cell1: Cell, val cell2: Cell) {
override fun equals(other: Any?): Boolean {
if (other === this) return true
if (other !is Edge) return false
return cell1 === other.cell1 && cell2 === other.cell2
|| cell1 === other.cell2 && cell2 === other.cell1
}
override fun hashCode() = if (cell1.position < cell2.position) {
Objects.hash(cell1, cell2)
} else {
Objects.hash(cell2, cell1)
}
}
private class Node {
var parent: Node? = null
fun root(): Node = if (parent != null) {
parent!!.root()
} else {
this
}
fun connectedTo(node: Node) = (root() === node.root())
fun connect(node: Node) {
node.root().parent = this
}
}
}
| 0 | Kotlin | 6 | 22 | f6471f8100a3e4a5e3f1136b714b50b5133a5318 | 4,216 | mazegen | MIT License |
app/src/main/java/com/fappslab/bookshelf/favorites/presentation/viewmodel/FavoritesViewAction.kt | F4bioo | 661,873,124 | false | null | package com.fappslab.bookshelf.favorites.presentation.viewmodel
sealed class FavoritesViewAction {
data class BuyBook(val url: String) : FavoritesViewAction()
object ShowErrorBuyBook : FavoritesViewAction()
object BackPressed : FavoritesViewAction()
}
| 0 | Kotlin | 0 | 0 | 3b3f5a9759e9f94068d3eba8a2fa01f647096b8d | 265 | Bookshelf | MIT License |
src/test/kotlin/br/com/zupacademy/pix/listAll/AllKeysTestIT.kt | eliasnepo | 395,002,824 | true | {"Kotlin": 77355, "Smarty": 1872, "Dockerfile": 166} | package br.com.zupacademy.pix.listAll
import br.com.zupacademy.*
import br.com.zupacademy.pix.KeyRepository
import br.com.zupacademy.pix.factory.createDynamicValidKey
import br.com.zupacademy.pix.factory.createValidKey
import br.com.zupacademy.shared.httpclients.BacenClient
import br.com.zupacademy.shared.httpclients.ItauClient
import br.com.zupacademy.shared.httpclients.dto.*
import io.grpc.ManagedChannel
import io.grpc.Status
import io.grpc.StatusRuntimeException
import io.micronaut.context.annotation.Factory
import io.micronaut.grpc.annotation.GrpcChannel
import io.micronaut.grpc.server.GrpcServerChannel
import io.micronaut.http.HttpResponse
import io.micronaut.test.annotation.MockBean
import io.micronaut.test.extensions.junit5.annotation.MicronautTest
import org.junit.jupiter.api.*
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertNotNull
import org.mockito.Mockito
import java.time.LocalDateTime
import java.util.*
import javax.inject.Singleton
@MicronautTest(transactional = false)
internal class AllKeysTestIT(val repository: KeyRepository,
val grpcClient: AllKeysServiceGrpc.AllKeysServiceBlockingStub,
val itauClient: ItauClient
) {
@BeforeEach
fun setUp() {
repository.deleteAll()
}
@Test
fun `should throw exception when client id is empty`() {
val request = FindAllKeysRequest.newBuilder()
.setClientId("")
.build()
val error = assertThrows<StatusRuntimeException> {
grpcClient.findAll(request)
}
with(error) {
assertEquals(Status.INVALID_ARGUMENT.code, status.code)
assertEquals("O id do cliente deve estar preenchido.", status.description)
}
}
@Test
fun `should throw exception when client id is null`() {
val request = FindAllKeysRequest.newBuilder()
.build()
val error = assertThrows<StatusRuntimeException> {
grpcClient.findAll(request)
}
with(error) {
assertEquals(Status.INVALID_ARGUMENT.code, status.code)
assertEquals("O id do cliente deve estar preenchido.", status.description)
}
}
@Test
fun `should throw exception when client id does not exists in itau system`() {
val clientId = UUID.randomUUID().toString()
val request = FindAllKeysRequest.newBuilder()
.setClientId(clientId)
.build()
Mockito.`when`(itauClient.findClientInfos(clientId)).thenReturn(HttpResponse.notFound())
val error = assertThrows<StatusRuntimeException> {
grpcClient.findAll(request)
}
with(error) {
assertEquals(Status.NOT_FOUND.code, status.code)
assertEquals("O cliente não existe na base do Itaú.", status.description)
}
}
@Test
fun `should return empty list when client does not have keys on database`() {
val clientId = UUID.randomUUID().toString()
val request = FindAllKeysRequest.newBuilder()
.setClientId(clientId)
.build()
Mockito.`when`(itauClient.findClientInfos(clientId)).thenReturn(HttpResponse.ok())
val response = assertDoesNotThrow {
grpcClient.findAll(request)
}
assertNotNull(response)
assertEquals(response.keysCount, 0)
}
@Test
fun `should return a list with keys of client specified`() {
val clientId = UUID.randomUUID().toString()
val pix1 = createDynamicValidKey("11111111111", clientId)
val pix2 = createDynamicValidKey("22222222222", clientId)
val pix3 = createDynamicValidKey("33333333333", clientId)
repository.save(pix1)
repository.save(pix2)
repository.save(pix3)
val request = FindAllKeysRequest.newBuilder()
.setClientId(clientId)
.build()
Mockito.`when`(itauClient.findClientInfos(clientId)).thenReturn(HttpResponse.ok())
val response = assertDoesNotThrow {
grpcClient.findAll(request)
}
assertNotNull(response)
assertEquals(response.keysCount, 3)
assertEquals("11111111111", response.getKeys(0).key)
assertEquals("22222222222", response.getKeys(1).key)
assertEquals("33333333333", response.getKeys(2).key)
}
@MockBean(ItauClient::class)
fun itauClient(): ItauClient {
return Mockito.mock(ItauClient::class.java)
}
}
@Factory
class Clients {
@Singleton
fun blockingStub(@GrpcChannel(GrpcServerChannel.NAME) channel: ManagedChannel):
AllKeysServiceGrpc.AllKeysServiceBlockingStub {
return AllKeysServiceGrpc.newBlockingStub(channel)
}
} | 0 | Kotlin | 0 | 0 | 70e6651594beddc45bca7ad95445f8051442cd34 | 4,842 | pix-grpc-challenge | Apache License 2.0 |
app/src/main/java/pl/edu/pb/wi/MainActivity.kt | mateuszhorczak | 708,566,146 | false | {"Kotlin": 13450} | package pl.edu.pb.wi
import android.annotation.SuppressLint
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import pl.edu.pb.wi.ui.theme.QuizTheme
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
QuizTheme {
// A surface container using the 'background' color from the theme
Surface(
modifier = Modifier.fillMaxSize(),
color = MaterialTheme.colorScheme.background
) {
QuizScreen();
}
}
}
}
}
val questionList: Array<Question> = arrayOf(
Question(R.string.question1, true),
Question(R.string.question2, false),
Question(R.string.question3, true),
Question(R.string.question4, true),
Question(R.string.question5, true),
)
@Composable
fun ScoreScreen(score: Int, onRestartQuiz: () -> Unit) {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center,
modifier = Modifier.padding(16.dp)
) {
Text(
text = "Twój wynik:",
fontSize = 24.sp,
fontWeight = FontWeight.Bold,
color = Color.Black
)
Text(
text = "$score / ${questionList.size}",
fontSize = 48.sp,
fontWeight = FontWeight.Bold,
color = Color.Magenta
)
Spacer(modifier = Modifier.height(16.dp))
Button(
onClick = { onRestartQuiz() },
modifier = Modifier.padding(8.dp)
) {
Text(text = "Zagraj jeszcze raz")
}
}
}
}
@SuppressLint("MutableCollectionMutableState")
@Composable
fun QuizScreen() {
var currentQuestionIndex by remember { mutableStateOf(0) }
var userAnswer: Boolean? by remember { mutableStateOf(null) }
var showDialog by remember { mutableStateOf(false) }
var scores by remember { mutableStateOf(MutableList(5) { 0 }) }
var showScoreScreen by remember { mutableStateOf(false) }
var sumScore by remember { mutableStateOf(0) }
fun showAnswerDialog() {
showDialog = true
}
fun sumScoreList(): Int {
if (currentQuestionIndex == 5) {
for (score in scores) {
sumScore += score
}
currentQuestionIndex++
return sumScore
}
return sumScore
}
if (currentQuestionIndex >= questionList.size) {
ScoreScreen(score = sumScoreList()) {
currentQuestionIndex = 0
userAnswer = null
scores[0] = 0
scores[1] = 0
scores[2] = 0
scores[3] = 0
scores[4] = 0
sumScore = 0
showScoreScreen = false
}
} else {
if (showDialog) {
AlertDialog(
onDismissRequest = {
currentQuestionIndex++
userAnswer = null
showDialog = false
},
title = {
Text("Odpowiedz")
},
text = {
userAnswer?.let {
val correctAnswer = questionList[currentQuestionIndex].isTrueAnswer()
val answerText = if (correctAnswer) "Prawda" else "Falsz"
val userAnswerText = if (it) "Prawda" else "Falsz"
if (it == correctAnswer) {
scores[currentQuestionIndex] = 1
}
Text(
text = "Odpowiedz $userAnswerText\nPoprawna odpowiedz: $answerText",
fontWeight = FontWeight.Bold,
color = if (it == correctAnswer) Color.Green else Color.Red
)
}
},
confirmButton = {
Button(
onClick = {
showDialog = false
currentQuestionIndex++
userAnswer = null
}
) {
Text("Następne pytanie")
}
},
modifier = Modifier.padding(8.dp),
)
}
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
Image(
painter = painterResource(id = R.drawable.tlo),
contentDescription = null,
contentScale = ContentScale.Crop,
modifier = Modifier.fillMaxSize()
)
Column(
modifier = Modifier.fillMaxSize(),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
Text(
text = stringResource(id = questionList[currentQuestionIndex].getQuestionId()),
color = Color.White,
fontSize = 25.sp,
fontWeight = FontWeight.Bold
)
Row(
modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
) {
Button(
onClick = {
userAnswer = true
showAnswerDialog()
},
modifier = Modifier.padding(8.dp),
colors = ButtonDefaults.buttonColors(
contentColor = Color.Black,
containerColor = Color.Green
)
) {
Text(text = "PRAWDA")
}
Spacer(modifier = Modifier.width(16.dp))
Button(
onClick = {
userAnswer = false
showAnswerDialog()
},
modifier = Modifier.padding(8.dp),
colors = ButtonDefaults.buttonColors(
contentColor = Color.Black,
containerColor = Color.Red
)
) {
Text(text = "FALSZ")
}
}
Button(
onClick = {
currentQuestionIndex++
userAnswer = null
},
modifier = Modifier.padding(8.dp)
) {
Text(text = "NASTEPNE PYTANIE")
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | a6875d4697a9c4f681c12fd5beb36267311ff3ec | 8,684 | SM1-2 | MIT License |
WPRKSDK/src/commonMain/kotlin/com/mwaibanda/wprksdk/data/repository/PodcastRepositoryImpl.kt | MwaiBanda | 455,768,879 | false | null | package com.mwaibanda.wprksdk.data.repository
import com.mwaibanda.wprksdk.data.episodeDTO.EpisodesDTO
import com.mwaibanda.wprksdk.data.podcastDTO.PodcastsDTO
import com.mwaibanda.wprksdk.main.repository.PodcastRepository
import com.mwaibanda.wprksdk.main.usecase.cache.GetAllItemsUseCase
import com.mwaibanda.wprksdk.main.usecase.cache.GetItemUseCase
import com.mwaibanda.wprksdk.main.usecase.cache.SetItemUseCase
import com.mwaibanda.wprksdk.util.Constants
import com.mwaibanda.wprksdk.util.EpisodeResponse
import com.mwaibanda.wprksdk.util.PodcastResponse
import com.mwaibanda.wprksdk.util.Resource
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.request.*
class PodcastRepositoryImpl(
private val httpClient: HttpClient,
private val getPodcastsUseCase: GetItemUseCase<PodcastResponse>,
private val setPodcastUseCase: SetItemUseCase<PodcastResponse>,
private val getEpisodesUseCase: GetItemUseCase<EpisodeResponse>,
private val setEpisodeUseCase: SetItemUseCase<EpisodeResponse>,
private val getAllEpisodesUseCase: GetAllItemsUseCase<EpisodeResponse>
) : PodcastRepository {
override suspend fun getPodcasts(): Resource<PodcastResponse> {
val cachedPodcasts = getPodcastsUseCase(Constants.PODCASTS_KEY).orEmpty()
if (cachedPodcasts.isNotEmpty()) return Resource.Success(cachedPodcasts)
try {
val remotePodcasts: PodcastResponse = httpClient.get {
url("${Constants.TRANSISTOR_BASE_URL}/shows")
headers {
append("x-api-key", Constants.TRANSISTOR_KEY)
}
}.body<PodcastsDTO>().collection.map { it.toPodcast() }
setPodcastUseCase(Constants.PODCASTS_KEY, remotePodcasts)
} catch (e: Exception) {
return Resource.Error(e.message.toString())
}
val newlyCachedPodcasts = getPodcastsUseCase(Constants.PODCASTS_KEY).orEmpty()
return Resource.Success(newlyCachedPodcasts)
}
override suspend fun getEpisodes(showID: String, pageNumber: Int): Resource<EpisodeResponse> {
val cachedResource = getEpisodesUseCase(key = "$showID-$pageNumber")
if (cachedResource != null) {
val (_, _, cachedEpisodes) = cachedResource
if (cachedEpisodes.isNotEmpty()) {
val allCachedEpisodeResponses: List<EpisodeResponse> = getAllEpisodesUseCase(showID)
return Resource.Success(
Triple(
pageNumber <= (allCachedEpisodeResponses.maxByOrNull { it.second }?.second
?: 1),
allCachedEpisodeResponses.maxByOrNull { it.second }?.second ?: 1,
allCachedEpisodeResponses.flatMap { it.third }
)
)
}
}
try {
val episodesDTO: EpisodesDTO = httpClient.get {
url("${Constants.TRANSISTOR_BASE_URL}/episodes")
headers {
append("x-api-key", Constants.TRANSISTOR_KEY)
}
parameter("show_id", "$showID")
parameter("pagination[page]", "$pageNumber")
}.body()
val remoteEpisodes = episodesDTO.episodes.map { it.toEpisode() }
val newlyCachedEpisodeResource = Triple(
(episodesDTO.meta?.currentPage ?: 1) <= (episodesDTO.meta?.totalPages ?: 1),
(episodesDTO.meta?.currentPage ?: 1),
remoteEpisodes
)
setEpisodeUseCase(
"$showID-$pageNumber",
newlyCachedEpisodeResource
)
return Resource.Success(newlyCachedEpisodeResource)
} catch (e: Exception) {
return Resource.Error(e.message.toString())
}
}
} | 0 | null | 8 | 46 | 1169628c70cca58408f5561293a7d09922ddfb21 | 3,848 | WPRK-MultiPlatform | MIT License |
platforms/android/library/src/main/java/io/element/android/wysiwyg/utils/CharContants.kt | matrix-org | 508,730,706 | false | {"Rust": 995171, "Kotlin": 415117, "Swift": 348195, "TypeScript": 255880, "HTML": 5880, "Shell": 5232, "JavaScript": 4482, "Objective-C": 3675, "Makefile": 1835, "CSS": 1782, "Ruby": 36} | package io.element.android.wysiwyg.utils
/**
* Constants for characters used as placeholders inside HTML.
*/
const val ZWSP: Char = '\u200B'
const val NBSP: Char = '\u00A0'
| 49 | Rust | 22 | 92 | c6ff119565685e9e604e894871067e0d8e4e4c05 | 176 | matrix-rich-text-editor | Apache License 2.0 |
app/src/main/java/weather/ekamp/com/weatherappkotlin/WeatherApplication.kt | ekamp | 101,588,492 | false | null | package weather.ekamp.com.weatherappkotlin
import android.app.Application
import toothpick.smoothie.module.SmoothieApplicationModule
import toothpick.Toothpick
import weather.ekamp.com.weatherappkotlin.model.inject.WeatherApplicationModule
import toothpick.configuration.Configuration.forDevelopment
import toothpick.configuration.Configuration.forProduction
import toothpick.registries.FactoryRegistryLocator
import toothpick.registries.MemberInjectorRegistryLocator
import toothpick.Toothpick.setConfiguration
class WeatherApplication : Application() {
override fun onCreate() {
super.onCreate()
val configuration = if (BuildConfig.DEBUG) forDevelopment() else forProduction()
setConfiguration(configuration.disableReflection())
FactoryRegistryLocator.setRootRegistry(FactoryRegistry())
MemberInjectorRegistryLocator.setRootRegistry(MemberInjectorRegistry())
val appScope = Toothpick.openScope(this)
appScope.installModules(SmoothieApplicationModule(this), WeatherApplicationModule(this))
}
}
| 3 | Kotlin | 5 | 15 | b4fde89650ae5c3505986f67ea7247b94ff167a4 | 1,063 | KotlinWeather | Apache License 2.0 |
app/src/main/java/com/romandevyatov/bestfinance/repositories/ExpenseSubGroupRepository.kt | RomanDevyatov | 587,557,441 | false | null | package com.romandevyatov.bestfinance.repositories
import androidx.lifecycle.LiveData
import com.romandevyatov.bestfinance.db.dao.ExpenseSubGroupDao
import com.romandevyatov.bestfinance.db.entities.ExpenseSubGroup
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ExpenseSubGroupRepository @Inject constructor(
private val expenseSubGroupDao: ExpenseSubGroupDao
) {
fun getAllExpenseSubGroups(): LiveData<List<ExpenseSubGroup>> = expenseSubGroupDao.getAllLiveData()
fun getAllExpenseGroupsNotArchivedLiveData(): LiveData<List<ExpenseSubGroup>> = expenseSubGroupDao.getAllNotArchivedLiveData()
suspend fun insertExpenseSubGroup(expenseGroup: ExpenseSubGroup) {
expenseSubGroupDao.insert(expenseGroup)
}
suspend fun deleteExpenseSubGroup(expenseGroup: ExpenseSubGroup) {
expenseSubGroupDao.delete(expenseGroup)
}
suspend fun updateExpenseSubGroup(expenseGroup: ExpenseSubGroup) {
expenseSubGroupDao.update(expenseGroup)
}
suspend fun deleteExpenseSubGroupById(id: Int) = expenseSubGroupDao.deleteById(id)
suspend fun deleteAllExpenseSubGroups() = expenseSubGroupDao.deleteAll()
fun getExpenseSubGroupByNameLiveData(name: String): LiveData<ExpenseSubGroup> = expenseSubGroupDao.getByNameLiveData(name)
fun getExpenseSubGroupByName(name: String): ExpenseSubGroup = expenseSubGroupDao.getByName(name)
fun getExpenseSubGroupByNameNotArchivedLiveData(name: String): LiveData<ExpenseSubGroup> = expenseSubGroupDao.getByNameNotArchivedLiveData(name)
fun getExpenseSubGroupByNameNotArchived(name: String): ExpenseSubGroup = expenseSubGroupDao.getExpenseSubGroupByNameNotArchived(name)
suspend fun unarchiveExpenseSubGroup(expenseSubGroup: ExpenseSubGroup) {
val expenseSubGroupNotArchived = ExpenseSubGroup(
id = expenseSubGroup.id,
name = expenseSubGroup.name,
description = expenseSubGroup.description,
expenseGroupId = expenseSubGroup.expenseGroupId,
archivedDate = null
)
updateExpenseSubGroup(expenseSubGroupNotArchived)
}
fun getExpenseSubGroupByNameAndExpenseGroupId(name: String, expenseGroupId: Long): ExpenseSubGroup = expenseSubGroupDao.getByNameAndGroupId(name, expenseGroupId)
}
| 0 | Kotlin | 0 | 1 | 0a1526005f81f6ca365193b99a3970033381aceb | 2,303 | BestFinance | Apache License 2.0 |
src/commonMain/kotlin/com/github/insanusmokrassar/AQICNAPI/WarningLevels.kt | InsanusMokrassar | 174,675,389 | false | null | package com.github.insanusmokrassar.AQICNAPI
val GOOD_LEVEL = 0 .. 50
val ACCEPTABLE_LEVEL = 51 .. 100
val WARNING_LEVEL = 101 .. 150
val DANGER_LEVEL = 151 .. 200
val EMERGENCY_LEVEL = 201 .. 300
val HAZARD_LEVEL = 301 .. Int.MAX_VALUE
private val levelsList = listOf(
GOOD_LEVEL,
ACCEPTABLE_LEVEL,
WARNING_LEVEL,
DANGER_LEVEL,
EMERGENCY_LEVEL,
HAZARD_LEVEL
)
fun aqiLevel(aqi: Int) = levelsList.indexOfFirst {
aqi in it
}
| 0 | Kotlin | 0 | 1 | 3e68fdf9de6ccffb9e3fc5bbdf070803342e2e34 | 455 | AQICNAPI | Apache License 2.0 |
compiler/ir/backend.js/src/org/jetbrains/kotlin/ir/backend/js/transformers/irToJs/jsAstUtils.kt | niksw7 | 126,284,061 | false | {"Markdown": 44, "Gradle": 288, "XML": 1491, "Gradle Kotlin DSL": 133, "Java Properties": 13, "Shell": 9, "Ignore List": 10, "Batchfile": 8, "Git Attributes": 1, "Protocol Buffer": 9, "Java": 5179, "Kotlin": 37457, "Proguard": 7, "Text": 7807, "JavaScript": 237, "JAR Manifest": 2, "Roff": 207, "Roff Manpage": 26, "JSON": 17, "INI": 77, "AsciiDoc": 1, "HTML": 385, "Groovy": 25, "Maven POM": 85, "CSS": 1, "JFlex": 2, "Ant Build System": 50, "ANTLR": 1} | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.ir.backend.js.transformers.irToJs
import org.jetbrains.kotlin.ir.expressions.IrExpression
import org.jetbrains.kotlin.js.backend.ast.JsDynamicScope
import org.jetbrains.kotlin.js.backend.ast.JsVars
import org.jetbrains.kotlin.name.Name
// TODO don't use JsDynamicScope
val dummyScope = JsDynamicScope
fun Name.toJsName() =
// TODO sanitize
dummyScope.declareName(asString())
fun jsVar(name: Name, initializer: IrExpression?): JsVars {
val jsInitializer = initializer?.accept(IrElementToJsExpressionTransformer(), null)
return JsVars(JsVars.JsVar(name.toJsName(), jsInitializer))
} | 1 | null | 1 | 1 | 833b9f2d5ee538cd5129a0843dcbee870562ca47 | 793 | kotlin | Apache License 2.0 |
src/main/kotlin/matt/nn/deephys/model/importformat/neuron/neuron.kt | mjgroth | 518,764,053 | false | {"Kotlin": 306350, "Python": 15494, "CSS": 778} | package matt.nn.deephys.model.importformat.neuron
import kotlinx.io.bytestring.ByteString
import kotlinx.serialization.Serializable
import matt.nn.deephys.load.cache.RAFCaches
import matt.nn.deephys.load.cache.raf.EvenlySizedRAFCache
import matt.nn.deephys.load.test.dtype.DType
@Serializable
class Neuron
class TestNeuron<A : Number>(
val index: Int,
val layerIndex: Int,
activationsRAF: EvenlySizedRAFCache,
numIms: Int,
dType: DType<A>
) : RAFCaches() {
override fun toString(): String = "TestNeuron $index of layer $layerIndex"
val activations =
object : CachedRAFProp<List<A>>(activationsRAF) {
override fun decode(bytes: ByteString): List<A> = dType.bytesToArray(bytes, numIms)
}
}
| 0 | Kotlin | 0 | 1 | 9c09c9b558cfca9e63b4d3c8491abc5285ce6094 | 749 | deephys | MIT License |
Android/feature/recipe/src/main/java/com/sundaegukbap/banchango/feature/recipe/detail/BtnMoveToRecipe.kt | Sundae-Gukbap | 798,589,515 | false | {"Kotlin": 114056, "Java": 71609, "Swift": 10513, "Dockerfile": 518} | package com.sundaegukbap.banchango.feature.recipe.detail
import android.content.Intent
import android.net.Uri
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonColors
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import com.sundaegukbap.banchango.core.designsystem.theme.LightOrange
import com.sundaegukbap.banchango.core.designsystem.theme.Orange
@Composable
fun BtnMoveToRecipe(
recipeLink: String,
modifier: Modifier = Modifier,
) {
val context = LocalContext.current
Button(
modifier = modifier,
colors =
ButtonColors(
containerColor = Orange,
contentColor = Color.White,
disabledContainerColor = LightOrange,
disabledContentColor = Color.White,
),
onClick = {
context.startActivity(
Intent(Intent.ACTION_VIEW, Uri.parse(recipeLink)),
)
},
) {
Text(text = "레시피 이동하기")
}
}
@Composable
@Preview
fun PreviewBtnMoveToRecipe() {
BtnMoveToRecipe(recipeLink = "https://www.google.com")
}
| 2 | Kotlin | 2 | 5 | ee8853cf410aade0b6e66447cf601ca490808969 | 1,329 | Banchango-AI | MIT License |
languages/php/src/main/kotlin/io/vrap/codegen/languages/php/model/PhpModelModule.kt | commercetools | 136,635,215 | false | null |
package io.vrap.codegen.languages.php.model
import io.vrap.codegen.languages.extensions.deprecated
import io.vrap.codegen.languages.php.ClientConstants
import io.vrap.rmf.codegen.di.RamlGeneratorModule
import io.vrap.rmf.codegen.di.Module
import io.vrap.rmf.codegen.rendering.*
object PhpModelModule: Module {
override fun configure(generatorModule: RamlGeneratorModule) = setOf<CodeGenerator> (
ObjectTypeGenerator(
setOf(
PhpInterfaceObjectTypeRenderer(generatorModule.vrapTypeProvider(), generatorModule.clientConstants()),
PhpObjectTypeRenderer(generatorModule.vrapTypeProvider(), generatorModule.clientConstants()),
PhpBuilderObjectTypeRenderer(generatorModule.vrapTypeProvider(), generatorModule.clientConstants()),
PhpCollectionRenderer(generatorModule.vrapTypeProvider(), generatorModule.clientConstants())
),
generatorModule.allObjectTypes()
),
UnionTypeGenerator(
setOf(
PhpUnionTypeRenderer(generatorModule.vrapTypeProvider(), generatorModule.clientConstants()),
PhpInterfaceUnionTypeRenderer(generatorModule.vrapTypeProvider(), generatorModule.clientConstants()),
PhpUnionCollectionRenderer(generatorModule.vrapTypeProvider(), generatorModule.clientConstants())
),
generatorModule.allUnionTypes()
),
FileGenerator(
setOf(
PhpFileProducer(generatorModule.provideRamlModel(), generatorModule.clientConstants()),
ApiRootFileProducer(generatorModule.provideRamlModel(), generatorModule.vrapTypeProvider(), generatorModule.clientConstants()),
DocsProducer(generatorModule.provideRamlModel(), generatorModule.vrapTypeProvider(), generatorModule.clientConstants())
)
),
MethodGenerator(
setOf(
PhpMethodRenderer(generatorModule.vrapTypeProvider(), generatorModule.clientConstants())
),
generatorModule.allResourceMethods().filterNot { it.deprecated() }
),
ResourceGenerator(
setOf(
PhpMethodBuilderRenderer(generatorModule.provideRamlModel(), generatorModule.vrapTypeProvider(), generatorModule.clientConstants())
),
generatorModule.allResources().filterNot { it.deprecated() }
),
TraitGenerator(setOf(
PhpTraitRenderer(generatorModule.vrapTypeProvider(), generatorModule.clientConstants())
), generatorModule.allTraits())
)
private fun RamlGeneratorModule.clientConstants() =
ClientConstants(this.provideSharedPackageName(), this.provideClientPackageName(), this.providePackageName())
}
| 20 | null | 6 | 14 | 1d29b69ae49e17c28a26be72fd28979ca74922ec | 2,946 | rmf-codegen | Apache License 2.0 |
src/main/kotlin/gq/genprog/dumbdog/game/net/packets/PacketWrapper.kt | general-programming | 135,825,878 | false | {"Kotlin": 24708, "JavaScript": 16582, "CSS": 4207, "HTML": 718} | package gq.genprog.dumbdog.game.net.packets
import com.google.gson.JsonElement
/**
* Written by @offbeatwitch.
* Licensed under MIT.
*/
data class PacketWrapper(val t: String, val d: JsonElement) | 0 | Kotlin | 0 | 1 | db945665706404b084c561f434a5911c319c470c | 200 | dumb-dog | MIT License |
rd-kt/rd-framework/src/jvmTest/kotlin/com/jetbrains/rd/framework/test/cross/CrossTestKtServerBigBuffer.kt | epeshk | 208,844,366 | true | {"C#": 864338, "Kotlin": 816076, "C++": 394787, "CMake": 26903, "Shell": 4363, "Batchfile": 3091, "C": 946} | //@file:Suppress("EXPERIMENTAL_API_USAGE", "EXPERIMENTAL_UNSIGNED_LITERALS")
//
//package com.jetbrains.rd.framework.test.cross
//
//import com.jetbrains.rd.framework.impl.RdProperty
//import com.jetbrains.rd.framework.test.cross.base.CrossTestKtServerBase
//import demo.DemoModel
//
//class CrossTestKtServerBigBuffer : CrossTestKtServerBase() {
// override fun start(args: Array<String>) {
// before(args)
//
// scheduler.queue {
// val model = DemoModel.create(modelLifetime, protocol)
//
// val entity = model.property_with_default
//
// var count = 0
//
// entity.advise(modelLifetime) {
// if (!entity.isLocalChange && (entity as RdProperty<*>).defaultValueChanged) {
// printer.printIfRemoteChange(entity, "property_with_default", it)
//
// if (++count == 2) {
// finished = true
// }
// }
// }
//
// entity.set("".padStart(100000, '1'))
// entity.set("".padStart(100000, '3'))
// }
//
// after()
// }
//}
//
//fun main(args: Array<String>) {
// CrossTestKtServerBigBuffer().run(args)
//} | 0 | C# | 0 | 0 | f291ee314fa23a5f8072cea79e46b9d38fbc7cf4 | 1,219 | rd | Apache License 2.0 |
demo/src/main/java/dev/jjerrell/android/playground/demo/ui/DemoListPage.kt | jjerrell | 698,455,619 | false | {"Kotlin": 23434} | /* (C) 2023 Jacob Jerrell */
package dev.jjerrell.android.playground.demo.ui
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import dev.jjerrell.android.playground.base.android.navigation.BasePlaygroundNavigation
import dev.jjerrell.android.playground.demo.navigation.DemoNavigationGroup
@Composable
fun DemoListPage(modifier: Modifier = Modifier, onRequestDemo: (BasePlaygroundNavigation) -> Unit) {
LazyVerticalGrid(modifier = modifier.padding(8.dp), columns = GridCells.Adaptive(156.dp)) {
items(DemoNavigationGroup.pages.filterNot { it is DemoNavigationGroup.Home }) {
Button(onClick = { onRequestDemo(it) }) { Text("Logging") }
}
}
}
@Preview
@Composable
private fun DemoListPage_Preview() {
DemoListPage(onRequestDemo = {})
}
| 2 | Kotlin | 0 | 0 | e8196d25444230f7d5457772deac6902a1322953 | 1,190 | AndroidPlayground | MIT License |
app/src/main/java/com/suihan74/satena/models/EntryReadActionType.kt | suihan74 | 207,459,108 | false | null | package com.suihan74.satena.models
import androidx.annotation.StringRes
import com.suihan74.satena.R
/** 「あとで読む」エントリを(エントリ一覧画面から)「読んだ」したときの挙動 */
enum class EntryReadActionType(
@StringRes override val textId: Int
) : TextIdContainer {
/** 無言ブクマ */
SILENT_BOOKMARK(R.string.entry_read_action_silent),
/** 「読んだ」タグをつけて無言ブクマ */
READ_TAG(R.string.entry_read_action_read_tag),
/** 任意の定型文でブコメする */
BOILERPLATE(R.string.entry_read_action_boilerplate),
/** ブコメ投稿ダイアログを表示する */
DIALOG(R.string.entry_read_action_dialog),
/** ブクマを削除 */
REMOVE(R.string.entry_read_action_remove);
companion object {
fun fromOrdinal(int: Int) = values().getOrElse(int) { SILENT_BOOKMARK }
}
}
| 14 | null | 1 | 7 | d18b936e17647745920115041fe15d761a209d8a | 729 | Satena | MIT License |
lib/src/main/kotlin/dev/hossain/android/catalogparser/Config.kt | priyankpat | 440,923,899 | true | {"Kotlin": 14100} | package dev.hossain.android.catalogparser
/**
* Contains CSV header names found in Google Play Device Catalog
* See https://play.google.com/console/about/devicecatalog/ to get latest version.
*/
object Config {
const val CSV_MULTI_VALUE_SEPARATOR = ";"
const val CSV_KEY_MANUFACTURER = "Manufacturer"
const val CSV_KEY_MODEL_NAME = "Model Name"
const val CSV_KEY_MODEL_CODE = "Model Code"
const val CSV_KEY_RAM = "RAM (TotalMem)"
const val CSV_KEY_FORM_FACTOR = "Form Factor"
const val CSV_KEY_SOC = "System on Chip"
const val CSV_KEY_SCREEN_SIZES = "Screen Sizes"
const val CSV_KEY_SCREEN_DENSITIES = "Screen Densities"
const val CSV_KEY_ABIS = "ABIs"
const val CSV_KEY_SDK_VERSIONS = "Android SDK Versions"
const val CSV_KEY_OPENGL_ES_VERSIONS = "OpenGL ES Versions"
} | 0 | null | 0 | 1 | 64867a574b016d28e4bec4cd388a65f438f3175b | 823 | android-device-catalog-parser | Apache License 2.0 |
app/src/main/java/hu/csabapap/seriesreminder/data/db/daos/SeasonsDao.kt | csabapap | 112,928,453 | false | null | package hu.csabapap.seriesreminder.data.db.daos
import androidx.lifecycle.LiveData
import androidx.room.*
import hu.csabapap.seriesreminder.data.db.entities.SRSeason
import hu.csabapap.seriesreminder.data.db.relations.SeasonWithEpisodes
import kotlinx.coroutines.coroutineScope
@Dao
abstract class SeasonsDao {
@Insert(onConflict = OnConflictStrategy.ABORT)
abstract fun insert(season: SRSeason): Long
@Insert(onConflict = OnConflictStrategy.IGNORE)
abstract suspend fun insertCoroutine(season: SRSeason): Long
@Query("SELECT * FROM seasons WHERE show_id = :showId ORDER BY number")
abstract suspend fun getSeasons(showId: Int): List<SRSeason>?
@Query("SELECT * FROM seasons WHERE show_id = :showId AND number > 0 ORDER BY number")
abstract fun getSeasonsLiveData(showId: Int): LiveData<List<SRSeason>>
@Query("SELECT * FROM seasons WHERE show_id = :showId AND number = :season LIMIT 1")
abstract suspend fun getSeason(showId: Int, season: Int): SRSeason?
@Query("SELECT * FROM seasons WHERE show_id = :showId AND number = :season LIMIT 1")
abstract suspend fun getSeasonWithEpisodes(showId: Int, season: Int): SeasonWithEpisodes?
@Update
abstract suspend fun update(season: SRSeason)
@Update
abstract suspend fun update(season: List<SRSeason>)
@Update
abstract fun updateSync(season: SRSeason)
@Transaction
open suspend fun upsert(seasons: List<SRSeason>) = coroutineScope {
seasons.map {
val result = insertCoroutine(it)
if (result == -1L) {
update(it)
}
}
}
} | 0 | Kotlin | 0 | 1 | 5e63b26f5ec8a1cf8d19f40f44fcb8a39325f34d | 1,625 | SeriesReminder | MIT License |
shared/presentation/src/commonMain/kotlin/com/moonlightbutterfly/rigplay/gamelist/view/GameListView.kt | Dragoonov | 653,808,838 | false | null | package com.moonlightbutterfly.rigplay.gamelist.view
import com.arkivanov.mvikotlin.core.view.MviView
import com.moonlightbutterfly.rigplay.gamelist.model.GameListItem
interface GameListView: MviView<GameListView.Model, GameListView.Event> {
data class Model(
val isLoading: Boolean,
val isError: Boolean,
val games: List<GameListItem>
)
sealed class Event {
object RefreshTriggered : Event()
}
} | 0 | Kotlin | 0 | 0 | c8a45a5db1fbe73f1801b67dbdd0b70a1757b380 | 448 | RigPlay | Apache License 2.0 |
src/test/kotlin/icu/windea/pls/dev/cwt/CwtGameRuleConfigGeneratorTest.kt | DragonKnightOfBreeze | 328,104,626 | false | null | package icu.windea.pls.dev.cwt
import icu.windea.pls.lang.model.*
import org.junit.*
class CwtGameRuleConfigGeneratorTest {
@Test
fun testForStellaris() {
CwtGameRuleConfigGenerator(
ParadoxGameType.Stellaris,
"common/game_rules/00_rules.txt",
"cwt/cwtools-stellaris-config/config/game_rules.cwt",
).generate()
}
} | 8 | Kotlin | 4 | 22 | c6c558b82c84b9e88c0ee179f64cbfdda66b8082 | 380 | Paradox-Language-Support | MIT License |
composeApp/src/commonMain/kotlin/com/jetbrains/kmpapp/domain/mappers/ShoppingItemMapper.kt | rodriguesv2 | 774,622,664 | false | {"Kotlin": 44401, "Swift": 661} | package com.jetbrains.kmpapp.domain.mappers
import com.jetbrains.kmpapp.data.models.ShoppingItemModel
import com.jetbrains.kmpapp.domain.entities.ShoppingItem
fun ShoppingItem.toShoppingItemModel() = ShoppingItemModel(
id = this.id?.toLong(),
name = this.title,
quantity = this.quantity.toInt(),
)
fun ShoppingItemModel.toShoppingItemEntity() = ShoppingItem(
id = this.id?.toString() ?: "",
title = this.name,
quantity = quantity.toString(),
) | 0 | Kotlin | 0 | 1 | d87ec90f2e16e528a5b49dc4fe6e5d5a60f3bb20 | 470 | shopping-list-kmp | Apache License 2.0 |
app/src/main/java/com/musicapp/cosymusic/local/SearchHistory.kt | OrientLegend | 497,603,962 | false | null | package com.musicapp.cosymusic.local
import android.os.Parcelable
import com.musicapp.cosymusic.application.App
import com.musicapp.cosymusic.util.KString
import kotlinx.parcelize.Parcelize
/**
* @author Eternal Epoch
* @date 2022/6/1 8:41
*/
//搜索历史单例类
object SearchHistory {
private var searchHistoryData = SearchHistoryData(mutableListOf())
fun addSearchHistory(searchText: String){
if(searchText !in searchHistoryData.list){
searchHistoryData.list.add(0, searchText)
}else{
searchHistoryData.list.remove(searchText)
searchHistoryData.list.add(0, searchText)
}
App.mmkv.encode(KString.SEARCH_HISTORY, searchHistoryData)
}
fun readSearchHistory(): MutableList<String>{
searchHistoryData = App.mmkv.decodeParcelable(KString.SEARCH_HISTORY, SearchHistoryData::class.java)
?: SearchHistoryData(mutableListOf())
return searchHistoryData.list
}
fun clearSearchHistory(){
searchHistoryData.list.clear()
App.mmkv.encode(KString.SEARCH_HISTORY, searchHistoryData)
}
@Parcelize
data class SearchHistoryData(
val list: MutableList<String>
): Parcelable
} | 0 | Kotlin | 0 | 1 | 27f41eb491bf8be8f928e9c5b28159a119ce6e07 | 1,217 | CosyMusic | Apache License 2.0 |
app/src/main/java/com/sdss/workout/program/OneRepProgramSetup.kt | charmas3r | 374,553,434 | true | {"Kotlin": 182117, "Swift": 21514, "Ruby": 2200, "HTML": 560} | package com.sdss.workout.program
import android.util.Log
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.material.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
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.text.input.KeyboardType
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.sdss.workout.R
import com.sdss.workout.ui.buttons.DropdownMenuItemContent
import com.sdss.workout.ui.buttons.PrimaryDropdownMenu
@Composable
fun OneRepMaxProgramSetupScreen(navController: NavController?) {
ProgramSetupTemplate(
primaryBtnTitle = stringResource(id = R.string.btn_continue),
onPrimaryClick = {
navController?.navigate(ProgramScreens.RepeatCycle.route)
}
) {
OneRepMaxProgramSetup()
}
}
@Composable
fun OneRepMaxProgramSetup() {
val benchState = remember { mutableStateOf(TextFieldValue()) }
val squatState = remember { mutableStateOf(TextFieldValue()) }
val deadState = remember { mutableStateOf(TextFieldValue()) }
val shoulState = remember { mutableStateOf(TextFieldValue()) }
Column(Modifier.padding(16.dp)) {
Text(text = stringResource(id = R.string.setup_one_rep_max_text))
Spacer(modifier = Modifier.height(8.dp))
Row {
OutlinedTextField(
value = benchState.value,
onValueChange = { benchState.value = it },
label = { Text(stringResource(id = R.string.lift_bench_press)) },
modifier = Modifier
.fillMaxWidth(.5f),
singleLine = true,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number
),
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Transparent
)
)
Spacer(modifier = Modifier.width(16.dp))
PrimaryDropdownMenu(
items = dropDownItems(),
menuModifier = Modifier.width(60.dp),
firstItemModifier = Modifier
.height(60.dp)
.padding(start = 16.dp, top = 32.dp)
)
}
Spacer(modifier = Modifier.height(8.dp))
Row {
OutlinedTextField(
value = squatState.value,
onValueChange = { squatState.value = it },
label = { Text(stringResource(id = R.string.lift_squats)) },
modifier = Modifier
.fillMaxWidth(.5f),
singleLine = true,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number
),
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Transparent
)
)
Spacer(modifier = Modifier.width(16.dp))
PrimaryDropdownMenu(
items = dropDownItems(),
menuModifier = Modifier.width(60.dp),
firstItemModifier = Modifier
.height(60.dp)
.padding(start = 16.dp, top = 32.dp)
)
}
Spacer(modifier = Modifier.height(8.dp))
Row {
OutlinedTextField(
value = deadState.value,
onValueChange = { deadState.value = it },
label = { Text(stringResource(id = R.string.lift_deadlifts)) },
modifier = Modifier
.fillMaxWidth(.5f),
singleLine = true,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number
),
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Transparent
)
)
Spacer(modifier = Modifier.width(16.dp))
PrimaryDropdownMenu(
items = dropDownItems(),
menuModifier = Modifier.width(60.dp),
firstItemModifier = Modifier
.height(60.dp)
.padding(start = 16.dp, top = 32.dp)
)
}
Spacer(modifier = Modifier.height(8.dp))
Row {
OutlinedTextField(
value = shoulState.value,
onValueChange = { shoulState.value = it },
label = { Text(stringResource(id = R.string.lift_shoulder_press)) },
modifier = Modifier
.fillMaxWidth(.5f),
singleLine = true,
keyboardOptions = KeyboardOptions(
keyboardType = KeyboardType.Number
),
colors = TextFieldDefaults.textFieldColors(
backgroundColor = Color.Transparent
)
)
Spacer(modifier = Modifier.width(16.dp))
PrimaryDropdownMenu(
items = dropDownItems(),
menuModifier = Modifier.width(60.dp),
firstItemModifier = Modifier
.height(60.dp)
.padding(start = 16.dp, top = 32.dp)
)
}
}
}
private fun dropDownItems(): List<DropdownMenuItemContent> {
return listOf(
DropdownMenuItemContent(
isFirstPosition = true,
titleRes = R.string.units_si,
onClick = {
Log.d("DropdownMenu", "menu item clicked")
}
),
DropdownMenuItemContent(
isFirstPosition = false,
titleRes = R.string.units_std,
onClick = {
Log.d("DropdownMenu", "menu item clicked")
},
)
)
} | 0 | Kotlin | 0 | 0 | 946c3deb810fdc01d5738457b2322457f6f08071 | 6,215 | WorkoutApp | Apache License 2.0 |
src/test/kotlin/g2801_2900/s2869_minimum_operations_to_collect_elements/SolutionTest.kt | javadev | 190,711,550 | false | {"Kotlin": 4870729, "TypeScript": 50437, "Python": 3646, "Shell": 994} | package g2801_2900.s2869_minimum_operations_to_collect_elements
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.MatcherAssert.assertThat
import org.junit.jupiter.api.Test
internal class SolutionTest {
@Test
fun minOperations() {
assertThat(Solution().minOperations(mutableListOf(3, 1, 5, 4, 2), 2), equalTo(4))
}
@Test
fun minOperations2() {
assertThat(Solution().minOperations(mutableListOf(3, 1, 5, 4, 2), 5), equalTo(5))
}
@Test
fun minOperations3() {
assertThat(Solution().minOperations(mutableListOf(3, 2, 5, 3, 1), 3), equalTo(4))
}
}
| 0 | Kotlin | 20 | 43 | e8b08d4a512f037e40e358b078c0a091e691d88f | 618 | LeetCode-in-Kotlin | MIT License |
jdbc-framework/src/main/kotlin/com/github/gr3gdev/jdbc/dao/StringGenerator.kt | gr3gdev | 338,283,560 | false | {"Gradle Kotlin DSL": 5, "Shell": 1, "Text": 16, "Ignore List": 1, "Batchfile": 1, "Markdown": 1, "INI": 6, "YAML": 1, "Java": 3, "SQL": 4, "Kotlin": 63} | package com.github.gr3gdev.jdbc.dao
import com.github.gr3gdev.jdbc.processor.JDBCProcessor
internal interface StringGenerator {
fun tabs(nb: Int = 3) = JDBCProcessor.TAB.repeat(nb)
} | 1 | null | 1 | 1 | 89cf92dc7374f0531b21449a6cd72edce188946d | 190 | jdbc-framework | MIT License |
library/src/main/java/org/meganekkovr/xml/ScaleHandler.kt | ejeinc | 42,510,284 | false | null | package org.meganekkovr.xml
import android.content.Context
import org.meganekkovr.Entity
/**
* Define `scale` attribute.
*/
internal class ScaleHandler : XmlAttributeParser.XmlAttributeHandler {
override val attributeName = "scale"
override fun parse(entity: Entity, rawValue: String, context: Context) {
val strs = rawValue.split("\\s+".toRegex(), 3)
when (strs.size) {
1 -> {
// ex. scale="1.2"
// Apply scaling to all axises.
val scale = java.lang.Float.parseFloat(strs[0])
entity.setScale(scale, scale, scale)
}
2 -> {
// ex. scale="0.5 2.0"
// Apply scaling to X and Y axises.
val x = java.lang.Float.parseFloat(strs[0])
val y = java.lang.Float.parseFloat(strs[1])
entity.setScale(x, y, 1.0f)
}
3 -> {
// ex. scale="1.1 1.25 2.0"
// Apply scaling to each axises.
val x = java.lang.Float.parseFloat(strs[0])
val y = java.lang.Float.parseFloat(strs[1])
val z = java.lang.Float.parseFloat(strs[2])
entity.setScale(x, y, z)
}
}
}
}
| 2 | C | 11 | 25 | c62d82e8a5d2eb67af056282f4ff7c90cbd73494 | 1,298 | Meganekko | Apache License 2.0 |
shared/src/commonMain/kotlin/com.sbga.sdgbapp/Net/VO/NetQuery.kt | NickJi2019 | 717,286,554 | false | {"Kotlin": 134744, "Ruby": 2257, "Swift": 1595, "JavaScript": 485, "HTML": 323} | package com.sbga.sdgbapp.Net.VO
import com.sbga.sdgbapp.Utility.Extensions.deserialize
import com.sbga.sdgbapp.Utility.Extensions.serialize
class NetQuery<T0 : VOSerializer, T1 : VOSerializer> {
var api: String
var UserId: ULong
var request: T0?
var response: T1?
constructor(api: String, userId: ULong) {
this.api = api + "MaimaiChn"
this.UserId = userId
this.request = null
this.response = null
}
inline fun <reified T : VOSerializer> getRequest(): String {
return (this.request as T).serialize<T>()
}
inline fun <reified T : VOSerializer> setResponse(str: String) {
this.response = str.deserialize<T>() as T1
}
}
| 0 | Kotlin | 1 | 4 | 4358ab163f560a9e28255b789e42b8054e4cd8f9 | 711 | SDGBApp | MIT License |
features/navigation/src/main/kotlin/com/schatzdesigns/features/navigation/di/NavigationModule.kt | zakayothuku | 282,235,374 | false | null | /*
* Copyright 2020 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.schatzdesigns.features.navigation.di
import androidx.annotation.VisibleForTesting
import androidx.annotation.VisibleForTesting.PRIVATE
import com.schatzdesigns.commons.ui.extensions.viewModel
import com.schatzdesigns.core.di.scopes.FeatureScope
import com.schatzdesigns.features.navigation.NavigationFragment
import com.schatzdesigns.features.navigation.NavigationViewModel
import dagger.Module
import dagger.Provides
/**
* Class that contributes to the object graph [NavigationComponent].
*
* @see Module
*/
@Module
class NavigationModule(@VisibleForTesting(otherwise = PRIVATE) val fragment: NavigationFragment) {
/**
* Create a provider method binding for [NavigationViewModel].
*
* @return Instance of view model.
* @see Provides
*/
@Provides
@FeatureScope
fun providesNavigationViewModel() = fragment.viewModel {
NavigationViewModel()
}
}
| 0 | Kotlin | 1 | 3 | d1113d3490e3ff486d8e0c5aedc8ea8060e71466 | 1,508 | kotlin-modular-mvvm-template | Apache License 2.0 |
Linear Keyboard/main.kt | oarsay | 462,390,563 | false | null | import java.lang.Math.abs
fun main() {
var t = readLine()!!.toInt()
while(t > 0){
val alphabet = readLine()!!
val str = readLine()!!
var time = 0
if(str.length != 1){
for(current in 0 until str.lastIndex){
time += kotlin.math.abs(getIndexOf(str[current], alphabet) - getIndexOf(str[current + 1], alphabet))
}
}
println(time)
t--
}
}
fun getIndexOf(char: Char, alphabet: String): Int{
for(i in alphabet.indices)
if(alphabet[i] == char) return i
return -1
}
| 0 | Kotlin | 0 | 0 | 98784bec880ce971924051a8ac7e9e783f4e7be4 | 588 | codeforces | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.