path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/io/sinzak/android/remote/dataclass/request/certify/UnivCertifyRequest.kt | SINZAK | 567,559,091 | false | {"Kotlin": 482864} | package io.sinzak.android.remote.dataclass.request.certify
import com.google.gson.annotations.SerializedName
import io.sinzak.android.remote.dataclass.CRequest
data class UnivCertifyRequest(
@SerializedName("univ") val univ : String,
@SerializedName("univ_email") val univ_email : String? = null,
) : CRequest()
| 1 | Kotlin | 0 | 3 | 3467e8ee8afeb6b91b51f3a454f7010bc717c436 | 322 | sinzak-android | MIT License |
services/test-suites/src/main/kotlin/io/github/mkutz/greatgradlegoodies/rating/ReadRatingDto.kt | mkutz | 788,417,831 | false | {"Kotlin": 94264, "Shell": 448} | package io.github.mkutz.greatgradlegoodies.rating
import java.time.format.DateTimeFormatter.ISO_INSTANT
data class ReadRatingDto(
val id: String,
val productId: String,
val userName: String,
val stars: Int,
val comment: String?,
val created: String
) {
constructor(
rating: Rating
) : this(
id = rating.id.toString(),
productId = rating.productId.toString(),
userName = rating.userName,
stars = rating.stars,
comment = rating.comment,
created = ISO_INSTANT.format(rating.created)
)
}
| 1 | Kotlin | 0 | 0 | e727ef17d48e63f14a7a30507efa5013ed3e5dd3 | 532 | great-gradle-goodies | Apache License 2.0 |
app/src/main/java/che/codes/posts/core/viewmodel/PostsViewModelFactory.kt | cjami | 182,398,150 | false | null | package che.codes.posts.core.viewmodel
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import che.codes.posts.core.data.PostsDataSource
import che.codes.posts.features.details.PostDetailsViewModel
import che.codes.posts.features.list.PostListViewModel
class PostsViewModelFactory(private val dataSource: PostsDataSource) : ViewModelProvider.Factory {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel> create(modelClass: Class<T>): T {
return when {
modelClass.isAssignableFrom(PostListViewModel::class.java) -> {
PostListViewModel(dataSource) as T
}
modelClass.isAssignableFrom(PostDetailsViewModel::class.java) -> {
PostDetailsViewModel(dataSource) as T
}
else -> throw IllegalArgumentException(
"${modelClass.simpleName} is an unknown view model type"
)
}
}
} | 0 | Kotlin | 0 | 0 | 09d55efda55b240ac0e317a072b9b426e0fe1573 | 951 | Posts | Academic Free License v1.1 |
common/src/commonMain/kotlin/tk/zwander/commonCompose/view/components/AboutInfo.kt | zacharee | 342,079,605 | false | {"Kotlin": 519700, "AIDL": 84} | package tk.zwander.commonCompose.view.components
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.text.ClickableText
import androidx.compose.material3.LocalContentColor
import androidx.compose.material3.LocalTextStyle
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.ExperimentalTextApi
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.UrlAnnotation
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.withAnnotation
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import tk.zwander.common.GradleConfig
import tk.zwander.common.util.UrlHandler
import tk.zwander.common.util.invoke
import tk.zwander.samloaderkotlin.resources.MR
@OptIn(ExperimentalTextApi::class)
@Composable
fun AboutInfo(
modifier: Modifier = Modifier
) {
Column(modifier = modifier) {
val primaryColor = MaterialTheme.colorScheme.primary
val contentColor = LocalContentColor.current
val copyrightAnnotated = buildAnnotatedString {
withStyle(
SpanStyle(
color = contentColor,
fontSize = 16.sp,
),
) {
append(MR.strings.version("${GradleConfig.versionName} © "))
withStyle(
SpanStyle(
color = MaterialTheme.colorScheme.primary,
textDecoration = TextDecoration.Underline,
),
) {
withAnnotation(UrlAnnotation("https://zwander.dev")) {
append(MR.strings.zacharyWander())
}
}
}
}
val samloaderAnnotated = buildAnnotatedString {
withStyle(
SpanStyle(
color = contentColor,
fontSize = 16.sp,
),
) {
append(MR.strings.basedOn())
append(" ")
withAnnotation(UrlAnnotation("https://github.com/nlscc/samloader")) {
withStyle(
SpanStyle(
color = primaryColor,
textDecoration = TextDecoration.Underline,
),
) {
append(MR.strings.samloader())
}
}
}
}
ClickableText(
text = copyrightAnnotated,
onClick = {
copyrightAnnotated.getUrlAnnotations(it, it)
.firstOrNull()?.let { item ->
UrlHandler.launchUrl(item.item.url)
}
},
style = LocalTextStyle.current.copy(LocalContentColor.current),
)
Spacer(Modifier.height(4.dp))
ClickableText(
text = samloaderAnnotated,
onClick = {
samloaderAnnotated.getUrlAnnotations(it, it)
.firstOrNull()?.let { item ->
UrlHandler.launchUrl(item.item.url)
}
},
style = LocalTextStyle.current.copy(LocalContentColor.current),
)
}
}
| 5 | Kotlin | 98 | 830 | bf5ee5afd620be2d400bc231997831518da14d4f | 3,576 | SamloaderKotlin | MIT License |
app/src/main/java/com/project/segunfrancis/coolmovies/ui/favorite/adapter/FavoriteMovieAdapter.kt | segunfrancis | 317,925,794 | false | null | package com.project.segunfrancis.coolmovies.ui.favorite.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import com.project.segunfrancis.coolmovies.R
import com.project.segunfrancis.coolmovies.data.model.Result
import com.project.segunfrancis.coolmovies.databinding.ItemMovieListBinding
/**
* Created by SegunFrancis
*/
class FavoriteMovieAdapter(private val onClick: (result: Result) -> Unit) :
ListAdapter<Result, FavoriteMovieViewHolder>(FavoriteDiffUtil) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavoriteMovieViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.item_movie_list, parent, false)
return FavoriteMovieViewHolder(ItemMovieListBinding.bind(view), onClick)
}
override fun onBindViewHolder(holder: FavoriteMovieViewHolder, position: Int) {
holder.bind(getItem(position))
}
companion object FavoriteDiffUtil : DiffUtil.ItemCallback<Result>() {
override fun areItemsTheSame(oldItem: Result, newItem: Result): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Result, newItem: Result): Boolean {
return oldItem == newItem
}
}
} | 0 | Kotlin | 0 | 0 | da876132cceb8db30b0074ec919ee9685ea42f1d | 1,373 | Cool-Movies | Apache License 2.0 |
app/src/main/java/com/project/segunfrancis/coolmovies/ui/favorite/adapter/FavoriteMovieAdapter.kt | segunfrancis | 317,925,794 | false | null | package com.project.segunfrancis.coolmovies.ui.favorite.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import com.project.segunfrancis.coolmovies.R
import com.project.segunfrancis.coolmovies.data.model.Result
import com.project.segunfrancis.coolmovies.databinding.ItemMovieListBinding
/**
* Created by SegunFrancis
*/
class FavoriteMovieAdapter(private val onClick: (result: Result) -> Unit) :
ListAdapter<Result, FavoriteMovieViewHolder>(FavoriteDiffUtil) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FavoriteMovieViewHolder {
val view =
LayoutInflater.from(parent.context).inflate(R.layout.item_movie_list, parent, false)
return FavoriteMovieViewHolder(ItemMovieListBinding.bind(view), onClick)
}
override fun onBindViewHolder(holder: FavoriteMovieViewHolder, position: Int) {
holder.bind(getItem(position))
}
companion object FavoriteDiffUtil : DiffUtil.ItemCallback<Result>() {
override fun areItemsTheSame(oldItem: Result, newItem: Result): Boolean {
return oldItem.id == newItem.id
}
override fun areContentsTheSame(oldItem: Result, newItem: Result): Boolean {
return oldItem == newItem
}
}
} | 0 | Kotlin | 0 | 0 | da876132cceb8db30b0074ec919ee9685ea42f1d | 1,373 | Cool-Movies | Apache License 2.0 |
cottontaildb-dbms/src/main/kotlin/org/vitrivr/cottontail/utilities/VectorUtility.kt | vitrivr | 160,775,368 | false | null | package org.vitrivr.cottontail.utilities
import org.vitrivr.cottontail.core.values.*
import org.vitrivr.cottontail.core.values.types.VectorValue
import java.util.*
/**
* Utility class used to generate a stream of [VectorValue]s.
*
* @author Ralph Gasser
* @version 1.2
*/
object VectorUtility {
/**
* Generates a sequence of random [BooleanVectorValue] of the given size.
*
* @param size The size of the random vectors.
* @param items The number of items to return from the [Iterator]
*/
fun randomBoolVectorSequence(size: Int, items: Int = Int.MAX_VALUE, random: SplittableRandom = SplittableRandom()): Iterator<BooleanVectorValue> = object : Iterator<BooleanVectorValue> {
var left = items
override fun hasNext(): Boolean = this.left > 0
override fun next(): BooleanVectorValue {
this.left -= 1
return BooleanVectorValue.random(size, random)
}
}
/**
* Generates a sequence of random [IntVectorValue] of the given size.
*
* @param size The size of the random vectors.
* @param items The number of items to return from the [Iterator]
*/
fun randomIntVectorSequence(size: Int, items: Int = Int.MAX_VALUE, random: SplittableRandom = SplittableRandom()): Iterator<IntVectorValue> = object : Iterator<IntVectorValue> {
var left = items
override fun hasNext(): Boolean = this.left > 0
override fun next(): IntVectorValue {
this.left -= 1
return IntVectorValue.random(size, random)
}
}
/**
* Generates a sequence of random [LongVectorValue] of the given size.
*
* @param size The size of the random vectors.
* @param items The number of items to return from the [Iterator]
*/
fun randomLongVectorSequence(size: Int, items: Int = Int.MAX_VALUE, random: SplittableRandom = SplittableRandom()): Iterator<LongVectorValue> = object : Iterator<LongVectorValue> {
var left = items
override fun hasNext(): Boolean = this.left > 0
override fun next(): LongVectorValue {
this.left -= 1
return LongVectorValue.random(size, random)
}
}
/**
* Generates a sequence of random [FloatVectorValue] of the given size.
*
* @param size The size of the random vectors.
* @param items The number of items to return from the [Iterator]
*/
fun randomFloatVectorSequence(size: Int, items: Int = Int.MAX_VALUE, random: SplittableRandom = SplittableRandom()): Iterator<FloatVectorValue> = object : Iterator<FloatVectorValue> {
var left = items
override fun hasNext(): Boolean = this.left > 0
override fun next(): FloatVectorValue {
this.left -= 1
return FloatVectorValue.random(size, random)
}
}
/**
* Generates a sequence of random [DoubleVectorValue] of the given size.
*
* @param size The size of the random vectors.
* @param items The number of items to return from the [Iterator]
*/
fun randomDoubleVectorSequence(size: Int, items: Int = Int.MAX_VALUE, random: SplittableRandom = SplittableRandom()): Iterator<DoubleVectorValue> = object : Iterator<DoubleVectorValue> {
var left = items
override fun hasNext(): Boolean = this.left > 0
override fun next(): DoubleVectorValue {
this.left -= 1
return DoubleVectorValue.random(size, random)
}
}
/**
* Generates a sequence of random [Complex32VectorValue] of the given size.
*
* @param size The size of the random vectors.
* @param items The number of items to return from the [Iterator]
*/
fun randomComplex32VectorSequence(size: Int, items: Int = Int.MAX_VALUE, random: SplittableRandom = SplittableRandom()): Iterator<Complex32VectorValue> = object : Iterator<Complex32VectorValue> {
var left = items
override fun hasNext(): Boolean = this.left > 0
override fun next(): Complex32VectorValue {
this.left -= 1
return Complex32VectorValue.random(size, random)
}
}
/**
* Generates a sequence of random [Complex64VectorValue] of the given size.
*
* @param size The size of the random vectors.
* @param items The number of items to return from the [Iterator]
*/
fun randomComplex64VectorSequence(size: Int, items: Int = Int.MAX_VALUE, random: SplittableRandom = SplittableRandom()): Iterator<Complex64VectorValue> = object : Iterator<Complex64VectorValue> {
var left = items
override fun hasNext(): Boolean = this.left > 0
override fun next(): Complex64VectorValue {
this.left -= 1
return Complex64VectorValue.random(size, random)
}
}
} | 8 | Kotlin | 15 | 15 | c6e06263d9163f697e0aa5dc334a910521620215 | 4,814 | cottontaildb | MIT License |
core/src/main/kotlin/in/specmatic/stub/RequestHandler.kt | znsio | 247,710,440 | false | {"Kotlin": 3061197, "Shell": 3149, "Python": 2412, "Nix": 391, "Dockerfile": 367} | package `in`.specmatic.stub
import `in`.specmatic.core.HttpRequest
interface RequestHandler {
val name: String
fun handleRequest(httpRequest: HttpRequest): HttpStubResponse?
} | 30 | Kotlin | 51 | 250 | 938c84c27a2cdbccff44467114ae243c63f91cb7 | 185 | specmatic | MIT License |
core/src/commonMain/kotlin/ru/krindra/vkkt/core/VkApi.kt | krindra | 780,080,411 | false | {"Kotlin": 1336107} | package ru.krindra.vkkt.core
import ru.krindra.vkkt.objects.VkApiError
import ru.krindra.vkkt.methods.*
import io.ktor.client.*
import io.ktor.client.request.*
import io.ktor.client.statement.*
import ru.krindra.vkkt.core.enums.VkLanguageEnum
class VkApi(
token: String,
language: VkLanguageEnum? = null,
version: String = "5.199",
val httpClient: HttpClient = HttpClient(),
) {
private val args = buildMap<String, Any> {
put("access_token", token)
put("v", version)
if (language != null) put("lang", language)
}
val account by lazy {Account(::method) }
val ads by lazy {Ads(::method) }
val adsweb by lazy {Adsweb(::method) }
val apps by lazy {Apps(::method) }
val appwidgets by lazy {Appwidgets(::method) }
val asr by lazy {Asr(::method) }
val auth by lazy {Auth(::method) }
val board by lazy {Board(::method) }
val bugtracker by lazy {Bugtracker(::method) }
val calls by lazy {Calls(::method) }
val database by lazy {Database(::method) }
val docs by lazy {Docs(::method) }
val donut by lazy {Donut(::method) }
val downloadedgames by lazy {Downloadedgames(::method) }
val execute by lazy {Execute(::method) }
val fave by lazy {Fave(::method) }
val friends by lazy {Friends(::method) }
val gifts by lazy {Gifts(::method) }
val groups by lazy {Groups(::method) }
val leadforms by lazy {Leadforms(::method) }
val likes by lazy {Likes(::method) }
val market by lazy {Market(::method) }
val messages by lazy {Messages(::method) }
val newsfeed by lazy {Newsfeed(::method) }
val notes by lazy {Notes(::method) }
val notifications by lazy {Notifications(::method) }
val orders by lazy {Orders(::method) }
val pages by lazy {Pages(::method) }
val photos by lazy {Photos(::method) }
val podcasts by lazy {Podcasts(::method) }
val polls by lazy {Polls(::method) }
val prettycards by lazy {Prettycards(::method) }
val search by lazy {Search(::method) }
val secure by lazy {Secure(::method) }
val stats by lazy {Stats(::method) }
val status by lazy {Status(::method) }
val storage by lazy {Storage(::method) }
val store by lazy {Store(::method) }
val stories by lazy {Stories(::method) }
val streaming by lazy {Streaming(::method) }
val users by lazy {Users(::method) }
val utils by lazy {Utils(::method) }
val video by lazy {Video(::method) }
val wall by lazy {Wall(::method) }
val widgets by lazy {Widgets(::method) }
suspend fun method(
method: String,
args: Map<String, Any?>? = null,
): String {
val arguments = if (args != null) args + this.args else this.args
val url = "$URL$method"
val response = httpClient.get(url, arguments)
if (response.contains("error")) {
val code = response.split("error_code\":")[1]
.split(",")[0].toInt()
val errorMsg = response.split("error_msg\":\"")[1]
.split("\",")[0]
throw VkApiError(code, errorMsg)
}
return response
}
companion object {
const val URL = "https://api.vk.com/method/"
}
}
private suspend fun HttpClient.get(url: String, parameters: Map<String, Any?>): String =
this.get(url) {
url {
for (p in parameters) {
if (p.value != null) this.parameters.append(p.key, p.value.toString())
}
}
}.bodyAsText()
| 0 | Kotlin | 0 | 1 | 58407ea02fc9d971f86702f3b822b33df65dd3be | 3,501 | VKKT | MIT License |
app/src/main/java/com/dede/nativetools/netspeed/typeface/DebugTypeface.kt | hushenghao | 242,718,110 | false | null | package com.dede.nativetools.netspeed.typeface
import android.content.Context
import android.graphics.Typeface
import com.dede.nativetools.R
class DebugTypeface(context: Context) : TypefaceGetter {
var fontName = "OpenSans-Regular.ttf"
private set
private val typeface =
kotlin
.runCatching { Typeface.createFromAsset(context.assets, fontName) }
.onFailure {
val sysDef = context.getString(R.string.summary_default)
fontName = "Debug Error(%s)".format(sysDef)
}
.getOrDefault(Typeface.DEFAULT)
override fun get(style: Int): Typeface {
return TypefaceGetter.applyStyle(typeface, style)
}
}
| 0 | Kotlin | 5 | 43 | a0194ca906fe36b68b29624203b7a80c7bc47bcc | 714 | NativeTools | Apache License 2.0 |
libraries/core/src/main/kotlin/com/bumble/appyx/navmodel/spotlight/SpotlightExt.kt | bumble-tech | 493,334,393 | false | null | package com.bumble.appyx.navmodel.spotlight
import kotlinx.coroutines.flow.map
fun <T : Any> Spotlight<T>.hasNext() =
elements.map { value -> value.lastIndex != elements.value.currentIndex }
fun <T : Any> Spotlight<T>.hasPrevious() =
elements.map { value -> value.currentIndex != 0 }
fun <T : Any> Spotlight<T>.activeIndex() =
elements.map { value -> value.currentIndex }
fun <T : Any> Spotlight<T>.current() =
elements.map { value -> value.current?.key?.navTarget }
fun <T : Any> Spotlight<T>.elementsCount() =
elements.value.size
| 68 | Kotlin | 45 | 754 | 1c13ab49fb3e2eb0bcd192332d597f8c05d3f6a9 | 558 | appyx | Apache License 2.0 |
app/src/main/java/com/example/quickmdcapture/TransparentActivity.kt | Fertion | 858,416,675 | false | {"Kotlin": 44865, "Ruby": 1021} | package com.example.quickmdcapture
import android.os.Bundle
import android.view.WindowManager
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.ViewModelProvider
class TransparentActivity : AppCompatActivity() {
private lateinit var settingsViewModel: SettingsViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
settingsViewModel = ViewModelProvider(this)[SettingsViewModel::class.java]
window.setFlags(
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE or
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
)
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = android.graphics.Color.TRANSPARENT
window.navigationBarColor = android.graphics.Color.TRANSPARENT
val isAutoSaveEnabled = settingsViewModel.isAutoSaveEnabled.value
val dialog = NoteDialog(this, isAutoSaveEnabled)
dialog.setOnDismissListener {
finish()
overridePendingTransition(0, 0)
}
dialog.show()
if (intent.getBooleanExtra("START_VOICE_INPUT", false)) {
dialog.startSpeechRecognition()
}
window.clearFlags(WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE)
}
} | 0 | Kotlin | 3 | 21 | e5e674d39ce76094cdabddcc0e8e5c6fc5ae1fea | 1,471 | QuickMDCapture | MIT License |
project-system/src/com/android/tools/idea/projectsystem/DynamicAppFeatureOnFeatureToken.kt | JetBrains | 60,701,247 | false | {"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19} | /*
* Copyright (C) 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.projectsystem
import com.intellij.openapi.extensions.ExtensionPointName
import com.intellij.openapi.module.Module
interface DynamicAppFeatureOnFeatureToken<P : AndroidProjectSystem> : Token {
fun getFeatureModulesDependingOnFeature(projectSystem: P, module: Module): List<Module>
fun getFeatureModuleDependenciesForFeature(projectSystem: P, module: Module): List<Module>
companion object {
@JvmField
val EP_NAME: ExtensionPointName<DynamicAppFeatureOnFeatureToken<AndroidProjectSystem>> =
ExtensionPointName("com.android.tools.idea.projectsystem.dynamicAppFeatureOnFeatureToken")
}
} | 5 | Kotlin | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 1,258 | android | Apache License 2.0 |
innsender/src/test/kotlin/no/nav/soknad/innsending/utils/builders/pdl/NavnTestBuilder.kt | navikt | 406,355,715 | false | {"Kotlin": 659125, "Dockerfile": 250} | package no.nav.soknad.innsending.utils.builders.pdl
import no.nav.soknad.innsending.pdl.generated.prefilldata.Metadata
import no.nav.soknad.innsending.pdl.generated.prefilldata.Navn
import no.nav.soknad.innsending.utils.Date
import java.time.LocalDateTime
class NavnTestBuilder {
private var fornavn: String = "John"
private var etternavn: String = "Doe"
private var mellomnavn: String? = null
private var gyldigFraOgMed: String? = Date.formatToLocalDate(LocalDateTime.now().minusDays(10))
private var metadata: Metadata = MetadataTestBuilder().build()
fun fornavn(fornavn: String) = apply { this.fornavn = fornavn }
fun mellomnavn(mellomnavn: String?) = apply { this.mellomnavn = mellomnavn }
fun etternavn(etternavn: String) = apply { this.etternavn = etternavn }
fun gyldigFraOgMed(gyldigFraOgMed: String?) = apply { this.gyldigFraOgMed = gyldigFraOgMed }
fun metadata(metadata: Metadata) = apply { this.metadata = metadata }
fun build() = Navn(
fornavn = fornavn,
mellomnavn = mellomnavn,
etternavn = etternavn,
gyldigFraOgMed = gyldigFraOgMed,
metadata = metadata
)
}
| 6 | Kotlin | 0 | 1 | c8e9e3398fc49e0133d99a7dcc04f1942054399f | 1,101 | innsending-api | MIT License |
app/src/main/java/com/vigyat/quicknote/view/AddNoteActivity.kt | VigyatGoel | 794,035,632 | false | {"Kotlin": 30085} | package com.vigyat.quicknote.view
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import com.vigyat.quicknote.R
import com.vigyat.quicknote.databinding.ActivityAddNoteBinding
import com.vigyat.quicknote.model.repository.Repository
import com.vigyat.quicknote.model.room.Note
import com.vigyat.quicknote.model.room.NotesDatabase
import com.vigyat.quicknote.viewmodel.NoteViewModel
import com.vigyat.quicknote.viewmodel.NoteViewModelFactory
class AddNoteActivity : AppCompatActivity() {
private lateinit var addNoteBinding: ActivityAddNoteBinding
private lateinit var noteViewModel: NoteViewModel
private var noteId: Int? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_add_note)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}
var isInitialDataLoaded = false
addNoteBinding = DataBindingUtil.setContentView(this, R.layout.activity_add_note)
addNoteBinding.saveBtn.isEnabled = false // disable the button initially
val dao = NotesDatabase.getInstance(applicationContext).noteDao
val repository = Repository(dao)
val factory = NoteViewModelFactory(repository)
noteViewModel = ViewModelProvider(this, factory)[NoteViewModel::class.java]
val textWatcher = object : TextWatcher {
override fun afterTextChanged(s: Editable) {
// Enable the button when text changes
if (isInitialDataLoaded) {
addNoteBinding.saveBtn.isEnabled = true
}
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
// No action needed here
}
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
// No action needed here
}
}
addNoteBinding.titleEt.addTextChangedListener(textWatcher)
addNoteBinding.contentEt.addTextChangedListener(textWatcher)
noteId = intent.getIntExtra("noteId", -1)
if (noteId != -1) {
noteViewModel.getNoteById(noteId!!).observe(this) { note ->
addNoteBinding.titleEt.setText(note.title)
addNoteBinding.contentEt.setText(note.content)
isInitialDataLoaded = true
}
addNoteBinding.AddORUpdateTV.text = "Update Note"
addNoteBinding.saveBtn.text = "Update Note"
} else {
addNoteBinding.AddORUpdateTV.text = "Add a New Note"
addNoteBinding.saveBtn.text = "Save Note"
isInitialDataLoaded = true
}
addNoteBinding.saveBtn.setOnClickListener {
val title = addNoteBinding.titleEt.text.toString()
val content = addNoteBinding.contentEt.text.toString()
val timeStamp = System.currentTimeMillis()
if (noteId != -1) {
noteViewModel.update(Note(noteId!!, title, content, timeStamp))
} else {
noteViewModel.insert(Note(0, title, content, timeStamp))
}
finish()
}
}
} | 0 | Kotlin | 0 | 0 | 13695cec3de403c8a9d9962c1653747794a39f66 | 3,777 | QuickNote | MIT License |
src/com/kingsleyadio/adventofcode/y2022/day06/Solution.kt | kingsleyadio | 435,430,807 | false | {"Kotlin": 114466, "JavaScript": 5423} | package com.kingsleyadio.adventofcode.y2022.day06
import com.kingsleyadio.adventofcode.util.readInput
fun main() {
val input = readInput(2022, 6).readText()
solution(input, 4)
solution(input, 14)
}
fun solution(input: String, distinctCount: Int) {
val lookup = IntArray(26) { -1 }
var start = -1
for (index in input.indices) {
val char = input[index]
val lastOccurrence = lookup[char - 'a']
if (lastOccurrence >= start) start = lastOccurrence + 1
lookup[char - 'a'] = index
if (index - start + 1 == distinctCount) {
println(index + 1)
break
}
}
}
| 0 | Kotlin | 0 | 1 | af9f580aafe0bcee4f8b1e720ca6a9cd62bb9594 | 650 | adventofcode | Apache License 2.0 |
features/coreandroid/src/main/java/com/jlndev/coreandroid/bases/adapter/BaseDiffItemView.kt | john-lobo | 706,271,485 | false | {"Kotlin": 183251} | package com.jlndev.coreandroid.bases.adapter
abstract class BaseDiffItemView {
abstract val id: String
} | 0 | Kotlin | 0 | 0 | 7473fb3cd2c9f3ff10b30fbd263344397cb5ef4c | 109 | faca-seu-pedido | MIT License |
car-lease-service/src/main/kotlin/org/jesperancinha/car/lease/dto/CustomerDto.kt | jesperancinha | 545,156,713 | false | {"Kotlin": 22660, "Shell": 614} | package org.jesperancinha.car.lease.dto
import com.fasterxml.jackson.annotation.JsonProperty
class CustomerDto(
@JsonProperty("id")
val id: Long? = null,
@JsonProperty("name")
val name: String? = null,
@JsonProperty("street")
val street: String? = null,
@JsonProperty("houseNumber")
val houseNumber: Long? = null,
@JsonProperty("zipCode")
val zipCode: String? = null,
@JsonProperty("place")
val place: String? = null,
@JsonProperty("email")
val email: String? = null,
@JsonProperty("phoneNumber")
val phoneNumber: String? = null
) | 0 | Kotlin | 0 | 1 | b5ba6e494bca55e3d688a2584b39d2e84aad5388 | 596 | car-lease | Apache License 2.0 |
androidApp/src/main/java/org/flepper/chatgpt/android/presentation/ui/home/HomeViewModel.kt | develNerd | 603,816,382 | false | null | package org.flepper.chatgpt.android.presentation.ui.home
import android.util.Log
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import org.flepper.chatgpt.android.presentation.core.BaseViewModel
import org.flepper.chatgpt.data.model.Content
import org.flepper.chatgpt.data.model.MessagesItem
import org.flepper.chatgpt.data.network.CONVERSATION_ID
import org.flepper.chatgpt.data.network.PARENT_MESSAGE_ID
import org.flepper.chatgpt.data.repositoryImpl.AuthRequest
import org.flepper.chatgpt.data.usecasefactories.AuthUseCaseFactory
import org.flepper.chatgpt.data.usecasefactories.ChatUseCaseFactory
import java.util.*
class HomeViewModel(
private val chatUseCaseFactory: ChatUseCaseFactory,
private val authUseCaseFactory: AuthUseCaseFactory
) : BaseViewModel() {
private val currentMessageUUID = UUID.randomUUID().toString()
var nextMapKey:Long = 3 // TODO("Replace with Size of Table rows when persisting')
/** Euti Replies*/
private val _chatGPTReplies = MutableStateFlow<Map<String,ChatType>>(
mapOf(Pair("1", ChatType.ChatGPT("Hi there User", true)),
Pair("2",ChatType.ChatGPT("How can I help you today ?", false)))
)
val chatGPTReplies: StateFlow<Map<String,ChatType>> = _chatGPTReplies
/** @AddReply*/
fun addToReplies(chatKey:String,chatType: ChatType) {
val replies: MutableMap<String, ChatType> = chatGPTReplies.value.toMutableMap()
replies[chatKey] = chatType
_chatGPTReplies.value = replies
if (chatType is ChatType.User){
getChatConversation(chatType.text)
setIsChatAdded(true)
}
}
private val _isChatLoading = MutableStateFlow(false)
val isChatLoading: StateFlow<Boolean> = _isChatLoading
fun setIsChatLoading(value: Boolean) {
_isChatLoading.value = value
}
private val _isChatAdded = MutableStateFlow<Boolean>(false)
val isChatAdded: StateFlow<Boolean>
get() = _isChatAdded
fun setIsChatAdded(value: Boolean) {
viewModelScope.launch {
_isChatAdded.value = value
delay(1000)
_isChatAdded.value = false
}
}
data class AuthResult(var authReady: Boolean? = null)
private val _isAuthReady = MutableStateFlow(AuthResult())
val isAuthReady: StateFlow<AuthResult>
get() = _isAuthReady
fun setIsAuthReady(value: Boolean){
_isAuthReady.value = AuthResult(value)
}
fun checkIsAuthReady() {
executeUseCase(Unit, authUseCaseFactory.checkAuthUseCase) { authSaved ->
if (authSaved){
streamPastConversations()
}else{
setIsAuthReady(false)
}
}
}
fun saveAuthRequest(bearer: String, cookie: String, userAgent: String) {
executeUseCase(AuthRequest(bearer, userAgent, cookie), authUseCaseFactory.authUseCase)
}
private fun streamPastConversations() {
executeApiUseCase(Unit, chatUseCaseFactory.getPreviousConversationsUseCase) { response ->
if (response.error == null && response.isLoaded) {
_isAuthReady.value = AuthResult(authReady = true)
}else{
_isAuthReady.value = AuthResult(authReady = false)
}
}
executeStreamUseCase(
Unit,
chatUseCaseFactory.streamPastConversationsUseCase
) { response ->
//Past Conversations
}
}
private fun getChatConversation(question: String) {
val currentMapKey = (0L..30000L).random()
val messagesItem =
MessagesItem(id = currentMessageUUID, uuid = UUID.randomUUID().toString() ,content = Content(parts = listOf(question)))
var idSet = false
setIsChatLoading(true)
executeApiUseCase(messagesItem, chatUseCaseFactory.getChatUseCase){ result ->
setIsChatLoading(false)
viewModelScope.launch {
delay(1000)
setIsChatAdded(true)
}
if (result.isLoaded && result.error != null){
Log.e("Result",result.toString())
}else{
//TODO("impl")
_isAuthReady.value = AuthResult(authReady = false)
Log.e("Result-Error",result.toString())
}
}
executeStreamUseCase(
Unit,
chatUseCaseFactory.streamChatUseCase
) { messageResponseItem ->
if (!idSet) {
updateConversationIds(
messageResponseItem.conversationId,
messageResponseItem.message?.id ?: ""
)
idSet = true
}
messageResponseItem.conversationId
val messagePart = messageResponseItem.message?.content?.parts?.firstOrNull()
if (messagePart != null){
addToReplies(messageResponseItem.message?.id ?: UUID.randomUUID().toString(), ChatType.ChatGPT(messagePart,true))
}
Log.e("Use CaseContent", messageResponseItem.toString())
}
}
private fun updateConversationIds(conversationId: String, messageID: String) {
val updateIds = mutableMapOf<String, String>()
updateIds[CONVERSATION_ID] = conversationId
updateIds[PARENT_MESSAGE_ID] = messageID
executeUseCase(updateIds, authUseCaseFactory.updateMessageIDsUseCase)
}
}
| 0 | Kotlin | 1 | 9 | 734aca530a3801d590b778d7e01c95876e24cddf | 5,588 | ChatGPT-Multiplatform | MIT License |
exkt-kvision/src/jsMain/kotlin/dev/d1s/exkt/kvision/bootstrap/Colors.kt | d1snin | 578,726,152 | false | {"Kotlin": 151825} | /*
* Copyright 2022-2024 Mikhail Titov
*
* 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 dev.d1s.exkt.kvision.bootstrap
import io.kvision.core.Component
public fun Component.textPrimary() {
addCssClass("text-primary")
}
public fun Component.textPrimaryEmphasis() {
addCssClass("text-primary-emphasis")
}
public fun Component.textSecondary() {
addCssClass("text-secondary")
}
public fun Component.textSecondaryEmphasis() {
addCssClass("text-secondary-emphasis")
}
public fun Component.textSuccess() {
addCssClass("text-success")
}
public fun Component.textSuccessEmphasis() {
addCssClass("text-success-emphasis")
}
public fun Component.textDanger() {
addCssClass("text-danger")
}
public fun Component.textDangerEmphasis() {
addCssClass("text-danger-emphasis")
}
public fun Component.textWarning() {
addCssClass("text-warning")
}
public fun Component.textWarningEmphasis() {
addCssClass("text-warning-emphasis")
}
public fun Component.textInfo() {
addCssClass("text-info")
}
public fun Component.textInfoEmphasis() {
addCssClass("text-info-emphasis")
}
public fun Component.textLight() {
addCssClass("text-light")
}
public fun Component.textLightEmphasis() {
addCssClass("text-light-emphasis")
}
public fun Component.textDark() {
addCssClass("text-dark")
}
public fun Component.textDarkEmphasis() {
addCssClass("text-dark-emphasis")
}
public fun Component.textBody() {
addCssClass("text-body")
}
public fun Component.textBodyEmphasis() {
addCssClass("text-body-emphasis")
}
public fun Component.textBodySecondary() {
addCssClass("text-body-secondary")
}
public fun Component.textBodyTertiary() {
addCssClass("text-body-tertiary")
}
public fun Component.textBlack() {
addCssClass("text-black")
}
public fun Component.textWhite() {
addCssClass("text-white")
}
public fun Component.textBlack50() {
addCssClass("text-black-50")
}
public fun Component.textWhite50() {
addCssClass("text-white-50")
}
public fun Component.textOpacity75() {
addCssClass("text-opacity-75")
}
public fun Component.textOpacity50() {
addCssClass("text-opacity-50")
}
public fun Component.textOpacity25() {
addCssClass("text-opacity-25")
} | 0 | Kotlin | 0 | 3 | 8c2c1f637256b1b4a19af7433d51d41ae14b02e3 | 2,765 | exkt | Apache License 2.0 |
sample/wallet/src/main/kotlin/com/reown/sample/wallet/domain/model/NotificationUI.kt | reown-com | 851,466,242 | false | null | package com.walletconnect.sample.wallet.domain.model
data class NotificationUI(
val id: String,
val topic: String,
val date: String,
val title: String,
val body: String,
val url: String?,
val icon: String?,
) | 78 | null | 74 | 8 | 893084b3df91b47daa77f8f964e37f84a02843b1 | 237 | reown-kotlin | Apache License 2.0 |
ton-kotlin-tlb/src/commonMain/kotlin/org/ton/tlb/CellRef.kt | andreypfau | 448,983,229 | false | null | package org.ton.tlb
import org.ton.cell.Cell
import org.ton.cell.CellBuilder
import org.ton.cell.CellSlice
import org.ton.cell.CellType
import kotlin.jvm.JvmStatic
public inline fun <T> CellRef(cell: Cell, codec: TlbCodec<T>): CellRef<T> = CellRef.valueOf(cell, codec)
public inline fun <T> CellRef(value: T): CellRef<T> = CellRef.valueOf(value)
public inline fun <T> CellRef(codec: TlbCodec<T>): TlbCodec<CellRef<T>> = CellRef.tlbCodec(codec)
public inline fun <T> Cell.asRef(codec: TlbCodec<T>): CellRef<T> = CellRef.valueOf(this, codec)
public interface CellRef<out T> : TlbObject {
public val value: T
public fun toCell(codec: TlbCodec<@UnsafeVariance T>? = null): Cell
public operator fun getValue(thisRef: Any?, property: Any?): T = value
override fun print(printer: TlbPrettyPrinter): TlbPrettyPrinter {
val value = value
return if (value is TlbObject) {
value.print(printer)
} else {
printer {
type(value.toString())
}
}
}
public companion object {
@JvmStatic
public fun <T> valueOf(cell: Cell, codec: TlbCodec<T>): CellRef<T> = CellRefImpl(cell, codec)
@JvmStatic
public fun <T> valueOf(value: T): CellRef<T> = CellRefValue(value)
@JvmStatic
public fun <T> tlbCodec(codec: TlbCodec<T>): TlbCodec<CellRef<T>> = CellRefTlbConstructor(codec)
}
}
private class CellRefImpl<T>(
val cell: Cell,
val codec: TlbCodec<T>
) : CellRef<T> {
override val value: T by lazy(LazyThreadSafetyMode.PUBLICATION) {
check(cell.type == CellType.ORDINARY) { "Can't load reference value: $cell" }
codec.loadTlb(cell)
}
override fun toCell(codec: TlbCodec<T>?): Cell {
return cell
}
override fun print(printer: TlbPrettyPrinter): TlbPrettyPrinter {
return if (cell.type == CellType.PRUNED_BRANCH) {
printer.type("!pruned_branch") {
field("cell", cell.bits)
}
} else {
super.print(printer)
}
}
override fun toString(): String = "CellRef($cell)"
}
private class CellRefValue<T>(
override val value: T,
) : CellRef<T> {
override fun toCell(codec: TlbCodec<T>?): Cell {
require(codec != null) { "Codec is not specified" }
return CellBuilder.createCell {
codec.storeTlb(this, value)
}
}
override fun toString(): String = "CellRef($value)"
}
private class CellRefTlbConstructor<T>(
val codec: TlbCodec<T>
) : TlbCodec<CellRef<T>> {
override fun storeTlb(cellBuilder: CellBuilder, value: CellRef<T>) {
cellBuilder.storeRef(value.toCell(codec))
}
override fun loadTlb(cellSlice: CellSlice): CellRef<T> {
return cellSlice.loadRef().asRef(codec)
}
}
public inline fun <T> CellBuilder.storeRef(codec: TlbCodec<T>, value: CellRef<T>) {
storeRef(value.toCell(codec))
}
public inline fun <T> CellSlice.loadRef(codec: TlbCodec<T>): CellRef<T> {
return loadRef().asRef(codec)
}
| 10 | Kotlin | 14 | 52 | 7f75444dc65cac96383bf088e4e31b77feae22e0 | 3,058 | ton-kotlin | Apache License 2.0 |
ton-kotlin-tlb/src/commonMain/kotlin/org/ton/tlb/CellRef.kt | andreypfau | 448,983,229 | false | null | package org.ton.tlb
import org.ton.cell.Cell
import org.ton.cell.CellBuilder
import org.ton.cell.CellSlice
import org.ton.cell.CellType
import kotlin.jvm.JvmStatic
public inline fun <T> CellRef(cell: Cell, codec: TlbCodec<T>): CellRef<T> = CellRef.valueOf(cell, codec)
public inline fun <T> CellRef(value: T): CellRef<T> = CellRef.valueOf(value)
public inline fun <T> CellRef(codec: TlbCodec<T>): TlbCodec<CellRef<T>> = CellRef.tlbCodec(codec)
public inline fun <T> Cell.asRef(codec: TlbCodec<T>): CellRef<T> = CellRef.valueOf(this, codec)
public interface CellRef<out T> : TlbObject {
public val value: T
public fun toCell(codec: TlbCodec<@UnsafeVariance T>? = null): Cell
public operator fun getValue(thisRef: Any?, property: Any?): T = value
override fun print(printer: TlbPrettyPrinter): TlbPrettyPrinter {
val value = value
return if (value is TlbObject) {
value.print(printer)
} else {
printer {
type(value.toString())
}
}
}
public companion object {
@JvmStatic
public fun <T> valueOf(cell: Cell, codec: TlbCodec<T>): CellRef<T> = CellRefImpl(cell, codec)
@JvmStatic
public fun <T> valueOf(value: T): CellRef<T> = CellRefValue(value)
@JvmStatic
public fun <T> tlbCodec(codec: TlbCodec<T>): TlbCodec<CellRef<T>> = CellRefTlbConstructor(codec)
}
}
private class CellRefImpl<T>(
val cell: Cell,
val codec: TlbCodec<T>
) : CellRef<T> {
override val value: T by lazy(LazyThreadSafetyMode.PUBLICATION) {
check(cell.type == CellType.ORDINARY) { "Can't load reference value: $cell" }
codec.loadTlb(cell)
}
override fun toCell(codec: TlbCodec<T>?): Cell {
return cell
}
override fun print(printer: TlbPrettyPrinter): TlbPrettyPrinter {
return if (cell.type == CellType.PRUNED_BRANCH) {
printer.type("!pruned_branch") {
field("cell", cell.bits)
}
} else {
super.print(printer)
}
}
override fun toString(): String = "CellRef($cell)"
}
private class CellRefValue<T>(
override val value: T,
) : CellRef<T> {
override fun toCell(codec: TlbCodec<T>?): Cell {
require(codec != null) { "Codec is not specified" }
return CellBuilder.createCell {
codec.storeTlb(this, value)
}
}
override fun toString(): String = "CellRef($value)"
}
private class CellRefTlbConstructor<T>(
val codec: TlbCodec<T>
) : TlbCodec<CellRef<T>> {
override fun storeTlb(cellBuilder: CellBuilder, value: CellRef<T>) {
cellBuilder.storeRef(value.toCell(codec))
}
override fun loadTlb(cellSlice: CellSlice): CellRef<T> {
return cellSlice.loadRef().asRef(codec)
}
}
public inline fun <T> CellBuilder.storeRef(codec: TlbCodec<T>, value: CellRef<T>) {
storeRef(value.toCell(codec))
}
public inline fun <T> CellSlice.loadRef(codec: TlbCodec<T>): CellRef<T> {
return loadRef().asRef(codec)
}
| 10 | Kotlin | 14 | 52 | 7f75444dc65cac96383bf088e4e31b77feae22e0 | 3,058 | ton-kotlin | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/hmpps/hmppsinterventionsservice/reporting/ndmis/performance/OutcomeProcessor.kt | ministryofjustice | 312,544,431 | false | null | package uk.gov.justice.digital.hmpps.hmppsinterventionsservice.reporting.ndmis.performance
import mu.KLogging
import org.springframework.stereotype.Component
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.jpa.entity.Referral
import uk.gov.justice.digital.hmpps.hmppsinterventionsservice.reporting.SentReferralProcessor
@Component
class OutcomeProcessor() : SentReferralProcessor<List<OutcomeData>> {
companion object : KLogging()
override fun processSentReferral(referral: Referral): List<OutcomeData>? {
return referral.endOfServiceReport?.outcomes?.map {
OutcomeData(
referralReference = referral.referenceNumber!!,
referralId = referral.id,
desiredOutcomeDescription = it.desiredOutcome.description,
achievementLevel = it.achievementLevel,
)
}?.ifEmpty { null }
}
}
| 12 | Kotlin | 1 | 2 | e77060a93c6736b5bf9032b3c917207d6b809568 | 845 | hmpps-interventions-service | MIT License |
xml/src/commonTest/kotlin/pw/binom/xml/sax/WriterTest.kt | caffeine-mgn | 182,165,415 | false | null | package pw.binom.xml.sax
import pw.binom.async
import pw.binom.io.asAsync
import kotlin.test.Test
import kotlin.test.assertEquals
class WriterTest {
@Test
fun test() {
async {
val sb = StringBuilder()
val b = XmlWriterVisiter("root", sb.asAsync())
b.start()
b.attribute("name", "root-node")
b.subNode("node1").apply {
start()
value("test-value")
end()
}
b.subNode("node2").apply {
start()
cdata("test-value")
end()
}
b.subNode("node3").apply {
start()
end()
}
b.end()
assertEquals("<root name=\"root-node\"><node1>test-value</node1><node2><![CDATA[test-value]]></node2><node3/></root>", sb.toString())
}
}
} | 7 | null | 2 | 59 | 580ff27a233a1384273ef15ea6c63028dc41dc01 | 910 | pw.binom.io | Apache License 2.0 |
src/main/kotlin/1. List with Multiple Types.kt | dakshj | 95,077,015 | false | null | fun main(args: Array<String>) {
println(listOf(1, "Two", '3', false))
}
| 0 | Kotlin | 0 | 0 | b10d30508eb88be644d7846d0a766fbfd5fd14cf | 76 | kotlin-learning | Apache License 2.0 |
plugins/plugin-common/src/main/java/win/techflowing/android/plugin/common/uitl/ASMUtil.kt | techflowing | 500,921,879 | false | null | package win.techflowing.android.plugin.common.uitl
import org.objectweb.asm.Opcodes
/**
* ASM 相关工具类
*
* @author <EMAIL>
* @since 2022/6/4 11:41 PM
*/
object ASMUtil {
/** 判断一个类是否是接口 */
fun isInterface(access: Int?): Boolean {
return access != null && (access and Opcodes.ACC_INTERFACE) != 0
}
/** 判断一个类是否是 Public */
fun isPublicClass(access: Int?): Boolean {
return access != null && (access and Opcodes.ACC_PUBLIC) != 0
}
/** 判断一个方法是否是 public */
fun isPublicMethod(access: Int?): Boolean {
return access != null && (access and Opcodes.ACC_PUBLIC) != 0
}
/** 判断一个方法是否是实例构造方法 */
fun isInitMethod(name: String): Boolean {
return name == "<init>"
}
/** 判断一个方法是否是实例构造方法 */
fun isStaticInitMethod(name: String): Boolean {
return name == "<clinit>"
}
} | 0 | Kotlin | 0 | 0 | 3de479a53425f1fe97470ceb71547bfd48c8fce0 | 859 | Universe | Apache License 2.0 |
core-data/src/main/java/com/carlos/data/repository/MainRepositoryImp.kt | Carlosokumu | 532,033,759 | false | null | package com.carlos.data.repository
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.PagingData
import com.carlos.data.paging.PokemonPagingDatasource
import com.carlos.database.dao.PokemonDao
import com.carlos.database.entity.PokemonEntity
import com.carlos.network.network.ApiClient
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
class MainRepositoryImp @Inject constructor(
private val apiClient: ApiClient,
private val pokemonDao: PokemonDao
) :
MainRepository {
override suspend fun fetchPokemonList(): Flow<PagingData<PokemonEntity>> {
return Pager(
config = PagingConfig(enablePlaceholders = false, pageSize = 20),
pagingSourceFactory = {
PokemonPagingDatasource(apiClient = apiClient, pokemonDao = pokemonDao)
}
).flow
}
override suspend fun updateDominantColor(color: Int, name: String) {
pokemonDao.updateDominantColor(color, name)
}
} | 0 | Kotlin | 0 | 3 | 3643e30c42c9172301684ebed0394d5dc0be3db3 | 1,009 | Pokemen | Apache License 2.0 |
app/src/main/java/com/rstit/connector/util/BindingAdapters.kt | rstgroup | 113,022,246 | false | {"Gradle": 5, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 100, "XML": 31, "Java": 3} | package com.rstit.connector.util
import android.databinding.BindingAdapter
import android.graphics.Typeface
import android.support.v4.content.ContextCompat
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.rstit.connector.R
import com.rstit.connector.model.inbox.MessageStatus
import jp.wasabeef.glide.transformations.CropCircleTransformation
/**
* @author <NAME>
* @since 2017-07-18
*/
@BindingAdapter("visibleIf")
fun changeVisibility(view: View?, visible: Boolean) {
view?.let { it.visibility = if (visible) View.VISIBLE else View.GONE }
}
@BindingAdapter("invisibleIf")
fun changeInvisibility(view: View?, visible: Boolean) {
view?.let { it.visibility = if (visible) View.INVISIBLE else View.VISIBLE }
}
@BindingAdapter("chatStatus")
fun changeChatIcon(view: ImageView?, status: MessageStatus) {
view?.apply {
visibility = if (status != MessageStatus.Sending && status != MessageStatus.Error) View.VISIBLE else View.GONE
setImageResource(if (status == MessageStatus.Error) R.drawable.ic_alert else R.drawable.ic_check_all)
setColorFilter(ContextCompat.getColor(context,
if (status == MessageStatus.Error)
android.R.color.holo_red_dark
else if (status == MessageStatus.Read)
R.color.colorAccent
else
android.R.color.darker_gray))
}
}
@BindingAdapter("animateLabel")
fun animateLabelVisibility(view: View?, visible: Boolean) {
view?.let {
if(visible) ChatUtil.expandView(it)else ChatUtil.collapseView(it) }
}
@BindingAdapter("circleImage")
fun loadCircleImage(view: ImageView?, avatar: String?) {
view?.let {
Glide.with(it.context)
.load(avatar)
.placeholder(R.drawable.ic_account_circle_grey)
.error(R.drawable.ic_account_circle_grey)
.bitmapTransform(CropCircleTransformation(it.context))
.into(view)
}
}
@BindingAdapter("rightTransitionVisibility")
fun translateView(view: View?, visible: Boolean) {
view?.let {
val anim = AnimationUtils.loadAnimation(it.context, if (visible) R.anim.slide_from_right else R.anim.slide_in_right).apply {
setAnimationListener(object : Animation.AnimationListener {
override fun onAnimationRepeat(p0: Animation?) {
/*no-op*/
}
override fun onAnimationEnd(p0: Animation?) {
if (!visible) view.visibility = View.GONE
}
override fun onAnimationStart(p0: Animation?) {
if (visible) view.visibility = View.VISIBLE
}
})
}
it.startAnimation(anim)
}
}
@BindingAdapter("boldIf")
fun setBoldIf(textView: TextView?, value: Boolean) {
textView?.setTypeface(null, if (value) Typeface.BOLD else Typeface.NORMAL)
}
| 0 | Kotlin | 0 | 0 | 4385ffd936f56a53aa1db9a83da4c9f3c3488fc9 | 3,087 | rst-connector | Apache License 2.0 |
core/src/commonTest/kotlin/com/ruben/spotify/api/test/spotify/SpotifyApiTest.kt | rubenquadros | 758,569,353 | false | {"Kotlin": 73960} | package com.ruben.spotify.api.test.spotify
import com.ruben.spotify.api.SpotifyApi
import org.junit.Assert.assertThrows
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class SpotifyApiTest {
private val spotifyApi = SpotifyApi
@Test
fun `cannot create the service with empty client id`() {
val exception = assertThrows(IllegalArgumentException::class.java) {
spotifyApi.createSpotifyApi("", "SECRET")
}
assertEquals("Client Id cannot be empty.", exception.message)
}
@Test
fun `cannot create the service with empty client secret`() {
val exception = assertThrows(IllegalArgumentException::class.java) {
spotifyApi.createSpotifyApi("ID", "")
}
assertEquals("Client secret cannot be empty.", exception.message)
}
@Test
fun `providing valid client id and secret creates a spotify service`() {
val spotifyService = spotifyApi.createSpotifyApi("ID", "SECRET")
assertNotNull(spotifyService)
}
} | 0 | Kotlin | 0 | 0 | b630400776330de682bd03d12b493be2efc2016d | 1,065 | Kotlin-Spotify-Api | MIT License |
desktopApp/src/main/kotlin/ui/theme/Type.kt | VictorKabata | 451,854,817 | false | {"Kotlin": 211021, "Swift": 19405, "Ruby": 2077} | package ui.theme
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.platform.Font
val logoFontFamily = FontFamily(
Font(
resource = "fonts/grandista.ttf",
weight = FontWeight.Bold,
style = FontStyle.Normal
)
)
| 1 | Kotlin | 4 | 39 | c076838dd5daab9025041025fbeb5e151fd68e10 | 368 | Gistagram | MIT License |
src/main/kotlin/elements/api/activator/Activator.kt | ElementsPlugin | 163,351,686 | false | null | package elements.api.activator
import org.spongepowered.api.CatalogType
/**
* An ability activator.
*
* An example could be one that activates an ability when the player sneaks.
*/
interface Activator : CatalogType | 0 | Kotlin | 0 | 0 | d86f268dd9e7f1799ec4ab33e6cf12d030e82de7 | 220 | elements-api | MIT License |
snabbdom.d.ts/generated/h.kt | gbaldeck | 94,640,750 | false | null | @file:Suppress("INTERFACE_WITH_SUPERCLASS", "OVERRIDING_FINAL_MEMBER", "RETURN_TYPE_MISMATCH_ON_OVERRIDE", "CONFLICTING_OVERLOADS")
import kotlin.js.*
import kotlin.js.Json
import org.khronos.webgl.*
import org.w3c.dom.*
import org.w3c.dom.events.*
import org.w3c.dom.parsing.*
import org.w3c.dom.svg.*
import org.w3c.dom.url.*
import org.w3c.fetch.*
import org.w3c.files.*
import org.w3c.notifications.*
import org.w3c.performance.*
import org.w3c.workers.*
import org.w3c.xhr.*
@JsModule("h")
external fun h(sel: String): VNode = definedExternally
@JsModule("h")
external fun h(sel: String, data: VNodeData): VNode = definedExternally
@JsModule("h")
external fun h(sel: String, text: String): VNode = definedExternally
@JsModule("h")
external fun h(sel: String, children: Array<VNode?>): VNode = definedExternally
@JsModule("h")
external fun h(sel: String, data: VNodeData, text: String): VNode = definedExternally
@JsModule("h")
external fun h(sel: String, data: VNodeData, children: Array<VNode?>): VNode = definedExternally
| 0 | Kotlin | 1 | 4 | 3de0752966e4b4231efe3200b140142565520087 | 1,031 | snabbdom-kotlin | MIT License |
app/src/main/java/com/example/HealthyMode/Adapter/Adapter_todo.kt | subhajit4980 | 591,903,677 | false | {"Kotlin": 223553} | package com.example.HealthyMode.Adapter
import android.graphics.Paint
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.HealthyMode.TodoDatabase.Todo
import com.example.HealthyMode.databinding.TodoItemBinding
class Adapter_todo(private val listener: OnItemClickListener) :
ListAdapter<Todo, Adapter_todo.TasksViewHolder>(DiffUtill()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TasksViewHolder {
val binding = TodoItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return TasksViewHolder(binding)
}
override fun onBindViewHolder(holder: TasksViewHolder, position: Int) {
val currentItem = getItem(position)
holder.bind(currentItem)
}
inner class TasksViewHolder(private val binding: TodoItemBinding) :
RecyclerView.ViewHolder(binding.root) {
init {
binding.apply {
status.setOnClickListener {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
val task = getItem(position)
listener.onCheckBoxClick(task, status.isChecked)
check(status,desc)
}
}
}
}
fun bind(task: Todo) {
binding.apply {
status.isChecked=task.status
desc.text = task.Desc
sd.text=task.Start_date
st.text=task.Start_time
ed.text=task.End_date
et.text=task.End_time
check(status,desc)
}
}
}
private fun check(status:CheckBox,desc:TextView)
{
if (status.isChecked) {
desc.paintFlags =
desc.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
} else {
desc.paintFlags =
desc.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
}
}
interface OnItemClickListener {
fun onCheckBoxClick(task: Todo, isChecked: Boolean)
}
class DiffUtill : DiffUtil.ItemCallback<Todo>() {
override fun areItemsTheSame(oldItem: Todo, newItem: Todo) =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: Todo, newItem: Todo) =
oldItem == newItem
}
} | 0 | Kotlin | 0 | 3 | f4ff9a225d9f0b302b7a442af8622e181f1fb55c | 2,542 | HealthyMode | MIT License |
app/src/main/java/com/example/HealthyMode/Adapter/Adapter_todo.kt | subhajit4980 | 591,903,677 | false | {"Kotlin": 223553} | package com.example.HealthyMode.Adapter
import android.graphics.Paint
import android.view.LayoutInflater
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.example.HealthyMode.TodoDatabase.Todo
import com.example.HealthyMode.databinding.TodoItemBinding
class Adapter_todo(private val listener: OnItemClickListener) :
ListAdapter<Todo, Adapter_todo.TasksViewHolder>(DiffUtill()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TasksViewHolder {
val binding = TodoItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return TasksViewHolder(binding)
}
override fun onBindViewHolder(holder: TasksViewHolder, position: Int) {
val currentItem = getItem(position)
holder.bind(currentItem)
}
inner class TasksViewHolder(private val binding: TodoItemBinding) :
RecyclerView.ViewHolder(binding.root) {
init {
binding.apply {
status.setOnClickListener {
val position = adapterPosition
if (position != RecyclerView.NO_POSITION) {
val task = getItem(position)
listener.onCheckBoxClick(task, status.isChecked)
check(status,desc)
}
}
}
}
fun bind(task: Todo) {
binding.apply {
status.isChecked=task.status
desc.text = task.Desc
sd.text=task.Start_date
st.text=task.Start_time
ed.text=task.End_date
et.text=task.End_time
check(status,desc)
}
}
}
private fun check(status:CheckBox,desc:TextView)
{
if (status.isChecked) {
desc.paintFlags =
desc.paintFlags or Paint.STRIKE_THRU_TEXT_FLAG
} else {
desc.paintFlags =
desc.paintFlags and Paint.STRIKE_THRU_TEXT_FLAG.inv()
}
}
interface OnItemClickListener {
fun onCheckBoxClick(task: Todo, isChecked: Boolean)
}
class DiffUtill : DiffUtil.ItemCallback<Todo>() {
override fun areItemsTheSame(oldItem: Todo, newItem: Todo) =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: Todo, newItem: Todo) =
oldItem == newItem
}
} | 0 | Kotlin | 0 | 3 | f4ff9a225d9f0b302b7a442af8622e181f1fb55c | 2,542 | HealthyMode | MIT License |
app/src/main/java/com/civciv/app/di/app/AppModule.kt | fatih-ozturk | 638,702,981 | false | {"Kotlin": 336135, "Shell": 934} | /*
* Copyright 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.civciv.app.di.app
import android.app.Application
import com.civciv.app.common.inject.ApplicationId
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@ApplicationId
@Provides
fun provideApplicationId(application: Application): String = application.packageName
}
| 10 | Kotlin | 1 | 2 | 213ee8c1cb824ec8a803d56d460225cec1cf8bc2 | 1,015 | Civciv | Apache License 2.0 |
app/src/main/java/com/a/vocabulary15/domain/usecases/GetGroups.kt | thedeveloperworldisyours | 405,696,476 | false | {"Kotlin": 188765} | package com.a.vocabulary15.domain.usecases
import com.a.vocabulary15.domain.model.Group
import kotlinx.coroutines.flow.Flow
interface GetGroups {
operator fun invoke(): Flow<List<Group>>
} | 0 | Kotlin | 6 | 33 | ef97e70a9eb9a71d4d8e44269711f47de220d072 | 194 | ComposeClean | MIT License |
app/src/main/java/com/example/movieshowstracker/data/model/MovieList.kt | danielmaman | 260,897,974 | false | null | package com.example.movieshowstracker.data.model
import com.google.gson.annotations.SerializedName
data class MovieList(@SerializedName("Search") val movieList : List<Movie>) | 0 | Kotlin | 0 | 0 | 27074ed8d51b5b9a022b4e6a3c3bea3f2fe6617f | 176 | MovieTracker | MIT License |
src/main/kotlin/com/grudus/planshboard/configuration/security/filters/StatelessAuthenticationFilter.kt | grudus | 115,259,708 | false | null | package com.grudus.planshboard.configuration.security.filters
import com.grudus.planshboard.configuration.security.token.TokenAuthenticationService
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.web.filter.OncePerRequestFilter
import javax.servlet.FilterChain
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
class StatelessAuthenticationFilter(private val authenticationService: TokenAuthenticationService) : OncePerRequestFilter() {
override fun doFilterInternal(request: HttpServletRequest, response: HttpServletResponse, filterChain: FilterChain) {
val auth = try {
authenticationService.getAuthentication(request)
} catch (exception: RuntimeException) {
logger.warn("Cannot authenticate user: [${exception.message}]")
null
}
SecurityContextHolder.getContext().authentication = auth
filterChain.doFilter(request, response)
}
} | 0 | Kotlin | 0 | 1 | 1b9fd909a75d5b0883e8ff39be9aa299bf0ff3ff | 1,012 | Planshboard | Apache License 2.0 |
conclave-common/src/main/kotlin/com/r3/conclave/common/internal/CallInterfaceStackFrame.kt | R3Conclave | 526,690,075 | false | null | package com.r3.conclave.common.internal
import java.nio.ByteBuffer
/**
* This is used in the call interface to relate return or exception messages back to the call message which
* they are intended for. See [com.r3.conclave.enclave.internal.NativeEnclaveHostInterface] and
* [com.r3.conclave.host.internal.NativeHostEnclaveInterface].
*/
class CallInterfaceStackFrame<CALL_TYPE>(
val callType: CALL_TYPE,
var returnBuffer: ByteBuffer? = null,
var exceptionBuffer: ByteBuffer? = null
)
| 0 | C++ | 8 | 41 | 9b49a00bb33a22f311698d7ed8609a189f38d6ae | 515 | conclave-core-sdk | Apache License 2.0 |
kotest-framework/kotest-framework-engine/src/jvmMain/kotlin/io/kotest/engine/spec/tempdir.kt | swanandvk | 267,582,713 | false | null | package io.kotest.engine.spec
import io.kotest.core.TestConfiguration
import java.io.File
fun TestConfiguration.tempdir(prefix: String? = null, suffix: String? = null): File {
val dir = createTempDir(prefix ?: "tmp", suffix)
afterSpec {
dir.delete()
}
return dir
}
| 5 | null | 0 | 1 | 5f0d6c5a7aa76ef373d62f2a4571ae89ae0ab21e | 285 | kotest | Apache License 2.0 |
compiler/testData/ir/irText/firProblems/delegatedSetterShouldBeSpecialized.kt | JetBrains | 3,432,266 | false | null | // FIR_IDENTICAL
// WITH_REFLECT
var topLevelInt: Int = 0
class MyClass {
var delegatedToTopLevel: Int by ::topLevelInt
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 128 | kotlin | Apache License 2.0 |
packages/jetbrains-plugin/src/main/kotlin/com/mongodb/jbplugin/observability/probe/AutocompleteSuggestionAcceptedProbe.kt | mongodb-js | 797,134,624 | false | {"Kotlin": 778765, "Java": 3236, "Shell": 1673, "HTML": 254} | package com.mongodb.jbplugin.observability.probe
import com.intellij.ide.AppLifecycleListener
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.diagnostic.logger
import com.mongodb.jbplugin.dialects.Dialect
import com.mongodb.jbplugin.meta.service
import com.mongodb.jbplugin.observability.TelemetryEvent
import com.mongodb.jbplugin.observability.TelemetryService
import com.mongodb.jbplugin.observability.useLogMessage
import kotlinx.coroutines.*
import java.util.concurrent.CopyOnWriteArrayList
import kotlin.time.Duration.Companion.hours
private val logger: Logger = logger<AutocompleteSuggestionAcceptedProbe>()
/**
* This probe is emitted when an autocomplete suggestion is emitted. However, events are aggregated
* and sent hourly to Segment.
*
* @param cs
*/
@Service
class AutocompleteSuggestionAcceptedProbe(
cs: CoroutineScope,
) : AppLifecycleListener {
private val telemetryJob: Job
private val events: CopyOnWriteArrayList<SuggestionEvent>
init {
ApplicationManager
.getApplication()
.messageBus
.connect()
.subscribe(AppLifecycleListener.TOPIC, this)
telemetryJob =
cs.launch {
telemetryLoop()
}
events = CopyOnWriteArrayList()
}
override fun appWillBeClosed(isRestart: Boolean) {
telemetryJob.cancel()
sendEvents()
}
fun databaseCompletionAccepted(dialect: Dialect<*, *>) {
events.add(SuggestionEvent(dialect, SuggestionEvent.SuggestionEventType.DATABASE))
}
fun collectionCompletionAccepted(dialect: Dialect<*, *>) {
events.add(SuggestionEvent(dialect, SuggestionEvent.SuggestionEventType.COLLECTION))
}
fun fieldCompletionAccepted(dialect: Dialect<*, *>) {
events.add(SuggestionEvent(dialect, SuggestionEvent.SuggestionEventType.FIELD))
}
private suspend fun telemetryLoop(): Unit =
withContext(Dispatchers.IO) {
while (true) {
// if it fails, ignore, we will retry in one hour
runCatching {
sendEvents()
}
delay(1.hours)
}
}
internal fun sendEvents() {
val listCopy = events.toList()
events.clear()
val telemetry by service<TelemetryService>()
listCopy
.groupingBy {
Pair(it.dialect, it.type)
}
.eachCount()
.map {
TelemetryEvent.AutocompleteGroupEvent(
it.key.first,
it.key.second.publicName,
it.value
)
}
.sortedBy { it.name }
.forEach {
telemetry.sendEvent(it)
logger.info(
useLogMessage("Autocomplete suggestion aggregated.")
.mergeTelemetryEventProperties(it)
.build(),
)
}
}
/**
* @property dialect
* @property type
*/
private data class SuggestionEvent(
val dialect: Dialect<*, *>,
val type: SuggestionEventType,
) {
/**
* @property publicName
*/
enum class SuggestionEventType(
val publicName: String,
) {
DATABASE("database"),
COLLECTION("collection"),
FIELD("field"),
}
}
}
| 2 | Kotlin | 0 | 4 | 212a3007dbc6e1235aa2ef60cc053316221b447b | 3,590 | intellij | Apache License 2.0 |
rpk-core/src/main/kotlin/com/rpkit/core/location/RPKLocation.kt | RP-Kit | 54,840,905 | false | null | package com.rpkit.core.location
data class RPKLocation(
val world: String,
val x: Double,
val y: Double,
val z: Double,
val yaw: Float,
val pitch: Float
) | 51 | null | 11 | 22 | aee4060598dc25cd8e4f3976ed5e70eb1bf874a2 | 179 | RPKit | Apache License 2.0 |
samples/kotlin-inject/shared/src/commonMain/kotlin/com/eygraber/portal/samples/kotlin/inject/home/HomeView.kt | eygraber | 418,759,025 | false | {"Kotlin": 78365, "Shell": 1351} | package com.eygraber.portal.samples.kotlin.inject.home
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import com.eygraber.portal.samples.icons.Alarm
import com.eygraber.portal.samples.icons.Icons
import com.eygraber.portal.samples.kotlin.inject.View
import me.tatarka.inject.annotations.Inject
@HomeScope
@Inject
class HomeView(
override val vm: HomeViewModel
) : View<Unit> {
@Composable
override fun Render() {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
Button(
onClick = vm::openAlarmsClicked
) {
Icon(
imageVector = Icons.Alarm,
contentDescription = "Open alarm list"
)
}
}
}
}
| 6 | Kotlin | 0 | 9 | bdf9e2cd2fd39196b1bd5c52db469d0a391f2e16 | 964 | portal | MIT License |
app/src/main/java/com/kyberswap/android/presentation/common/TutorialView.kt | KYRDTeam | 181,612,742 | false | null | package com.kyberswap.android.presentation.common
interface TutorialView {
fun skipTutorial()
} | 1 | null | 10 | 26 | abd4ab033d188918849e5224cc8204409776391b | 100 | android-app | MIT License |
notifikasjon/src/main/kotlin/no/nav/helsearbeidsgiver/inntektsmelding/notifikasjon/OpprettSakService.kt | navikt | 495,713,363 | false | {"Kotlin": 754534, "Dockerfile": 68} | package no.nav.helsearbeidsgiver.inntektsmelding.notifikasjon
import no.nav.helse.rapids_rivers.JsonMessage
import no.nav.helse.rapids_rivers.RapidsConnection
import no.nav.helsearbeidsgiver.felles.BehovType
import no.nav.helsearbeidsgiver.felles.EventName
import no.nav.helsearbeidsgiver.felles.Key
import no.nav.helsearbeidsgiver.felles.PersonDato
import no.nav.helsearbeidsgiver.felles.json.lesOrNull
import no.nav.helsearbeidsgiver.felles.json.toMap
import no.nav.helsearbeidsgiver.felles.rapidsrivers.DelegatingFailKanal
import no.nav.helsearbeidsgiver.felles.rapidsrivers.StatefullDataKanal
import no.nav.helsearbeidsgiver.felles.rapidsrivers.StatefullEventListener
import no.nav.helsearbeidsgiver.felles.rapidsrivers.composite.CompositeEventListener
import no.nav.helsearbeidsgiver.felles.rapidsrivers.composite.Transaction
import no.nav.helsearbeidsgiver.felles.rapidsrivers.model.Fail
import no.nav.helsearbeidsgiver.felles.rapidsrivers.redis.RedisKey
import no.nav.helsearbeidsgiver.felles.rapidsrivers.redis.RedisStore
import no.nav.helsearbeidsgiver.felles.utils.Log
import no.nav.helsearbeidsgiver.utils.json.fromJson
import no.nav.helsearbeidsgiver.utils.json.parseJson
import no.nav.helsearbeidsgiver.utils.json.serializer.UuidSerializer
import no.nav.helsearbeidsgiver.utils.json.toJsonStr
import no.nav.helsearbeidsgiver.utils.log.MdcUtils
import no.nav.helsearbeidsgiver.utils.log.logger
import no.nav.helsearbeidsgiver.utils.log.sikkerLogger
import java.util.UUID
class OpprettSakService(private val rapidsConnection: RapidsConnection, override val redisStore: RedisStore) : CompositeEventListener(redisStore) {
private val logger = logger()
private val sikkerLogger = sikkerLogger()
override val event: EventName = EventName.SAK_OPPRETT_REQUESTED
init {
withEventListener {
StatefullEventListener(
redisStore,
event,
arrayOf(Key.ORGNRUNDERENHET, Key.IDENTITETSNUMMER, Key.FORESPOERSEL_ID, Key.UUID),
this,
rapidsConnection
)
}
withDataKanal {
StatefullDataKanal(
arrayOf(Key.ARBEIDSTAKER_INFORMASJON, Key.SAK_ID, Key.PERSISTERT_SAK_ID),
event,
this,
rapidsConnection,
redisStore
)
}
withFailKanal { DelegatingFailKanal(event, this, rapidsConnection) }
}
override fun dispatchBehov(message: JsonMessage, transaction: Transaction) {
MdcUtils.withLogFields(
Log.klasse(this),
Log.event(EventName.SAK_OPPRETT_REQUESTED)
) {
val json = message.toJson().parseJson().toMap()
val transaksjonsId = json[Key.UUID]?.fromJson(UuidSerializer)
if (transaksjonsId == null) {
"Mangler transaksjonId. Klarer ikke opprette sak.".also {
logger.error(it)
sikkerLogger.error(it)
}
return
}
val forespoerselId = redisStore.get(RedisKey.of(transaksjonsId, Key.FORESPOERSEL_ID))?.let(UUID::fromString)
?: json[Key.FORESPOERSEL_ID]?.fromJson(UuidSerializer)
if (forespoerselId == null) {
MdcUtils.withLogFields(
Log.transaksjonId(transaksjonsId)
) {
"Mangler forespoerselId. Klarer ikke opprette sak.".also {
logger.error(it)
sikkerLogger.error(it)
}
}
return
}
MdcUtils.withLogFields(
Log.transaksjonId(transaksjonsId),
Log.forespoerselId(forespoerselId)
) {
dispatch(transaction, transaksjonsId, forespoerselId)
}
}
}
private fun dispatch(transaction: Transaction, transaksjonsId: UUID, forespoerselId: UUID) {
if (transaction == Transaction.NEW) {
val fnr = redisStore.get(RedisKey.of(transaksjonsId, Key.IDENTITETSNUMMER))
if (fnr == null) {
"Mangler fnr i redis. Klarer ikke opprette sak.".also {
logger.error(it)
sikkerLogger.error(it)
}
return
}
rapidsConnection.publish(
JsonMessage.newMessage(
mapOf(
Key.EVENT_NAME.str to event.name,
Key.UUID.str to transaksjonsId,
Key.BEHOV.str to BehovType.FULLT_NAVN.name,
Key.IDENTITETSNUMMER.str to fnr,
Key.FORESPOERSEL_ID.str to forespoerselId
)
).toJson()
)
} else if (transaction == Transaction.IN_PROGRESS) {
if (isDataCollected(*steg3(transaksjonsId))) {
val sakId = redisStore.get(RedisKey.of(transaksjonsId, Key.SAK_ID))
if (sakId == null) {
"Mangler sakId i redis. Klarer ikke opprette sak.".also {
logger.error(it)
sikkerLogger.error(it)
}
return
}
rapidsConnection.publish(
JsonMessage.newMessage(
mapOf(
Key.EVENT_NAME.str to event.name,
Key.UUID.str to transaksjonsId,
Key.BEHOV.str to BehovType.PERSISTER_SAK_ID.name,
Key.FORESPOERSEL_ID.str to forespoerselId,
Key.SAK_ID.str to sakId
)
).toJson()
)
} else if (isDataCollected(*steg2(transaksjonsId))) {
val orgnr = redisStore.get(RedisKey.of(transaksjonsId, Key.ORGNRUNDERENHET))
if (orgnr == null) {
"Mangler orgnr i redis. Klarer ikke opprette sak.".also {
logger.error(it)
sikkerLogger.error(it)
}
return
}
val arbeidstaker = redisStore.get(RedisKey.of(transaksjonsId, Key.ARBEIDSTAKER_INFORMASJON))
?.fromJson(PersonDato.serializer())
?: ukjentArbeidstaker()
rapidsConnection.publish(
JsonMessage.newMessage(
mapOf(
Key.EVENT_NAME.str to event.name,
Key.UUID.str to transaksjonsId,
Key.BEHOV.str to BehovType.OPPRETT_SAK,
Key.FORESPOERSEL_ID.str to forespoerselId,
Key.ORGNRUNDERENHET.str to orgnr,
Key.ARBEIDSTAKER_INFORMASJON.str to arbeidstaker
)
).toJson()
)
}
}
}
override fun finalize(message: JsonMessage) {
val transaksjonsId = message[Key.UUID.str].asText().let(UUID::fromString)
MdcUtils.withLogFields(
Log.klasse(this),
Log.event(EventName.SAK_OPPRETT_REQUESTED),
Log.transaksjonId(transaksjonsId)
) {
val sakId = redisStore.get(RedisKey.of(transaksjonsId, Key.SAK_ID))
if (sakId == null) {
"Mangler sakId i redis. Klarer ikke publisere event om opprettet sak.".also {
logger.error(it)
sikkerLogger.error(it)
}
return
}
rapidsConnection.publish(
JsonMessage.newMessage(
mapOf(
Key.EVENT_NAME.str to EventName.SAK_OPPRETTET.name,
Key.FORESPOERSEL_ID.str to message[Key.FORESPOERSEL_ID.str],
Key.SAK_ID.str to sakId
)
).toJson()
)
}
}
override fun terminate(fail: Fail) {
MdcUtils.withLogFields(
Log.klasse(this),
Log.event(EventName.SAK_OPPRETT_REQUESTED),
Log.transaksjonId(fail.transaksjonId)
) {
val clientId = redisStore.get(RedisKey.of(fail.transaksjonId, event))
?.let(UUID::fromString)
if (clientId == null) {
sikkerLogger.error("Forsøkte å terminere, men clientId mangler i Redis. forespoerselId=${fail.forespoerselId}")
} else {
redisStore.set(RedisKey.of(clientId), fail.feilmelding)
}
}
}
override fun onError(feil: Fail): Transaction {
val utloesendeBehov = Key.BEHOV.lesOrNull(BehovType.serializer(), feil.utloesendeMelding.toMap())
if (utloesendeBehov == BehovType.FULLT_NAVN) {
val arbeidstakerKey = RedisKey.of(feil.transaksjonId, Key.ARBEIDSTAKER_INFORMASJON)
redisStore.set(arbeidstakerKey, ukjentArbeidstaker().toJsonStr(PersonDato.serializer()))
return Transaction.IN_PROGRESS
}
return Transaction.TERMINATE
}
private fun ukjentArbeidstaker(): PersonDato =
PersonDato("Ukjent person", null, "")
private fun steg2(transactionId: UUID) = arrayOf(RedisKey.of(transactionId, Key.ARBEIDSTAKER_INFORMASJON))
private fun steg3(transactionId: UUID) = arrayOf(RedisKey.of(transactionId, Key.SAK_ID))
}
| 20 | Kotlin | 0 | 2 | ec21fe630fc45296cd3b7809d76bc3c725333e84 | 9,580 | helsearbeidsgiver-inntektsmelding | MIT License |
sample/src/main/java/com/tomcz/sample/feature/login/LoginViewModel.kt | mtomczynski | 352,071,135 | false | null | package com.tomcz.sample.feature.login
import androidx.lifecycle.ViewModel
import com.tomcz.mvi.StateEffectProcessor
import com.tomcz.mvi.common.stateEffectProcessor
import com.tomcz.sample.feature.login.state.LoginEffect
import com.tomcz.sample.feature.login.state.LoginEvent
import com.tomcz.sample.feature.login.state.LoginPartialState
import com.tomcz.sample.feature.login.state.LoginState
import com.tomcz.sample.util.thenNoAction
import kotlinx.coroutines.flow.flow
class LoginViewModel : ViewModel() {
val processor: StateEffectProcessor<LoginEvent, LoginState, LoginEffect> =
stateEffectProcessor(initialState = LoginState()) { effects, event ->
when (event) {
is LoginEvent.LoginClick -> flow {
emit(LoginPartialState.ShowLoading)
val isSuccess = loginUser(event.email, event.pass)
emit(LoginPartialState.HideLoading)
if (isSuccess) {
effects.send(LoginEffect.GoToHome)
} else {
effects.send(LoginEffect.ShowError)
}
}
LoginEvent.GoToRegister -> effects
.send(LoginEffect.GoToRegister).thenNoAction()
}
}
private suspend fun loginUser(email: String, pass: String): Boolean = true
}
| 1 | Kotlin | 3 | 9 | 7259b2d776152e578d5727f51bb0c718837e2948 | 1,379 | MVI | MIT License |
sample/src/main/java/com/tomcz/sample/feature/login/LoginViewModel.kt | mtomczynski | 352,071,135 | false | null | package com.tomcz.sample.feature.login
import androidx.lifecycle.ViewModel
import com.tomcz.mvi.StateEffectProcessor
import com.tomcz.mvi.common.stateEffectProcessor
import com.tomcz.sample.feature.login.state.LoginEffect
import com.tomcz.sample.feature.login.state.LoginEvent
import com.tomcz.sample.feature.login.state.LoginPartialState
import com.tomcz.sample.feature.login.state.LoginState
import com.tomcz.sample.util.thenNoAction
import kotlinx.coroutines.flow.flow
class LoginViewModel : ViewModel() {
val processor: StateEffectProcessor<LoginEvent, LoginState, LoginEffect> =
stateEffectProcessor(initialState = LoginState()) { effects, event ->
when (event) {
is LoginEvent.LoginClick -> flow {
emit(LoginPartialState.ShowLoading)
val isSuccess = loginUser(event.email, event.pass)
emit(LoginPartialState.HideLoading)
if (isSuccess) {
effects.send(LoginEffect.GoToHome)
} else {
effects.send(LoginEffect.ShowError)
}
}
LoginEvent.GoToRegister -> effects
.send(LoginEffect.GoToRegister).thenNoAction()
}
}
private suspend fun loginUser(email: String, pass: String): Boolean = true
}
| 1 | Kotlin | 3 | 9 | 7259b2d776152e578d5727f51bb0c718837e2948 | 1,379 | MVI | MIT License |
actions/src/main/java/io/em2m/actions/xforms/CookieTokenTransformer.kt | JackVCurtis | 120,828,436 | true | {"Kotlin": 502339, "Java": 1906} | package io.em2m.actions.xforms
import io.em2m.actions.model.ActionContext
import io.em2m.actions.model.ActionTransformer
import io.em2m.flows.Priorities
import rx.Observable
import javax.servlet.http.Cookie
class CookieTokenTransformer(val cookieName: String, override val priority: Int = Priorities.PRE_AUTHENTICATE) : ActionTransformer {
override fun call(obs: Observable<ActionContext>): Observable<ActionContext> {
return obs.doOnNext { context ->
val cookies = context.environment["cookies"]
if (cookies is List<*>) {
cookies.forEach { cookie ->
if (cookie is Cookie && cookie.name == cookieName) {
context.environment["Token"] = cookie.value
}
}
}
}
}
}
| 0 | Kotlin | 0 | 0 | 9ed71d839103fe356c652cf2f6a411ef104d37e1 | 822 | em2m-java-sdk | Apache License 2.0 |
buildSrc/src/main/kotlin/gradle/ProjectExts.kt | TeamDev-IP | 773,887,729 | false | {"Kotlin": 108773, "JavaScript": 98311, "Java": 23294, "HTML": 13110, "CSS": 8390} | /*
* Copyright (c) 2024 TeamDev
*
* 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 gradle
import org.gradle.accessors.dm.LibrariesForLibs
import org.gradle.api.Project
import org.gradle.api.internal.catalog.ExternalModuleDependencyFactory.VersionNotationSupplier
import org.gradle.kotlin.dsl.the
/**
* Returns generated type-safe version catalogs accessors for the conventional
* `libs` catalog.
*/
val Project.libs
get() = the<LibrariesForLibs>()
/**
* Allows to access the version immediately, omitting the intermediate call
* to `asProvider()` method.
*
* The method is useful when the declared version has subversion(s). For example,
* if there are both `versions.java` and `versions.java.vendor`, then it is
* impossible to call `get()` directly on `java`.
*/
fun VersionNotationSupplier.get(): String = asProvider().get()
/**
* Returns the version of JxBrowser for packaging the Compose builds.
*
* This method removes `-eap...` suffix from the returned version, if any.
* For example, if the currently used version is `8.0.0-eap.7`,
* then the method would return just `8.0.0`.
*
* This is needed because `.dmg` version descriptor must be
* in the following format: `MAJOR[.MINOR][.PATCH]`.
*/
fun Project.jxBrowserPackagingVersion(): String {
val pattern = "(.*?)-eap".toRegex()
val version = libs.versions.jxbrowser.get()
val matchResult = pattern.find(version)
return matchResult?.groups?.get(1)?.value ?: version
}
| 8 | Kotlin | 0 | 0 | d7355dc53a8b18e2bbc5645ee6e280b4a9d61332 | 2,523 | JxBrowser-Gallery | MIT License |
security/src/main/java/com/boomesh/security/di/MainModule.kt | boomesh | 194,716,066 | false | null | package com.boomesh.security.di
import android.content.Context
import android.content.SharedPreferences
import com.boomesh.security.preferences.SecurePrefs
internal class MainModule(private val context: Context) {
private val commonModule: CommonModule = CommonModule(context)
private val encryptionModule: EncryptionModule
init {
encryptionModule = EncryptionModule(context, commonModule)
}
fun providesEncryptedSharedPreferences(fileName: String): SharedPreferences {
return SecurePrefs(
context.getSharedPreferences(fileName, Context.MODE_PRIVATE),
encryptionModule.providesSecurable(),
commonModule.provideBase64Decoder(),
commonModule.provideBase64Encoder()
)
}
} | 0 | Kotlin | 2 | 12 | e5e22598f9bc4d96eea9544f01979bf9c5ecda79 | 768 | EncryptedSharedPreferences | MIT License |
src/main/java/net/estinet/EstiConsole/ShutdownHook.kt | GenesisHub | 94,350,266 | true | {"Kotlin": 46740} | package net.estinet.EstiConsole
class ShutdownHook : Runnable{
override fun run() {
EstiConsole.autoStartOnStop = false
if(mode == Modes.BUNGEE) EstiConsole.sendJavaInput("end")
else if (mode == Modes.SPIGOT || mode == Modes.PAPERSPIGOT) EstiConsole.sendJavaInput("stop")
val thr: Thread = Thread({
Thread.sleep(30000)
if(EstiConsole.javaProcess.isAlive()) EstiConsole.javaProcess.destroyForcibly()
})
thr.start()
}
} | 0 | Kotlin | 0 | 0 | 0aaef440625ea6ccfcee878913a174022f787cae | 498 | EstiConsole | Apache License 2.0 |
src/main/java/net/estinet/EstiConsole/ShutdownHook.kt | GenesisHub | 94,350,266 | true | {"Kotlin": 46740} | package net.estinet.EstiConsole
class ShutdownHook : Runnable{
override fun run() {
EstiConsole.autoStartOnStop = false
if(mode == Modes.BUNGEE) EstiConsole.sendJavaInput("end")
else if (mode == Modes.SPIGOT || mode == Modes.PAPERSPIGOT) EstiConsole.sendJavaInput("stop")
val thr: Thread = Thread({
Thread.sleep(30000)
if(EstiConsole.javaProcess.isAlive()) EstiConsole.javaProcess.destroyForcibly()
})
thr.start()
}
} | 0 | Kotlin | 0 | 0 | 0aaef440625ea6ccfcee878913a174022f787cae | 498 | EstiConsole | Apache License 2.0 |
app-backend/ms-web-service/src/main/kotlin/com/javawebapp/web/exception/ApiExceptionHandler.kt | awarenessxz | 298,534,050 | false | {"TypeScript": 232578, "Kotlin": 26519, "JavaScript": 22522, "SCSS": 6816, "Dockerfile": 2131, "HTML": 1032} | package com.javawebapp.web.exception
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.ControllerAdvice
import org.springframework.web.bind.annotation.ExceptionHandler
import org.springframework.web.context.request.WebRequest
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
import java.util.*
@ControllerAdvice
class ApiExceptionHandler: ResponseEntityExceptionHandler() {
// Global Exception Handler
@ExceptionHandler(value = [(Exception::class)])
fun handleAnyException(ex: Exception, request: WebRequest): ResponseEntity<Any> {
val errorMsgDescription = if (ex.localizedMessage == null) ex.toString() else ex.localizedMessage
val errorMsg = ErrorMessage(Date(), errorMsgDescription)
return ResponseEntity(errorMsg, HttpHeaders(), HttpStatus.INTERNAL_SERVER_ERROR)
}
// Api Exception Handler
@ExceptionHandler(value = [(ApiException::class)])
fun handleApiException(ex: ApiException, request: WebRequest): ResponseEntity<Any> {
val errorMsgDescription = if (ex.localizedMessage == null) ex.toString() else ex.localizedMessage
val errorMsg = ErrorMessage(Date(), errorMsgDescription, ex.errorType)
return ResponseEntity(errorMsg, HttpHeaders(), ex.status)
}
} | 0 | TypeScript | 0 | 0 | e0cd2034081e5c5d5e614f5f7383200af55c55a8 | 1,419 | java-web-app | Apache License 2.0 |
browser-kotlin/src/jsMain/kotlin/web/gpu/GPUCompilationMessage.kt | karakum-team | 393,199,102 | false | {"Kotlin": 6272741} | // Automatically generated - do not modify!
package web.gpu
import js.core.JsLong
sealed external interface GPUCompilationMessage {
val message: String
val type: GPUCompilationMessageType
val lineNum: JsLong
val linePos: JsLong
}
| 0 | Kotlin | 8 | 36 | 95b065622a9445caf058ad2581f4c91f9e2b0d91 | 249 | types-kotlin | Apache License 2.0 |
app/src/main/java/chat/rocket/android/main/presentation/MainPresenter.kt | RocketChat | 48,179,404 | false | null | package chat.rocket.android.main.presentation
import chat.rocket.android.authentication.domain.model.DeepLinkInfo
import chat.rocket.android.core.behaviours.AppLanguageView
import chat.rocket.android.core.lifecycle.CancelStrategy
import chat.rocket.android.helper.UserHelper
import chat.rocket.android.push.GroupedPush
import chat.rocket.android.push.retrieveCurrentPushNotificationToken
import chat.rocket.android.server.domain.GetCurrentLanguageInteractor
import chat.rocket.android.server.domain.GetSettingsInteractor
import chat.rocket.android.server.domain.RefreshPermissionsInteractor
import chat.rocket.android.server.domain.RefreshSettingsInteractor
import chat.rocket.android.server.domain.RemoveAccountInteractor
import chat.rocket.android.server.domain.SaveAccountInteractor
import chat.rocket.android.server.domain.TokenRepository
import chat.rocket.android.server.domain.favicon
import chat.rocket.android.server.domain.model.Account
import chat.rocket.android.server.domain.siteName
import chat.rocket.android.server.domain.wideTile
import chat.rocket.android.server.infrastructure.ConnectionManagerFactory
import chat.rocket.android.server.infrastructure.RocketChatClientFactory
import chat.rocket.android.util.extension.launchUI
import chat.rocket.android.util.extensions.avatarUrl
import chat.rocket.android.util.extensions.serverLogoUrl
import javax.inject.Inject
import javax.inject.Named
class MainPresenter @Inject constructor(
@Named("currentServer") private val currentServer: String?,
private val strategy: CancelStrategy,
private val mainNavigator: MainNavigator,
private val appLanguageView: AppLanguageView,
private val refreshSettingsInteractor: RefreshSettingsInteractor,
private val refreshPermissionsInteractor: RefreshPermissionsInteractor,
private val getSettingsInteractor: GetSettingsInteractor,
private val connectionManagerFactory: ConnectionManagerFactory,
private var getLanguageInteractor: GetCurrentLanguageInteractor,
private val groupedPush: GroupedPush,
private val tokenRepository: TokenRepository,
private val userHelper: UserHelper,
private val saveAccountInteractor: SaveAccountInteractor,
private val removeAccountInteractor: RemoveAccountInteractor,
private val factory: RocketChatClientFactory
) {
fun connect() = currentServer?.let {
refreshSettingsInteractor.refreshAsync(it)
refreshPermissionsInteractor.refreshAsync(it)
connectionManagerFactory.create(it)?.connect()
}
fun clearNotificationsForChatRoom(chatRoomId: String?) {
if (chatRoomId == null) return
groupedPush.hostToPushMessageList[currentServer].let { list ->
list?.removeAll { it.info.roomId == chatRoomId }
}
}
fun getAppLanguage() {
with(getLanguageInteractor) {
getLanguage()?.let { language ->
appLanguageView.updateLanguage(language, getCountry())
}
}
}
fun removeOldAccount() = currentServer?.let {
removeAccountInteractor.remove(currentServer)
}
fun saveNewAccount() {
currentServer?.let { currentServer ->
with(getSettingsInteractor.get(currentServer)) {
val icon = favicon()?.let {
currentServer.serverLogoUrl(it)
}
val logo = wideTile()?.let {
currentServer.serverLogoUrl(it)
}
val token = tokenRepository.get(currentServer)
val thumb = currentServer.avatarUrl(
userHelper.username() ?: "",
token?.userId,
token?.authToken
)
val account = Account(
serverName = siteName() ?: currentServer,
serverUrl = currentServer,
serverLogoUrl = icon,
serverBackgroundImageUrl = logo,
userName = userHelper.username() ?: "",
userAvatarUrl = thumb,
authToken = token?.authToken,
userId = token?.userId
)
saveAccountInteractor.save(account)
}
}
}
fun registerPushNotificationToken() = launchUI(strategy) {
currentServer?.let { retrieveCurrentPushNotificationToken(factory.get(it)) }
}
fun showChatList(chatRoomId: String? = null, deepLinkInfo: DeepLinkInfo? = null) =
mainNavigator.toChatList(chatRoomId, deepLinkInfo)
}
| 283 | Kotlin | 585 | 877 | f832d59cb2130e5c058f5d9e9de5ff961d5d3380 | 4,555 | Rocket.Chat.Android | MIT License |
korge/src/commonMain/kotlin/com/soywiz/korge/bus/Bus.kt | dwursteisen | 237,209,432 | true | {"Kotlin": 1824737, "Java": 182026, "Shell": 1955, "Batchfile": 1618} | package com.soywiz.korge.bus
import com.soywiz.korge.internal.fastForEach
import com.soywiz.korinject.*
import com.soywiz.korio.lang.*
import kotlin.reflect.*
//@Prototype
class Bus(
private val globalBus: GlobalBus
) : Closeable, InjectedHandler {
private val closeables = arrayListOf<Closeable>()
suspend fun send(message: Any) {
globalBus.send(message)
}
fun <T : Any> register(clazz: KClass<out T>, handler: suspend (T) -> Unit): Closeable {
val closeable = globalBus.register(clazz, handler)
closeables += closeable
return closeable
}
fun registerInstance(instance: Any) {
TODO()
//for (method in instance.javaClass.allDeclaredMethods) {
// if (method.getAnnotation(BusHandler::class.java) != null) {
// val param = method.parameterTypes.firstOrNull() ?: continue
// register(param) {
// method.invokeSuspend(instance, listOf(it))
// }
// }
//}
}
suspend override fun injectedInto(instance: Any) {
registerInstance(instance)
}
override fun close() {
closeables.fastForEach { c ->
c.close()
}
}
}
//@Singleton
class GlobalBus {
val perClassHandlers = HashMap<KClass<*>, ArrayList<suspend (Any) -> Unit>>()
suspend fun send(message: Any) {
val clazz = message::class
perClassHandlers[clazz]?.fastForEach { handler ->
handler(message)
}
}
private fun forClass(clazz: KClass<*>) = perClassHandlers.getOrPut(clazz) { arrayListOf() }
@Suppress("UNCHECKED_CAST")
fun <T : Any> register(clazz: KClass<out T>, handler: suspend (T) -> Unit): Closeable {
val chandler = handler as (suspend (Any) -> Unit)
forClass(clazz).add(chandler)
return Closeable {
forClass(clazz).remove(chandler)
}
}
}
//@JTranscKeep
//@JTranscKeepName
annotation class BusHandler
| 0 | null | 0 | 0 | 713eb6a9e5644b8bba7ec6d8c274c2d7ed66a431 | 1,740 | korge | Apache License 2.0 |
lib_base/src/main/java/com/czl/lib_base/util/ToastHelper.kt | cdalwyn | 336,133,347 | false | null | package com.czl.lib_base.util
import android.content.Context
import android.graphics.Color
import android.text.TextUtils
import android.view.Gravity
import android.widget.Toast
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.ThreadUtils.runOnUiThread
import com.blankj.utilcode.util.Utils
import es.dmoral.toasty.Toasty
/**
* @author Alwyn
* @Date 2020/3/18
* @Description
*/
object ToastHelper {
fun showWarnToast(msg: String?) {
if (!TextUtils.isEmpty(msg))
runOnUiThread {
Toasty.warning(Utils.getApp(), msg!!).show()
}
}
fun showInfoToast(msg: String?) {
if (!TextUtils.isEmpty(msg))
runOnUiThread { Toasty.info(Utils.getApp(), msg!!).show() }
}
fun showLongInfoToast(msg: String?) {
if (!TextUtils.isEmpty(msg))
runOnUiThread { Toasty.info(Utils.getApp(), msg!!,Toast.LENGTH_LONG).show() }
}
fun showNormalToast(msg: String?) {
if (!TextUtils.isEmpty(msg))
runOnUiThread {
Toasty.normal(Utils.getApp(), msg!!).show()
}
}
fun showErrorToast(msg: String?) {
if (!TextUtils.isEmpty(msg))
runOnUiThread { Toasty.error(Utils.getApp(), msg!!).show() }
}
fun showErrorLongToast(msg: String?) {
if (!TextUtils.isEmpty(msg))
runOnUiThread { Toasty.error(Utils.getApp(), msg!!, Toast.LENGTH_LONG).show() }
}
fun showSuccessToast(msg: String?) {
if (!TextUtils.isEmpty(msg))
runOnUiThread {
if (!TextUtils.isEmpty(msg))
Toasty.success(Utils.getApp(), msg!!).show()
}
}
fun showSuccessLongToast(msg: String?) {
if (!TextUtils.isEmpty(msg))
runOnUiThread {
if (!TextUtils.isEmpty(msg))
Toasty.success(Utils.getApp(), msg!!,Toasty.LENGTH_LONG).show()
}
}
fun showSuccessLongCenterToast(msg: String?){
if (!TextUtils.isEmpty(msg))
runOnUiThread {
if (!TextUtils.isEmpty(msg))
Toasty.success(Utils.getApp(), msg!!,Toasty.LENGTH_LONG).apply {
setGravity(Gravity.CENTER,0,0)
show()
}
}
}
fun showWarnToast(msg: Int) {
if (!TextUtils.isEmpty(Utils.getApp().getString(msg)))
runOnUiThread {
Toasty.warning(Utils.getApp(), msg).show()
}
}
fun showInfoToast(msg: Int) {
if (!TextUtils.isEmpty(Utils.getApp().getString(msg)))
runOnUiThread {
Toasty.info(Utils.getApp(), msg).show()
}
}
fun showNormalToast(msg: Int) {
if (!TextUtils.isEmpty(Utils.getApp().getString(msg)))
runOnUiThread {
Toasty.normal(Utils.getApp(), msg).show()
}
}
fun showLongNormalToast(msg: Int) {
if (!TextUtils.isEmpty(Utils.getApp().getString(msg)))
runOnUiThread {
Toasty.normal(Utils.getApp(), msg,Toast.LENGTH_LONG).show()
}
}
fun showErrorToast(msg: Int) {
if (!TextUtils.isEmpty(Utils.getApp().getString(msg)))
runOnUiThread {
Toasty.error(Utils.getApp(), msg).show()
}
}
fun showSuccessToast(msg: Int) {
if (!TextUtils.isEmpty(Utils.getApp().getString(msg)))
runOnUiThread {
Toasty.success(Utils.getApp(), msg).show()
}
}
} | 1 | null | 70 | 267 | 77298b416cc15f168499c0b29c8f9017e6c187ca | 3,633 | PlayAndroid | Apache License 2.0 |
kotlin-cdk-wrapper/src/main/kotlin/io/cloudshiftdev/awscdk/services/msk/CfnReplicatorProps.kt | cloudshiftinc | 667,063,030 | false | {"Kotlin": 149148378} | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package io.cloudshiftdev.awscdk.services.msk
import io.cloudshiftdev.awscdk.CfnTag
import io.cloudshiftdev.awscdk.IResolvable
import io.cloudshiftdev.awscdk.common.CdkDslMarker
import io.cloudshiftdev.awscdk.common.CdkObject
import io.cloudshiftdev.awscdk.common.CdkObjectWrappers
import kotlin.Any
import kotlin.String
import kotlin.Unit
import kotlin.collections.List
/**
* Properties for defining a `CfnReplicator`.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import io.cloudshiftdev.awscdk.services.msk.*;
* CfnReplicatorProps cfnReplicatorProps = CfnReplicatorProps.builder()
* .kafkaClusters(List.of(KafkaClusterProperty.builder()
* .amazonMskCluster(AmazonMskClusterProperty.builder()
* .mskClusterArn("mskClusterArn")
* .build())
* .vpcConfig(KafkaClusterClientVpcConfigProperty.builder()
* .subnetIds(List.of("subnetIds"))
* // the properties below are optional
* .securityGroupIds(List.of("securityGroupIds"))
* .build())
* .build()))
* .replicationInfoList(List.of(ReplicationInfoProperty.builder()
* .consumerGroupReplication(ConsumerGroupReplicationProperty.builder()
* .consumerGroupsToReplicate(List.of("consumerGroupsToReplicate"))
* // the properties below are optional
* .consumerGroupsToExclude(List.of("consumerGroupsToExclude"))
* .detectAndCopyNewConsumerGroups(false)
* .synchroniseConsumerGroupOffsets(false)
* .build())
* .sourceKafkaClusterArn("sourceKafkaClusterArn")
* .targetCompressionType("targetCompressionType")
* .targetKafkaClusterArn("targetKafkaClusterArn")
* .topicReplication(TopicReplicationProperty.builder()
* .topicsToReplicate(List.of("topicsToReplicate"))
* // the properties below are optional
* .copyAccessControlListsForTopics(false)
* .copyTopicConfigurations(false)
* .detectAndCopyNewTopics(false)
* .startingPosition(ReplicationStartingPositionProperty.builder()
* .type("type")
* .build())
* .topicNameConfiguration(ReplicationTopicNameConfigurationProperty.builder()
* .type("type")
* .build())
* .topicsToExclude(List.of("topicsToExclude"))
* .build())
* .build()))
* .replicatorName("replicatorName")
* .serviceExecutionRoleArn("serviceExecutionRoleArn")
* // the properties below are optional
* .currentVersion("currentVersion")
* .description("description")
* .tags(List.of(CfnTag.builder()
* .key("key")
* .value("value")
* .build()))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-msk-replicator.html)
*/
public interface CfnReplicatorProps {
/**
* The current version number of the replicator.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-msk-replicator.html#cfn-msk-replicator-currentversion)
*/
public fun currentVersion(): String? = unwrap(this).getCurrentVersion()
/**
* A summary description of the replicator.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-msk-replicator.html#cfn-msk-replicator-description)
*/
public fun description(): String? = unwrap(this).getDescription()
/**
* Kafka Clusters to use in setting up sources / targets for replication.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-msk-replicator.html#cfn-msk-replicator-kafkaclusters)
*/
public fun kafkaClusters(): Any
/**
* A list of replication configurations, where each configuration targets a given source cluster
* to target cluster replication flow.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-msk-replicator.html#cfn-msk-replicator-replicationinfolist)
*/
public fun replicationInfoList(): Any
/**
* The name of the replicator.
*
* Alpha-numeric characters with '-' are allowed.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-msk-replicator.html#cfn-msk-replicator-replicatorname)
*/
public fun replicatorName(): String
/**
* The ARN of the IAM role used by the replicator to access resources in the customer's account
* (e.g source and target clusters).
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-msk-replicator.html#cfn-msk-replicator-serviceexecutionrolearn)
*/
public fun serviceExecutionRoleArn(): String
/**
* List of tags to attach to created Replicator.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-msk-replicator.html#cfn-msk-replicator-tags)
*/
public fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
/**
* A builder for [CfnReplicatorProps]
*/
@CdkDslMarker
public interface Builder {
/**
* @param currentVersion The current version number of the replicator.
*/
public fun currentVersion(currentVersion: String)
/**
* @param description A summary description of the replicator.
*/
public fun description(description: String)
/**
* @param kafkaClusters Kafka Clusters to use in setting up sources / targets for replication.
*/
public fun kafkaClusters(kafkaClusters: IResolvable)
/**
* @param kafkaClusters Kafka Clusters to use in setting up sources / targets for replication.
*/
public fun kafkaClusters(kafkaClusters: List<Any>)
/**
* @param kafkaClusters Kafka Clusters to use in setting up sources / targets for replication.
*/
public fun kafkaClusters(vararg kafkaClusters: Any)
/**
* @param replicationInfoList A list of replication configurations, where each configuration
* targets a given source cluster to target cluster replication flow.
*/
public fun replicationInfoList(replicationInfoList: IResolvable)
/**
* @param replicationInfoList A list of replication configurations, where each configuration
* targets a given source cluster to target cluster replication flow.
*/
public fun replicationInfoList(replicationInfoList: List<Any>)
/**
* @param replicationInfoList A list of replication configurations, where each configuration
* targets a given source cluster to target cluster replication flow.
*/
public fun replicationInfoList(vararg replicationInfoList: Any)
/**
* @param replicatorName The name of the replicator.
* Alpha-numeric characters with '-' are allowed.
*/
public fun replicatorName(replicatorName: String)
/**
* @param serviceExecutionRoleArn The ARN of the IAM role used by the replicator to access
* resources in the customer's account (e.g source and target clusters).
*/
public fun serviceExecutionRoleArn(serviceExecutionRoleArn: String)
/**
* @param tags List of tags to attach to created Replicator.
*/
public fun tags(tags: List<CfnTag>)
/**
* @param tags List of tags to attach to created Replicator.
*/
public fun tags(vararg tags: CfnTag)
}
private class BuilderImpl : Builder {
private val cdkBuilder: software.amazon.awscdk.services.msk.CfnReplicatorProps.Builder =
software.amazon.awscdk.services.msk.CfnReplicatorProps.builder()
/**
* @param currentVersion The current version number of the replicator.
*/
override fun currentVersion(currentVersion: String) {
cdkBuilder.currentVersion(currentVersion)
}
/**
* @param description A summary description of the replicator.
*/
override fun description(description: String) {
cdkBuilder.description(description)
}
/**
* @param kafkaClusters Kafka Clusters to use in setting up sources / targets for replication.
*/
override fun kafkaClusters(kafkaClusters: IResolvable) {
cdkBuilder.kafkaClusters(kafkaClusters.let(IResolvable.Companion::unwrap))
}
/**
* @param kafkaClusters Kafka Clusters to use in setting up sources / targets for replication.
*/
override fun kafkaClusters(kafkaClusters: List<Any>) {
cdkBuilder.kafkaClusters(kafkaClusters.map{CdkObjectWrappers.unwrap(it)})
}
/**
* @param kafkaClusters Kafka Clusters to use in setting up sources / targets for replication.
*/
override fun kafkaClusters(vararg kafkaClusters: Any): Unit =
kafkaClusters(kafkaClusters.toList())
/**
* @param replicationInfoList A list of replication configurations, where each configuration
* targets a given source cluster to target cluster replication flow.
*/
override fun replicationInfoList(replicationInfoList: IResolvable) {
cdkBuilder.replicationInfoList(replicationInfoList.let(IResolvable.Companion::unwrap))
}
/**
* @param replicationInfoList A list of replication configurations, where each configuration
* targets a given source cluster to target cluster replication flow.
*/
override fun replicationInfoList(replicationInfoList: List<Any>) {
cdkBuilder.replicationInfoList(replicationInfoList.map{CdkObjectWrappers.unwrap(it)})
}
/**
* @param replicationInfoList A list of replication configurations, where each configuration
* targets a given source cluster to target cluster replication flow.
*/
override fun replicationInfoList(vararg replicationInfoList: Any): Unit =
replicationInfoList(replicationInfoList.toList())
/**
* @param replicatorName The name of the replicator.
* Alpha-numeric characters with '-' are allowed.
*/
override fun replicatorName(replicatorName: String) {
cdkBuilder.replicatorName(replicatorName)
}
/**
* @param serviceExecutionRoleArn The ARN of the IAM role used by the replicator to access
* resources in the customer's account (e.g source and target clusters).
*/
override fun serviceExecutionRoleArn(serviceExecutionRoleArn: String) {
cdkBuilder.serviceExecutionRoleArn(serviceExecutionRoleArn)
}
/**
* @param tags List of tags to attach to created Replicator.
*/
override fun tags(tags: List<CfnTag>) {
cdkBuilder.tags(tags.map(CfnTag.Companion::unwrap))
}
/**
* @param tags List of tags to attach to created Replicator.
*/
override fun tags(vararg tags: CfnTag): Unit = tags(tags.toList())
public fun build(): software.amazon.awscdk.services.msk.CfnReplicatorProps = cdkBuilder.build()
}
private class Wrapper(
cdkObject: software.amazon.awscdk.services.msk.CfnReplicatorProps,
) : CdkObject(cdkObject),
CfnReplicatorProps {
/**
* The current version number of the replicator.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-msk-replicator.html#cfn-msk-replicator-currentversion)
*/
override fun currentVersion(): String? = unwrap(this).getCurrentVersion()
/**
* A summary description of the replicator.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-msk-replicator.html#cfn-msk-replicator-description)
*/
override fun description(): String? = unwrap(this).getDescription()
/**
* Kafka Clusters to use in setting up sources / targets for replication.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-msk-replicator.html#cfn-msk-replicator-kafkaclusters)
*/
override fun kafkaClusters(): Any = unwrap(this).getKafkaClusters()
/**
* A list of replication configurations, where each configuration targets a given source cluster
* to target cluster replication flow.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-msk-replicator.html#cfn-msk-replicator-replicationinfolist)
*/
override fun replicationInfoList(): Any = unwrap(this).getReplicationInfoList()
/**
* The name of the replicator.
*
* Alpha-numeric characters with '-' are allowed.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-msk-replicator.html#cfn-msk-replicator-replicatorname)
*/
override fun replicatorName(): String = unwrap(this).getReplicatorName()
/**
* The ARN of the IAM role used by the replicator to access resources in the customer's account
* (e.g source and target clusters).
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-msk-replicator.html#cfn-msk-replicator-serviceexecutionrolearn)
*/
override fun serviceExecutionRoleArn(): String = unwrap(this).getServiceExecutionRoleArn()
/**
* List of tags to attach to created Replicator.
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-msk-replicator.html#cfn-msk-replicator-tags)
*/
override fun tags(): List<CfnTag> = unwrap(this).getTags()?.map(CfnTag::wrap) ?: emptyList()
}
public companion object {
public operator fun invoke(block: Builder.() -> Unit = {}): CfnReplicatorProps {
val builderImpl = BuilderImpl()
return Wrapper(builderImpl.apply(block).build())
}
internal fun wrap(cdkObject: software.amazon.awscdk.services.msk.CfnReplicatorProps):
CfnReplicatorProps = CdkObjectWrappers.wrap(cdkObject) as? CfnReplicatorProps ?:
Wrapper(cdkObject)
internal fun unwrap(wrapped: CfnReplicatorProps):
software.amazon.awscdk.services.msk.CfnReplicatorProps = (wrapped as CdkObject).cdkObject as
software.amazon.awscdk.services.msk.CfnReplicatorProps
}
}
| 0 | Kotlin | 0 | 4 | 652b030da47fc795f7a987eba0f8c82f64035d24 | 13,983 | kotlin-cdk-wrapper | Apache License 2.0 |
app/src/main/java/com/sergiobelda/androidtodometer/domain/repository/ITaskRepository.kt | serbelga | 245,540,004 | false | {"Kotlin": 173227} | /*
* Copyright 2022 <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.sergiobelda.androidtodometer.data.localdatasource
import com.sergiobelda.androidtodometer.domain.model.Task
import kotlinx.coroutines.flow.Flow
interface ITaskLocalDataSource {
fun getTask(id: Int): Flow<Task?>
suspend fun deleteTask(id: Int)
suspend fun insert(task: Task): Long?
suspend fun setTaskDone(id: Int)
suspend fun setTaskDoing(id: Int)
suspend fun updateTask(task: Task)
}
| 1 | Kotlin | 33 | 310 | 4ce465e3e494821a2c538898fc016e0984ad4b19 | 1,020 | ToDometer | Apache License 2.0 |
src/Day08.kt | icoffiel | 572,651,851 | false | {"Kotlin": 29350} | private const val DAY = "Day08"
fun main() {
fun <T> Iterable<T>.takeWhileInclusive(
predicate: (T) -> Boolean
): List<T> {
var shouldContinue = true
return takeWhile {
val result = shouldContinue
shouldContinue = predicate(it)
result
}
}
fun part1(input: List<String>): Int {
val grid: List<List<Int>> = input
.map { row ->
row.map { it.digitToInt() }
}
val visibilityMatrix: List<List<Boolean>> = grid.mapIndexed { rowIndex, row ->
row.mapIndexed { columnIndex, column ->
val sizeToBeat = column
when {
rowIndex == 0 -> true // at the top of the grid
rowIndex == grid.size - 1 -> true // at the bottom of the grid
columnIndex == 0 -> true
columnIndex == grid[0].size - 1 -> true
else -> {
val rowLeftBeat: Boolean = (0 until columnIndex)
.map {
when {
grid[rowIndex][it] < sizeToBeat -> true
else -> false
}
}
.all { it }
val rowRightBeat = (columnIndex + 1 until row.size)
.map {
when {
grid[rowIndex][it] < sizeToBeat -> true
else -> false
}
}
.all { it }
val columnUpBeat = (0 until rowIndex)
.map {
when {
grid[it][columnIndex] < sizeToBeat -> true
else -> false
}
}
.all { it }
val columnDownBeat = (rowIndex + 1 until grid.size)
.map {
when {
grid[it][columnIndex] < sizeToBeat -> true
else -> false
}
}
.all { it }
when {
rowLeftBeat || rowRightBeat -> true // check if visible along the row
columnUpBeat || columnDownBeat -> true // check if visible along the column
else -> false // otherwise return false
}
}
}
}
}
return visibilityMatrix
.flatten()
.count { it }
}
fun part2(input: List<String>): Int {
val grid: List<List<Int>> = input
.map { row ->
row.map { it.digitToInt() }
}
val visibilityMatrix: List<List<Int>> = grid.mapIndexed { rowIndex, row ->
row.mapIndexed { columnIndex, column ->
val currentValue = column
val rowLeftScan = when (columnIndex) {
0 -> 0
else -> {
(columnIndex - 1 downTo 0)
.map { grid[rowIndex][it] }
.takeWhileInclusive { it < currentValue }
.count()
}
}
val rowRightBeat = when (columnIndex) {
row.size -> 0
else -> {
(columnIndex + 1 until row.size)
.map { grid[rowIndex][it] }
.takeWhileInclusive { it < currentValue }
.count()
}
}
val columnUpBeat = when (rowIndex) {
0 -> 0
else -> {
(rowIndex - 1 downTo 0)
.map { grid[it][columnIndex] }
.takeWhileInclusive { it < currentValue }
.count()
}
}
val columnDownBeat = when (rowIndex) {
grid.size -> 0
else -> {
(rowIndex + 1 until grid.size)
.map { grid[it][columnIndex] }
.takeWhileInclusive { it < currentValue }
.count()
}
}
rowLeftScan * rowRightBeat * columnUpBeat * columnDownBeat
}
}
return visibilityMatrix
.flatten()
.max()
}
val testInput = readInput("${DAY}_test")
check(part1(testInput) == 21)
check(part2(testInput) == 8)
val input = readInput(DAY)
println("Part One: ${part1(input)}")
check(part1(input) == 1676)
println("Part Two: ${part2(input)}")
check(part2(input) == 313200)
} | 0 | Kotlin | 0 | 0 | 515f5681c385f22efab5c711dc983e24157fc84f | 5,288 | advent-of-code-2022 | Apache License 2.0 |
backend/src/main/kotlin/ru/glitchless/santa/routing/chat/ChatRoute.kt | glitchless | 225,166,682 | false | {"TypeScript": 92354, "Kotlin": 85133, "SCSS": 22802, "JavaScript": 12185, "HTML": 8829, "Dockerfile": 913, "Shell": 886} | package ru.glitchless.santa.routing.chat
import com.google.gson.GsonBuilder
import io.ktor.application.*
import io.ktor.routing.*
import ru.glitchless.santa.model.api.ApiResponse
import ru.glitchless.santa.model.api.HttpError
import ru.glitchless.santa.model.api.chat.CompanionType
import ru.glitchless.santa.model.api.chat.MessageSendObject
import ru.glitchless.santa.model.exception.throwables.HttpSupportException
import ru.glitchless.santa.model.exception.throwables.receiveOrThrow
import ru.glitchless.santa.repository.chat.ChatRepository
import ru.glitchless.santa.utils.getSession
import ru.glitchless.santa.utils.respondWithCode
import java.lang.Integer.min
val gson = GsonBuilder().create()
fun Route.initRouteChat() {
get {
val with = call.request.queryParameters["with"] ?: throw HttpSupportException(HttpError.NOT_ALLOW_EMPTY_PARAM)
val limit = call.request.queryParameters["limit"]?.toInt() ?: 50
val offset_id = call.request.queryParameters["offset_id"]?.toInt() ?: Int.MAX_VALUE
val type = gson.fromJson(with, CompanionType::class.java)
val real_limit = min(limit, 50)
val userId = call.getSession().userId
val chat = ChatRepository.getChat(userId, type, real_limit, offset_id)
call.respondWithCode(ApiResponse(chat))
}
post {
val messageSendObject = call.receiveOrThrow<MessageSendObject>()
val userId = call.getSession().userId
ChatRepository.sendMessage(userId, messageSendObject.to, messageSendObject.text)
call.respondWithCode(ApiResponse(null))
}
get("wait_new") {
val with = call.request.queryParameters["with"] ?: throw HttpSupportException(HttpError.NOT_ALLOW_EMPTY_PARAM)
val last_id = call.request.queryParameters["last_id"]?.toInt() ?: Int.MAX_VALUE
val timeout = call.request.queryParameters["timeout"]?.toLong() ?: 120
val type = gson.fromJson(with, CompanionType::class.java)
val userId = call.getSession().userId
val chat = ChatRepository.getChat(userId, type, 50, last_id, false)
if (chat.count != 0L) {
call.respondWithCode(ApiResponse(chat))
return@get
}
val message = ChatRepository.waitMessage(userId, type, timeout)
chat.countTotal++
chat.count = 1
chat.messages = listOf(message)
call.respondWithCode(ApiResponse(chat))
}
}
| 0 | TypeScript | 0 | 1 | a50be3d0a8f9fbbc6f2268e213bb8c92e02ba70a | 2,423 | SecretSanta | Apache License 2.0 |
src/main/kotlin/de/idealo/security/endpointexporter/processing/RequestMappingProcessor.kt | idealo | 415,060,733 | false | {"Kotlin": 88006, "Shell": 147} | package de.idealo.security.endpointexporter.processing
import de.idealo.security.endpointexporter.classreading.type.AnnotatedTypeMetadata
import de.idealo.security.endpointexporter.classreading.type.AnnotationMetadata
import de.idealo.security.endpointexporter.classreading.type.ClassMetadata
import de.idealo.security.endpointexporter.classreading.type.MethodMetadata
import org.springframework.http.HttpMethod
import org.springframework.http.HttpStatus
import org.springframework.stereotype.Service
import org.springframework.web.bind.annotation.DeleteMapping
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PatchMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.PutMapping
import org.springframework.web.util.pattern.PathPatternParser
import org.springframework.web.bind.annotation.RequestMapping as RequestMappingAnnotation
@Service
class RequestMappingProcessor(
private val requestParameterProcessor: RequestParameterProcessor,
private val pathVariableProcessor: PathVariableProcessor,
private val requestHeaderProcessor: RequestHeaderProcessor,
private val responseStatusProcessor: ResponseStatusProcessor,
) : MetadataProcessor<ClassMetadata, List<RequestMapping>> {
private val patternParser: PathPatternParser = PathPatternParser()
private val requestMappingAnnotations = listOf(
RequestMappingAnnotation::class.qualifiedName!!,
GetMapping::class.qualifiedName!!,
PostMapping::class.qualifiedName!!,
PutMapping::class.qualifiedName!!,
PatchMapping::class.qualifiedName!!,
DeleteMapping::class.qualifiedName!!
)
override fun process(metadata: ClassMetadata): List<RequestMapping> {
val classLevelRequestMappings = getClassLevelRequestMappings(metadata)
val methodLevelRequestMappings = getMethodLevelRequestMappings(metadata)
return when {
classLevelRequestMappings.isEmpty() -> methodLevelRequestMappings
else -> methodLevelRequestMappings.flatMap { methodLevelRequestInformation ->
classLevelRequestMappings.map { classLevelRequestInformation ->
classLevelRequestInformation.combine(methodLevelRequestInformation)
}
}
}.map(RequestMapping::normalize)
}
private fun getClassLevelRequestMappings(classMetadata: ClassMetadata): List<RequestMapping> {
val classRequestMapping = getFirstRequestMappingAnnotation(classMetadata) ?: return emptyList()
return getRequestMapping(classMetadata, classRequestMapping, null)
}
private fun getMethodLevelRequestMappings(classMetadata: ClassMetadata): List<RequestMapping> {
val methodsWithRequestMapping = requestMappingAnnotations.flatMap { classMetadata.getAnnotatedMethods(it) }
return methodsWithRequestMapping.flatMap { methodMetadata ->
val methodRequestMapping = getFirstRequestMappingAnnotation(methodMetadata)!!
getRequestMapping(classMetadata, methodRequestMapping, methodMetadata)
}
}
private fun getRequestMapping(classMetadata: ClassMetadata, annotationMetadata: AnnotationMetadata, methodMetadata: MethodMetadata?): List<RequestMapping> {
val urlPatterns = getUrlPatterns(annotationMetadata)
val httpMethods = arrayOf(
*annotationMetadata.getStringArray("method"),
getDefaultHttpMethodForRequestMappingAnnotation(annotationMetadata)
)
val consumes = annotationMetadata.getStringArray("consumes")
val produces = annotationMetadata.getStringArray("produces")
return urlPatterns.map { urlPattern ->
RequestMapping(
urlPattern = patternParser.parse(urlPattern),
httpMethods = httpMethods.filterNotNull().map { HttpMethod.valueOf(it) }.toSet(),
responseStatus = methodMetadata?.let { responseStatusProcessor.process(it) } ?: HttpStatus.OK,
requestParameters = methodMetadata?.let { requestParameterProcessor.process(it) } ?: emptyList(),
pathVariables = methodMetadata?.let { pathVariableProcessor.process(it) } ?: emptyList(),
requestHeaders = methodMetadata?.let { requestHeaderProcessor.process(it) } ?: emptyList(),
consumes = consumes.asList(),
produces = produces.asList(),
declaringClassName = classMetadata.name,
methodName = methodMetadata?.name
)
}
}
private fun getUrlPatterns(annotationMetadata: AnnotationMetadata): Array<String> {
val urlPatterns = arrayOf(
*annotationMetadata.getStringArray("path"),
*annotationMetadata.getStringArray("value")
)
return when (urlPatterns.isEmpty()) {
true -> arrayOf("/")
false -> urlPatterns
}
}
private fun getDefaultHttpMethodForRequestMappingAnnotation(annotationMetadata: AnnotationMetadata): String? {
return when (annotationMetadata.name) {
GetMapping::class.qualifiedName!! -> HttpMethod.GET.name()
PostMapping::class.qualifiedName!! -> HttpMethod.POST.name()
PutMapping::class.qualifiedName!! -> HttpMethod.PUT.name()
PatchMapping::class.qualifiedName!! -> HttpMethod.PATCH.name()
DeleteMapping::class.qualifiedName!! -> HttpMethod.DELETE.name()
else -> null
}
}
private fun getFirstRequestMappingAnnotation(annotatedTypeMetadata: AnnotatedTypeMetadata): AnnotationMetadata? {
return annotatedTypeMetadata.getAnnotations()
.firstOrNull { requestMappingAnnotations.contains(it.name) }
}
}
| 2 | Kotlin | 1 | 6 | 7f536f8015102a8539d1b11e595e71fae511cc76 | 5,806 | spring-endpoint-exporter | Apache License 2.0 |
server_kotlin_sample/src/main/kotlin/SendSimpleSample.kt | grachro | 101,850,717 | false | null | import cn.jpush.api.JPushClient
import cn.jpush.api.push.model.Platform
import cn.jpush.api.push.model.PushPayload
import cn.jpush.api.push.model.audience.Audience
import cn.jpush.api.push.model.audience.AudienceTarget
import cn.jpush.api.push.model.notification.Notification
fun main(args: Array<String>) {
val appkey = args[0]
val secret = args[1]
val registrationId = args[2]
val jpushClient = JPushClient(secret, appkey)
val target = AudienceTarget.registrationId(registrationId)
val audience = Audience.newBuilder()
.addAudienceTarget(target)
.build()
val extras = mapOf("key1" to "val1", "key2" to "val2")
val payload = PushPayload.newBuilder()
.setPlatform(Platform.android())
.setAudience(audience)
.setNotification(Notification.android("**alert:1**", "*Simple*Title", extras))
.build()
val result = jpushClient.sendPush(payload)
println(result)
}
| 1 | null | 1 | 1 | 57dc4999dcb7e6e35db574a12dab1fe03cc6a448 | 975 | JPush_samples | Apache License 2.0 |
demo/src/commonMain/kotlin/com/huanshankeji/compose/material/demo/App.kt | huanshankeji | 570,509,992 | false | {"Kotlin": 346678} | package com.huanshankeji.compose.material.demo
import androidx.compose.runtime.Composable
import androidx.compose.ui.unit.dp
import androidx.navigation.NavHostController
import com.huanshankeji.androidx.navigation.compose.NavHost
import com.huanshankeji.androidx.navigation.compose.composable
import com.huanshankeji.androidx.navigation.compose.rememberNavController
import com.huanshankeji.compose.foundation.layout.Arrangement
import com.huanshankeji.compose.foundation.layout.Box
import com.huanshankeji.compose.foundation.layout.Column
import com.huanshankeji.compose.foundation.layout.ext.fillMaxSizeStretch
import com.huanshankeji.compose.foundation.layout.ext.innerPadding
import com.huanshankeji.compose.foundation.layout.ext.outerPadding
import com.huanshankeji.compose.material3.Button
import com.huanshankeji.compose.material3.ext.TaglessText
import com.huanshankeji.compose.ui.Alignment
import com.huanshankeji.compose.ui.Modifier
internal enum class Selection {
A, B, C
}
val listSize = 160.dp
fun Modifier.outerContentPadding() = outerPadding(16.dp)
fun Modifier.innerContentPadding() = innerPadding(16.dp)
val contentPaddingModifier = Modifier.outerContentPadding()
enum class Screen {
Home, Common, Material2, Material3
}
@Composable
fun App() {
val navController = rememberNavController()
NavHost(navController, Screen.Home.name) {
composable(Screen.Home.name) { Home(navController) }
//fun subDemoModifier()
composable(Screen.Common.name) { Common() }
composable(Screen.Material2.name) { Material2() }
composable(Screen.Material3.name) { Material3() }
}
}
@Composable
fun Home(navController: NavHostController) {
Box(Modifier.fillMaxSizeStretch(), contentAlignment = Alignment.Center) {
Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
Button({ navController.navigate(Screen.Common.name) }) {
TaglessText("Common")
}
Button({ navController.navigate(Screen.Material2.name) }) {
TaglessText("Material 2")
}
Button({ navController.navigate(Screen.Material3.name) }) {
TaglessText("Material 3")
}
}
}
}
| 15 | Kotlin | 0 | 16 | 755a2593006cfd9f117793a11efd23f83eecc851 | 2,239 | compose-multiplatform-material | Apache License 2.0 |
app/src/main/java/be/renaudraas/kotlinplayground/util/mpv/BaseMvpPresenter.kt | Hoolii | 97,982,593 | false | null | package be.renaudraas.kotlinplayground.util.mpv
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
open class BaseMvpPresenter<V : MvpView> : MvpPresenter<V> {
private var view : V? = null
private val compositeDisposable = CompositeDisposable()
protected fun <T> subscribe(observable: Observable<T>, observer: DisposableObserver<T>) {
val disposable = observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(observer)
this.compositeDisposable.add(disposable)
}
override fun attachView(view: V) {
this.view = view
}
fun getView() : V {
this.view?.let {
return this.view!!
}
throw NullPointerException("MvpView reference is null. Have you called attachView()?")
}
private fun dispose() {
compositeDisposable.clear()
}
override fun detachView() {
this.view = null
dispose()
}
} | 0 | Kotlin | 0 | 0 | aa505488e4b7fabb674d8338344a359cedee4233 | 1,187 | kotlin-playground | MIT License |
services/src/main/java/knaufdan/android/services/media/implementation/MediaRequestResolverException.kt | DanielKnauf | 219,150,024 | false | null | package knaufdan.android.services.media.implementation
import knaufdan.android.services.media.IMediaRequestResolver
object MediaRequestResolverException : Throwable() {
override val message: String
get() = "Context does not implementing ${IMediaRequestResolver::class.simpleName}"
}
| 0 | Kotlin | 0 | 2 | a6bdc7efa3c6d48d6d84f55266c430f99913526e | 297 | ArchServices | Apache License 2.0 |
src/main/kotlin/littleowle/ai/ollama/commit/settings/clients/LLMClientPanel.kt | LittleOwle | 834,545,437 | false | {"Kotlin": 98917} | package littleowle.ai.ollama.commit.settings.clients
import littleowle.ai.ollama.commit.OllamaCommitBundle.message
import littleowle.ai.ollama.commit.isInt
import littleowle.ai.ollama.commit.notBlank
import littleowle.ai.ollama.commit.temperatureValid
import com.intellij.openapi.ui.ComboBox
import com.intellij.ui.components.JBLabel
import com.intellij.ui.components.JBTextField
import com.intellij.ui.dsl.builder.*
import kotlin.reflect.KMutableProperty0
abstract class LLMClientPanel(
private val clientConfiguration: LLMClientConfiguration,
) {
val hostComboBox = ComboBox(clientConfiguration.getHosts().toTypedArray())
val socketTimeoutTextField = JBTextField()
val modelComboBox = ComboBox(clientConfiguration.getModelIds().toTypedArray())
val temperatureTextField = JBTextField()
val verifyLabel = JBLabel()
open fun create() = panel {
nameRow()
modelIdRow()
temperatureRow()
verifyRow()
}
open fun Panel.nameRow() {
row {
label(message("settings.llmClient.name"))
.widthGroup("label")
textField()
.bindText(clientConfiguration::name)
.align(Align.FILL)
.validationOnInput { notBlank(it.text) }
}
}
open fun Panel.hostRow(property: MutableProperty<String?>) {
row {
label(message("settings.llmClient.host"))
.widthGroup("label")
cell(hostComboBox)
.applyToComponent {
isEditable = true
}
.bindItem(property)
.align(Align.FILL)
.onApply { clientConfiguration.addHost(hostComboBox.item) }
}
}
open fun Panel.timeoutRow(property: KMutableProperty0<Int>) {
row {
label(message("settings.llmClient.timeout")).widthGroup("label")
cell(socketTimeoutTextField)
.bindIntText(property)
.resizableColumn()
.align(Align.FILL)
.validationOnInput { isInt(it.text) }
}
}
open fun Panel.modelIdRow() {
row {
label(message("settings.llmClient.modelId"))
.widthGroup("label")
cell(modelComboBox)
.applyToComponent {
isEditable = true
}
.bindItem({ clientConfiguration.modelId }, {
if (it != null) {
clientConfiguration.modelId = it
}
})
.align(Align.FILL)
.resizableColumn()
.onApply { clientConfiguration.addModelId(modelComboBox.item) }
clientConfiguration.getRefreshModelsFunction()?.let { f ->
button(message("settings.refreshModels")) {
f.invoke(modelComboBox)
}
.align(AlignX.RIGHT)
.widthGroup("button")
}
}
}
open fun Panel.temperatureRow() {
row {
label(message("settings.llmClient.temperature"))
.widthGroup("label")
cell(temperatureTextField)
.bindText(clientConfiguration::temperature)
.align(Align.FILL)
.validationOnInput { temperatureValid(it.text) }
.resizableColumn()
contextHelp(message("settings.llmClient.temperature.comment"))
.align(AlignX.RIGHT)
}
}
open fun Panel.verifyRow() {
row {
cell(verifyLabel)
.applyToComponent {
setAllowAutoWrapping(true)
setCopyable(true)
}
.align(AlignX.LEFT)
button(message("settings.verifyToken")) { verifyConfiguration() }
.align(AlignX.RIGHT)
.widthGroup("button")
}
}
abstract fun verifyConfiguration()
}
| 0 | Kotlin | 0 | 0 | 90e532bd78e2f4090754c41876e43d01041500f6 | 4,025 | littleowle-ai-ollama-commit-plugin-intellij-platform | Apache License 2.0 |
commonTestUtils/src/test/java/io/github/pelmenstar1/digiDict/commonTestUtils/AssertsTests.kt | pelmenstar1 | 512,710,767 | false | null | package io.github.pelmenstar1.digiDict.commonTestUtils
import kotlinx.coroutines.delay
import kotlinx.coroutines.runBlocking
import org.junit.Test
import kotlin.test.assertFailsWith
class AssertsTests {
@Test
fun assertTimeoutShouldThrowTest(): Unit = runBlocking {
assertFailsWith<AssertionError> {
assertTimeout(timeout = 100) {}
}
}
@Test
fun assertTimeoutShouldNotThrowTest(): Unit = runBlocking {
assertTimeout(timeout = 100) {
delay(200)
}
}
} | 6 | Kotlin | 0 | 3 | 76a8229099c3775bb36fff5cedb15b5bf54945df | 532 | DigiDictionary | MIT License |
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/subsystems/LiftSys.kt | Harshiv15 | 707,737,032 | false | {"Java": 96767, "Kotlin": 48194} | package org.firstinspires.ftc.teamcode.subsystems
import com.qualcomm.robotcore.hardware.DcMotorEx
class LiftSys(left: DcMotorEx, right: DcMotorEx) {
} | 1 | null | 1 | 1 | 5da72750dec25a8173fb38716d8fefab123c7ed0 | 154 | Blackout-CENTERSTAGE | BSD 3-Clause Clear License |
src/main/java/uk/gov/justice/hmpps/prison/service/enteringandleaving/StaffAwareMovementService.kt | ministryofjustice | 156,829,108 | false | {"Java": 4638197, "Kotlin": 1943430, "PLSQL": 947199, "Gherkin": 130468, "Dockerfile": 1126, "Shell": 944} | package uk.gov.justice.hmpps.prison.service.enteringandleaving
import org.springframework.data.repository.findByIdOrNull
import uk.gov.justice.hmpps.prison.repository.jpa.model.StaffUserAccount
import uk.gov.justice.hmpps.prison.repository.jpa.repository.StaffUserAccountRepository
import uk.gov.justice.hmpps.prison.security.AuthenticationFacade
import uk.gov.justice.hmpps.prison.service.EntityNotFoundException
abstract class StaffAwareMovementService(
private val staffUserAccountRepository: StaffUserAccountRepository,
private val authenticationFacade: AuthenticationFacade,
) {
internal fun getLoggedInStaff(): Result<StaffUserAccount> {
return staffUserAccountRepository.findByIdOrNull(authenticationFacade.currentUsername)
?.let { Result.success(it) } ?: Result.failure(
EntityNotFoundException.withId(authenticationFacade.currentUsername),
)
}
}
| 5 | Java | 6 | 6 | c3d08a4c67f24e3c3bea9af8f9f8cfc16f787b6d | 885 | prison-api | MIT License |
multinode/src/main/kotlin/jetbrains/exodus/log/replication/S3FileFactory.kt | manualstar | 128,652,359 | true | {"Java Properties": 1, "Shell": 1, "Markdown": 6, "Batchfile": 1, "Java": 747, "Kotlin": 110, "JavaScript": 4, "INI": 1} | /**
* Copyright 2010 - 2018 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package jetbrains.exodus.log.replication
import jetbrains.exodus.log.Log
import jetbrains.exodus.log.LogUtil
import software.amazon.awssdk.core.AwsRequestOverrideConfig
import software.amazon.awssdk.services.s3.S3AsyncClient
import java.nio.file.Path
class S3FileFactory(
override val s3: S3AsyncClient,
val dir: Path,
override val bucket: String,
override val requestOverrideConfig: AwsRequestOverrideConfig? = null
) : S3FactoryBoilerplate {
override fun fetchFile(log: Log, address: Long, expectedLength: Long, finalFile: Boolean): WriteResult {
if (checkPreconditions(log, expectedLength)) return WriteResult.empty
log.ensureWriter().fileSetMutable.add(address)
val filename = LogUtil.getLogFilename(address)
val handler = if (finalFile) {
// this is intentional, aligns last page within file
val lastPageStart = log.getHighPageAddress(expectedLength)
FileAsyncHandler(dir.resolve(filename), lastPageStart, log.ensureWriter().allocLastPage(address + lastPageStart))
} else {
FileAsyncHandler(dir.resolve(filename), 0, null)
}
return getRemoteFile(expectedLength, filename, handler).get().also {
log.ensureWriter().apply {
incHighAddress(it.written)
lastPageWritten = it.lastPageWritten
}
}
}
}
| 0 | Java | 0 | 0 | fd5257cc6af0a51623a6e84853043a66a2bb900e | 2,017 | xodus | Apache License 2.0 |
common/src/main/java/com/bcm/messenger/common/grouprepository/room/dao/AdHocMessageDao.kt | Era-CyberLabs | 576,196,269 | false | {"Java": 6276144, "Kotlin": 5427066, "HTML": 92928, "C": 30870, "Groovy": 12495, "C++": 6551, "CMake": 2728, "Python": 1600, "AIDL": 1267, "Makefile": 472} | package com.bcm.messenger.common.grouprepository.room.dao
import androidx.room.*
import com.bcm.messenger.common.grouprepository.room.entity.AdHocMessageDBEntity
@Dao
interface AdHocMessageDao {
@Query("SELECT * FROM ${AdHocMessageDBEntity.TABLE_NAME} WHERE session_id == :session AND _id < :index ORDER BY _id DESC LIMIT :count")
fun loadMessageBefore(session: String, index: Long, count: Int): List<AdHocMessageDBEntity>
@Query("SELECT * FROM ${AdHocMessageDBEntity.TABLE_NAME} WHERE session_id == :session AND _id > :index ORDER BY _id DESC LIMIT :count")
fun loadMessageAfter(session: String, index: Long, count: Int): List<AdHocMessageDBEntity>
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertMessage(messageDBEntity: AdHocMessageDBEntity): Long
@Insert(onConflict = OnConflictStrategy.REPLACE)
fun insertMessages(messageDBEntityList: List<AdHocMessageDBEntity>)
@Delete
fun deleteMessage(messageDBEntityList: List<AdHocMessageDBEntity>)
@Query("SELECT MAX(_id) FROM ${AdHocMessageDBEntity.TABLE_NAME} WHERE session_id == :session")
fun queryMaxIndexId(session: String): Long
@Query("SELECT * FROM ${AdHocMessageDBEntity.TABLE_NAME} WHERE session_id == :session ORDER BY _id DESC LIMIT 1")
fun findLastMessage(session: String): AdHocMessageDBEntity?
@Query("DELETE FROM ${AdHocMessageDBEntity.TABLE_NAME} WHERE session_id == :session")
fun deleteAllMessage(session: String)
@Query("UPDATE ${AdHocMessageDBEntity.TABLE_NAME} SET is_read = 1 WHERE session_id == :session")
fun readAllMessage(session: String)
@Update(onConflict = OnConflictStrategy.IGNORE)
fun updateMessage(messageDBEntityList: List<AdHocMessageDBEntity>)
@Query("UPDATE ${AdHocMessageDBEntity.TABLE_NAME} SET state = ${AdHocMessageDBEntity.STATE_FAILURE} WHERE session_id == :session AND state == ${AdHocMessageDBEntity.STATE_SENDING}")
fun setSendingMessageFail(session: String)
@Query("SELECT * FROM ${AdHocMessageDBEntity.TABLE_NAME} WHERE is_read == 1 AND session_id == :session ORDER BY _id DESC LIMIT 1")
fun findLastSeen(session: String): AdHocMessageDBEntity?
@Query("SELECT COUNT(*) FROM ${AdHocMessageDBEntity.TABLE_NAME} WHERE is_read != 1 AND session_id == :session ORDER BY _id DESC ")
fun queryUnreadCount(session: String): Int
@Query("SELECT * FROM ${AdHocMessageDBEntity.TABLE_NAME} WHERE message_id == :mid AND session_id == :session")
fun findMessage(session: String, mid: String): AdHocMessageDBEntity?
@Query("SELECT * FROM ${AdHocMessageDBEntity.TABLE_NAME} WHERE _id == :index AND session_id == :session")
fun findMessage(session: String, index: Long): AdHocMessageDBEntity?
@Query("SELECT * FROM ${AdHocMessageDBEntity.TABLE_NAME} LIMIT 100 OFFSET :page")
fun loadByPage(page: Int): List<AdHocMessageDBEntity>
} | 1 | null | 1 | 1 | 65a11e5f009394897ddc08f4252969458454d052 | 2,863 | cyberland-android | Apache License 2.0 |
AOS/app/src/main/java/com/example/eeos/presentation/login/LoginScreen.kt | jiucchu | 702,890,068 | false | {"Markdown": 11, "Git Attributes": 1, "Text": 2, "Gradle": 9, "Shell": 3, "YAML": 15, "Dockerfile": 1, "Batchfile": 2, "Ignore List": 5, "Java": 215, "INI": 4, "XML": 33, "SQL": 5, "JavaScript": 2, "JSON with Comments": 1, "JSON": 9, "SVG": 20, "TSX": 92, "CSS": 3, "Python": 2, "Java Properties": 2, "Diff": 1, "Proguard": 1, "Kotlin": 74} | package com.example.eeos.presentation.login
import android.content.ActivityNotFoundException
import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.Image
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.State
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.dimensionResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.core.content.ContextCompat.startActivity
import androidx.hilt.navigation.compose.hiltViewModel
import com.example.eeos.BuildConfig
import com.example.eeos.R
@Composable
fun LoginScreen(
loginUiState: State<LoginUiState>,
code: String?,
postLogin: (String) -> Unit
) {
val context = LocalContext.current
val slackUri = "https://slack.com/oauth/v2/authorize?" +
"client_id=${BuildConfig.client_id}" +
"&scope=" +
"&user_scope=${BuildConfig.user_scope}" +
"&team_id=${BuildConfig.team_id}" +
"&&redirect_uri=${BuildConfig.redirect_uri}"
if (code != null) {
postLogin(code)
}
Scaffold(
snackbarHost = { SnackbarHost(hostState = loginUiState.value.snackbarHostState) },
) { innerPadding ->
Box(
modifier = Modifier
.fillMaxSize()
.padding(innerPadding),
contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally
) {
if (loginUiState.value.isLogin) {
CircularProgressIndicator()
Spacer(
modifier = Modifier
.height(
dimensionResource(
id = R.dimen.height_login_screen_between_progress_and_text
)
)
)
Text(
text = stringResource(R.string.login_try_login),
style = MaterialTheme.typography.bodySmall,
color = colorResource(R.color.gray_700)
)
} else {
Image(
painter = painterResource(id = R.drawable.eeos_logo_symbol),
contentDescription = "Logo of EEOS",
modifier = Modifier.size(
dimensionResource(id = R.dimen.size_common_screen_logo_120dp)
)
)
Spacer(
modifier = Modifier
.height(
dimensionResource(
id = R.dimen.margin_login_screen_between_logo_and_button
)
)
)
Image(
painter = painterResource(
id = R.drawable.btn_add_to_slack_4000x1172_d770e0c
),
contentDescription = "",
modifier = Modifier
.size(
width = dimensionResource(
id = R.dimen.width_login_screen_slack_button
),
height = dimensionResource(
id = R.dimen.height_login_screen_slack_button
)
)
.clickable {
val webIntent: Intent =
Uri
.parse(slackUri)
.let { webPage ->
Intent(Intent.ACTION_VIEW, webPage)
}
try {
startActivity(context, webIntent, null)
} catch (e: ActivityNotFoundException) {
}
}
)
}
}
}
}
}
@Preview(showSystemUi = true)
@Composable
private fun LoginScreenPreview() {
MaterialTheme {
LoginScreen(
loginUiState = hiltViewModel<LoginViewModel>().loginUiState.collectAsState(),
code = "",
postLogin = { p -> }
)
}
}
| 1 | null | 1 | 1 | 93a05026466892b293b682d12219e3350d0b3ebf | 5,499 | black-company | MIT License |
RxDemo/src/main/java/com/tamsiree/rxdemo/activity/ActivityOrangeJuice.kt | baggio1117 | 249,188,371 | true | {"Java Properties": 3, "Markdown": 5, "Gradle": 9, "Shell": 1, "YAML": 1, "Batchfile": 1, "Text": 1, "XML": 237, "Ignore List": 8, "INI": 1, "Proguard": 7, "Java": 269, "Kotlin": 152} | package com.tamsiree.rxdemo.activity
import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import android.view.animation.Animation
import android.widget.Button
import android.widget.SeekBar
import android.widget.SeekBar.OnSeekBarChangeListener
import android.widget.TextView
import butterknife.BindView
import butterknife.ButterKnife
import com.tamsiree.rxdemo.R
import com.tamsiree.rxkit.RxAnimationTool.initRotateAnimation
import com.tamsiree.rxui.activity.ActivityBase
import com.tamsiree.rxui.view.RxTitle
import com.tamsiree.rxui.view.progress.TOrangeJuice
import java.util.*
@SuppressLint("HandlerLeak")
class ActivityOrangeJuice : ActivityBase(), OnSeekBarChangeListener, View.OnClickListener {
@JvmField
@BindView(R.id.rx_title)
var mRxTitle: RxTitle? = null
private var mLeafLoadingView: TOrangeJuice? = null
private var mAmpireSeekBar: SeekBar? = null
private var mDistanceSeekBar: SeekBar? = null
private var mMplitudeText: TextView? = null
private var mDisparityText: TextView? = null
private var mFanView: View? = null
private var mClearButton: Button? = null
private var mProgress = 0
private var mHandler: Handler = object : Handler() {
override fun handleMessage(msg: Message) {
when (msg.what) {
REFRESH_PROGRESS -> if (mProgress < 40) {
mProgress += 1
// 随机800ms以内刷新一次
sendEmptyMessageDelayed(REFRESH_PROGRESS,
Random().nextInt(800).toLong())
mLeafLoadingView!!.setProgress(mProgress)
} else {
mProgress += 1
// 随机1200ms以内刷新一次
sendEmptyMessageDelayed(REFRESH_PROGRESS,
Random().nextInt(1200).toLong())
mLeafLoadingView!!.setProgress(mProgress)
}
else -> {
}
}
}
}
private var mProgressText: TextView? = null
private var mAddProgress: View? = null
private var mFloatTimeSeekBar: SeekBar? = null
private var mRotateTimeSeekBar: SeekBar? = null
private var mFloatTimeText: TextView? = null
private var mRotateTimeText: TextView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_orange_juice)
ButterKnife.bind(this)
initViews()
mHandler.sendEmptyMessageDelayed(REFRESH_PROGRESS, 3000)
}
@SuppressLint("StringFormatMatches")
private fun initViews() {
mRxTitle!!.setLeftFinish(this)
mFanView = findViewById(R.id.fan_pic)
mProgressText = findViewById(R.id.text_progress)
val rotateAnimation = initRotateAnimation(false, 1500, true,
Animation.INFINITE)
mFanView?.startAnimation(rotateAnimation)
mClearButton = findViewById(R.id.clear_progress)
mClearButton?.setOnClickListener(this)
mLeafLoadingView = findViewById(R.id.leaf_loading)
mMplitudeText = findViewById(R.id.text_ampair)
mMplitudeText?.text = getString(R.string.current_mplitude,
mLeafLoadingView?.middleAmplitude)
mDisparityText = findViewById(R.id.text_disparity)
mDisparityText?.text = getString(R.string.current_Disparity,
mLeafLoadingView?.mplitudeDisparity)
mAmpireSeekBar = findViewById(R.id.seekBar_ampair)
mAmpireSeekBar?.setOnSeekBarChangeListener(this)
mAmpireSeekBar?.progress = mLeafLoadingView?.middleAmplitude!!
mAmpireSeekBar?.max = 50
mDistanceSeekBar = findViewById(R.id.seekBar_distance)
mDistanceSeekBar?.setOnSeekBarChangeListener(this)
mDistanceSeekBar?.progress = mLeafLoadingView?.mplitudeDisparity!!
mDistanceSeekBar?.max = 20
mAddProgress = findViewById(R.id.add_progress)
mAddProgress?.setOnClickListener(this)
mFloatTimeText = findViewById(R.id.text_float_time)
mFloatTimeSeekBar = findViewById(R.id.seekBar_float_time)
mFloatTimeSeekBar?.setOnSeekBarChangeListener(this)
mFloatTimeSeekBar?.max = 5000
mFloatTimeSeekBar?.progress = mLeafLoadingView?.leafFloatTime!!.toInt()
mFloatTimeText?.text = resources.getString(R.string.current_float_time,
mLeafLoadingView?.leafFloatTime)
mRotateTimeText = findViewById(R.id.text_rotate_time)
mRotateTimeSeekBar = findViewById(R.id.seekBar_rotate_time)
mRotateTimeSeekBar?.setOnSeekBarChangeListener(this)
mRotateTimeSeekBar?.max = 5000
mRotateTimeSeekBar?.progress = mLeafLoadingView?.leafRotateTime!!.toInt()
mRotateTimeText?.text = resources.getString(R.string.current_float_time,
mLeafLoadingView?.leafRotateTime)
}
@SuppressLint("StringFormatMatches")
override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
when {
seekBar === mAmpireSeekBar -> {
mLeafLoadingView!!.middleAmplitude = progress
mMplitudeText!!.text = getString(R.string.current_mplitude, progress)
}
seekBar === mDistanceSeekBar -> {
mLeafLoadingView!!.mplitudeDisparity = progress
mDisparityText!!.text = getString(R.string.current_Disparity, progress)
}
seekBar === mFloatTimeSeekBar -> {
mLeafLoadingView!!.leafFloatTime = progress.toLong()
mFloatTimeText!!.text = resources.getString(R.string.current_float_time, progress)
}
seekBar === mRotateTimeSeekBar -> {
mLeafLoadingView!!.leafRotateTime = progress.toLong()
mRotateTimeText!!.text = resources.getString(R.string.current_rotate_time, progress)
}
}
mProgressText!!.text = mProgress.toString()
}
override fun onStartTrackingTouch(seekBar: SeekBar) {}
override fun onStopTrackingTouch(seekBar: SeekBar) {}
override fun onClick(v: View) {
if (v === mClearButton) {
mLeafLoadingView!!.setProgress(0)
mHandler.removeCallbacksAndMessages(null)
mProgress = 0
} else if (v === mAddProgress) {
mProgress++
mLeafLoadingView!!.setProgress(mProgress)
mProgressText!!.text = mProgress.toString()
}
}
companion object {
private const val REFRESH_PROGRESS = 0x10
}
} | 0 | null | 0 | 0 | c7d50fc47e9bc9b4053358089dfff0c0556147a7 | 6,631 | RxTool | Apache License 2.0 |
cropImage/src/main/java/com/haibox/cropimage/CroppingActivity.kt | hhbgk | 684,346,961 | false | {"Java Properties": 1, "Shell": 1, "Markdown": 2, "Batchfile": 1, "Proguard": 5, "Java": 55, "INI": 3, "C": 1, "Makefile": 2, "C++": 2, "Kotlin": 3} | package com.haibox.cropimage
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.View
import com.haibox.cropimage.databinding.ActivityClipImageBinding
import java.io.ByteArrayOutputStream
class CroppingActivity: Activity() {
companion object {
private const val TAG = "ClipImageActivity"
const val KEY_CLIP_TYPE = "clip_type"
const val KEY_FILE_PATH = "file_path"
const val KEY_RESULT_DATA = "result_data"
@JvmStatic
fun getClipIntent(context: Activity, filePath: String, type: Int): Intent {
val intent = Intent()
intent.setClass(context, CroppingActivity::class.java)
intent.putExtra(KEY_CLIP_TYPE, type)
intent.putExtra(KEY_FILE_PATH, filePath)
return intent
}
}
private lateinit var binding: ActivityClipImageBinding
private var mType = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityClipImageBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.clipViewLayout.visibility = View.VISIBLE
mType = intent.getIntExtra(KEY_CLIP_TYPE, ClipView.ClipType.CIRCLE)
initData()
//设置点击事件监听器
binding.btnCancel.setOnClickListener { finish() }
binding.btnOk.setOnClickListener { generateUriAndReturn() }
}
private fun initData() {
val path = intent.getStringExtra(KEY_FILE_PATH)
Log.i(TAG, "Type =$mType, $path")
//设置图片资源
binding.clipViewLayout.setImageSrc(path)
}
/**
* 生成Uri并且通过setResult返回给打开的activity
*/
private fun generateUriAndReturn() {
//调用返回剪切图
val zoomedCropBitmap = binding.clipViewLayout.clip()
if (zoomedCropBitmap == null) {
Log.e(TAG, "Zoomed Crop Bitmap is null")
return
}
val intent = Intent()
intent.putExtra(KEY_CLIP_TYPE, mType)
// Log.i(TAG, "zoomed CropBitmap=" + zoomedCropBitmap.width + ", " + zoomedCropBitmap.height)
val byteStream = ByteArrayOutputStream()
zoomedCropBitmap.compress(Bitmap.CompressFormat.JPEG, 60, byteStream)
val data = byteStream.toByteArray()
intent.putExtra(KEY_RESULT_DATA, data)
byteStream.close()
setResult(RESULT_OK, intent)
finish()
}
} | 1 | null | 1 | 1 | 2b61a54a77aaa40bbd1ec80240c9087fe294db47 | 2,480 | uCrop | Apache License 2.0 |
lawnchair/src/app/lawnchair/ui/util/navigationResult.kt | DariaRnD | 481,438,445 | true | {"Java Properties": 1, "YAML": 14, "Text": 9, "Markdown": 6, "XML": 880, "INI": 2, "Makefile": 3, "Gradle": 7, "Shell": 1, "EditorConfig": 1, "Git Attributes": 1, "Batchfile": 1, "Soong": 3, "Python": 5, "Proguard": 1, "Ignore List": 1, "Git Config": 1, "AIDL": 12, "Java": 899, "Kotlin": 319, "JSON": 6, "Protocol Buffer": 6} | package app.lawnchair.ui.util
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import app.lawnchair.ui.preferences.LocalNavController
@Composable
fun <T> resultSender(): (T) -> Unit {
val navController = LocalNavController.current
return { item: T ->
navController.previousBackStackEntry
?.savedStateHandle
?.set("result", item)
navController.popBackStack()
Unit
}
}
@Composable
fun <T> OnResult(callback: (result: T) -> Unit) {
val currentCallback = rememberUpdatedState(callback)
var fired by remember { mutableStateOf(false) }
val handle = LocalNavController.current.currentBackStackEntry?.savedStateHandle
val result = handle?.getLiveData<T>("result")?.observeAsState()
SideEffect {
result?.value?.let {
if (fired) return@let
fired = true
currentCallback.value(it)
handle.remove<T>("result")
Unit
}
}
}
| 10 | Java | 1 | 5 | 1b13066090b80104c6524e93bd09856f76b2f814 | 1,013 | lawnchair | Apache License 2.0 |
generated-sources/kotlin-spring/mojang-authentication/src/main/kotlin/com/github/asyncmc/mojang/authentication/kotlin/spring/model/GameProfileProperty.kt | AsyncMC | 269,845,234 | false | null | package com.github.asyncmc.mojang.authentication.kotlin.spring.model
import java.util.Objects
import com.fasterxml.jackson.annotation.JsonProperty
import javax.validation.Valid
import javax.validation.constraints.*
/**
*
* @param name
* @param value
*/
data class GameProfileProperty (
@JsonProperty("name") val name: String? = null,
@JsonProperty("value") val value: String? = null
) {
}
| 4 | null | 1 | 1 | b01bbd2bce44bfa2b9ed705a128cf4ecda077916 | 418 | Mojang-API-Libs | Apache License 2.0 |
app/src/main/java/com/earthquakesaroundme/MainActivity.kt | phillausofia | 218,242,220 | false | null | package com.earthquakesaroundme
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.DisplayMetrics
import androidx.navigation.findNavController
import androidx.navigation.ui.NavigationUI
import com.google.android.gms.ads.AdSize
import com.google.android.gms.ads.MobileAds
class MainActivity : AppCompatActivity() {
private val adSize: AdSize
get() {
val display = windowManager.defaultDisplay
val outMetrics = DisplayMetrics()
display.getMetrics(outMetrics)
val density = outMetrics.density
Utils.densityDpi = density
var adWidthPixels = 0f
if (adWidthPixels == 0f) {
adWidthPixels = outMetrics.widthPixels.toFloat()
}
val adWidth = (adWidthPixels / density).toInt()
return AdSize.getCurrentOrientationBannerAdSizeWithWidth(this, adWidth)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
MobileAds.initialize(this)
Utils.adSize = adSize
//Setting up support for up button
val navController = this.findNavController(R.id.nav_host_fragment)
NavigationUI.setupActionBarWithNavController(this, navController)
}
override fun onSupportNavigateUp(): Boolean {
val navController = this.findNavController(R.id.nav_host_fragment)
return navController.navigateUp()
}
}
| 0 | Kotlin | 0 | 0 | 72339c245c1e825bc2ab4a5c30286046c39fee3e | 1,536 | earthquakes-around-me | Apache License 2.0 |
Object-Detection-App-master/app/src/main/java/com/jscode/camerax/util/util.kt | fasihmuhammadvirk | 659,337,036 | false | null | package com.jscode.camerax.util
import android.animation.ObjectAnimator
import android.view.View
fun viewFadeIn(layout: View) {
layout.visibility=View.VISIBLE
ObjectAnimator.ofFloat(layout,View.ALPHA,1F).apply {
start()
}
}
fun viewFadeOut(layout: View) {
ObjectAnimator.ofFloat(layout,View.ALPHA,0f).apply {
start()
}
layout.visibility=View.GONE
} | 0 | Kotlin | 0 | 0 | f0e6dc60650c5cc2d20801db63ad7c28645d6b38 | 391 | Object-Detection-App | MIT License |
Compose-Ur-Pres/plugin/cup-speaker-window/src/jvmMain/kotlin/net/kodein/cup/speaker/PresentationState.kt | KodeinKoders | 786,962,808 | false | {"Kotlin": 178691, "HTML": 1674} | package net.kodein.cup.speaker
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import net.kodein.cup.PresentationState
import net.kodein.cup.PresentationStateWrapper
import net.kodein.cup.Slide
import net.kodein.cup.currentSlide
internal class ShiftedPresentationState(state: PresentationState) : PresentationStateWrapper(state) {
override val currentSlideIndex: Int get() = when {
originalState.currentSlideIndex == originalState.slides.lastIndex -> originalState.currentSlideIndex
originalState.currentStep == originalState.currentSlide.lastStep -> originalState.currentSlideIndex + 1
else -> originalState.currentSlideIndex
}
override val currentStep: Int get() = when {
originalState.currentSlideIndex == originalState.slides.lastIndex && originalState.currentStep == originalState.currentSlide.lastStep -> originalState.currentStep
originalState.currentStep == originalState.currentSlide.lastStep -> 0
else -> originalState.currentStep + 1
}
}
internal class SWPresentationState(state: PresentationState) : PresentationStateWrapper(state) {
override var isInOverview: Boolean by mutableStateOf(false)
}
| 0 | Kotlin | 1 | 39 | 9fc76016b439734817afc89afaae2a05af04bbb6 | 1,260 | CuP | Apache License 2.0 |
android/app/src/main/kotlin/com/example/iccaura/MainActivity.kt | regi-gouale | 402,514,024 | false | {"Dart": 5431, "HTML": 3693, "Swift": 404, "Kotlin": 124, "Objective-C": 38} | package com.example.iccaura
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
| 0 | Dart | 0 | 0 | c5471173196fc68fe13f59627b4b1fed7dc2d8cd | 124 | iccaura | MIT License |
app/src/main/java/com/jadebyte/jadeplayer/onBoarding/Board.kt | wilburt | 177,040,268 | false | null | // Copyright (c) 2019 . <NAME>. All Rights Reserved.
package com.jadebyte.jadeplayer.onBoarding
import androidx.annotation.DrawableRes
import androidx.annotation.StringRes
/**
* Created by Wilberforce on 28/03/2019 at 02:38.
*/
data class Board(@DrawableRes val image: Int, @StringRes val title: Int, @StringRes val description: Int) | 5 | Kotlin | 28 | 75 | e8b887c5074c6dde830252e322869d0ff8d362c5 | 338 | Jade-Player | Apache License 2.0 |
src/main/kotlin/no/digdir/informasjonsforvaltning/fdk_dataset_harvester/controller/DatasetsController.kt | Informasjonsforvaltning | 221,007,735 | false | {"Kotlin": 145929, "Dockerfile": 234} | package no.digdir.informasjonsforvaltning.fdk_dataset_harvester.controller
import no.digdir.informasjonsforvaltning.fdk_dataset_harvester.model.DuplicateIRI
import no.digdir.informasjonsforvaltning.fdk_dataset_harvester.rdf.jenaTypeFromAcceptHeader
import no.digdir.informasjonsforvaltning.fdk_dataset_harvester.service.DatasetService
import no.digdir.informasjonsforvaltning.fdk_dataset_harvester.service.EndpointPermissions
import org.apache.jena.riot.Lang
import org.springframework.http.HttpHeaders
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.security.core.annotation.AuthenticationPrincipal
import org.springframework.security.oauth2.jwt.Jwt
import org.springframework.stereotype.Controller
import org.springframework.web.bind.annotation.*
@Controller
@CrossOrigin
@RequestMapping(
value = ["/datasets"],
produces = ["text/turtle", "text/n3", "application/rdf+json", "application/ld+json", "application/rdf+xml",
"application/n-triples", "application/n-quads", "application/trig", "application/trix"]
)
open class DatasetsController(
private val datasetService: DatasetService,
private val endpointPermissions: EndpointPermissions
) {
@GetMapping("/{id}")
fun getDatasetById(
@RequestHeader(HttpHeaders.ACCEPT) accept: String?,
@PathVariable id: String,
@RequestParam(value = "catalogrecords", required = false) catalogRecords: Boolean = false
): ResponseEntity<String> {
val returnType = jenaTypeFromAcceptHeader(accept)
return if (returnType == Lang.RDFNULL) ResponseEntity(HttpStatus.NOT_ACCEPTABLE)
else {
datasetService.getDataset(id, returnType ?: Lang.TURTLE, catalogRecords)
?.let { ResponseEntity(it, HttpStatus.OK) }
?: ResponseEntity(HttpStatus.NOT_FOUND)
}
}
@PostMapping("/{id}/remove")
fun removeDatasetById(
@AuthenticationPrincipal jwt: Jwt,
@PathVariable id: String
): ResponseEntity<Void> =
if (endpointPermissions.hasAdminPermission(jwt)) {
datasetService.removeDataset(id)
ResponseEntity(HttpStatus.OK)
} else ResponseEntity(HttpStatus.FORBIDDEN)
@DeleteMapping("/{id}")
fun purgeDatasetById(
@AuthenticationPrincipal jwt: Jwt,
@PathVariable id: String
): ResponseEntity<Void> =
if (endpointPermissions.hasAdminPermission(jwt)) {
datasetService.purgeByFdkId(id)
ResponseEntity(HttpStatus.NO_CONTENT)
} else ResponseEntity(HttpStatus.FORBIDDEN)
@PostMapping("/remove-duplicates")
fun removeDuplicates(
@AuthenticationPrincipal jwt: Jwt,
@RequestBody duplicates: List<DuplicateIRI>
): ResponseEntity<Void> =
if (endpointPermissions.hasAdminPermission(jwt)) {
datasetService.removeDuplicates(duplicates)
ResponseEntity(HttpStatus.OK)
} else ResponseEntity(HttpStatus.FORBIDDEN)
}
| 7 | Kotlin | 0 | 0 | 731ba08b2d8480b1cd193c0f0212a017946c2cee | 3,011 | fdk-dataset-harvester | Apache License 2.0 |
app/src/main/java/com/mbmc/fiinfo/helper/WidgetManager.kt | mbmc | 43,665,769 | false | null | package com.mbmc.fiinfo.helper
import com.mbmc.fiinfo.data.Event
import android.appwidget.AppWidgetManager
import android.content.Context
import android.content.Intent
import com.mbmc.fiinfo.R
import com.mbmc.fiinfo.widget.WidgetProvider
import com.mbmc.fiinfo.util.EVENT_PARCEL
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
class WidgetManager @Inject constructor(@ApplicationContext private val context: Context) {
fun update(event: Event) {
val intent = Intent(context, WidgetProvider::class.java)
intent.action = AppWidgetManager.ACTION_APPWIDGET_UPDATE
intent.putExtra(EVENT_PARCEL, event)
val ids = intArrayOf(R.layout.widget)
intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, ids)
context.sendBroadcast(intent)
}
} | 3 | Kotlin | 6 | 33 | ebbf058c19b5045958d22035c8529bf8070703f4 | 823 | FiInfo | Apache License 2.0 |
app/src/main/java/chat/rocket/android/dagger/qualifier/WorkerKey.kt | RocketChat | 48,179,404 | false | null | package chat.rocket.android.dagger.qualifier
import androidx.work.Worker
import dagger.MapKey
import kotlin.reflect.KClass
@MapKey
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.FUNCTION)
annotation class WorkerKey(val value: KClass<out Worker>)
| 283 | null | 585 | 877 | f832d59cb2130e5c058f5d9e9de5ff961d5d3380 | 266 | Rocket.Chat.Android | MIT License |
data/IRCdata/tourney/holdem 4/199612/pdb/pdb.kt | kaidenj3254 | 479,069,182 | true | {"Parrot": 3093541, "Max": 2063113, "Squirrel": 1844174, "Awk": 1738495, "Jupyter Notebook": 1428032, "HTML": 1203258, "Racket": 1187566, "Arc": 1145915, "JavaScript": 966627, "PogoScript": 875786, "Red": 834397, "Pike": 701373, "Shell": 684042, "Kotlin": 654456, "DM": 553193, "COBOL": 488858, "Kit": 444083, "AspectJ": 434343, "Swift": 416508, "Yacc": 337389, "Mathematica": 332080, "CSS": 172635, "LOLCODE": 167659, "HLSL": 158838, "C++": 153307, "Pan": 150242, "GAP": 149339, "Makefile": 133926, "Ruby": 131246, "Slash": 130592, "Nim": 130247, "Tcl": 128957, "FLUX": 104275, "Click": 103677, "Brainfuck": 98597, "Julia": 98497, "Dylan": 98254, "Perl": 82477, "Jasmin": 79072, "R": 76410, "Opal": 73876, "Mask": 72817, "Slice": 58804, "Uno": 54954, "Lex": 47910, "Moocode": 44434, "Monkey": 41740, "Eiffel": 29847, "Roff": 24503, "Oz": 24059, "Logos": 23838, "Mako": 23639, "Scala": 21699, "Common Lisp": 20280, "Java": 19833, "Stan": 18687, "Gnuplot": 17636, "Ox": 17424, "Io": 16358, "Stata": 15882, "Modula-3": 15852, "M": 15009, "Python": 13350, "AGS Script": 11632, "eC": 11348, "MoonScript": 11245, "PHP": 9613, "LLVM": 9562, "TypeScript": 9064, "Rebol": 9036, "Perl 6": 8915, "Ada": 8230, "C": 7588, "Clojure": 5706, "Metal": 4586, "Terra": 4237, "CoffeeScript": 3956, "Forth": 3813, "BlitzBasic": 3698, "Genshi": 3465, "BitBake": 2856, "GLSL": 2468, "Grammatical Framework": 2195, "Groovy": 1929, "OpenEdge ABL": 1871, "TeX": 1793, "Go": 1501, "Coq": 1093, "Visual Basic": 685, "Mercury": 617, "LiveScript": 564, "D": 413, "Isabelle": 413, "PureBasic": 408, "Crystal": 277, "Smalltalk": 277, "E": 272, "Elixir": 272, "Scheme": 214, "q": 73, "Boo": 69, "Emacs Lisp": 68, "MATLAB": 68, "Pascal": 68} | kt 849487067 14 13 c b c f 2000 265 0
kt 849487183 14 12 f - - - 1735 0 0
kt 849487220 14 11 f - - - 1735 0 0
kt 849487303 14 10 f - - - 1735 0 0
kt 849487401 14 9 f - - - 1735 0 0
kt 849487505 14 8 c r b - 1735 1370 2100
kt 849487585 14 7 f - - - 2465 0 0
kt 849487655 14 6 crc - - - 2465 1930 0 Jd Ah
kt 849487734 14 5 c bA - - 535 535 1210 Ts Th
kt 849487827 14 4 f - - - 1210 0 0
kt 849487888 14 3 r b bA - 1210 1210 0 Jd Jh
kt 849598664 14 5 cf - - - 800 6 0
kt 849598701 14 4 f - - - 794 0 0
kt 849598721 14 3 f - - - 794 0 0
kt 849598773 14 2 Bk kf - - 794 6 0
kt 849598821 14 1 Bf - - - 788 3 0
kt 849598880 14 14 f - - - 785 0 0
kt 849598941 14 13 f - - - 785 0 0
kt 849598994 14 12 f - - - 785 0 0
kt 849599036 14 11 f - - - 785 0 0
kt 849599089 14 10 f - - - 785 0 0
kt 849599202 14 9 f - - - 785 0 0
kt 849599254 14 8 f - - - 785 0 0
kt 849599279 14 7 f - - - 785 0 0
kt 849599379 13 6 f - - - 785 0 0
kt 849599460 13 5 f - - - 785 0 0
kt 849599547 13 4 f - - - 785 0 0
kt 849599574 13 3 f - - - 785 0 0
kt 849599602 13 2 Bf - - - 785 24 0
kt 849599654 13 1 Bc krA - - 761 761 1696 Jc Jd
kt 849599730 12 12 c f - - 1696 74 0
kt 849599831 12 11 f - - - 1622 0 0
kt 849599882 12 10 f - - - 1622 0 0
kt 849599928 12 9 f - - - 1622 0 0
kt 849600040 12 8 f - - - 1622 0 0
kt 849600119 11 6 f - - - 1622 0 0
kt 849600206 11 5 f - - - 1622 0 0
kt 849600249 10 4 f - - - 1622 0 0
kt 849600305 10 3 f - - - 1622 0 0
kt 849600335 10 2 Bf - - - 1622 96 0
kt 849600415 9 1 Bc k k k 1526 96 288 Ah As
kt 849600472 9 9 f - - - 1718 0 0
kt 849600503 9 8 f - - - 1718 0 0
kt 849600546 8 6 f - - - 1718 0 0
kt 849600586 8 6 f - - - 1718 0 0
kt 849600637 8 5 f - - - 1718 0 0
kt 849600659 8 4 f - - - 1718 0 0
kt 849600705 8 3 f - - - 1718 0 0
kt 849600738 8 2 Bf - - - 1718 192 0
kt 849600756 8 1 Bf - - - 1526 96 0
kt 849600803 8 8 f - - - 1430 0 0
kt 849600824 7 6 rA - - - 1430 1430 1718
kt 849600848 7 5 f - - - 1718 0 0
kt 849600888 7 4 f - - - 1718 0 0
kt 849600943 7 3 f - - - 1718 0 0
kt 849600974 7 2 Bf - - - 1718 384 0
kt 849601004 7 1 Bf - - - 1334 192 0
kt 849601025 6 6 f - - - 1142 0 0
kt 849601042 6 6 f - - - 1142 0 0
kt 849601069 5 4 f - - - 1142 0 0
kt 849601092 5 3 rA - - - 1142 1142 1718
kt 849601114 5 2 Bk k b - 1718 1152 1536
kt 849601170 5 1 Bf - - - 2102 192 0
kt 849601183 5 5 f - - - 1910 0 0
kt 849601223 5 4 f - - - 1910 0 0
kt 849601248 5 3 f - - - 1910 0 0
kt 849601282 5 2 Bf - - - 1910 384 0
kt 849601316 4 1 Br - - - 1526 1152 296 8h 8s
kt 849601341 4 4 cA - - - 670 670 2394 Kc Ah
kt 849601357 4 3 f - - - 2394 0 0
kt 849601383 4 2 Bf - - - 2394 768 0
kt 849601417 4 1 Bf - - - 1626 384 0
kt 849601484 3 3 f - - - 1242 0 0
kt 849601556 3 3 rA - - - 1242 1242 0 As 8c
kt 850188938 12 7 c f - - 2000 90 0
kt 850189028 11 5 f - - - 1910 0 0
kt 850189095 11 4 f - - - 1910 0 0
kt 850189170 11 3 c kf - - 1910 20 0
kt 850189281 11 2 Bk kf - - 1890 20 0
kt 850189341 11 1 Bc kf - - 1870 40 0
kt 850189459 11 11 f - - - 1830 0 0
kt 850189520 10 9 f - - - 1830 0 0
kt 850189577 9 7 c k b b 1830 1500 2040
kt 850189616 9 6 f - - - 2370 0 0
kt 850189676 9 5 cf - - - 2370 40 0
kt 850189755 8 3 cc c cA - 2330 2330 4820 Tc Td
kt 850189815 8 2 Bk kc - - 4820 4040 0 8c 7d
kt 850189914 8 1 Bf - - - 780 40 0
kt 850189979 7 7 f - - - 740 0 0
kt 850190023 7 6 f - - - 740 0 0
kt 850190057 7 5 r cA - - 740 740 0 Ah Tc
kt 850788650 14 10 f - - - 3500 0 0
kt 850788742 14 9 f - - - 3500 0 0
kt 850788776 13 7 f - - - 3500 0 0
kt 850788842 13 6 f - - - 3500 0 0
kt 850788892 13 5 f - - - 3500 0 0
kt 850788960 13 4 f - - - 3500 0 0
kt 850789005 13 3 c b - - 3500 165 270
kt 850789046 13 2 Bk kf - - 3605 60 0
kt 850789205 12 1 Bf - - - 3545 30 0
kt 850789270 12 12 f - - - 3515 0 0
kt 850789345 11 10 f - - - 3515 0 0
kt 850789422 11 9 f - - - 3515 0 0
kt 850789540 11 8 f - - - 3515 0 0
kt 850789564 11 7 f - - - 3515 0 0
kt 850789627 11 6 f - - - 3515 0 0
kt 850789662 11 5 cc kf - - 3515 780 0
kt 850789736 11 4 f - - - 2735 0 0
kt 850789781 11 3 f - - - 2735 0 0
kt 850789826 11 2 Bf - - - 2735 240 0
kt 850789887 11 1 Bf - - - 2495 120 0
kt 850789932 10 10 f - - - 2375 0 0
kt 850790007 10 9 f - - - 2375 0 0
kt 850790131 9 8 r bA - - 2375 2375 5410 As Kd
kt 850790193 8 6 f - - - 5410 0 0
kt 850790215 8 5 r bA - - 5410 5410 7810
kt 850790261 8 4 f - - - 7810 0 0
kt 850790309 8 3 f - - - 7810 0 0
kt 850790388 8 2 Bf - - - 7810 480 0
kt 850790425 8 1 Bf - - - 7330 240 0
kt 850790470 8 8 f - - - 7090 0 0
kt 850790532 7 7 r - - - 7090 1680 2400
kt 850790558 7 6 f - - - 7810 0 0
kt 850790600 7 5 f - - - 7810 0 0
kt 850790629 7 4 f - - - 7810 0 0
kt 850790695 7 3 f - - - 7810 0 0
kt 850790731 7 2 Bf - - - 7810 960 0
kt 850790757 7 1 Bf - - - 6850 480 0
kt 850790816 6 6 f - - - 6370 0 0
kt 850790850 6 5 f - - - 6370 0 0
kt 850790880 5 3 f - - - 6370 0 0
kt 850790909 5 3 f - - - 6370 0 0
kt 850790942 4 2 Bf - - - 6370 1920 0
kt 850790958 4 1 Bf - - - 4450 960 0
kt 850790965 4 4 f - - - 3490 0 0
kt 850790979 4 3 rA - - - 3490 3490 6370
kt 850790993 4 2 B - - - 6370 1920 2880
kt 850791001 4 1 Bf - - - 7330 960 0
kt 850791013 4 4 f - - - 6370 0 0
kt 850791028 4 3 f - - - 6370 0 0
kt 850791049 4 2 Bf - - - 6370 1920 0
kt 850791070 4 1 BcA - - - 4450 4450 10820 Qd As
kt 850791077 4 4 f - - - 10820 0 0
kt 850791095 4 3 f - - - 10820 0 0
kt 850791113 4 2 BrA - - - 10820 10820 16228 9h Ah
kt 850791122 3 1 Bf - - - 16228 960 0
kt 850791154 3 3 r - - - 15268 6720 3520 Jh Ts
kt 850791168 3 2 Bf - - - 12068 1920 0
kt 850791179 3 1 Br - - - 10148 5760 7680
kt 850791187 3 3 rcA - - - 12068 12068 25096 Tc As
kt 850791205 3 2 B - - - 25096 1920 2880
kt 850791224 3 1 Bf - - - 26056 960 0
kt 850791245 3 3 r - - - 25096 6720 9600
kt 850791254 3 2 Bf - - - 27976 1920 0
kt 850791265 3 1 Br - - - 26056 5760 7680
kt 850791291 3 3 f - - - 27976 0 0
kt 850791323 3 2 Bc - - - 27976 11372 22744 As 5s
kt 850791333 2 1 Bc - - - 39348 2560 5120 3s 6d
kt 850791579 10 9 f - - - 2000 0 0
kt 850791612 10 8 c b bf - 2000 340 0
kt 850791681 10 7 c f - - 1660 20 0
kt 850791732 10 6 f - - - 1640 0 0
kt 850791821 10 5 f - - - 1640 0 0
kt 850791933 10 4 f - - - 1640 0 0
kt 850791975 10 3 f - - - 1640 0 0
kt 850792034 10 2 Bk krA - - 1640 1640 3800 Js Ks
kt 850792141 10 1 Bf - - - 3800 20 0
kt 850792226 9 9 f - - - 3780 0 0
kt 850792275 9 8 f - - - 3780 0 0
kt 850792355 9 7 f - - - 3780 0 0
kt 850792403 9 6 f - - - 3780 0 0
kt 850792445 9 5 f - - - 3780 0 0
kt 850792502 9 4 f - - - 3780 0 0
kt 850792527 9 3 c kf - - 3780 80 0
kt 850792601 9 2 Bk kr - - 3700 1520 2160
kt 850792666 9 1 Bc bc - - 4340 1480 3280 Kd Jc
kt 850792741 8 8 f - - - 6140 0 0
kt 850792849 8 7 f - - - 6140 0 0
kt 850792938 6 4 f - - - 6140 0 0
kt 850792997 6 4 f - - - 6140 0 0
kt 850793016 6 3 f - - - 6140 0 0
kt 850793084 6 2 Bf - - - 6140 160 0
kt 850793121 6 1 Br - - - 5980 960 1280
kt 850793146 6 6 f - - - 6300 0 0
kt 850793193 6 5 f - - - 6300 0 0
kt 850793203 6 4 f - - - 6300 0 0
kt 850793247 6 3 f - - - 6300 0 0
kt 850793289 6 2 Bf - - - 6300 320 0
kt 850793316 6 1 Bf - - - 5980 160 0
kt 850793395 6 6 f - - - 5820 0 0
kt 850793445 5 4 Q - - - 5820 0 0
| 0 | null | 0 | 0 | 5e12754e9326ac8e991fdee0ca9f3c2a87c8f920 | 13,095 | poker_learn | MIT License |
app/src/main/java/org/fnives/tiktokdownloader/di/ViewModelDelegate.kt | fknives | 309,122,353 | false | {"HTML": 1099221, "Kotlin": 222872} | package org.fnives.tiktokdownloader.di
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelLazy
inline fun <reified VM : ViewModel> ComponentActivity.provideViewModels() =
ViewModelLazy(
viewModelClass = VM::class,
storeProducer = { viewModelStore },
factoryProducer = { createViewModelFactory() }
)
inline fun <reified VM : ViewModel> Fragment.provideViewModels() =
ViewModelLazy(
viewModelClass = VM::class,
storeProducer = { viewModelStore },
factoryProducer = { createViewModelFactory() })
fun ComponentActivity.createViewModelFactory() =
ServiceLocator.viewModelFactory(this, intent?.extras ?: Bundle.EMPTY)
fun Fragment.createViewModelFactory() =
ServiceLocator.viewModelFactory(this, arguments ?: Bundle.EMPTY) | 7 | HTML | 4 | 16 | 027f4e89d6b0fddf899005b2cb1dec0437129c6c | 915 | TikTok-Downloader | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/SquareRoot.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Outline.SquareRoot: ImageVector
get() {
if (_squareRoot != null) {
return _squareRoot!!
}
_squareRoot = Builder(name = "SquareRoot", defaultWidth = 512.0.dp, defaultHeight =
512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(8.76f, 22.0f)
horizontalLineToRelative(-2.46f)
lineToRelative(-3.761f, -10.342f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, -0.939f, -0.658f)
horizontalLineToRelative(-1.6f)
verticalLineToRelative(-2.0f)
horizontalLineToRelative(1.6f)
arcToRelative(3.007f, 3.007f, 0.0f, false, true, 2.819f, 1.975f)
lineToRelative(3.021f, 8.307f)
lineToRelative(4.19f, -15.082f)
arcToRelative(3.009f, 3.009f, 0.0f, false, true, 2.891f, -2.2f)
horizontalLineToRelative(9.479f)
verticalLineToRelative(2.0f)
horizontalLineToRelative(-9.479f)
arcToRelative(1.0f, 1.0f, 0.0f, false, false, -0.964f, 0.732f)
close()
moveTo(20.693f, 17.0f)
lineTo(24.0f, 12.0f)
horizontalLineToRelative(-2.385f)
lineToRelative(-2.115f, 3.2f)
lineToRelative(-2.115f, -3.2f)
horizontalLineToRelative(-2.385f)
lineToRelative(3.307f, 5.0f)
lineToRelative(-3.307f, 5.0f)
horizontalLineToRelative(2.385f)
lineToRelative(2.115f, -3.2f)
lineToRelative(2.115f, 3.2f)
horizontalLineToRelative(2.385f)
close()
}
}
.build()
return _squareRoot!!
}
private var _squareRoot: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,667 | icons | MIT License |
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/Meter.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Filled.Meter: ImageVector
get() {
if (_meter != null) {
return _meter!!
}
_meter = Builder(name = "Meter", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(12.0f, 0.0f)
curveTo(5.383f, 0.0f, 0.0f, 5.383f, 0.0f, 12.0f)
reflectiveCurveToRelative(5.383f, 12.0f, 12.0f, 12.0f)
reflectiveCurveToRelative(12.0f, -5.383f, 12.0f, -12.0f)
reflectiveCurveTo(18.617f, 0.0f, 12.0f, 0.0f)
close()
moveTo(7.0f, 11.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-4.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(4.0f)
close()
moveTo(11.0f, 11.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-4.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(4.0f)
close()
moveTo(15.0f, 11.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-4.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(4.0f)
close()
moveTo(19.0f, 11.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-4.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(4.0f)
close()
}
}
.build()
return _meter!!
}
private var _meter: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,513 | icons | MIT License |
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/Meter.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Filled.Meter: ImageVector
get() {
if (_meter != null) {
return _meter!!
}
_meter = Builder(name = "Meter", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(12.0f, 0.0f)
curveTo(5.383f, 0.0f, 0.0f, 5.383f, 0.0f, 12.0f)
reflectiveCurveToRelative(5.383f, 12.0f, 12.0f, 12.0f)
reflectiveCurveToRelative(12.0f, -5.383f, 12.0f, -12.0f)
reflectiveCurveTo(18.617f, 0.0f, 12.0f, 0.0f)
close()
moveTo(7.0f, 11.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-4.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(4.0f)
close()
moveTo(11.0f, 11.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-4.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(4.0f)
close()
moveTo(15.0f, 11.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-4.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(4.0f)
close()
moveTo(19.0f, 11.0f)
horizontalLineToRelative(-2.0f)
verticalLineToRelative(-4.0f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(4.0f)
close()
}
}
.build()
return _meter!!
}
private var _meter: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 2,513 | icons | MIT License |
statemachine-uml-plugin/src/test/kotlin/io/github/yonigev/sfsm/uml/UmlAnnotationScannerTest.kt | yonigev | 639,817,171 | false | {"Kotlin": 126987, "Java": 22944} | package io.github.yonigev.sfsm.uml
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
class UmlAnnotationScannerTest {
@Test
fun testUmlAnnotationScanner_detectsUmlAnnotation() {
val scannedStateMachineDefiners = UmlAnnotationScanner().scan()
val definitions = scannedStateMachineDefiners.map { it.getDefinition() }
assert(definitions.isNotEmpty())
}
@Test
fun testUmlAnnotationScanner_extracts_ProperStateMachineDefinitions() {
val scannedStateMachineDefiner = UmlAnnotationScanner().scan().first()
val scannedStateMachineDefinition = scannedStateMachineDefiner.getDefinition()
val dummyStateMachineDefinition = createDummyStateMachineDefinition(scannedStateMachineDefinition.name)
val scannedDefinitionUmlString = scannedStateMachineDefinition.toDotUmlString()
val expectedDefinitionUmlString = dummyStateMachineDefinition.toDotUmlString()
assertEquals(scannedDefinitionUmlString, expectedDefinitionUmlString)
}
} | 0 | Kotlin | 0 | 4 | 937fbcf1a92bc513eef185fa4b4f2d7e48ae95b9 | 1,032 | simple-finite-state-machine | Apache License 2.0 |
app/src/main/java/com/zasa/newsapp/ui/FavouriteFragment.kt | zansangeeth | 536,936,024 | false | null | package com.zasa.newsapp.ui
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.zasa.newsapp.R
class FavouriteFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_favourite, container, false)
}
} | 0 | Kotlin | 0 | 0 | b0a3304a6bd5d0ad1affa1b8d57a4da91b4495ba | 525 | NewsApp | Apache License 2.0 |
arrow-libs/ank/arrow-ank-gradle/src/main/kotlin/arrow/ank/AnkExtension.kt | magott | 409,870,116 | true | {"Kotlin": 1701186, "SCSS": 99310, "JavaScript": 82683, "HTML": 25756, "Java": 7588, "Shell": 4448, "Ruby": 903} | package arrow.ank
import org.gradle.api.file.FileCollection
import java.io.File
public data class AnkExtension(
var source: File? = null,
var target: File? = null,
var classpath: FileCollection? = null
)
| 0 | Kotlin | 0 | 0 | e30e29820a06fd585389e6e0570e2007d926284d | 212 | arrow | Apache License 2.0 |
service/src/main/java/de/inovex/blog/aidldemo/chatbot/service/ServiceApplication.kt | inovex | 645,052,604 | false | null | package de.inovex.blog.aidldemo.chatbot.service
import android.app.Application
import android.content.Context
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import org.koin.android.ext.koin.androidContext
import org.koin.androidx.viewmodel.dsl.viewModel
import org.koin.core.context.GlobalContext.startKoin
import org.koin.dsl.module
import timber.log.Timber
/**
* Basic Service Application with Timber, Koin and DataStore setup
*/
class ServiceApplication : Application() {
override fun onCreate() {
super.onCreate()
Timber.plant(Timber.DebugTree())
startKoin {
androidContext(this@ServiceApplication)
modules(modules)
}
}
}
val modules = listOf(module {
single { get<Context>().dataStore }
single { LocalBotRepository(get()) }
single { BotServiceDelegate(get(), CoroutineScope(Dispatchers.IO)) }
viewModel { ServiceMainViewModel(get()) }
})
val Context.dataStore by preferencesDataStore(name = "bot-datastore")
| 0 | Kotlin | 0 | 0 | c8b84373ccd5ec0953ec88365a32267b170e8729 | 1,090 | blog-android-service-kotlin-api-demo | Apache License 2.0 |
progressbars/src/main/java/com/kagaconnect/loaderspack/LoaderContract.kt | kagaconnect | 274,061,143 | false | null | package com.kagaconnect.loaderspack
import android.util.AttributeSet
interface LoaderContract {
fun initAttributes(attrs: AttributeSet)
} | 1 | null | 1 | 1 | 5be93063a84f628e6c94df016ae728864bf32c8f | 143 | android-libraries | MIT License |
prime-router/src/testIntegration/kotlin/datatests/mappinginventory/catchall/hd/HDToLocationTests.kt | CDCgov | 304,423,150 | false | null | package gov.cdc.prime.router.datatests.mappinginventory.hd
import gov.cdc.prime.router.datatests.mappinginventory.verifyHL7ToFHIRToHL7Mapping
import org.junit.jupiter.api.Test
/**
* The mapping of HD to Location is typically used within an existing HL7 Data type -> FHIR resource
* These tests use MSH.22.6 to test the mapping.
*/
class HDToLocationTests {
@Test
fun `test correctly handles ISO universal id type`() {
assert(verifyHL7ToFHIRToHL7Mapping("hd/HD-to-Location-iso").passed)
}
@Test
fun `test correctly handles UUID universal id type`() {
assert(verifyHL7ToFHIRToHL7Mapping("hd/HD-to-Location-uuid").passed)
}
@Test
fun `test correctly handles unknown universal id type`() {
assert(verifyHL7ToFHIRToHL7Mapping("hd/HD-to-Location-dns").passed)
}
@Test
fun `test correctly handles HD3 being empty`() {
assert(verifyHL7ToFHIRToHL7Mapping("hd/HD-to-Location-empty-hd3").passed)
}
} | 1,478 | null | 40 | 71 | ad7119e2c47671e0e69b942dafd804876f104414 | 977 | prime-reportstream | Creative Commons Zero v1.0 Universal |
app/src/main/java/com/kondroid/sampleproject/dto/websocket/WebSocketErrorDto.kt | kondroid00 | 104,654,160 | false | null | package com.kondroid.sampleproject.dto.websocket
/**
* Created by kondo on 2017/10/19.
*/
data class WebSocketErrorDto(val errorCode: Int,
val message: String) | 0 | Kotlin | 0 | 0 | 3892ddf080a44472f0e4997f79020729e33b7658 | 192 | SampleProject_Android | MIT License |
src/test/kotlin/com/adamratzman/spotify/private/ClientPersonalizationAPITest.kt | kptlronyttcna | 206,928,095 | true | {"Kotlin": 317955} | /* Spotify Web API - Kotlin Wrapper; MIT License, 2019; Original author: Adam Ratzman */
package com.adamratzman.spotify.private
import com.adamratzman.spotify.api
import com.adamratzman.spotify.endpoints.client.ClientPersonalizationAPI
import com.adamratzman.spotify.SpotifyClientAPI
import org.junit.jupiter.api.Assertions.assertTrue
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
class ClientPersonalizationAPITest : Spek({
describe("personalization endpoints") {
if (api !is SpotifyClientAPI) return@describe
it("top artists") {
assertTrue(api.personalization.getTopArtists(5, timeRange = ClientPersonalizationAPI.TimeRange.MEDIUM_TERM)
.complete().isNotEmpty())
}
it("top tracks") {
assertTrue(api.personalization.getTopTracks(5).complete().isNotEmpty())
}
}
}) | 0 | null | 0 | 0 | e239e725b438880949635d76633cc23065d5ee82 | 910 | spotify-web-api-kotlin | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.