path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/kotlin/me/indexyz/strap/define/telegram/Venue.kt
Indexyz
148,460,079
false
null
package me.indexyz.strap.define.telegram data class Venue ( val location: Location, val title: String, val address: String, val foursquare_id: String?, val foursquare_type: String? )
0
Kotlin
1
0
870ceaf4712c5f0ac78d589b3058221368c1e5f9
203
Strap
MIT License
testbot/src/main/kotlin/com/mrkirby153/botcore/testbot/Bot.kt
mrkirby153
137,817,672
false
{"Kotlin": 133086}
package com.mrkirby153.botcore.testbot import com.mrkirby153.botcore.command.slashcommand.dsl.DslCommandExecutor import com.mrkirby153.botcore.coroutine.enableCoroutines import com.mrkirby153.botcore.testbot.command.TestCommands import com.mrkirby153.botcore.utils.SLF4J import net.dv8tion.jda.api.sharding.DefaultShardManagerBuilder val log by SLF4J("Test Bot") fun main() { val token = System.getenv("TOKEN")?.trim() requireNotNull(token) { "Token must be provided" } val shardManager = DefaultShardManagerBuilder.createDefault(token).enableCoroutines().build() // Wait for ready shardManager.shards.forEach { it.awaitReady() } log.info("All shards ready!") val dslCommandExecutor = DslCommandExecutor() shardManager.addEventListener(dslCommandExecutor.getListener()) val testCommands = TestCommands() testCommands.register(dslCommandExecutor) val guilds = (System.getenv("SLASH_COMMAND_GUILDS")?.trim() ?: "").split(",") require(guilds.isNotEmpty()) { "Slash command guilds not provided" } log.info("Committing slash commands to guilds: $guilds") dslCommandExecutor.commit(shardManager.shards[0], *guilds.toTypedArray()).thenRun { log.info("Slash commands committed") } }
0
Kotlin
1
0
f4d45e0dbff56aa4707734a48f39123381bf25fc
1,252
bot-core
MIT License
kotstep/src/main/java/com/binayshaw7777/kotstep/components/vertical/VerticalTabStep.kt
binayshaw7777
691,987,900
false
{"Kotlin": 195544}
package com.binayshaw7777.kotstep.components.vertical import androidx.compose.animation.animateColor import androidx.compose.animation.core.updateTransition import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.StrokeCap import com.binayshaw7777.kotstep.components.divider.KotStepVerticalDivider import com.binayshaw7777.kotstep.components.tabs.CurrentTab import com.binayshaw7777.kotstep.components.tabs.DoneTab import com.binayshaw7777.kotstep.components.tabs.TodoTab import com.binayshaw7777.kotstep.model.LineType import com.binayshaw7777.kotstep.model.StepState import com.binayshaw7777.kotstep.model.StepStyle import com.binayshaw7777.kotstep.util.noRippleClickable /** * Renders a vertical tab step. * * @param modifier The modifier to be applied to the step. * @param stepStyle The style of the step. * @param stepState The state of the step. * @param isLastStep A flag indicating whether the step is the last step in the stepper. * @param lineProgress The progress of the line connecting the step to the next step. * @param onClick A callback that is invoked when the step is clicked. */ @Composable internal fun VerticalTabStep( modifier: Modifier = Modifier, stepStyle: StepStyle, stepState: StepState, isLastStep: Boolean, lineProgress: Float, onClick: () -> Unit ) { val transition = updateTransition(targetState = stepState, label = "") val containerColor: Color by transition.animateColor(label = "itemColor") { when (it) { StepState.TODO -> stepStyle.colors.todoContainerColor StepState.CURRENT -> stepStyle.colors.currentContainerColor StepState.DONE -> stepStyle.colors.doneContainerColor } } val lineColor: Color by transition.animateColor(label = "lineColor") { when (it) { StepState.TODO -> stepStyle.colors.todoLineColor StepState.CURRENT -> stepStyle.colors.currentLineColor StepState.DONE -> stepStyle.colors.doneLineColor } } val lineTrackStyle: LineType = when (stepState) { StepState.TODO -> stepStyle.lineStyle.todoLineTrackType StepState.CURRENT -> stepStyle.lineStyle.currentLineTrackType StepState.DONE -> stepStyle.lineStyle.doneLineTrackType } val lineProgressStyle: LineType = when (stepState) { StepState.TODO -> stepStyle.lineStyle.todoLineProgressType StepState.CURRENT -> stepStyle.lineStyle.currentLineProgressType StepState.DONE -> stepStyle.lineStyle.doneLineProgressType } val trackStrokeCap: StrokeCap = when (stepState) { StepState.TODO -> StrokeCap.Round StepState.CURRENT -> StrokeCap.Square StepState.DONE -> stepStyle.lineStyle.trackStrokeCap } val progressStrokeCap: StrokeCap = when (stepState) { StepState.TODO -> StrokeCap.Round StepState.CURRENT -> StrokeCap.Square StepState.DONE -> stepStyle.lineStyle.progressStrokeCap } Column( modifier = Modifier .noRippleClickable { onClick() } .then(modifier), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center ) { Box( contentAlignment = Alignment.Center, modifier = Modifier.size(stepStyle.stepSize) ) { when (stepState) { StepState.TODO -> { TodoTab( strokeColor = containerColor, strokeThickness = stepStyle.stepStroke, stepShape = stepStyle.stepShape ) } StepState.CURRENT -> { CurrentTab( circleColor = containerColor, strokeThickness = stepStyle.stepStroke, stepShape = stepStyle.stepShape, ) } StepState.DONE -> { DoneTab( circleColor = containerColor, showTick = stepStyle.showCheckMarkOnDone, checkMarkColor = stepStyle.colors.checkMarkColor, stepShape = stepStyle.stepShape ) } } } if (!isLastStep) { KotStepVerticalDivider( modifier = Modifier.padding( top = stepStyle.lineStyle.linePaddingTop, bottom = stepStyle.lineStyle.linePaddingBottom ), height = stepStyle.lineStyle.lineSize, width = stepStyle.lineStyle.lineThickness, lineTrackColor = stepStyle.colors.todoLineColor, lineProgressColor = lineColor, lineTrackStyle = lineTrackStyle, lineProgressStyle = lineProgressStyle, progress = lineProgress, trackStrokeCap = trackStrokeCap, progressStrokeCap = progressStrokeCap ) } } }
1
Kotlin
10
158
422bc0ed6edbd362cb06fabeee6c34181b25cef4
5,500
KotStep
Apache License 2.0
compiler/fir/checkers/checkers.js/src/org/jetbrains/kotlin/fir/analysis/js/checkers/expression/FirJsDefinedExternallyCallChecker.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.fir.analysis.js.checkers.expression import org.jetbrains.kotlin.diagnostics.DiagnosticReporter import org.jetbrains.kotlin.diagnostics.reportOn import org.jetbrains.kotlin.fir.analysis.checkers.closestNonLocal import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext import org.jetbrains.kotlin.fir.analysis.checkers.expression.FirBasicExpressionChecker import org.jetbrains.kotlin.fir.analysis.diagnostics.js.FirJsErrors import org.jetbrains.kotlin.fir.analysis.js.checkers.isNativeObject import org.jetbrains.kotlin.fir.analysis.js.checkers.isPredefinedObject import org.jetbrains.kotlin.fir.expressions.FirQualifiedAccessExpression import org.jetbrains.kotlin.fir.expressions.FirStatement import org.jetbrains.kotlin.fir.expressions.FirVariableAssignment import org.jetbrains.kotlin.fir.expressions.calleeReference import org.jetbrains.kotlin.fir.references.toResolvedCallableSymbol import org.jetbrains.kotlin.name.JsStandardClassIds object FirJsDefinedExternallyCallChecker : FirBasicExpressionChecker() { override fun check(expression: FirStatement, context: CheckerContext, reporter: DiagnosticReporter) { val symbol = expression.calleeReference?.toResolvedCallableSymbol() ?: return if (symbol.callableId !in JsStandardClassIds.Callables.definedExternallyPropertyNames) { return } val container = context.closestNonLocal?.symbol ?: return if (!container.isNativeObject(context) && !container.isPredefinedObject(context)) { reporter.reportOn(expression.source, FirJsErrors.CALL_TO_DEFINED_EXTERNALLY_FROM_NON_EXTERNAL_DECLARATION, context) } } }
181
null
5771
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,892
kotlin
Apache License 2.0
src/main/kotlin/gay/floof/hana/core/discord/commands/InfoOnApiKeyCommand.kt
AugustArchive
284,512,985
false
{"Kotlin": 198485, "Shell": 5362, "Dockerfile": 2602}
/* * 🥀 hana: API to proxy different APIs like GitHub Sponsors, source code for api.floofy.dev * Copyright (c) 2020-2022 Noel <[email protected]> * * 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 gay.floof.hana.core.discord.commands import dev.kord.common.Color import gay.floof.hana.core.database.asyncTransaction import gay.floof.hana.core.database.tables.ApiKeyEntity import net.perfectdreams.discordinteraktions.common.builder.message.embed import net.perfectdreams.discordinteraktions.common.commands.ApplicationCommandContext import net.perfectdreams.discordinteraktions.common.commands.SlashCommandExecutor import net.perfectdreams.discordinteraktions.common.commands.SlashCommandExecutorDeclaration import net.perfectdreams.discordinteraktions.common.commands.options.SlashCommandArguments class InfoOnApiKeyCommand: SlashCommandExecutor() { companion object: SlashCommandExecutorDeclaration(InfoOnApiKeyCommand::class) override suspend fun execute(context: ApplicationCommandContext, args: SlashCommandArguments) { context.deferChannelMessageEphemerally() // Check if the user has an API key registered. val found = asyncTransaction { ApiKeyEntity.findById(context.sender.id.value.toLong()) } if (found == null) { context.sendEphemeralMessage { content = ":thinking: **| You don't have any API keys registered. Use the `/create` slash command to register one!**" } } context.sendEphemeralMessage { embed { color = Color(0x6AAFDC) this.description = buildString { appendLine("• **Application Name**: ${found!!.name}") appendLine("• **Application Description**: ${found.description}") appendLine("• **API Key**: ||${found.token}||") val nsfw = found.permissions?.split("|")?.contains("nsfw") ?: false val im = found.permissions?.split("|")?.contains("im") ?: false appendLine("• **NSFW Enabled**: ${if (nsfw) "Yes" else "No"}") appendLine("• **(Alpha) Image Manipulation Enabled**: ${if (im) "Yes" else "No"}") } } } } }
9
Kotlin
0
5
58da85686a0e0f5e59ed0fb6022411b5cfe967d3
3,314
hana
MIT License
gradle-plugins/compose/src/main/kotlin/org/jetbrains/compose/internal/utils/gradleUtils.kt
JetBrains
293,498,508
false
null
/* * Copyright 2020-2023 JetBrains s.r.o. and respective authors and developers. * Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE.txt file. */ package org.jetbrains.compose.internal.utils import org.gradle.api.DomainObjectCollection import org.gradle.api.Project import org.gradle.api.artifacts.Configuration import org.gradle.api.logging.Logger import org.jetbrains.compose.ComposeBuildConfig import java.util.* internal inline fun Logger.info(fn: () -> String) { if (isInfoEnabled) { info(fn()) } } internal inline fun Logger.debug(fn: () -> String) { if (isDebugEnabled) { debug(fn()) } } val Project.localPropertiesFile get() = project.rootProject.file("local.properties") fun Project.getLocalProperty(key: String): String? { if (localPropertiesFile.exists()) { val properties = Properties() localPropertiesFile.inputStream().buffered().use { input -> properties.load(input) } return properties.getProperty(key) } else { localPropertiesFile.createNewFile() return null } } internal fun Project.detachedComposeGradleDependency( artifactId: String, groupId: String = "org.jetbrains.compose", ): Configuration = detachedDependency(groupId = groupId, artifactId = artifactId, version = ComposeBuildConfig.composeGradlePluginVersion) internal fun Project.detachedComposeDependency( artifactId: String, groupId: String = "org.jetbrains.compose", ): Configuration = detachedDependency(groupId = groupId, artifactId = artifactId, version = ComposeBuildConfig.composeVersion) internal fun Project.detachedDependency( groupId: String, artifactId: String, version: String ): Configuration = project.configurations.detachedConfiguration( project.dependencies.create("$groupId:$artifactId:$version") ) internal fun Configuration.excludeTransitiveDependencies(): Configuration = apply { isTransitive = false } internal inline fun <reified SubT> DomainObjectCollection<*>.configureEachWithType( crossinline fn: SubT.() -> Unit ) { configureEach { if (it is SubT) { it.fn() } } }
64
null
953
16,150
7e9832f6494edf3e7967082c11417e78cfd1d9d0
2,230
compose-multiplatform
Apache License 2.0
app/src/main/kotlin/org/emunix/insteadlauncher/di/AppModule.kt
btimofeev
125,632,007
false
null
/* * Copyright (c) 2020-2021 <NAME> <<EMAIL>> * Distributed under the MIT License (license terms are at http://opensource.org/licenses/MIT). */ package org.emunix.insteadlauncher.di import android.content.Context import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import org.emunix.instead.InsteadApiImpl import org.emunix.instead_api.InsteadApi import org.emunix.insteadlauncher.helpers.eventbus.EventBus import org.emunix.insteadlauncher.helpers.eventbus.RxBus import org.emunix.insteadlauncher.helpers.resourceprovider.ResourceProvider import org.emunix.insteadlauncher.helpers.resourceprovider.ResourceProviderImpl import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module class AppModule { @Provides @Singleton fun provideContext(@ApplicationContext context: Context): Context = context @Provides @Singleton fun provideEventBus(): EventBus = RxBus @Provides fun provideFeatureInstead(context: Context): InsteadApi = InsteadApiImpl(context) @Provides fun provideResourceProvider(context: Context): ResourceProvider = ResourceProviderImpl(context) }
6
Java
6
22
13e2e650a1368835d0e079e864803892ea0dba83
1,248
instead-launcher-android
MIT License
app/src/test/java/com/example/currencyconverter/apartmentpricecalculator/ApartmentPriceCalculatorTest.kt
nicolegeorgieva
679,840,622
false
{"Kotlin": 118225}
package com.example.currencyconverter.apartmentpricecalculator import com.example.currencyconverter.screen.apartmentinfo.ApartmentPriceCalculator import io.kotest.core.spec.style.FreeSpec import io.kotest.matchers.shouldBe class ApartmentPriceCalculatorTest : FreeSpec({ val apartmentPriceCalculator = ApartmentPriceCalculator() "Real m2 price should be 2800.0 for 140000 total price and 50m2 real area" { apartmentPriceCalculator.calculateRealM2Price("140000", "50") shouldBe 2800.0 } "Should return 0.0 for invalid total price and invalid real area" { apartmentPriceCalculator.calculateRealM2Price("total", "real") shouldBe 0.0 } "Total m2 price should be 140000.0 for 2000EUR per m2 and 70m2 area" { apartmentPriceCalculator.calculateTotalM2Price("2000", "70") shouldBe 140000.0 } "Should return 0.0 for invalid eur per m2 and valid total m2" { apartmentPriceCalculator.calculateTotalM2Price("eur per m2", "70") shouldBe 0.0 } })
0
Kotlin
0
0
2212c466f906b306ef76272f45cedfaf2aee3770
1,070
currency-converter
MIT License
src/main/kotlin/nobility/downloader/ui/windows/ConsoleWindow.kt
NobilityDeviant
836,259,311
false
null
package nobility.downloader.ui.windows import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.material3.MaterialTheme import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.unit.DpSize import androidx.compose.ui.unit.dp import nobility.downloader.core.BoxHelper.Companion.boolean import nobility.downloader.core.Core import nobility.downloader.core.settings.Defaults import nobility.downloader.ui.theme.CoreTheme import nobility.downloader.ui.windows.utils.ApplicationState object ConsoleWindow { private const val TITLE = "Console" fun close() { ApplicationState.removeWindowWithTitle(TITLE) } fun open() { Core.consolePoppedOut = true ApplicationState.newWindow( TITLE, size = DpSize(400.dp, 250.dp), windowAlignment = Alignment.BottomEnd, alwaysOnTop = Defaults.CONSOLE_ON_TOP.boolean(), onClose = { Core.consolePoppedOut = false return@newWindow true } ) { CoreTheme { Column( verticalArrangement = Arrangement.spacedBy(4.dp), horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.background( MaterialTheme.colorScheme.surface ) ) { Core.console.textField(true) } } } } }
3
null
0
9
cf9790e125c977646f63e800a0ee949b5f806ec4
1,622
ZenDownloader
Apache License 2.0
app/src/main/java/com/huhx0015/androidbooster/injections/modules/ViewModelModule.kt
huhx0015
95,202,520
false
null
package com.huhx0015.androidbooster.injections.modules import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.ViewModelProviders import com.huhx0015.androidbooster.viewmodel.ApiRecyclerViewModel import dagger.Module import dagger.Provides @Module class ViewModelModule { /** MODULE METHODS _________________________________________________________________________ */ @Provides fun providesApiRecyclerViewModel(activity: AppCompatActivity): ApiRecyclerViewModel { return ViewModelProviders.of(activity).get(ApiRecyclerViewModel::class.java) } }
0
Kotlin
3
4
19c5b41eab5efedf4f404f660cc15e612bb5edb1
591
AndroidBooster
Apache License 2.0
lib/src/main/kotlin/com/bethibande/actors/system/local/LocalActorSystem.kt
Bethibande
748,695,349
false
{"Kotlin": 54137}
package com.bethibande.actors.system.local import com.bethibande.actors.Actor import com.bethibande.actors.behavior.Behavior import com.bethibande.actors.system.ActorContext import com.bethibande.actors.system.ActorId import com.bethibande.actors.system.ActorSystem import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.cancelAndJoin import java.util.UUID class LocalActorSystem<A, C, S>( private val apiFactory: (Actor<C, S>) -> A, private val defaultBehavior: Behavior<C, S>, private val actorFactory: (ActorContext<C, S>) -> Actor<C, S> = ::Actor, ): ActorSystem<A, C, S> { private val cache = LocalActorCache<C, S>() private val job = Job() private val scope = CoroutineScope(job + Dispatchers.Default) private suspend fun newId(): ActorId { var id: ActorId.ActorIdUUID do { id = ActorId.ActorIdUUID(UUID.randomUUID()) } while (cache.exists(id)) return id } override suspend fun new(state: S, id: ActorId?, behavior: Behavior<C, S>?): A { if (id != null && cache.exists(id)) throw IllegalStateException("There already is an actor with the given id") val context = ActorContext( id ?: newId(), this, scope, behavior ?: defaultBehavior, state, ) val actor = actorFactory.invoke(context) actor.launch() val api = apiFactory.invoke(actor) cache.put(actor) return api } override suspend fun getById(id: ActorId): A? = cache.getById(id)?.let { apiFactory.invoke(it) } override suspend fun exists(id: ActorId): Boolean = cache.exists(id) override suspend fun actorClosed(actor: Actor<C, S>) { cache.remove(actor) } override suspend fun close() { job.cancelAndJoin() } override suspend fun isOpen(): Boolean = job.isActive && !job.isCancelled }
6
Kotlin
0
2
3e43988f81f3efe8f0eb36c1937d66866aa9e2b9
1,989
actors
Apache License 2.0
app/src/main/java/com/miguelbrmfreitas/mcdonaldsmenu/application/MainApplication.kt
MiguelbrmFreitas
533,079,271
false
{"Kotlin": 25443}
package com.miguelbrmfreitas.mcdonaldsmenu.application import android.app.Application import androidx.multidex.MultiDex import com.miguelbrmfreitas.data.datasources.remote.remoteDataModule import com.miguelbrmfreitas.mcdonaldsmenu.di.appModule import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.context.startKoin import org.koin.core.logger.Level class MainApplication : Application() { override fun onCreate() { super.onCreate() MultiDex.install(this) startKoin { androidLogger(Level.DEBUG) androidContext(this@MainApplication) modules(listOf(remoteDataModule, appModule)) } } }
0
Kotlin
0
1
9fe866e42fd76a3808eb28f15a791d60a031f320
725
mc-donalds-menu
MIT License
app/src/main/java/com/example/tdah/util/Navigation.kt
WayDougwas
847,444,410
false
{"Kotlin": 45473}
package com.example.tdah.util import android.content.Context import android.content.Intent import com.example.tdah.ui.DashboardActivity import com.example.tdah.ui.MainActivity import com.example.tdah.ui.QuizActivity /** * Utility object for handling navigation between activities. */ object NavigationUtils { /** * Starts the DashboardActivity. * * @param context The context from which the activity is started. */ fun toDashboard(context: Context) { val intent = Intent(context, DashboardActivity::class.java).apply { // Add any additional flags or extras here if needed } context.startActivity(intent) } /** * Starts the QuizActivity. * * @param context The context from which the activity is started. * @param name The user's name. * @param email The user's email. * @param age The user's age. */ fun toQuiz(context: Context, name: String, email: String, age: String) { val intent = Intent(context, QuizActivity::class.java).apply { putExtra("USER_NAME", name) putExtra("USER_EMAIL", email) putExtra("USER_BIRTHDAY", age) } context.startActivity(intent) } fun toHome(context: Context) { val intent = Intent(context, MainActivity::class.java).apply { // Add any additional flags or extras here if needed } context.startActivity(intent) } }
1
Kotlin
0
0
c6f0506de8f53d9b65d52aac3a416d807c82bb04
1,467
TDAH
MIT License
kotlin-eclipse-ui-test/src/org/jetbrains/kotlin/ui/tests/editors/KotlinAutoIndentTestCase.kt
Crazyjavahacking
151,690,588
true
{"Markdown": 3, "Maven POM": 12, "Text": 22, "Ignore List": 6, "Git Attributes": 1, "Java Properties": 6, "XML": 41, "Gradle": 2, "Shell": 1, "Batchfile": 1, "JAR Manifest": 7, "INI": 22, "Java": 271, "Kotlin": 849, "Groovy": 8, "AspectJ": 15}
package org.jetbrains.kotlin.ui.tests.editors import org.jetbrains.kotlin.testframework.editor.KotlinEditorWithAfterFileTestCase import org.junit.Before import org.eclipse.jface.text.TextUtilities import org.eclipse.ui.editors.text.EditorsUI import org.eclipse.ui.texteditor.AbstractDecoratedTextEditorPreferenceConstants import org.jetbrains.kotlin.testframework.utils.EditorTestUtils import org.jetbrains.kotlin.ui.tests.editors.formatter.KotlinFormatActionTestCase import org.jetbrains.kotlin.ui.formatter.settings import com.intellij.psi.codeStyle.CodeStyleSettings import org.junit.After abstract class KotlinAutoIndentTestCase : KotlinEditorWithAfterFileTestCase() { @Before fun before() { configureProject() } @After fun setDefaultSettings() { settings = CodeStyleSettings() } override fun performTest(fileText: String, expectedFileText: String) { KotlinFormatActionTestCase.configureSettings(fileText) EditorsUI.getPreferenceStore().setValue(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_SPACES_FOR_TABS, true) EditorsUI.getPreferenceStore().setValue(AbstractDecoratedTextEditorPreferenceConstants.EDITOR_TAB_WIDTH, 4) testEditor.typeEnter() EditorTestUtils.assertByEditor(testEditor.getEditor(), expectedFileText) } }
0
Kotlin
0
0
7c1b041673246674aebedd62e58c5ca52b85d7ec
1,362
kotlin-eclipse
Apache License 2.0
kellocharts/src/main/java/co/csadev/kellocharts/formatter/DateFormatters.kt
gtcompscientist
116,437,926
false
null
@file:Suppress("unused") package co.csadev.kellocharts.formatter import co.csadev.kellocharts.model.* import java.text.DateFormat import java.util.* import kotlin.math.roundToLong private const val nullTerminator = '\u0000' private fun DateFormat.formatValue(formattedValue: CharArray, value: Float): Int { val dateResult = format(Date(value.roundToLong())) val dateLength = dateResult.length dateResult.mapIndexed { index, c -> formattedValue[index] = c } for (i in dateLength until formattedValue.size) { formattedValue[i] = nullTerminator } return dateLength } class DateAxisValueFormatter(private val dateFormat: DateFormat) : AxisValueFormatter { override fun formatValueForManualAxis(formattedValue: CharArray, axisValue: AxisValue) = dateFormat.formatValue(formattedValue, axisValue.value) override fun formatValueForAutoGeneratedAxis(formattedValue: CharArray, value: Float, autoDecimalDigits: Int) = dateFormat.formatValue(formattedValue, value) } class DateBubbleChartValueFormatterX(private val dateFormat: DateFormat) : BubbleChartValueFormatter { override fun formatChartValue(formattedValue: CharArray, value: BubbleValue) = dateFormat.formatValue(formattedValue, value.x) } class DateBubbleChartValueFormatterY(private val dateFormat: DateFormat) : BubbleChartValueFormatter { override fun formatChartValue(formattedValue: CharArray, value: BubbleValue) = dateFormat.formatValue(formattedValue, value.y) } class DateBubbleChartValueFormatterZ(private val dateFormat: DateFormat) : BubbleChartValueFormatter { override fun formatChartValue(formattedValue: CharArray, value: BubbleValue) = dateFormat.formatValue(formattedValue, value.z) } class DateColumnChartValueFormatter(private val dateFormat: DateFormat) : ColumnChartValueFormatter { override fun formatChartValue(formattedValue: CharArray, value: SubcolumnValue) = dateFormat.formatValue(formattedValue, value.value) } class DateLineChartValueFormatterX(private val dateFormat: DateFormat) : LineChartValueFormatter { override fun formatChartValue(formattedValue: CharArray, value: PointValue) = dateFormat.formatValue(formattedValue, value.x) } class DateLineChartValueFormatterY(private val dateFormat: DateFormat) : LineChartValueFormatter { override fun formatChartValue(formattedValue: CharArray, value: PointValue) = dateFormat.formatValue(formattedValue, value.y) } class DatePieChartValueFormatter(private val dateFormat: DateFormat) : PieChartValueFormatter { override fun formatChartValue(formattedValue: CharArray, value: SliceValue) = dateFormat.formatValue(formattedValue, value.value) }
6
null
6
50
c78ce8c4ba1991f30f379ec47cf4c38749341c57
2,770
KelloCharts
Apache License 2.0
app/src/main/java/com/qochealth/qoctest/scenes/listEntries/ListEntriesRouter.kt
theblissprogrammer
142,545,857
false
null
package com.qochealth.qoctest.scenes.listEntries import android.support.v4.app.Fragment import com.qochealth.qoctest.scenes.listEntries.common.ListEntriesRoutable import com.qochealth.qoctest.scenes.showEntry.ShowEntryFragment import java.lang.ref.WeakReference /** * Created by ahmedsaad on 2018-07-26. */ class ListEntriesRouter(override var fragment: WeakReference<Fragment?>): ListEntriesRoutable { override fun showEntry(id: Int) { val showEntryFragment = ShowEntryFragment() showEntryFragment.entryID = id show(fragment = showEntryFragment) } }
1
null
1
1
803929a63b5c4bf1c7c8af3740357186f00ee956
589
sample-app-android
MIT License
src/main/kotlin/github/zimo/autojsx/action/run/doc/DocRunButton.kt
zimoyin
675,280,596
false
{"Kotlin": 197049, "JavaScript": 25641, "HTML": 15259}
package github.zimo.autojsx.action.run.doc import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonDataKeys import com.intellij.openapi.editor.Document import com.intellij.openapi.fileEditor.FileDocumentManager import com.intellij.openapi.fileEditor.FileEditorManager import com.intellij.openapi.module.ModuleType import com.intellij.openapi.project.modules import com.intellij.openapi.vfs.VirtualFile import github.zimo.autojsx.module.MODULE_TYPE_ID import github.zimo.autojsx.server.VertxCommand import github.zimo.autojsx.util.logE import github.zimo.autojsx.util.runServer import github.zimo.autojsx.window.AutojsxConsoleWindow /** * 运行当前脚本 */ class DocRunButton : AnAction(github.zimo.autojsx.icons.ICONS.START_16) { override fun actionPerformed(e: AnActionEvent) { val project = e.project AutojsxConsoleWindow.show(project) runServer(project) if (project != null) { val fileEditorManager = FileEditorManager.getInstance(project) //保存正在修改的文件 fileEditorManager.selectedFiles.apply { val documentManager = FileDocumentManager.getInstance() for (file in this) { val document: Document? = documentManager.getDocument(file!!) if (document != null) { documentManager.saveDocument(document) } } } //获取正在编辑的文件 val selectedEditor = fileEditorManager.selectedEditor if (selectedEditor != null) { val selectedFile: VirtualFile = fileEditorManager.selectedFiles[0] runCatching { VertxCommand.rerunJS(selectedFile.path) AutojsxConsoleWindow.show(project) }.onFailure { logE("js脚本网络引擎执行失败${selectedFile.path} ", it) } } } } override fun update(e: AnActionEvent) { super.update(e) val file = e.getData(CommonDataKeys.VIRTUAL_FILE) val isJsFile = file != null && "js" == file.extension e.presentation.isEnabledAndVisible = isJsFile && (e.project?.modules?.count { ModuleType.get(it).id == MODULE_TYPE_ID } ?: 0) > 0 } }
0
Kotlin
5
10
f1f3d49ef087c83e8eaaa708e4f4e1dae1448400
2,355
Autojsx.WIFI
Apache License 2.0
j2k/new/tests/testData/inference/common/listAssignment.kt
JetBrains
278,369,660
false
null
fun test() { val x: /*T2@*/List</*T1@*/Int> = listOf</*T0@*/Int>()/*List<T0@Int>*/ val y: /*T4@*/List</*T3@*/Int> = x/*T2@List<T1@Int>*/ } //T0 <: T1 due to 'INITIALIZER' //T1 <: T3 due to 'INITIALIZER' //T2 <: T4 due to 'INITIALIZER'
0
null
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
244
intellij-kotlin
Apache License 2.0
src/test/kotlin/mb/gitonium/GitoniumVersionTests.kt
metaborg
171,890,485
false
{"Kotlin": 106144}
package mb.gitonium import io.kotest.core.spec.style.FunSpec import io.kotest.engine.spec.tempdir import io.kotest.matchers.shouldBe import io.kotest.assertions.assertSoftly import io.kotest.assertions.throwables.shouldThrow import mb.gitonium.git.GitTestUtils.commitFile import mb.gitonium.git.GitTestUtils.copyTestGitConfig import mb.gitonium.git.GitTestUtils.createEmptyRepository import mb.gitonium.git.NativeGitRepo import java.io.File import java.io.IOException /** Tests the [GitoniumVersion] class. */ class GitoniumVersionTests: FunSpec({ val gitConfigPath: File = copyTestGitConfig() fun buildGitRepo(directory: File): NativeGitRepo { return NativeGitRepo(directory, environment = mapOf( // Override the git configuration (Git >= 2.32.0) "GIT_CONFIG_GLOBAL" to gitConfigPath.absolutePath, )) } context("determineVersion()") { test("should throw, when the directory is not a Git repository") { // Arrange val repoDir = tempdir() // Act/Assert shouldThrow<IOException> { GitoniumVersion.determineVersion( repoDirectory = repoDir, ) } } test("should return no version, when the directory is an empty Git repository") { // Arrange val repo = createEmptyRepository(::buildGitRepo) // Act val versionInfo = GitoniumVersion.determineVersion( repoDirectory = repo.directory, ) // Assert assertSoftly { versionInfo.version shouldBe null versionInfo.versionString shouldBe null versionInfo.branch shouldBe "main" versionInfo.isDirty shouldBe false versionInfo.isRelease shouldBe false versionInfo.isSnapshot shouldBe true } } test("should return the version of the last release tag, when the HEAD points to a release tag") { // Arrange val repo = createEmptyRepository(::buildGitRepo) repo.commitFile("Initial commit", "file1.txt") repo.tag("release-1.0.0") // Act val versionInfo = GitoniumVersion.determineVersion( repoDirectory = repo.directory, ) // Assert assertSoftly { versionInfo.version shouldBe SemanticVersion(1, 0, 0) versionInfo.versionString shouldBe "1.0.0" versionInfo.isDirty shouldBe false versionInfo.isRelease shouldBe true versionInfo.isSnapshot shouldBe false } } test("should return a dirty release version, when the HEAD points to a release tag and there are changes") { // Arrange val repo = createEmptyRepository(::buildGitRepo) repo.commitFile("Initial commit", "file1.txt") repo.tag("release-1.0.0") File(repo.directory, "uncommitted.txt").writeText("uncommitted") // Act val versionInfo = GitoniumVersion.determineVersion( repoDirectory = repo.directory, ) // Assert assertSoftly { versionInfo.version shouldBe SemanticVersion(1, 0, 0, listOf(), listOf("dirty")) versionInfo.versionString shouldBe "1.0.0+dirty" versionInfo.isDirty shouldBe true versionInfo.isRelease shouldBe true versionInfo.isSnapshot shouldBe false } } test("should return the snapshot version ahead of the last release tag, when the HEAD points to a commit after a release tag") { // Arrange val repo = createEmptyRepository(::buildGitRepo) repo.commitFile("Initial commit", "file1.txt") repo.tag("release-1.0.0") repo.commitFile("Second commit", "file2.txt") // Act val versionInfo = GitoniumVersion.determineVersion( repoDirectory = repo.directory, ) // Assert assertSoftly { versionInfo.version shouldBe SemanticVersion(1, 0, 1, listOf("main-SNAPSHOT")) versionInfo.versionString shouldBe "1.0.1-main-SNAPSHOT" versionInfo.isDirty shouldBe false versionInfo.isRelease shouldBe false versionInfo.isSnapshot shouldBe true } } test("should return a dirty snapshot version, when the HEAD points to a commit after a release tag and there are changes") { // Arrange val repo = createEmptyRepository(::buildGitRepo) repo.commitFile("Initial commit", "file1.txt") repo.tag("release-1.0.0") repo.commitFile("Second commit", "file2.txt") File(repo.directory, "uncommitted.txt").writeText("uncommitted") // Act val versionInfo = GitoniumVersion.determineVersion( repoDirectory = repo.directory, ) // Assert assertSoftly { versionInfo.version shouldBe SemanticVersion(1, 0, 1, listOf("main-SNAPSHOT"), listOf("dirty")) versionInfo.versionString shouldBe "1.0.1-main-SNAPSHOT+dirty" versionInfo.isDirty shouldBe true versionInfo.isRelease shouldBe false versionInfo.isSnapshot shouldBe true } } } })
3
Kotlin
1
4
fcc31f1176d3692ea20be99fe291e0da4b2fc41d
5,601
gitonium
Apache License 2.0
app/src/main/java/com/qingmei2/sample/ui/main/profile/ProfileViewModel.kt
armpending
161,976,998
true
{"Kotlin": 120341}
package com.qingmei2.sample.ui.main.profile import androidx.lifecycle.* import androidx.fragment.app.FragmentActivity import arrow.core.Option import arrow.core.none import arrow.core.toOption import com.qingmei2.rhine.base.viewmodel.BaseViewModel import com.qingmei2.rhine.ext.arrow.whenNotNull import com.qingmei2.rhine.ext.viewmodel.addLifecycle import com.qingmei2.sample.entity.LoginUser import com.qingmei2.sample.manager.UserManager class ProfileViewModel( private val repo: ProfileRepository ) : BaseViewModel() { val error: MutableLiveData<Option<Throwable>> = MutableLiveData() val loading: MutableLiveData<Boolean> = MutableLiveData() val user: MutableLiveData<LoginUser> = MutableLiveData() override fun onCreate(lifecycleOwner: LifecycleOwner) { super.onCreate(lifecycleOwner) applyState(user = UserManager.INSTANCE.toOption()) } private fun applyState(isLoading: Boolean = false, user: Option<LoginUser> = none(), error: Option<Throwable> = none()) { this.loading.postValue(isLoading) this.error.postValue(error) user.whenNotNull { this.user.postValue(it) } } companion object { fun instance(activity: FragmentActivity, repo: ProfileRepository): ProfileViewModel = ViewModelProviders .of(activity, ProfileViewModelFactory(repo)) .get(ProfileViewModel::class.java).apply { addLifecycle(activity) } } } class ProfileViewModelFactory( private val repo: ProfileRepository ) : ViewModelProvider.Factory { @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(modelClass: Class<T>): T { return ProfileViewModel(repo) as T } }
0
Kotlin
0
0
ce0dad28d50dfd1505cf0d0c73bd897b07f283c9
1,864
MVVM-Rhine
Apache License 2.0
autofill/autofill-impl/src/main/java/com/duckduckgo/autofill/impl/engagement/AutofillRefreshRetentionListener.kt
duckduckgo
78,869,127
false
{"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784}
/* * Copyright (c) 2024 DuckDuckGo * * 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.duckduckgo.autofill.impl.engagement import com.duckduckgo.app.di.AppCoroutineScope import com.duckduckgo.app.statistics.api.AtbLifecyclePlugin import com.duckduckgo.autofill.impl.engagement.store.AutofillEngagementRepository import com.duckduckgo.common.utils.DispatcherProvider import com.duckduckgo.di.scopes.AppScope import com.squareup.anvil.annotations.ContributesMultibinding import javax.inject.Inject import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @ContributesMultibinding(AppScope::class) class AutofillRefreshRetentionListener @Inject constructor( private val engagementRepository: AutofillEngagementRepository, @AppCoroutineScope private val coroutineScope: CoroutineScope, private val dispatchers: DispatcherProvider, ) : AtbLifecyclePlugin { override fun onSearchRetentionAtbRefreshed() { coroutineScope.launch(dispatchers.io()) { engagementRepository.recordSearchedToday() } } override fun onAppRetentionAtbRefreshed() { // no-op } }
75
Kotlin
901
3,823
6415f0f087a11a51c0a0f15faad5cce9c790417c
1,654
Android
Apache License 2.0
presentation/src/main/kotlin/com/lightteam/modpeide/presentation/main/customview/TextProcessor.kt
eltonkola
233,129,826
true
{"HTML": 1488208, "Kotlin": 327734, "Lua": 94117, "CSS": 7331, "Shell": 436}
/* * Licensed to the Light Team Software (Light Team) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The Light Team licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.lightteam.modpeide.presentation.main.customview import android.annotation.SuppressLint import android.content.ClipData import android.content.ClipboardManager import android.content.Context import android.graphics.* import android.text.* import android.text.style.BackgroundColorSpan import android.text.style.ForegroundColorSpan import android.util.AttributeSet import android.view.MotionEvent import android.view.VelocityTracker import android.view.ViewConfiguration import android.view.inputmethod.EditorInfo import android.widget.Scroller import androidx.appcompat.widget.AppCompatMultiAutoCompleteTextView import androidx.core.text.getSpans import com.lightteam.modpeide.R import com.lightteam.modpeide.data.patterns.completion.ModPECompletion import com.lightteam.modpeide.data.patterns.completion.UnknownCompletion import com.lightteam.modpeide.data.patterns.language.JavaScriptLanguage import com.lightteam.modpeide.presentation.main.adapters.CodeCompletionAdapter import com.lightteam.modpeide.presentation.main.customview.internal.codecompletion.SymbolsTokenizer import com.lightteam.modpeide.data.storage.collection.LinesCollection import com.lightteam.modpeide.presentation.main.customview.internal.syntaxhighlight.StyleSpan import com.lightteam.modpeide.presentation.main.customview.internal.syntaxhighlight.SyntaxHighlightSpan import com.lightteam.modpeide.domain.patterns.language.Language import com.lightteam.modpeide.presentation.main.customview.internal.textscroller.OnScrollChangedListener import com.lightteam.modpeide.data.storage.collection.UndoStack import com.lightteam.modpeide.domain.patterns.completion.CodeCompletion import com.lightteam.modpeide.utils.extensions.getScaledDensity import com.lightteam.modpeide.utils.extensions.toPx import java.util.regex.Pattern class TextProcessor(context: Context, attrs: AttributeSet) : AppCompatMultiAutoCompleteTextView(context, attrs) { data class Configuration( //Font var fontSize: Float = 14f, var fontType: Typeface = Typeface.MONOSPACE, //Editor var wordWrap: Boolean = true, var codeCompletion: Boolean = true, var pinchZoom: Boolean = true, var highlightCurrentLine: Boolean = true, var highlightDelimiters: Boolean = true, //Keyboard var softKeyboard: Boolean = false, var imeKeyboard: Boolean = false, //Code Style var autoIndentation: Boolean = true, var autoCloseBrackets: Boolean = true, var autoCloseQuotes: Boolean = false ) data class Theme( var textColor: Int = Color.WHITE, var backgroundColor: Int = Color.DKGRAY, var gutterColor: Int = Color.GRAY, var gutterTextColor: Int = Color.WHITE, var gutterDividerColor: Int = Color.WHITE, var gutterCurrentLineNumberColor: Int = Color.GRAY, var selectedLineColor: Int = Color.GRAY, var selectionColor: Int = Color.LTGRAY, var filterableColor: Int = Color.DKGRAY, var searchBgColor: Int = Color.GREEN, var bracketsBgColor: Int = Color.GREEN, //Syntax Highlighting var numbersColor: Int = Color.WHITE, var symbolsColor: Int = Color.WHITE, var bracketsColor: Int = Color.WHITE, var keywordsColor: Int = Color.WHITE, var methodsColor: Int = Color.WHITE, var stringsColor: Int = Color.WHITE, var commentsColor: Int = Color.WHITE ) var configuration: Configuration = Configuration() set(value) { field = value configure() } var theme: Theme = Theme() set(value) { field = value colorize() } var undoStack = UndoStack() var redoStack = UndoStack() var language: Language = JavaScriptLanguage() //= UnknownLanguage() var completion: CodeCompletion = UnknownCompletion() private val textScroller = Scroller(context) private val completionAdapter = CodeCompletionAdapter(context, R.layout.item_completion) private val clipboardManager = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager private val scaledDensity = context.getScaledDensity() private val textWatcher = object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { textChangeStart = start textChangeEnd = start + count if (!isDoingUndoRedo) { if (count < UndoStack.MAX_SIZE) { textLastChange = UndoStack.TextChange() textLastChange?.oldText = s?.subSequence(start, start + count).toString() textLastChange?.start = start return } undoStack.removeAll() redoStack.removeAll() textLastChange = null } abortFling() } override fun onTextChanged(text: CharSequence?, start: Int, before: Int, count: Int) { newText = text?.subSequence(start, start + count).toString() completeIndentation(start, count) textChangedNewText = text?.subSequence(start, start + count).toString() replaceText(textChangeStart, textChangeEnd, textChangedNewText) if (!isDoingUndoRedo && textLastChange != null) { if (count < UndoStack.MAX_SIZE) { textLastChange?.newText = text?.subSequence(start, start + count).toString() if (start == textLastChange?.start && (textLastChange?.oldText?.isNotEmpty()!! || textLastChange?.newText?.isNotEmpty()!!) && !textLastChange?.oldText?.equals(textLastChange?.newText)!!) { undoStack.push(textLastChange!!) redoStack.removeAll() } } else { undoStack.removeAll() redoStack.removeAll() } textLastChange = null } newText = "" if(configuration.codeCompletion) { onPopupChangePosition() } } override fun afterTextChanged(s: Editable?) { clearSearchSpans() clearSyntaxSpans() syntaxHighlight() } } private val lines = LinesCollection() private val editableFactory = Editable.Factory.getInstance() private val selectedLinePaint = Paint() private val gutterPaint = Paint() private val gutterDividerPaint = Paint() private val gutterCurrentLineNumberPaint = Paint() private val gutterTextPaint = Paint() private val numbersSpan = StyleSpan(color = theme.numbersColor) private val symbolsSpan = StyleSpan(color = theme.symbolsColor) private val bracketsSpan = StyleSpan(color = theme.bracketsColor) private val keywordsSpan = StyleSpan(color = theme.keywordsColor) private val methodsSpan = StyleSpan(color = theme.methodsColor) private val stringsSpan = StyleSpan(color = theme.stringsColor) private val commentsSpan = StyleSpan(color = theme.commentsColor, italic = true) private val tabString = " " // 4 spaces private val bracketTypes = charArrayOf('{', '[', '(', '}', ']', ')') private var openBracketSpan = BackgroundColorSpan(theme.bracketsBgColor) private var closedBracketSpan = BackgroundColorSpan(theme.bracketsBgColor) private var isDoingUndoRedo = false private var isAutoIndenting = false private var isFindSpansVisible = false private var scrollListeners = arrayOf<OnScrollChangedListener>() private var maximumVelocity = 0f private var zoomPinch = false private var zoomFactor = 1f private var gutterWidth = 0 private var gutterDigitCount = 0 private var gutterMargin = 4.toPx() // 4 dp to pixels private var textLastChange: UndoStack.TextChange? = null private var textChangeStart = 0 private var textChangeEnd = 0 private var textChangedNewText = "" private var newText = "" private var topDirtyLine = 0 private var bottomDirtyLine = 0 private var facadeText = editableFactory.newEditable("") private var velocityTracker: VelocityTracker? = null // region INIT init { //language = JavaScriptLanguage() completion = ModPECompletion() completionAdapter.dataSet = completion.getAll().toMutableList() maximumVelocity = ViewConfiguration.get(context).scaledMaximumFlingVelocity * 100f colorize() } private fun configure() { imeOptions = if(configuration.softKeyboard) { 0 //Normal } else { EditorInfo.IME_FLAG_NO_EXTRACT_UI } inputType = if (configuration.imeKeyboard) { InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE } else { InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_MULTI_LINE or InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD } textSize = configuration.fontSize typeface = configuration.fontType setHorizontallyScrolling(!configuration.wordWrap) if(configuration.codeCompletion) { setAdapter(completionAdapter) setTokenizer(SymbolsTokenizer()) } else { setTokenizer(null) } if(configuration.pinchZoom) { setOnTouchListener { _, event -> pinchZoom(event) } } else { setOnTouchListener { _, event -> onTouchEvent(event) } } } private fun colorize() { post { setTextColor(theme.textColor) setBackgroundColor(theme.backgroundColor) highlightColor = theme.selectionColor selectedLinePaint.color = theme.selectedLineColor selectedLinePaint.isAntiAlias = false selectedLinePaint.isDither = false gutterPaint.color = theme.gutterColor gutterPaint.isAntiAlias = false gutterPaint.isDither = false gutterDividerPaint.color = theme.gutterDividerColor gutterDividerPaint.isAntiAlias = false gutterDividerPaint.isDither = false gutterDividerPaint.style = Paint.Style.STROKE gutterDividerPaint.strokeWidth = 2.6f gutterCurrentLineNumberPaint.color = theme.gutterCurrentLineNumberColor gutterCurrentLineNumberPaint.isAntiAlias = true gutterCurrentLineNumberPaint.isDither = false gutterCurrentLineNumberPaint.textAlign = Paint.Align.RIGHT gutterTextPaint.color = theme.gutterTextColor gutterTextPaint.isAntiAlias = true gutterTextPaint.isDither = false gutterTextPaint.textAlign = Paint.Align.RIGHT numbersSpan.color = theme.numbersColor symbolsSpan.color = theme.symbolsColor bracketsSpan.color = theme.bracketsColor keywordsSpan.color = theme.keywordsColor methodsSpan.color = theme.methodsColor stringsSpan.color = theme.stringsColor commentsSpan.color = theme.commentsColor completionAdapter.color = theme.filterableColor openBracketSpan = BackgroundColorSpan(theme.bracketsBgColor) closedBracketSpan = BackgroundColorSpan(theme.bracketsBgColor) } } // endregion INIT // region CORE override fun setTextSize(size: Float) { super.setTextSize(size) post { gutterCurrentLineNumberPaint.textSize = textSize gutterTextPaint.textSize = textSize } } override fun setTypeface(tf: Typeface?) { super.setTypeface(tf) post { gutterCurrentLineNumberPaint.typeface = typeface gutterTextPaint.typeface = typeface } } override fun onDraw(canvas: Canvas) { if(layout != null) { val currentLineStart = lines.getLineForIndex(selectionStart) var top: Int if (configuration.highlightCurrentLine) { if (currentLineStart == lines.getLineForIndex(selectionEnd)) { val selectedLineStartIndex = getIndexForStartOfLine(currentLineStart) val selectedLineEndIndex = getIndexForEndOfLine(currentLineStart) val topVisualLine = layout.getLineForOffset(selectedLineStartIndex) val bottomVisualLine = layout.getLineForOffset(selectedLineEndIndex) top = layout.getLineTop(topVisualLine) + paddingTop val right = layout.width + paddingLeft + paddingRight val bottom = layout.getLineBottom(bottomVisualLine) + paddingTop canvas.drawRect( gutterWidth.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), selectedLinePaint ) } } updateGutter() super.onDraw(canvas) canvas.drawRect( scrollX.toFloat(), scrollY.toFloat(), (gutterWidth + scrollX).toFloat(), (scrollY + height).toFloat(), gutterPaint ) var i = getTopVisibleLine() if (i >= 2) { i -= 2 } else { i = 0 } var prevLineNumber = -1 val textRight = (gutterWidth - gutterMargin / 2) + scrollX while (i <= getBottomVisibleLine()) { val number = lines.getLineForIndex(layout.getLineStart(i)) if (number != prevLineNumber) { canvas.drawText( Integer.toString(number + 1), textRight.toFloat(), (layout.getLineBaseline(i) + paddingTop).toFloat(), if(number == currentLineStart) { gutterCurrentLineNumberPaint } else { gutterTextPaint } ) } prevLineNumber = number i++ } top = scrollY canvas.drawLine( (gutterWidth + scrollX).toFloat(), top.toFloat(), (gutterWidth + scrollX).toFloat(), (top + height).toFloat(), gutterDividerPaint ) } } override fun onSelectionChanged(selStart: Int, selEnd: Int) { if (selStart == selEnd) { checkMatchingBracket(selStart) } //invalidate() } fun getFacadeText(): String { return facadeText.toString() } fun setFacadeText(newText: String) { newText.removeSuffix("\n") disableUndoRedo() setText(newText) undoStack.clear() redoStack.clear() facadeText.clear() replaceText(0, facadeText.length, newText) lines.clear() var line = 0 var lineStart = 0 newText.lines().forEach { lines.add(line, lineStart) lineStart += it.length + 1 line++ } lines.add(line, lineStart) //because the last \n was removed enableUndoRedo() syntaxHighlight() } fun clearText() { setFacadeText("") } private fun enableUndoRedo() { addTextChangedListener(textWatcher) } private fun disableUndoRedo() { removeTextChangedListener(textWatcher) } // endregion CORE // region METHODS fun hasPrimaryClip(): Boolean = clipboardManager.hasPrimaryClip() fun insert(delta: CharSequence) { var selectionStart = Math.max(0, selectionStart) var selectionEnd = Math.max(0, selectionEnd) selectionStart = Math.min(selectionStart, selectionEnd) selectionEnd = Math.max(selectionStart, selectionEnd) editableText.delete(selectionStart, selectionEnd) editableText.insert(selectionStart, delta) //text.replace(selectionStart, selectionEnd, delta) } fun cut() { clipboardManager.primaryClip = ClipData.newPlainText("CUT", selectedText()) editableText.replace(selectionStart, selectionEnd, "") } fun copy() { clipboardManager.primaryClip = ClipData.newPlainText("COPY", selectedText()) } fun paste() { val clip = clipboardManager.primaryClip?.getItemAt(0)?.coerceToText(context) editableText.replace(selectionStart, selectionEnd, clip) } fun selectLine() { var start = Math.min(selectionStart, selectionEnd) var end = Math.max(selectionStart, selectionEnd) if (end > start) { end-- } while (end < text.length && text[end] != '\n') { end++ } while (start > 0 && text[start - 1] != '\n') { start-- } setSelection(start, end) } fun deleteLine() { var start = Math.min(selectionStart, selectionEnd) var end = Math.max(selectionStart, selectionEnd) if (end > start) { end-- } while (end < text.length && text[end] != '\n') { end++ } while (start > 0 && text[start - 1] != '\n') { start-- } editableText.delete(start, end) } fun duplicateLine() { var start = Math.min(selectionStart, selectionEnd) var end = Math.max(selectionStart, selectionEnd) if (end > start) { end-- } while (end < text.length && text[end] != '\n') { end++ } while (start > 0 && text[start - 1] != '\n') { start-- } editableText.insert(end, "\n" + text.subSequence(start, end)) } fun canUndo(): Boolean = undoStack.canUndo() fun canRedo(): Boolean = redoStack.canUndo() fun undo() { val textChange = undoStack.pop() as UndoStack.TextChange when { textChange.start >= 0 -> { isDoingUndoRedo = true if (textChange.start > text.length) { textChange.start = text.length } var end = textChange.start + textChange.newText.length if (end < 0) { end = 0 } if (end > text.length) { end = text.length } text.replace(textChange.start, end, textChange.oldText) Selection.setSelection(text, textChange.start + textChange.oldText.length) redoStack.push(textChange) isDoingUndoRedo = false } else -> undoStack.clear() } } fun redo() { val textChange = redoStack.pop() as UndoStack.TextChange when { textChange.start >= 0 -> { isDoingUndoRedo = true text.replace( textChange.start, textChange.start + textChange.oldText.length, textChange.newText ) Selection.setSelection(text, textChange.start + textChange.newText.length) undoStack.push(textChange) isDoingUndoRedo = false } else -> undoStack.clear() } } fun find(what: String, matchCase: Boolean, regExp: Boolean, wordsOnly: Boolean) { val pattern: Pattern = if (regExp) { if (matchCase) { Pattern.compile(what) } else { Pattern.compile(what, Pattern.CASE_INSENSITIVE or Pattern.UNICODE_CASE) } } else { if (wordsOnly) { if (matchCase) { Pattern.compile("\\s$what\\s") } else { Pattern.compile("\\s" + Pattern.quote(what) + "\\s", Pattern.CASE_INSENSITIVE or Pattern.UNICODE_CASE) } } else { if (matchCase) { Pattern.compile(Pattern.quote(what)) } else { Pattern.compile(Pattern.quote(what), Pattern.CASE_INSENSITIVE or Pattern.UNICODE_CASE) } } } clearSearchSpans() val matcher = pattern.matcher(text) while (matcher.find()) { text.setSpan( BackgroundColorSpan(theme.searchBgColor), matcher.start(), matcher.end(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE ) } isFindSpansVisible = true } fun replaceAll(replaceWhat: String, replaceWith: String) { setText(text.toString().replace(replaceWhat, replaceWith)) } fun gotoLine(lineNumber: Int) { setSelection(lines.getIndexForLine(lineNumber)) } private fun selectedText(): Editable { return text.subSequence(selectionStart, selectionEnd) as Editable } // endregion METHODS // region LINE_NUMBERS fun getArrayLineCount(): Int { return lines.lineCount - 1 } private fun updateGutter() { var max = 3 var widestNumber = 0 var widestWidth = 0f gutterDigitCount = Integer.toString(lines.lineCount).length for (i in 0..9) { val width = paint.measureText(Integer.toString(i)) if (width > widestWidth) { widestNumber = i widestWidth = width } } if (gutterDigitCount >= max) { max = gutterDigitCount } val builder = StringBuilder() for (i in 0 until max) { builder.append(Integer.toString(widestNumber)) } gutterWidth = paint.measureText(builder.toString()).toInt() gutterWidth += gutterMargin if (paddingLeft != gutterWidth + gutterMargin) { setPadding(gutterWidth + gutterMargin, gutterMargin, paddingRight, 0) } } private fun getTopVisibleLine(): Int { if (lineHeight == 0) { return 0 } val line = scrollY / lineHeight if (line < 0) { return 0 } return if (line >= lineCount) { lineCount - 1 } else { line } } private fun getBottomVisibleLine(): Int { if (lineHeight == 0) { return 0 } val line = Math.abs((scrollY + height) / lineHeight) + 1 if (line < 0) { return 0 } return if (line >= lineCount) { lineCount - 1 } else { line } } private fun getIndexForStartOfLine(lineNumber: Int): Int { return lines.getIndexForLine(lineNumber) } private fun getIndexForEndOfLine(lineNumber: Int): Int { return if (lineNumber == lineCount - 1) { facadeText.length } else { lines.getIndexForLine(lineNumber + 1) - 1 } } private fun replaceText(newStart: Int, newEnd: Int, newText: CharSequence) { var start = if (newStart < 0) 0 else newStart var end = if (newEnd >= facadeText.length) facadeText.length else newEnd val newCharCount = newText.length - (end - start) val startLine = lines.getLineForIndex(start) var i = start while (i < end) { if (facadeText[i] == '\n') { lines.remove(startLine + 1) } i++ } lines.shiftIndexes(lines.getLineForIndex(start) + 1, newCharCount) i = 0 while (i < newText.length) { if (newText[i] == '\n') { lines.add(lines.getLineForIndex(start + i) + 1, start + i + 1) } i++ } if (start > end) { end = start } if (start > facadeText.length) { start = facadeText.length } if (end > facadeText.length) { end = facadeText.length } if (start < 0) { start = 0 } if (end < 0) { end = 0 } facadeText.replace(start, end, newText) } // endregion LINE_NUMBERS // region INDENTATION private fun completeIndentation(start: Int, count: Int) { if(!isDoingUndoRedo && !isAutoIndenting) { val result = executeIndentation(start) val replacementValue = if (result[0] != null || result[1] != null) { val preText = result[0] ?: "" val postText = result[1] ?: "" if (preText != "" || postText != "") { preText + newText + postText } else { return } } else if (result[2] != null) { result[2]!! } else { return } val newCursorPosition: Int newCursorPosition = if (result[3] != null) { Integer.parseInt(result[3]!!) } else { start + replacementValue.length } post { isAutoIndenting = true text.replace(start, start + count, replacementValue) undoStack.pop() val change = undoStack.pop() if (replacementValue != "") { if(change != null) { change.newText = replacementValue undoStack.push(change) } } Selection.setSelection(text, newCursorPosition) isAutoIndenting = false } } } private fun executeIndentation(start: Int): Array<String?> { val strArr: Array<String?> if (newText == "\n" && configuration.autoIndentation) { val prevLineIndentation = getIndentationForOffset(start) val indentation = StringBuilder(prevLineIndentation) var newCursorPosition = indentation.length + start + 1 if (start > 0 && text[start - 1] == '{') { indentation.append(tabString) newCursorPosition = indentation.length + start + 1 } if (start + 1 < text.length && text[start + 1] == '}') { indentation.append("\n").append(prevLineIndentation) } strArr = arrayOfNulls(4) strArr[1] = indentation.toString() strArr[3] = Integer.toString(newCursorPosition) return strArr } else if (newText == "\"" && configuration.autoCloseQuotes) { if (start + 1 >= text.length) { strArr = arrayOfNulls(4) strArr[1] = "\"" strArr[3] = Integer.toString(start + 1) return strArr } else if (text[start + 1] == '\"' && text[start - 1] != '\\') { strArr = arrayOfNulls(4) strArr[2] = "" strArr[3] = Integer.toString(start + 1) return strArr } else if (!(text[start + 1] == '\"' && text[start - 1] == '\\')) { strArr = arrayOfNulls(4) strArr[1] = "\"" strArr[3] = Integer.toString(start + 1) return strArr } } else if (newText == "'" && configuration.autoCloseQuotes) { if (start + 1 >= text.length) { strArr = arrayOfNulls(4) strArr[1] = "'" strArr[3] = Integer.toString(start + 1) return strArr } else if (start + 1 >= text.length) { strArr = arrayOfNulls(4) strArr[1] = "'" strArr[3] = Integer.toString(start + 1) return strArr } else if (text[start + 1] == '\'' && start > 0 && text[start - 1] != '\\') { strArr = arrayOfNulls(4) strArr[2] = "" strArr[3] = Integer.toString(start + 1) return strArr } else if (!(text[start + 1] == '\'' && start > 0 && text[start - 1] == '\\')) { strArr = arrayOfNulls(4) strArr[1] = "'" strArr[3] = Integer.toString(start + 1) return strArr } } else if (newText == "{" && configuration.autoCloseBrackets) { strArr = arrayOfNulls(4) strArr[1] = "}" strArr[3] = Integer.toString(start + 1) return strArr } else if (newText == "}" && configuration.autoCloseBrackets) { if (start + 1 < text.length && text[start + 1] == '}') { strArr = arrayOfNulls(4) strArr[2] = "" strArr[3] = Integer.toString(start + 1) return strArr } } else if (newText == "(" && configuration.autoCloseBrackets) { strArr = arrayOfNulls(4) strArr[1] = ")" strArr[3] = Integer.toString(start + 1) return strArr } else if (newText == ")" && configuration.autoCloseBrackets) { if (start + 1 < text.length && text[start + 1] == ')') { strArr = arrayOfNulls(4) strArr[2] = "" strArr[3] = Integer.toString(start + 1) return strArr } } else if (newText == "[" && configuration.autoCloseBrackets) { strArr = arrayOfNulls(4) strArr[1] = "]" strArr[3] = Integer.toString(start + 1) return strArr } else if (newText == "]" && configuration.autoCloseBrackets && start + 1 < text.length && text[start + 1] == ']') { strArr = arrayOfNulls(4) strArr[2] = "" strArr[3] = Integer.toString(start + 1) return strArr } return arrayOfNulls(4) } private fun getIndentationForOffset(offset: Int): String { return getIndentationForLine(lines.getLineForIndex(offset)) } private fun getIndentationForLine(line: Int): String { val realLine = lines.getLine(line) ?: return "" val start = realLine.start var i = start while (i < text.length) { val char = text[i] if (!Character.isWhitespace(char) || char == '\n') { break } i++ } return text.subSequence(start, i).toString() } // endregion INDENTATION // region SYNTAX_HIGHLIGHT private fun syntaxHighlight() { if(layout != null) { var topLine = scrollY / lineHeight - 10 var bottomLine = (scrollY + height) / lineHeight + 11 if (topLine < 0) { topLine = 0 } if (bottomLine > layout.lineCount) { bottomLine = layout.lineCount } if (topLine > layout.lineCount) { topLine = layout.lineCount } if (bottomLine >= 0 && topLine >= 0) { topDirtyLine = topLine bottomDirtyLine = bottomLine val topLineOffset = layout.getLineStart(topLine) val bottomLineOffset = if (bottomLine < lineCount) { layout.getLineStart(bottomLine) } else { layout.getLineStart(lineCount) } // region HIGHLIGHTING var matcher = language.getPatternOfNumbers().matcher( //Numbers text.subSequence(topLineOffset, bottomLineOffset) ) while (matcher.find()) { text.setSpan( SyntaxHighlightSpan(numbersSpan, topLineOffset, bottomLineOffset), matcher.start() + topLineOffset, matcher.end() + topLineOffset, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } matcher = language.getPatternOfSymbols().matcher( //Symbols text.subSequence(topLineOffset, bottomLineOffset) ) while (matcher.find()) { text.setSpan( SyntaxHighlightSpan(symbolsSpan, topLineOffset, bottomLineOffset), matcher.start() + topLineOffset, matcher.end() + topLineOffset, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } matcher = language.getPatternOfBrackets().matcher( //Brackets text.subSequence(topLineOffset, bottomLineOffset) ) while (matcher.find()) { text.setSpan( SyntaxHighlightSpan(bracketsSpan, topLineOffset, bottomLineOffset), matcher.start() + topLineOffset, matcher.end() + topLineOffset, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } matcher = language.getPatternOfKeywords().matcher( //Keywords text.subSequence(topLineOffset, bottomLineOffset) ) while (matcher.find()) { text.setSpan( SyntaxHighlightSpan(keywordsSpan, topLineOffset, bottomLineOffset), matcher.start() + topLineOffset, matcher.end() + topLineOffset, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } matcher = language.getPatternOfMethods().matcher( //Methods text.subSequence(topLineOffset, bottomLineOffset) ) while (matcher.find()) { text.setSpan( SyntaxHighlightSpan(methodsSpan, topLineOffset, bottomLineOffset), matcher.start() + topLineOffset, matcher.end() + topLineOffset, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } matcher = language.getPatternOfStrings().matcher( //Strings text.subSequence(topLineOffset, bottomLineOffset) ) while (matcher.find()) { for (span in text.getSpans( matcher.start() + topLineOffset, matcher.end() + topLineOffset, ForegroundColorSpan::class.java)) { text.removeSpan(span) } text.setSpan( SyntaxHighlightSpan(stringsSpan, topLineOffset, bottomLineOffset), matcher.start() + topLineOffset, matcher.end() + topLineOffset, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } matcher = language.getPatternOfComments().matcher( //Comments text.subSequence(topLineOffset, bottomLineOffset) ) while (matcher.find()) { var skip = false for (span in text.getSpans( topLineOffset, matcher.end() + topLineOffset, ForegroundColorSpan::class.java)) { val spanStart = text.getSpanStart(span) val spanEnd = text.getSpanEnd(span) if (matcher.start() + topLineOffset in spanStart..spanEnd && matcher.end() + topLineOffset > spanEnd || matcher.start() + topLineOffset >= topLineOffset + spanEnd && matcher.start() + topLineOffset <= spanEnd) { skip = true break } } if (!skip) { for (span in text.getSpans( matcher.start() + topLineOffset, matcher.end() + topLineOffset, ForegroundColorSpan::class.java)) { text.removeSpan(span) } text.setSpan( SyntaxHighlightSpan(commentsSpan, topLineOffset, bottomLineOffset), matcher.start() + topLineOffset, matcher.end() + topLineOffset, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } } // endregion HIGHLIGHTING //post(::invalidateVisibleArea) } } } private fun clearSearchSpans() { if(isFindSpansVisible) { val spans = text.getSpans<BackgroundColorSpan>(0, text.length) for (span in spans) { text.removeSpan(span) } isFindSpansVisible = false } } private fun clearSyntaxSpans() { val spans = text.getSpans<SyntaxHighlightSpan>(0, text.length) for (span in spans) { text.removeSpan(span) } } /*private fun invalidateVisibleArea() { invalidate( paddingLeft, scrollY + paddingTop, width, scrollY + paddingTop + height ) }*/ private fun checkMatchingBracket(pos: Int) { if(layout != null) { text.removeSpan(openBracketSpan) text.removeSpan(closedBracketSpan) if (configuration.highlightDelimiters) { if (pos > 0 && pos <= text.length) { val c1 = text[pos - 1] for (i in 0 until bracketTypes.size) { if (bracketTypes[i] == c1) { val open = i <= 2 val c2 = bracketTypes[(i + 3) % 6] var k = pos if (open) { var nob = 1 while (k < text.length) { if (text[k] == c2) { nob-- } if (text[k] == c1) { nob++ } if (nob == 0) { showBracket(pos - 1, k) break } k++ } } else { var ncb = 1 k -= 2 while (k >= 0) { if (text[k] == c2) { ncb-- } if (text[k] == c1) { ncb++ } if (ncb == 0) { showBracket(k, pos - 1) break } k-- } } } } } } } } private fun showBracket(i: Int, j: Int) { text.setSpan(openBracketSpan, i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) text.setSpan(closedBracketSpan, j, j + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE) } // endregion SYNTAX_HIGHLIGHT // region SCROLLER override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { syntaxHighlight() for (listener in scrollListeners) { listener.onScrollChanged(scrollX, scrollY, scrollX, scrollY) } if(configuration.codeCompletion) { onDropDownSizeChange(w, h) } } @SuppressLint("ClickableViewAccessibility") override fun onTouchEvent(event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_DOWN -> { abortFling() if (velocityTracker == null) { velocityTracker = VelocityTracker.obtain() } else { velocityTracker?.clear() } super.onTouchEvent(event) } MotionEvent.ACTION_UP -> { velocityTracker?.computeCurrentVelocity(1000, maximumVelocity) val velocityX: Int? = if(configuration.wordWrap) { 0 } else { velocityTracker?.xVelocity?.toInt() } val velocityY: Int? = velocityTracker?.yVelocity?.toInt() if(velocityX != null && velocityY != null) { if (Math.abs(velocityY) >= 0 || Math.abs(velocityX) >= 0) { if (layout == null) { return super.onTouchEvent(event) } textScroller.fling( scrollX, scrollY, -velocityX, -velocityY, 0, layout.width - width + paddingLeft + paddingRight, 0, layout.height - height + paddingTop + paddingBottom ) } else if (velocityTracker != null) { velocityTracker?.recycle() velocityTracker = null } } super.onTouchEvent(event) } MotionEvent.ACTION_MOVE -> { velocityTracker?.addMovement(event) super.onTouchEvent(event) } else -> super.onTouchEvent(event) } return true } override fun onScrollChanged(horiz: Int, vert: Int, oldHoriz: Int, oldVert: Int) { super.onScrollChanged(horiz, vert, oldHoriz, oldVert) for (listener in scrollListeners) { listener.onScrollChanged(horiz, vert, oldHoriz, oldVert) } if (topDirtyLine > getTopVisibleLine() || bottomDirtyLine < getBottomVisibleLine()) { clearSyntaxSpans() syntaxHighlight() } } override fun computeScroll() { if (textScroller.computeScrollOffset()) { scrollTo(textScroller.currX, textScroller.currY) } } fun addOnScrollChangedListener(listener: OnScrollChangedListener) { val newListener = arrayOfNulls<OnScrollChangedListener>(scrollListeners.size + 1) val length = scrollListeners.size System.arraycopy(scrollListeners, 0, newListener, 0, length) newListener[newListener.size - 1] = listener scrollListeners = newListener.requireNoNulls() } fun abortFling() { if (!textScroller.isFinished) { textScroller.abortAnimation() } } // endregion SCROLLER // region PINCH_ZOOM private fun pinchZoom(event: MotionEvent): Boolean { when (event.action) { MotionEvent.ACTION_CANCEL, MotionEvent.ACTION_UP -> zoomPinch = false MotionEvent.ACTION_MOVE -> { if (event.pointerCount == 2) { val distance = getDistanceBetweenTouches(event) if (!zoomPinch) { zoomFactor = textSize / scaledDensity / distance zoomPinch = true } validateTextSize(zoomFactor * distance) } } } return zoomPinch } private fun getDistanceBetweenTouches(event: MotionEvent): Float { val xx = event.getX(1) - event.getX(0) val yy = event.getY(1) - event.getY(0) return Math.sqrt((xx * xx + yy * yy).toDouble()).toFloat() } private fun validateTextSize(size: Float) { textSize = when { size < 10 -> //minimum 10f //minimum size > 20 -> //maximum 20f //maximum else -> size } } // endregion PINCH_ZOOM // region CODE_COMPLETION override fun showDropDown() { if(!isPopupShowing) { if(hasFocus()) { super.showDropDown() } } } private fun onDropDownSizeChange(width: Int, height: Int) { val rect = Rect() getWindowVisibleDisplayFrame(rect) dropDownWidth = width * 1/2 // 1/2 width of screen dropDownHeight = height * 1/2 // 1/2 height of screen onPopupChangePosition() // change position } private fun onPopupChangePosition() { if(layout != null) { val charHeight = paint.measureText("M").toInt() val line = layout.getLineForOffset(selectionStart) val baseline = layout.getLineBaseline(line) val ascent = layout.getLineAscent(line) val x = layout.getPrimaryHorizontal(selectionStart) val y = baseline + ascent val offsetHorizontal = x + gutterWidth dropDownHorizontalOffset = offsetHorizontal.toInt() val offsetVertical = y + charHeight - scrollY var tmp = offsetVertical + dropDownHeight + charHeight if (tmp < getVisibleHeight()) { tmp = offsetVertical + charHeight / 2 dropDownVerticalOffset = tmp } else { tmp = offsetVertical - dropDownHeight - charHeight dropDownVerticalOffset = tmp } } } private fun getVisibleHeight(): Int { val rect = Rect() getWindowVisibleDisplayFrame(rect) return rect.bottom - rect.top } // endregion CODE_COMPLETION }
0
HTML
0
2
85e08c43e73c2046bd3f5bd9f63cecafe4a1763a
47,233
LoveCode-IDE
Apache License 2.0
lighty-codec/src/test/java/io/github/light0x00/lighty/codec/StatefulCharsetDecoderTest.kt
light0x00
640,510,313
false
null
package io.github.light0x00.lighty.codec import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Test import java.nio.ByteBuffer import java.nio.charset.MalformedInputException import java.nio.charset.StandardCharsets /** * @author light0x00 * @since 2023/8/20 */ class StatefulCharsetDecoderTest { val decoder = StatefulCharsetDecoder(StandardCharsets.UTF_8.newDecoder()) /** * 测试, 一个 4 字节字符分割为两次解码, 在第二次解码是否能正确解析 */ @Test fun test() { val decode1 = decoder.decode( ByteBuffer.wrap( byteArrayOf( 'S'.code.toByte(), 'a'.code.toByte(), 'k'.code.toByte(), 'u'.code.toByte(), 'r'.code.toByte(), 'a'.code.toByte(), 0xf0.toByte() ) ), ByteBuffer.wrap(byteArrayOf(0x9f.toByte(), 0x8c.toByte())) ) val decode2 = decoder.decode(ByteBuffer.wrap(byteArrayOf(0xb8.toByte()))) Assertions.assertEquals("Sakura", decode1) Assertions.assertEquals("🌸", decode2) } /** * 测试在解码 “畸形”字节序列 时, 还能否继续解码正常字节序列 */ @Test fun test2() { Assertions.assertThrows(MalformedInputException::class.java) { decoder.decode(ByteBuffer.wrap(byteArrayOf(0x9f.toByte(), 0x8c.toByte()))) } val decode = decoder.decode( ByteBuffer.wrap( byteArrayOf( 'S'.code.toByte(), 'a'.code.toByte(), 'k'.code.toByte(), 'u'.code.toByte(), 'r'.code.toByte(), 'a'.code.toByte(), 0xf0.toByte(), 0x9f.toByte(), 0x8c.toByte(), 0xb8.toByte() ) ) ) Assertions.assertEquals("Sakura🌸", decode) } /** * 测试能否正常解码混合了不同编码长度的字符 */ @Test fun test3() { val decode1 = decoder.decode( ByteBuffer.wrap( byteArrayOf( 'S'.code.toByte(), 'a'.code.toByte(), 'k'.code.toByte(), 'u'.code.toByte(), 'r'.code.toByte(), 'a'.code.toByte(), 0xf0.toByte() ) ), ByteBuffer.wrap(byteArrayOf(0x9f.toByte(), 0x8c.toByte())), ByteBuffer.wrap(byteArrayOf(0xb8.toByte())) ) Assertions.assertEquals("Sakura🌸", decode1) } }
6
null
3
12
04edba2c742ac0adc090da114f2db9cc26fc3445
2,575
lighty
MIT License
app/src/main/java/com/compose/jreader/di/FirebaseModule.kt
alinbabu2010
493,496,121
false
null
package com.compose.jreader.di import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @InstallIn(SingletonComponent::class) @Module object FirebaseModule { @Singleton @Provides fun provideFirebaseAuth(): FirebaseAuth = FirebaseAuth.getInstance() @Singleton @Provides fun provideFireStore(): FirebaseFirestore = FirebaseFirestore.getInstance() }
0
Kotlin
0
4
32adce102da33f2f12693da8f47db6b93ebba64c
570
jReader
MIT License
app/src/main/java/com/wolken/weatherForecast/features/main/WeatherForeCastActivity.kt
archana2020-wellnesys
279,258,277
false
null
package com.wolken.weatherForecast.features.main import android.annotation.SuppressLint import android.os.Bundle import android.os.Handler import android.util.Log import android.view.Gravity import androidx.recyclerview.widget.LinearLayoutManager import android.view.View import android.view.animation.AnimationUtils import android.widget.Toast import androidx.recyclerview.widget.RecyclerView import com.wolken.weatherForecast.R import com.wolken.weatherForecast.features.base.BaseActivity import com.wolken.weatherForecast.features.common.ErrorView import com.wolken.weatherForecast.features.main.weathermodels.ResponseWeatherModels import com.wolken.weatherForecast.util.NetworkUtil import com.wolken.weatherForecast.util.gone import com.wolken.weatherForecast.util.visible import kotlinx.android.synthetic.main.activity_main.* import timber.log.Timber import java.lang.Exception import javax.inject.Inject class WeatherForeCastActivity : BaseActivity(), WeatherForecastMvpView, WeatherForeCastAdapter.ClickListener, ErrorView.ErrorListener { @Inject lateinit var weatherForeCastAdapter: WeatherForeCastAdapter @Inject lateinit var weatherForeCastPresenter: WeatherForeCastPresenter @SuppressLint("WrongConstant") override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) activityComponent().inject(this) weatherForeCastPresenter.attachView(this) try { if (NetworkUtil.isNetworkConnected(this@WeatherForeCastActivity)) { Handler().postDelayed({ weatherForeCastPresenter.getWeatherData(getString(R.string.wsd_rest_service_api_key), getString(R.string.location), 6) },1000) } else { Toast.makeText(this@WeatherForeCastActivity, "No Internet Found", Toast.LENGTH_LONG).show() } } catch (e: Exception) { Toast.makeText(this@WeatherForeCastActivity, e.toString(), Toast.LENGTH_LONG).show() } weatherForeCastAdapter.setClickListener(this) recyclerViewWeather?.apply { val resId = R.anim.layout_animation_from_bottom val animation = AnimationUtils.loadLayoutAnimation(this@WeatherForeCastActivity, resId) layoutAnimation = animation layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, true) adapter = weatherForeCastAdapter } viewError?.setErrorListener(this) } override fun layoutId() = R.layout.activity_main override fun onDestroy() { super.onDestroy() weatherForeCastPresenter.detachView() } override fun showWeatherList(weatherList: List<ResponseWeatherModels>) { for (list in 0 until weatherList.size) { if (weatherList[list].current?.tempC.toString().isNotEmpty()) { tv_location_temp.text = weatherList[list].current?.tempC.toString() + " " + "C" } if (weatherList[list].location?.name.toString().isNotEmpty()) { tv_location_name.text = weatherList[list].location?.name.toString() } } weatherForeCastAdapter.apply { setWeatherList(weatherList) notifyDataSetChanged() } recyclerViewWeather?.visible() //swipeToRefresh?.visible() } override fun showProgress(show: Boolean) { if (show) { progressBar.visibility = View.VISIBLE } else { progressBar.visibility = View.GONE } } override fun showError(error: Throwable) { frame_layout_main?.visibility = View.GONE recyclerViewWeather?.gone() progressBar.visibility = View.GONE viewError?.visible() Timber.e(error, "There was an error retrieving the weather list") } override fun onWeatherItem(pokemon: String) { //startActivity(DetailActivity.getStartIntent(this, pokemon)) } override fun onReloadData() { // weatherForeCastPresenter.getPokemon(POKEMON_COUNT) try { if (NetworkUtil.isNetworkConnected(this@WeatherForeCastActivity)) { weatherForeCastPresenter.getWeatherData(getString(R.string.wsd_rest_service_api_key), getString(R.string.location), 6) } else { Toast.makeText(this@WeatherForeCastActivity, "No Internet Found", Toast.LENGTH_LONG).show() } } catch (e: Exception) { Toast.makeText(this@WeatherForeCastActivity, e.toString(), Toast.LENGTH_LONG).show() } } }
0
Kotlin
0
0
c61b91213c01e0bc25097943efcce3c48fa91bea
4,677
weather
The Unlicense
androidApp/src/main/java/com/EENX15_22_17/digital_journal/android/screens/journal/triage/suicideAssessment/data/StatisticalRiskFactorsData.kt
j-nordin
464,391,828
false
{"Kotlin": 187041, "Swift": 345}
package com.EENX15_22_17.digital_journal.android.screens.journal.triage.suicideAssessment.statisticalriskfactors enum class StatisticalRiskFactorsData { IS_MALE_AGE_BETWEEN_19_AND_45, SOMATIC_DISEASE, MISUSE_OR_ADDICTION, PREVIOUS_SUICIDE_ATTEMPTS, LIVING_ALONE_WITHOUT_RELATIONS, SUICIDE_EQUIPMENT_IS_AVAILABLE, PREVIOUS_OR_CURRENT_AGGRESSION_OR_IMPULSIVE_BEHAVIOUR, PSYCHOLOGICAL_DISEASE_AND_COMORBIDITY, REACTION_ON_ACUTE_LIFE_EVENTS_SEPARATIONS_DEATH_OR_VIOLATION, HIGH_LEVEL_OF_ANXIETY_THOUGHT_DISORDER_PSYCHOTIC_THINKING_REGARDLESS_OF_UNDERLYING_DISEASE, } val statisticalRiskFactorsLabels = mapOf<StatisticalRiskFactorsData, String>( StatisticalRiskFactorsData.IS_MALE_AGE_BETWEEN_19_AND_45 to "Man och mellan 19 och 45 år", StatisticalRiskFactorsData.SOMATIC_DISEASE to "Somatisk sjukdom", StatisticalRiskFactorsData.MISUSE_OR_ADDICTION to "Missbruk/Beroende", StatisticalRiskFactorsData.PREVIOUS_SUICIDE_ATTEMPTS to "Tidigare suicidförsök", StatisticalRiskFactorsData.LIVING_ALONE_WITHOUT_RELATIONS to "Ensamboende utan relationer", StatisticalRiskFactorsData.SUICIDE_EQUIPMENT_IS_AVAILABLE to "Finns självmordsredskap tillgängligt", StatisticalRiskFactorsData.PREVIOUS_OR_CURRENT_AGGRESSION_OR_IMPULSIVE_BEHAVIOUR to "Tidigare eller aktuell aggressivitet", StatisticalRiskFactorsData.PSYCHOLOGICAL_DISEASE_AND_COMORBIDITY to "Psykisk sjukdom och dess svårighetsgrad/fas/samsjuklighet", StatisticalRiskFactorsData.REACTION_ON_ACUTE_LIFE_EVENTS_SEPARATIONS_DEATH_OR_VIOLATION to "Reaktion på akuta livshändelser/seperation/dödsfall/kränkning", StatisticalRiskFactorsData.HIGH_LEVEL_OF_ANXIETY_THOUGHT_DISORDER_PSYCHOTIC_THINKING_REGARDLESS_OF_UNDERLYING_DISEASE to "Hög ångestnivå/tankestörning/psykotiskt tänkande oavsett grundsjuk", )
0
Kotlin
0
3
dea51ca7126887b210bad1243c97c6ad5fdbc072
1,827
Digital-Journal
MIT License
nee-core/src/test/kotlin/dev/neeffect/nee/effects/tx/DBLikeResource.kt
jarekratajski
225,063,998
true
{"Kotlin": 159108, "Shell": 222}
package dev.neeffect.nee.effects.tx import io.vavr.control.Either import io.vavr.control.Option import dev.neeffect.nee.effects.async.AsyncStack import java.lang.IllegalStateException internal class DBLikeProvider( val db: DBLike, val conn: TxConnection<DBLike> = DBConnection(db) ) : TxProvider<DBLike, DBLikeProvider> { override fun getConnection(): TxConnection<DBLike> = if (!db.connected()) { if (db.connect()) { conn } else { throw IllegalStateException("cannot connect DB") } } else { conn } override fun setConnectionState(newState: TxConnection<DBLike>) = DBLikeProvider(db, newState) } internal open class DBConnection(val db: DBLike, val level:Int = 0) : TxConnection<DBLike> { override fun hasTransaction(): Boolean = false override fun begin(): Either<TxError, TxStarted<DBLike>> = if (db.begin()) { Either.right(DBTxConnection(db, level + 1)) } else { Either.left<TxError, TxStarted<DBLike>>( TxErrorType.CannotStartTransaction) } override fun continueTx(): Either<TxError, TxStarted<DBLike>> = if (db.continueTransaction()) { Either.right(DBTxConnection(db, level)) } else { Either.left<TxError, TxStarted<DBLike>>( TxErrorType.CannotContinueTransaction) } override fun getResource(): DBLike = db override fun close() { db.close() } } internal class DBTxConnection(db: DBLike, level:Int) : DBConnection(db, level), TxStarted<DBLike> { override fun hasTransaction(): Boolean = true override fun commit(): Pair<Option<TxError>, TxConnection<DBLike>> = if (db.commit()) { Pair(Option.none<TxError>(), DBConnection(db, level - 1)) } else { Pair(Option.some<TxError>(TxErrorType.CannotCommitTransaction), this) } override fun rollback(): Pair<Option<TxError>, TxConnection<DBLike>> = if (db.rollback()) { Pair(Option.none<TxError>(), DBConnection(db, level - 1)) } else { Pair(Option.some<TxError>(TxErrorType.CannotRollbackTransaction), this) } }
1
Kotlin
0
1
02500b91cce537b10b6024f6b507b4e5c7212b48
2,293
nee
Apache License 2.0
app/src/main/java/com/personal/themovieproject/model/Movie.kt
vaishakhbg
271,788,449
false
null
package com.personal.themovieproject.model class Movie ( var name:String, var movieID:Double, var poster_img_path:String, var popularity:Float, var rating:Float, var release_date: Double )
0
Kotlin
0
0
b77d022691dc55bc6ee5178558e411749c7388aa
215
mvvm-app-movielist
Apache License 2.0
src/test/kotlin/org/edudev/domain/users/profiles/ProfileHelper.kt
Duduxs
360,320,691
false
null
package org.edudev.domain.users.profiles import org.edudev.domain.users.profile.Profile import org.edudev.domain.users.profile.ProfileDTO import org.junit.jupiter.api.Assertions.assertEquals infix fun Profile.assertEquals(dto: ProfileDTO){ assertEquals(this.id, dto.id) assertEquals(this.name, dto.name) if(!this.permissions.isEmpty() && !dto.permissions.isEmpty()){ assertEquals(this.permissions.size,dto.permissions.size) this.permissions.forEachIndexed { i, permission -> val dtoPermission = dto.permissions.elementAt(i) assertEquals(permission.functionality, dtoPermission.functionality) if(!permission.actions.isEmpty() && !dtoPermission.actions.isEmpty()){ permission.actions.forEach { crudAction -> assertEquals(dtoPermission.containsAction(crudAction), true) } } } } }
0
Kotlin
1
1
811a977f0059ba5fba2f022441bfc56834c6d9d6
923
auth-api
MIT License
api/src/main/kotlin/br/com/vitorsalgado/example/api/graphapi/dtos/FacebookCursor.kt
vitorsalgado
89,657,739
false
null
package br.com.vitorsalgado.example.api.graphapi.dtos class FacebookCursor { val before: String? = null val after: String? = null }
3
Kotlin
2
5
e9c902760bfcaf0f58e9a2a92568c5470bd55d75
137
android-boilerplate
Apache License 2.0
data/src/main/java/pakisan/telegraphcli/data/gson/data/page/node/GNode.kt
Pakisan
108,777,608
false
null
/* * Copyright 2017 pakisan * * 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 pakisan.telegraphcli.data.gson.data.page.node import com.google.gson.GsonBuilder import com.google.gson.reflect.TypeToken import pakisan.telegraphcli.data.gson.NodeDeserializer import pakisan.telegraphcli.data.gson.NodeListDeserializer import pakisan.telegraphcli.data.gson.NodeSerializer import pakisan.telegraphcli.data.page.node.Node /** * Serialize [Node] to json or Deserialize it from last. */ object GNode { private val listOfNodes = object: TypeToken<List<Node>>(){}.type private val gson = GsonBuilder() .registerTypeAdapter(Node::class.java, NodeDeserializer()) .registerTypeAdapter(Node::class.java, NodeSerializer()) .registerTypeAdapter(listOfNodes, NodeListDeserializer()) .create() private val prettyGson = GsonBuilder() .registerTypeAdapter(Node::class.java, NodeDeserializer()) .registerTypeAdapter(Node::class.java, NodeSerializer()) .registerTypeAdapter(listOfNodes, NodeListDeserializer()) .setPrettyPrinting() .create() /** * Deserialize [Node] from JSON. * * @param json [Node] as JSON. * @return [Node] * @throws [com.google.gson.JsonSyntaxException] in case when JSON was malformed. */ @Synchronized fun node(json: String): Node { return gson.fromJson(json, Node::class.java) } /** * Serialize [Node] to JSON. * * @param node [Node] to serialize to JSON. * @return [Node] as JSON. * @throws [com.google.gson.JsonSyntaxException] in case when JSON was malformed. */ @Synchronized fun node(node: Node, pretty: Boolean = false): String { return if(pretty) { prettyGson.toJson(node, Node::class.java) } else { gson.toJson(node, Node::class.java) } } /** * Serialize [Node] to JSON. * * @param nodes [Node] to serialize to JSON. * @return [Node] as JSON. * @throws [com.google.gson.JsonSyntaxException] in case when JSON was malformed. */ @Synchronized fun nodes(nodes: List<Node>, pretty: Boolean = false): String { return if(pretty) { prettyGson.toJson(nodes, listOfNodes) } else { gson.toJson(nodes, listOfNodes) } } /** * Deserialize [Node] from JSON. * * @param json [Node] as JSON. * @return [Node] * @throws [com.google.gson.JsonSyntaxException] in case when JSON was malformed. */ @Synchronized fun nodes(json: String): List<Node> { return gson.fromJson(json, listOfNodes) } }
0
Kotlin
0
3
3dd0fe70e97ed8e7b3ccc38108b31fc2a3995376
3,754
telegraph-cli
MIT License
drm-blockchain/src/main/kotlin/service/LicenseService.kt
Smileslime47
738,883,139
false
null
package moe._47saikyo.service import moe._47saikyo.annotation.ViewFunction import moe._47saikyo.contract.License import moe._47saikyo.models.LicenseData import moe._47saikyo.models.LicenseDeployForm import org.web3j.tx.TransactionManager import java.math.BigInteger /** * 授权合约Service接口 * * @author 刘一邦 */ interface LicenseService { /** * 估算部署合约所需的gas * * @param form 授权部署表单 * @return 估算的gas */ fun estimateDeploy(form: LicenseDeployForm): BigInteger /** * 添加授权合约 * * @param transactionManager 交易管理器 * @param form 授权部署表单 * @return 授权合约 */ fun addLicense( transactionManager: TransactionManager, form: LicenseDeployForm ): License /** * 获取授权合约的纯数据对象 * * @param licenseAddr 授权合约地址 * @return 纯数据对象 */ @ViewFunction fun getPureData( licenseAddr: String ): LicenseData /** * 获取用户的授权 * * @param owner 用户地址 * @return 授权合约列表 */ @ViewFunction fun getLicenses( owner:String ): List<LicenseData> }
0
null
0
2
8ef270753c3f0cc520f0befcde8d60cb97c25f75
1,083
Digital-Rights-Management
MIT License
common/ui-kit/src/main/kotlin/ru/maksonic/beresta/common/ui_kit/widget/trash_screen/TrashModalSheetDeleteDataContent.kt
maksonic
580,058,579
false
{"Kotlin": 1619980}
package ru.maksonic.beresta.common.ui_kit.widget.trash_screen import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import ru.maksonic.beresta.common.ui_kit.icons.AppIcon import ru.maksonic.beresta.common.ui_kit.icons.Close import ru.maksonic.beresta.common.ui_kit.icons.Delete import ru.maksonic.beresta.common.ui_kit.icons.Restart import ru.maksonic.beresta.common.ui_kit.sheet.ModalSheetItem import ru.maksonic.beresta.common.ui_theme.provide.dp24 import ru.maksonic.beresta.language_engine.shell.provider.text /** * @Author maksonic on 20.10.2023 */ @Composable fun TrashModalSheetDeleteDataContent( hideSheet: () -> Unit, onRestoreClicked: () -> Unit, onDeleteClicked: () -> Unit, modifier: Modifier = Modifier ) { Column(modifier) { ModalSheetItem(AppIcon.Restart, text.shared.btnTitleRestore, onRestoreClicked) ModalSheetItem(AppIcon.Delete, text.shared.btnTitleDelete, onDeleteClicked) ModalSheetItem(AppIcon.Close, text.shared.btnTitleClose, hideSheet) Spacer(modifier.size(dp24)) } }
0
Kotlin
0
0
d9a53cc50c6e149923fc5bc6fc2c38013bfadb9d
1,223
Beresta
MIT License
app/src/main/java/com/smallur/feeds/data/source/PostModule.kt
SanjayMallur
163,112,263
false
{"Kotlin": 59882, "Java": 9797}
package com.smallur.feeds.data.source import com.smallur.feeds.data.DataModule import com.smallur.feeds.data.source.remote.ApiClientModule import com.smallur.feeds.data.source.remote.PostApi import com.smallur.feeds.data.source.remote.PostRemoteDataSource import dagger.Module import dagger.Provides import javax.inject.Named import javax.inject.Singleton /** * Created by Sanjay * Post module to provide singleton postData source instance * */ @Module(includes = [((ApiClientModule::class))]) class PostModule { @Provides @Singleton @Named(DataModule.REMOTE) fun postRemoteDataSource(apiClient: PostApi) : PostDataSource{ return PostRemoteDataSource(apiClient) // singleton post remote data source instance } }
0
Kotlin
0
0
af199bf2cc48583fd6cde53d116033c268041e11
744
Recipe-Feed
Apache License 2.0
newsApp/app/src/main/java/com/example/newsapp/app/resources/news/data/repository/NewsRepository.kt
Triunvir4to
829,130,872
false
{"Kotlin": 121321}
package com.example.newsapp.app.resources.news.data.repository import com.example.newsapp.services.api.utils.ApiResponse import com.example.newsapp.app.resources.news.data.response.NewsResponse import com.example.newsapp.app.resources.news.domain.NewsApiCaller import com.example.newsapp.app.resources.news.domain.repository.INewsRepository import javax.inject.Inject import kotlin.coroutines.CoroutineContext class NewsRepository @Inject constructor( override val apiCaller: NewsApiCaller ) : INewsRepository { override suspend fun getNews( language: String?, text: String?, country: String?, context: CoroutineContext ): ApiResponse<NewsResponse> { return if (language != null) apiCaller.getNews( language = language, country = country, context = context ) else apiCaller.getNews( country = country, context = context ) } }
0
Kotlin
0
0
d794ec96b889f1dde8bcfd76aa779d72aabf9c7c
968
Android
MIT License
src/main/kotlin/com/petukhovsky/snake/ws/WSHandler.kt
arthur-snake
114,157,008
false
null
package com.petukhovsky.snake.ws import com.petukhovsky.snake.game.Game import org.springframework.web.socket.CloseStatus import org.springframework.web.socket.TextMessage import org.springframework.web.socket.WebSocketSession import org.springframework.web.socket.handler.TextWebSocketHandler open class SnakeHandler(val game: Game): TextWebSocketHandler() { val map = mutableMapOf<String, WebSnakeSession>() override fun handleTextMessage(session: WebSocketSession, message: TextMessage) { map[session.id]?.onMessage(message.payload) } override fun afterConnectionEstablished(session: WebSocketSession) { map[session.id] = WebSnakeSession(game, session).apply { init() } } override fun afterConnectionClosed(session: WebSocketSession, status: CloseStatus) { map[session.id]?.close() map.remove(session.id) } }
4
Kotlin
0
3
e24da15441f6b6c673d1f1128ced494f4ed3d313
877
server
MIT License
app/src/main/java/com/example/android/guesstheword/Constants.kt
Rdy2code
275,421,395
false
null
package com.example.android.guesstheword import com.example.android.guesstheword.screens.game.GameViewModel const val GameViewModelTag: String = "GameViewModel"
0
Kotlin
0
0
bddcd75b2f3351e51667fdb86a3359c74761a811
162
GuessTheWord
Apache License 2.0
android/khajit/app/src/main/java/com/project/khajit_app/activity/HomeFeedPageGuestActivity.kt
bounswe
170,124,936
false
null
package com.project.khajit_app.activity import android.app.Notification import android.content.Context import android.content.Intent import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.widget.FrameLayout import com.google.android.material.bottomnavigation.BottomNavigationView import androidx.appcompat.app.AppCompatActivity import androidx.fragment.app.Fragment import com.project.khajit_app.R import com.project.khajit_app.activity.ui.article.ListArticleFragment import com.project.khajit_app.activity.ui.equipment.EquipmentFragment import com.project.khajit_app.activity.ui.event.ListEventFragment import com.project.khajit_app.activity.ui.home.HomeFragment import com.project.khajit_app.activity.ui.home.HomeFragmentGuest import com.project.khajit_app.activity.ui.mailbox.MailboxFragment import com.project.khajit_app.activity.ui.notifications.NotificationsFragment import com.project.khajit_app.activity.ui.search.SearchFragment import interfaces.fragmentOperationsInterface class HomeFeedPageGuestActivity : AppCompatActivity() , fragmentOperationsInterface { private var content: FrameLayout? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_home_feed_page_guest) setSupportActionBar(findViewById(R.id.home_top_menu_guest_options_bar)) content = findViewById(R.id.content_guest) val navigation = findViewById<BottomNavigationView>(R.id.nav_view_guest) navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener) //val fragment = HomeFragmentGuest.Companion.newInstance() val fragment = ListArticleFragment.Companion.newInstance(1,0,1,0,-1) /*val user = UserAllInfo( listOf("1","2"), 9, "[email protected]", "cer3", "dardi", "[email protected]", "locationInfo", "905086395214", "0", "", "I am para babasi.", "para baba", "2019-11-24T14:31:15.031985Z")*/ //val article = GeneralArticleModel(1," DENEME TITLE", "ASLJFGHKLJFG",user,true,"2 mayıs") //val fragment = displayArticleFragment.Companion.newInstance(article,1,0,1,0,-1) fragmentTransaction( supportFragmentManager, fragment, content!!.id, true, true, false ) } private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item -> when (item.itemId) { R.id.navigation_home_guest -> { //val fragment = HomeFragmentGuest.Companion.newInstance() val fragment = ListArticleFragment.Companion.newInstance(1,0,1,0,-1) /*val user = UserAllInfo( listOf("1","2"), 9, "[email protected]", "cer3", "dardi", "[email protected]", "locationInfo", "905086395214", "0", "", "I am para babasi.", "para baba", "2019-11-24T14:31:15.031985Z")*/ //val article = GeneralArticleModel(1," DENEME TITLE", "ASLJFGHKLJFG",user,true,"2 mayıs") //val fragment = displayArticleFragment.Companion.newInstance(article,1,0,1,0,-1) fragmentTransaction( supportFragmentManager, fragment, content!!.id, true, true, false ) return@OnNavigationItemSelectedListener true } R.id.navigation_events_guest -> { val fragment = ListEventFragment() fragmentTransaction( supportFragmentManager, fragment, content!!.id, true, true, false ) return@OnNavigationItemSelectedListener true } R.id.navigation_equipments_guest -> { val fragment = EquipmentFragment.newInstance(1) fragmentTransaction( supportFragmentManager, fragment, content!!.id, true, true, false ) return@OnNavigationItemSelectedListener true } } false } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.menu_top_guest, menu) return true } override fun onOptionsItemSelected(item: MenuItem): Boolean = when (item.itemId) { R.id.register_direct_guest -> { startActivity(Intent(this, SignUpPageActivity::class.java)) true } R.id.login_direct_guest -> { startActivity(Intent(this, LoginPageActivity::class.java)) true } else -> super.onOptionsItemSelected(item) } companion object { fun getLaunchIntent(from : Context) = Intent(from, MainPageActivity::class.java).apply { addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK) } } }
32
Kotlin
2
9
9572fd307345b3f842c2c2ff4426857086484ed5
5,422
bounswe2019group1
MIT License
buildSrc/src/main/kotlin/dependency/lib/Work.kt
OmarAliSaid
353,353,985
true
{"Kotlin": 514136, "Ruby": 8743, "Java": 2159}
package dependency.lib import dependency.Dependency object Work : Dependency { override val group = "androidx.work" override val artifact = "work" override val version = "2.5.0" }
0
null
0
0
ed77fc2e0358177e1ebeca1e1ffe3963dd488b7e
195
instantsearch-android
Apache License 2.0
compiler/fir/checkers/checkers.js/src/org/jetbrains/kotlin/fir/analysis/js/checkers/FirJsHelpers.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2022 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ @file:OptIn(SymbolInternals::class) package org.jetbrains.kotlin.fir.analysis.js.checkers import org.jetbrains.kotlin.descriptors.Modality import org.jetbrains.kotlin.descriptors.Visibilities import org.jetbrains.kotlin.fir.FirSession import org.jetbrains.kotlin.fir.analysis.checkers.* import org.jetbrains.kotlin.fir.analysis.checkers.context.CheckerContext import org.jetbrains.kotlin.fir.declarations.* import org.jetbrains.kotlin.fir.declarations.utils.* import org.jetbrains.kotlin.fir.declarations.utils.isExpect import org.jetbrains.kotlin.fir.declarations.utils.isExternal import org.jetbrains.kotlin.fir.isSubstitutionOrIntersectionOverride import org.jetbrains.kotlin.fir.resolve.providers.firProvider import org.jetbrains.kotlin.fir.symbols.FirBasedSymbol import org.jetbrains.kotlin.fir.symbols.SymbolInternals import org.jetbrains.kotlin.fir.symbols.impl.* import org.jetbrains.kotlin.js.PredefinedAnnotation import org.jetbrains.kotlin.js.common.isES5IdentifierPart import org.jetbrains.kotlin.js.common.isES5IdentifierStart import org.jetbrains.kotlin.name.JsStandardClassIds private val FirBasedSymbol<*>.isExternal get() = when (this) { is FirCallableSymbol<*> -> isExternal is FirClassSymbol<*> -> isExternal else -> false } fun FirBasedSymbol<*>.isEffectivelyExternal(session: FirSession): Boolean { if (fir is FirMemberDeclaration && isExternal) return true if (this is FirPropertyAccessorSymbol) { val property = propertySymbol if (property.isEffectivelyExternal(session)) return true } if (this is FirPropertySymbol) { if (getterSymbol?.isExternal == true && (!isVar || setterSymbol?.isExternal == true)) { return true } } return getContainingClassSymbol(session)?.isEffectivelyExternal(session) == true } fun FirBasedSymbol<*>.isEffectivelyExternalMember(session: FirSession): Boolean { return fir is FirMemberDeclaration && isEffectivelyExternal(session) } fun FirBasedSymbol<*>.isEffectivelyExternal(context: CheckerContext) = isEffectivelyExternal(context.session) fun FirFunctionSymbol<*>.isOverridingExternalWithOptionalParams(context: CheckerContext): Boolean { if (!isSubstitutionOrIntersectionOverride && modality == Modality.ABSTRACT) return false val overridden = (this as? FirNamedFunctionSymbol)?.directOverriddenFunctions(context) ?: return false for (overriddenFunction in overridden.filter { it.isEffectivelyExternal(context) }) { if (overriddenFunction.valueParameterSymbols.any { it.hasDefaultValue }) return true } return false } fun FirBasedSymbol<*>.getJsName(session: FirSession): String? { return getAnnotationStringParameter(JsStandardClassIds.Annotations.JsName, session) } fun sanitizeName(name: String): String { if (name.isEmpty()) return "_" val first = name.first().let { if (it.isES5IdentifierStart()) it else '_' } return first.toString() + name.drop(1).map { if (it.isES5IdentifierPart()) it else '_' }.joinToString("") } fun FirBasedSymbol<*>.isNativeObject(session: FirSession): Boolean { if (hasAnnotationOrInsideAnnotatedClass(JsStandardClassIds.Annotations.JsNative, session) || isEffectivelyExternal(session)) { return true } if (this is FirPropertyAccessorSymbol) { val property = propertySymbol return property.hasAnnotationOrInsideAnnotatedClass(JsStandardClassIds.Annotations.JsNative, session) } return false } fun FirBasedSymbol<*>.isNativeInterface(session: FirSession): Boolean { return isNativeObject(session) && (fir as? FirClass)?.isInterface == true } private val FirBasedSymbol<*>.isExpect get() = when (this) { is FirCallableSymbol<*> -> isExpect is FirClassSymbol<*> -> isExpect else -> false } fun FirBasedSymbol<*>.isPredefinedObject(session: FirSession): Boolean { if (fir is FirMemberDeclaration && isExpect) return true if (isEffectivelyExternalMember(session)) return true for (annotation in PredefinedAnnotation.values()) { if (hasAnnotationOrInsideAnnotatedClass(annotation.classId, session)) { return true } } return false } fun FirBasedSymbol<*>.isExportedObject(session: FirSession): Boolean { val declaration = fir if (declaration is FirMemberDeclaration) { val visibility = declaration.visibility if (visibility != Visibilities.Public && visibility != Visibilities.Protected) { return false } } return when { hasAnnotationOrInsideAnnotatedClass(JsStandardClassIds.Annotations.JsExportIgnore, session) -> false hasAnnotationOrInsideAnnotatedClass(JsStandardClassIds.Annotations.JsExport, session) -> true else -> getContainingFile(session)?.hasAnnotation(JsStandardClassIds.Annotations.JsExport, session) == true } } private fun FirBasedSymbol<*>.getContainingFile(session: FirSession): FirFile? { return when (this) { is FirCallableSymbol<*> -> session.firProvider.getFirCallableContainerFile(this) is FirClassLikeSymbol<*> -> session.firProvider.getFirClassifierContainerFileIfAny(this) else -> return null } } fun FirBasedSymbol<*>.isNativeObject(context: CheckerContext) = isNativeObject(context.session) fun FirBasedSymbol<*>.isNativeInterface(context: CheckerContext) = isNativeInterface(context.session) fun FirBasedSymbol<*>.isPredefinedObject(context: CheckerContext) = isPredefinedObject(context.session) fun FirBasedSymbol<*>.isExportedObject(context: CheckerContext) = isExportedObject(context.session)
154
Kotlin
5566
45,025
8a69904d02dd3e40fae5f2a1be4093d44a227788
5,834
kotlin
Apache License 2.0
plugin/src/test/kotlin/no/ntnu/ihb/sspgen/SSPGenPluginTest.kt
SFI-Mechatronics
339,847,573
true
{"Java": 580979, "Kotlin": 47956}
package no.ntnu.ihb.sspgen import org.gradle.testfixtures.ProjectBuilder import org.junit.jupiter.api.Test class SSPGenPluginTest { @Test fun sspgenPluginAddsTaskToProject() { val project = ProjectBuilder.builder().build() project.pluginManager.apply("no.ntnu.ihb.sspgen") } }
0
null
0
0
3a8f0f9da228b34080290d26db4949353bbb2ef9
309
sspgen
MIT License
app/src/main/kotlin/nasa/android/app/NasaBuildConfig.kt
jonapoul
794,260,725
false
{"Kotlin": 393364}
package nasa.android.app import alakazam.android.core.IBuildConfig import android.content.Context import android.os.Build import kotlinx.datetime.Instant import nasa.android.BuildConfig import javax.inject.Inject import nasa.core.ui.R as CoreR /** * Gives other modules access to the app module's build metadata. */ internal class NasaBuildConfig @Inject constructor(context: Context) : IBuildConfig { override val debug = BuildConfig.DEBUG override val applicationId = BuildConfig.APPLICATION_ID override val versionCode = BuildConfig.VERSION_CODE override val versionName = BuildConfig.VERSION_NAME override val buildTime: Instant = BuildConfig.BUILD_TIME override val gitId = BuildConfig.GIT_HASH override val manufacturer: String = Build.MANUFACTURER override val model: String = Build.MODEL override val os = Build.VERSION.SDK_INT override val platform = context.getString(CoreR.string.app_name) override val repoName = "jonapoul/nasa-android" override val repoUrl = "https://github.com/$repoName" }
1
Kotlin
0
1
9a5444ec72b41bcd3c44e0fa7f044fd56e5f16bf
1,033
nasa-android
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/bold/Down.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Bold.Down: ImageVector get() { if (_down != null) { return _down!! } _down = Builder(name = "Down", defaultWidth = 512.0.dp, defaultHeight = 512.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 24.0f) curveToRelative(-1.1f, 0.0f, -2.2f, -0.42f, -3.04f, -1.25f) lineToRelative(-5.98f, -6.0f) curveToRelative(-0.96f, -0.96f, -1.25f, -2.4f, -0.73f, -3.66f) curveToRelative(0.52f, -1.26f, 1.74f, -2.08f, 3.1f, -2.08f) horizontalLineToRelative(1.64f) verticalLineTo(3.5f) curveToRelative(0.0f, -1.93f, 1.57f, -3.5f, 3.5f, -3.5f) horizontalLineToRelative(3.0f) curveToRelative(1.93f, 0.0f, 3.5f, 1.57f, 3.5f, 3.5f) verticalLineToRelative(7.5f) horizontalLineToRelative(1.64f) curveToRelative(1.37f, 0.0f, 2.58f, 0.83f, 3.1f, 2.08f) curveToRelative(0.52f, 1.26f, 0.23f, 2.7f, -0.73f, 3.66f) lineToRelative(-5.97f, 5.99f) reflectiveCurveToRelative(0.0f, 0.0f, 0.0f, 0.0f) curveToRelative(-0.84f, 0.84f, -1.94f, 1.25f, -3.04f, 1.25f) close() moveTo(5.36f, 14.0f) curveToRelative(-0.16f, 0.0f, -0.27f, 0.08f, -0.33f, 0.23f) curveToRelative(-0.06f, 0.15f, -0.04f, 0.28f, 0.08f, 0.4f) lineToRelative(5.98f, 6.0f) curveToRelative(0.5f, 0.5f, 1.32f, 0.5f, 1.83f, 0.0f) lineToRelative(5.97f, -6.0f) curveToRelative(0.12f, -0.12f, 0.14f, -0.25f, 0.08f, -0.4f) reflectiveCurveToRelative(-0.17f, -0.23f, -0.34f, -0.23f) horizontalLineToRelative(-3.13f) curveToRelative(-0.83f, 0.0f, -1.5f, -0.67f, -1.5f, -1.5f) verticalLineTo(3.5f) curveToRelative(0.0f, -0.27f, -0.23f, -0.5f, -0.5f, -0.5f) horizontalLineToRelative(-3.0f) curveToRelative(-0.28f, 0.0f, -0.5f, 0.22f, -0.5f, 0.5f) verticalLineTo(12.5f) curveToRelative(0.0f, 0.83f, -0.67f, 1.5f, -1.5f, 1.5f) horizontalLineToRelative(-3.14f) close() } } .build() return _down!! } private var _down: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,254
icons
MIT License
src/rider/main/kotlin/com/intelligentcomments/core/comments/states/CommentState.kt
aerooneqq
413,810,255
false
{"C#": 669410, "Kotlin": 636063}
package com.intelligentcomments.core.comments.states import com.intelligentcomments.core.settings.CommentsDisplayKind class CommentState { companion object { val defaultInstance = CommentState() } constructor() constructor(displayKind: CommentsDisplayKind) { this.displayKind = displayKind } constructor(snapshot: CommentStateSnapshot) { displayKind = snapshot.displayKind lastRelativeCaretOffsetWithinComment = snapshot.lastRelativeCaretPositionWithinComment } var displayKind = CommentsDisplayKind.Render private set var lastRelativeCaretOffsetWithinComment = 0 val isInRenderMode: Boolean get() = displayKind != CommentsDisplayKind.Code fun setDisplayKind(displayKind: CommentsDisplayKind) { this.displayKind = displayKind } }
0
C#
2
11
90eff49e8f712a51fc07be3b64cca11843371e7f
791
IntelligentComments
MIT License
app/src/main/java/me/spica/weather/view/weather_bg/NowWeatherView.kt
yangSpica27
457,724,719
false
null
package me.spica.weather.view.weather_bg import android.animation.ObjectAnimator import android.animation.ValueAnimator import android.content.Context import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.Path import android.hardware.Sensor import android.hardware.SensorEvent import android.hardware.SensorEventListener import android.util.AttributeSet import android.view.View import android.view.animation.Animation import android.view.animation.LinearInterpolator import androidx.core.content.ContextCompat import me.spica.weather.R import me.spica.weather.common.WeatherType import me.spica.weather.tools.dp /** * 目前的天气 */ open class NowWeatherView { enum class WeatherType() { SUNNY,// 晴朗 CLOUDY,// 多云 RAIN,// 下雨 SNOW,// 下雪 FOG, UNKNOWN,// 无效果 } }
0
Kotlin
0
0
f5b6a083bf0d2188caffaf427394fad21c8251a1
852
SpicaWeather
MIT License
plugins/kotlin/idea/tests/testData/quickfix/deprecatedSymbolUsage/classUsages/qualifiedClassNameInPattern.kt
ingokegel
72,937,917
false
null
// "Replace with 'java.io.File'" "true" @Deprecated("", ReplaceWith("java.io.File")) class OldClass fun foo(): OldClass<caret>? { return null } // FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.replaceWith.DeprecatedSymbolUsageFix
1
null
1
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
244
intellij-community
Apache License 2.0
app/src/main/java/com/kylecorry/trail_sense/tools/weather/infrastructure/persistence/PressureReadingEntity.kt
kylecorry31
215,154,276
false
null
package com.kylecorry.trail_sense.tools.weather.infrastructure.persistence import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import com.kylecorry.sol.units.Coordinate import com.kylecorry.sol.units.Reading import com.kylecorry.trail_sense.tools.weather.domain.RawWeatherObservation import java.time.Instant @Entity( tableName = "pressures" ) data class PressureReadingEntity( @ColumnInfo(name = "pressure") val pressure: Float, @ColumnInfo(name = "altitude") val altitude: Float, @ColumnInfo(name = "altitude_accuracy") val altitudeAccuracy: Float?, @ColumnInfo(name = "temperature") val temperature: Float, @ColumnInfo(name = "humidity") val humidity: Float, @ColumnInfo(name = "time") val time: Long, @ColumnInfo(name = "latitude") val latitude: Double, @ColumnInfo(name = "longitude") val longitude: Double ) { @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "_id") var id: Long = 0 fun toWeatherObservation(): Reading<RawWeatherObservation> { return Reading( RawWeatherObservation( id, pressure, altitude, temperature, altitudeAccuracy, humidity, Coordinate(latitude, longitude) ), Instant.ofEpochMilli(time) ) } companion object { fun from(reading: Reading<RawWeatherObservation>): PressureReadingEntity { return PressureReadingEntity( reading.value.pressure, reading.value.altitude, reading.value.altitudeError, reading.value.temperature, reading.value.humidity ?: 0f, reading.time.toEpochMilli(), reading.value.location.latitude, reading.value.location.longitude ).also { it.id = reading.value.id } } } }
456
null
66
989
41176d17b498b2dcecbbe808fbe2ac638e90d104
1,987
Trail-Sense
MIT License
github-top-contributors-api/src/main/kotlin/com/fabioandreola/github/topcontributors/api/GitHubUserDto.kt
fabioandreola
233,411,103
false
null
package com.fabioandreola.github.topcontributors.api data class GitHubUserDto( val username: String, val location: String?, val url: String, val publicRepositoryCount: Int, val avatarUrl: String)
0
Kotlin
0
1
c815350d9b975b34da523dd75ef3e4ac315dcf8c
237
github-top-contributors-app
MIT License
komapper-core/src/main/kotlin/org/komapper/core/dsl/options/TemplateExecuteOptions.kt
komapper
349,909,214
false
{"Kotlin": 2922039, "Java": 57131}
package org.komapper.core.dsl.options import org.komapper.core.Dialect data class TemplateExecuteOptions( /** * The escape sequence to be used in the LIKE predicate. * If null is returned, the value of [Dialect.escapeSequence] will be used. */ val escapeSequence: String? = DEFAULT.escapeSequence, override val queryTimeoutSeconds: Int? = DEFAULT.queryTimeoutSeconds, override val suppressLogging: Boolean = DEFAULT.suppressLogging, ) : QueryOptions { companion object { val DEFAULT = TemplateExecuteOptions( escapeSequence = null, queryTimeoutSeconds = null, suppressLogging = false, ) } }
11
Kotlin
14
301
9fbc0b5652ee732583e977180cdc493e116e1022
684
komapper
Apache License 2.0
src/iosMain/kotlin/com/outsidesource/oskitcompose/systemui/iOSSystemBars.kt
outsidesource
607,444,788
false
{"Kotlin": 303688}
package com.outsidesource.oskitcompose.systemui import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.remember import androidx.compose.ui.graphics.Color import androidx.compose.ui.interop.LocalUIViewController import com.outsidesource.oskitcompose.uikit.OSUIViewControllerWrapper import platform.UIKit.UIColor @Composable actual fun SystemBarColorEffect( statusBarColor: Color, statusBarIconColor: SystemBarIconColor, navigationBarColor: Color, navigationBarIconColor: SystemBarIconColor, ) { val sbc = rememberSystemBarColorController() DisposableEffect(statusBarColor, statusBarIconColor) { sbc.setStatusBarColor(statusBarColor) sbc.setNavigationBarColor(navigationBarColor) sbc.setStatusBarIconColor(statusBarIconColor) onDispose { } } } @Composable actual fun rememberSystemBarColorController(): ISystemBarColorController { val vc = LocalUIViewController.current.parentViewController return remember { object : ISystemBarColorController { override fun setStatusBarColor(color: Color) { if (vc !is OSUIViewControllerWrapper) return vc.setStatusBarBackground(color) } override fun setStatusBarIconColor(color: SystemBarIconColor) { if (vc !is OSUIViewControllerWrapper) return when (color) { SystemBarIconColor.Unspecified -> {} SystemBarIconColor.Dark -> vc.setStatusBarIconColor(true) SystemBarIconColor.Light -> vc.setStatusBarIconColor(false) } } override fun setNavigationBarColor(color: Color) { if (vc !is OSUIViewControllerWrapper) return vc.setNavigationBarBackground(color) } override fun setNavigationBarIconColor(color: SystemBarIconColor) {} } } }
0
Kotlin
1
6
1944fbf21f17ea550a79d44c52cbf67363125694
1,986
OSKit-Compose-KMP
MIT License
ui/src/main/java/app/allever/android/lib/demo/ui/sticktop/BaseTwoViewStickyTopActivity.kt
devallever
522,186,250
false
null
package app.allever.android.lib.demo.ui.sticktop import android.os.Build import android.view.View import androidx.annotation.RequiresApi import app.allever.android.lib.common.BaseActivity import app.allever.android.lib.demo.databinding.ActivityBaseTwoViewStickyTopBinding import app.allever.android.lib.mvvm.base.BaseViewModel class BaseTwoViewStickyTopActivity : BaseActivity<ActivityBaseTwoViewStickyTopBinding, BaseTwoViewStickyTopViewModel>() { override fun inflateChildBinding() = ActivityBaseTwoViewStickyTopBinding.inflate(layoutInflater) @RequiresApi(Build.VERSION_CODES.M) override fun init() { initTopBar("基础吸顶") var firstViewHeight = 0 binding.firstView.post { firstViewHeight = binding.firstView.height } binding.scrollView.setOnScrollChangeListener(object : View.OnScrollChangeListener { override fun onScrollChange( v: View?, scrollX: Int, scrollY: Int, oldScrollX: Int, oldScrollY: Int ) { if (firstViewHeight == 0) { return } // log("scrollY = $scrollY, firstViewHeight = $firstViewHeight") if (scrollY >= firstViewHeight) { //重点 通过距离变化隐藏内外固定栏实现 binding.tvStickyTopViewFirst.visibility = View.VISIBLE binding.tvStickyTopView.visibility = View.INVISIBLE } else { binding.tvStickyTopViewFirst.visibility = View.INVISIBLE binding.tvStickyTopView.visibility = View.VISIBLE } } }) } } class BaseTwoViewStickyTopViewModel : BaseViewModel() { override fun init() { } }
1
Kotlin
0
3
4616e9458f39380dc44e3e987a2b51fe0ba33a29
1,804
AndroidSampleLibs
Apache License 2.0
src/test/kotlin/no/nav/eessi/pensjon/eux/model/SedP15000Test.kt
navikt
358,172,246
false
null
package no.nav.eessi.pensjon.eux.model import no.nav.eessi.pensjon.eux.model.sed.SED import no.nav.eessi.pensjon.utils.toJson import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test class SedP15000Test { @Test fun `compare SED P15000 to P15000 from json datafile`() { val p15000json = getTestJsonFile("P15000-NAV.json") val p15000sed = SED.fromJson(p15000json) p15000sed.toJson() //hovedperson assertEquals("Mandag", p15000sed.nav?.bruker?.person?.fornavn) assertEquals(null, p15000sed.nav?.bruker?.bank?.konto?.sepa?.iban) assertEquals("21811", p15000sed.nav?.bruker?.person?.foedested?.by) assertEquals("2019-02-01", p15000sed.nav?.krav?.dato) assertEquals("01", p15000sed.nav?.krav?.type) } }
3
Kotlin
0
4
b5d65bb8df9a82e0640e5ba0eaec85e338501802
817
eessi-pensjon-prefill
MIT License
app/src/main/java/hibernate/v2/testyourandroid/ui/info/monitor/MonitorFragment.kt
himphen
369,255,395
false
null
package hibernate.v2.testyourandroid.ui.info.monitor import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.viewpager2.widget.ViewPager2 import com.google.android.material.tabs.TabLayoutMediator import hibernate.v2.testyourandroid.R import hibernate.v2.testyourandroid.databinding.FragmentViewPagerConatinerBinding import hibernate.v2.testyourandroid.ui.base.BaseActivity import hibernate.v2.testyourandroid.ui.base.BaseFragment /** * Created by himphen on 21/5/16. */ class MonitorFragment : BaseFragment<FragmentViewPagerConatinerBinding>() { override fun getViewBinding( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): FragmentViewPagerConatinerBinding = FragmentViewPagerConatinerBinding.inflate(inflater, container, false) override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) activity?.let { activity -> val tabTitles = resources.getStringArray(R.array.test_monitor_tab_title) val adapter = MonitorFragmentPagerAdapter(this) (activity as BaseActivity<*>).supportActionBar?.title = tabTitles[0] viewBinding!!.viewPager.adapter = adapter viewBinding!!.viewPager.offscreenPageLimit = 2 viewBinding!!.viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() { override fun onPageSelected(position: Int) { activity.supportActionBar?.title = (tabTitles[position]) } }) TabLayoutMediator(viewBinding!!.tabLayout, viewBinding!!.viewPager) { tab, position -> tab.customView = adapter.getTabView(position) }.attach() } } }
0
Kotlin
1
0
d9a0966651a1c6c48912b578fff9ade8d84dcb7b
1,885
TestYourAndroid
Apache License 2.0
AndroidStudioSplitRes/approach1/src/main/java/com/example/approach2/ui/search/Search.kt
jhwsx
286,041,929
false
null
package com.example.approach2.ui.search /** * * @author wangzhichao * @since 2021/5/16 */
0
Kotlin
12
14
4f0270c31b0e1d3751f1e15bcc88ac4474b8d17a
94
BlogCodes
Apache License 2.0
composeexample/src/main/java/com/example/composeexample/data/articles/ArticlesRepository.kt
p3ol
808,201,128
false
{"Kotlin": 66254}
package com.example.composeexample.data.articles import com.example.composeexample.model.Article import com.example.composeexample.model.ArticlesFeed import com.example.composeexample.data.Result import kotlinx.coroutines.flow.Flow interface ArticlesRepository { suspend fun getArticle(articleId: String?): Result<Article> suspend fun getArticlesFeed(): Result<ArticlesFeed> fun observeArticlesFeed(): Flow<ArticlesFeed?> }
0
Kotlin
0
0
57f2d7d288ed80a390f851bc023d17c8bdf06247
441
android-access-example
MIT License
app/app/src/main/java/com/example/party_lojo_game/ui/vo/AskTypeVO.kt
ajloinformatico
381,492,665
false
null
package com.example.party_lojo_game.ui.vo import com.example.party_lojo_game.data.AskTypeBO import com.example.party_lojo_game.data.constants.Constants enum class AskTypeVO(type: String) { TITLE(""), BEBE_QUIEN(Constants.BEBE_QUIEN_DTO_TYPE), YO_NUNCA(Constants.YO_NUNCA_DTO_TYPE), VERDAD_O_RETO(Constants.VERDAD_O_RETO_TYPE), UNKNONW("") } fun AskTypeVO.toBO(): AskTypeBO = when (this) { AskTypeVO.BEBE_QUIEN -> AskTypeBO.BEBE_QUIEN AskTypeVO.YO_NUNCA -> AskTypeBO.YO_NUNCA AskTypeVO.VERDAD_O_RETO -> AskTypeBO.VERDAD_O_RETO else -> AskTypeBO.UNKNOWN }
0
Kotlin
0
0
8662a2d6824930a5dac2a5c1f83a867b72fa9972
593
party-lojo-game
MIT License
src/main/kotlin/Main.kt
Trilgon
484,536,097
false
{"Kotlin": 2146}
import java.util.* fun main(args: Array<String>) { val input: StringBuilder = StringBuilder("10.3 + -2") val queueNumbers: Queue<Double> = LinkedList<Double>() val queueActions: Queue<Char> = LinkedList<Char>() println('\"' + input.toString() + '\"') prepareIn(input, queueNumbers, queueActions) calculateIn(queueNumbers, queueActions) } fun prepareIn(input: StringBuilder, queueNumbers: Queue<Double>, queueActions: Queue<Char>) { var numDetected = false var startIndex = 0 val trimmedIn = input.filter { !it.isWhitespace() } for (i in 0..trimmedIn.lastIndex) { when { trimmedIn[i].isDigit() && !numDetected -> { startIndex = i numDetected = true } !trimmedIn[i].isDigit() && numDetected && trimmedIn[i] != '.' -> { queueNumbers.add(trimmedIn.substring(startIndex, i).toDouble()) queueActions.add(trimmedIn[i]) numDetected = false } !trimmedIn[i].isDigit() && !numDetected && trimmedIn[i] == '-' -> { startIndex = i numDetected = true } } } if (numDetected) { queueNumbers.add(trimmedIn.substring(startIndex..trimmedIn.lastIndex).toDouble()) } println(queueNumbers) println(queueActions) } fun calculateIn(queueNumbers: Queue<Double>, queueActions: Queue<Char>) { var action: Char var result = queueNumbers.poll() var operand: Double while (!queueNumbers.isEmpty()) { operand = queueNumbers.poll() action = queueActions.poll() when (action) { '-' -> result -= operand '+' -> result += operand '*' -> result *= operand '/' -> result /= operand '%' -> result = result % operand * -1.0 } } var pointNum = 8.3 println("pointNum = " + pointNum) println(if(pointNum.compareTo(pointNum.toInt()) == 0) pointNum.toInt() else pointNum) println("result = " + result) println(if(result.compareTo(result.toInt()) == 0) result.toInt() else result) }
0
Kotlin
0
0
8273ff6e20072015b01a1b8ba3432b8e17728601
2,146
LearningKotlin
MIT License
android-studio-projects/SpotifyApiTest/app/src/main/java/com/crazyj36/spotifyapitest/MainActivity.kt
CrazyJ36
186,721,837
false
{"Text": 23, "Ignore List": 56, "Markdown": 5, "Makefile": 3, "C": 34, "Shell": 699, "Python": 5, "Ruby": 3, "Git Attributes": 1, "RPM Spec": 1, "YAML": 2, "Diff": 881, "C++": 3, "PowerShell": 1, "Dockerfile": 1, "Roff Manpage": 3, "Emacs Lisp": 1, "Vim Script": 3, "XML": 415, "Java": 87, "JSON": 13, "Gradle": 35, "Java Properties": 34, "Batchfile": 20, "Proguard": 12, "Kotlin": 28, "Gradle Kotlin DSL": 24, "EditorConfig": 1, "TOML": 1, "INI": 3}
package com.crazyj36.spotifyapitest import android.app.Activity import android.os.Bundle import android.widget.Button import android.widget.TextView import android.widget.Toast import com.spotify.android.appremote.api.ConnectionParams import com.spotify.android.appremote.api.Connector import com.spotify.android.appremote.api.SpotifyAppRemote import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import okhttp3.OkHttpClient import okhttp3.Request import java.io.IOException import java.util.Timer import java.util.TimerTask class MainActivity : Activity() { private var globalSpotifyAppRemote: SpotifyAppRemote? = null private var isPaused: Boolean? = null private var timer: Timer? = null private lateinit var pauseButton: Button private lateinit var resumeButton: Button private lateinit var artistInfoString: String override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) pauseButton = findViewById(R.id.pauseButton) resumeButton = findViewById(R.id.resumeButton) val followersTextView: TextView = findViewById(R.id.followersTextView) val okHttpClient = OkHttpClient() try { val request = Request.Builder() .url("https://api.spotify.com/v1/artist/02UTIVsX3sxUEjvIONrzFe") .addHeader("myHeader","Authorization: Bearer BQCbnwqEc7zFZ9mFfQ7v8PB3GJi79lfpzNYB8hRkZ3Q2GOqms8pN4Xa5ZADkKXSSMfHvZ4ipJLxcZklNypnQ_WIVRHfoO0ACFUbIUmnlE0ZjR0toGgU") .build() CoroutineScope(Dispatchers.IO).launch { artistInfoString = okHttpClient .newCall(request).execute().body!!.string() while (!this@MainActivity::artistInfoString.isInitialized) { delay(100) } runOnUiThread { followersTextView.text = artistInfoString } } } catch (exception: IOException) { Toast.makeText( applicationContext, exception.localizedMessage, Toast.LENGTH_LONG ).show() } pauseButton.setOnClickListener { if (globalSpotifyAppRemote != null) { if (isPaused != null) { if (!isPaused!!) { globalSpotifyAppRemote!!.playerApi.pause() } } } } resumeButton.setOnClickListener { if (globalSpotifyAppRemote != null) { if (isPaused != null) { if (isPaused!!) { globalSpotifyAppRemote!!.playerApi.resume() } } } } } override fun onResume() { super.onResume() SpotifyAppRemote.connect( this, ConnectionParams.Builder( "9730141f6f79463282864c10a0bb008d" ) .setRedirectUri("http://localhost:8080") .showAuthView(true) .build(), object : Connector.ConnectionListener { override fun onConnected(connectedSpotifyAppRemote: SpotifyAppRemote) { globalSpotifyAppRemote = connectedSpotifyAppRemote Toast.makeText( applicationContext, "Connected Spotify App Remote", Toast.LENGTH_SHORT ).show() connectedSpotifyAppRemote.playerApi.play( "spotify:playlist:29Q1fd9uetB3q306eWWsK0?si=8c5024b00d4b4ed2" ) globalSpotifyAppRemote!!.playerApi .subscribeToPlayerState() .setEventCallback { isPaused = it.isPaused } } override fun onFailure(error: Throwable) { Toast.makeText( applicationContext, "Failed To Connect Spotify App Remote:\n" + error.message, Toast.LENGTH_SHORT ).show() } } ) timer = Timer() timer!!.schedule(object : TimerTask() { override fun run() { if (this@MainActivity::pauseButton.isInitialized && this@MainActivity::resumeButton.isInitialized ) { if (isPaused != null) { if (isPaused!!) { runOnUiThread { pauseButton.isEnabled = false resumeButton.isEnabled = true } } else { runOnUiThread { pauseButton.isEnabled = true resumeButton.isEnabled = false } } } } } }, 0, 10) } override fun onPause() { super.onPause() if (globalSpotifyAppRemote != null) { Toast.makeText( applicationContext, "Disconnecting Spotify Remote.", Toast.LENGTH_SHORT ).show() SpotifyAppRemote.disconnect(globalSpotifyAppRemote) globalSpotifyAppRemote = null } if (timer != null) { timer!!.cancel() timer!!.purge() timer = null } if (isPaused != null) isPaused = null } override fun onDestroy() { super.onDestroy() if (globalSpotifyAppRemote != null) { Toast.makeText( applicationContext, "Disconnecting Spotify Remote.", Toast.LENGTH_SHORT ).show() SpotifyAppRemote.disconnect(globalSpotifyAppRemote) globalSpotifyAppRemote = null } if (timer != null) { timer!!.cancel() timer!!.purge() timer = null } if (isPaused != null) isPaused = null } }
1
null
1
1
7d0b28a0987c266cfc4db1dceabd97264a00b1c1
6,399
android
MIT License
src/main/kotlin/no/nav/tiltaksarrangor/model/Veiledertype.kt
navikt
616,496,742
false
{"Kotlin": 436831, "PLpgSQL": 635, "Dockerfile": 96}
package no.nav.tiltaksarrangor.model enum class Veiledertype { VEILEDER, MEDVEILEDER }
1
Kotlin
0
2
b9badb943a716011f853027397f8c278130bdae8
89
amt-tiltaksarrangor-bff
MIT License
lib/src/apiTest/kotlin/com/lemonappdev/konsist/architecture/assertarchitecture/architecture5/project/presentation/sample/PresentationSecondClass.kt
LemonAppDev
621,181,534
false
{"Kotlin": 5054558, "Python": 46133}
package com.lemonappdev.konsist.architecture.assertarchitecture.architecture5.project.presentation.sample import com.lemonappdev.konsist.architecture.assertarchitecture.architecture5.project.presentation.PresentationFirstClass class PresentationSecondClass( val sampleParameter: PresentationFirstClass, )
6
Kotlin
27
1,141
696b67799655e2154447ab45f748e983d8bcc1b5
311
konsist
Apache License 2.0
base/src/main/java/com/example/base/utils/ToastUtils.kt
Flany
319,829,284
false
null
package com.example.base.utils import android.os.Handler import android.os.Looper import android.widget.Toast import com.example.base.SyAppConfig object ToastUtils { fun toast(msg: String) { kotlin.runCatching { if (Looper.myLooper() == Looper.getMainLooper()) { Toast.makeText(SyAppConfig.applicationContext, msg, Toast.LENGTH_SHORT).show() } else { Handler(Looper.getMainLooper()).post { Toast.makeText(SyAppConfig.applicationContext, msg, Toast.LENGTH_SHORT).show() } } } } }
0
Kotlin
0
1
efd2d3630ff139073a6209fc250848ebd0a13487
609
ShuyiApp
Apache License 2.0
domain/src/main/java/org/lotka/xenon/domain/model/CardModel.kt
armanqanih
860,856,530
false
{"Kotlin": 162391}
package org.lotka.xenon.domain.model data class CardModel( val categoryId: String, val title: String, val price: Double, val picUrl: String, val rating: Double? = null, val isOptionRevealed: Boolean = false, )
0
Kotlin
0
0
420b3b63a22ec3dd38e99a9bd4eb11a250af0e4b
238
ModernNews
Apache License 2.0
domain/src/main/java/org/lotka/xenon/domain/model/CardModel.kt
armanqanih
860,856,530
false
{"Kotlin": 162391}
package org.lotka.xenon.domain.model data class CardModel( val categoryId: String, val title: String, val price: Double, val picUrl: String, val rating: Double? = null, val isOptionRevealed: Boolean = false, )
0
Kotlin
0
0
420b3b63a22ec3dd38e99a9bd4eb11a250af0e4b
238
ModernNews
Apache License 2.0
app/src/main/java/com/youtubedl/data/local/room/dao/ConfigDao.kt
bolucci
163,008,789
true
{"Kotlin": 69335}
package com.youtubedl.data.local.room.dao /** * Created by cuongpm on 12/8/18. */
0
Kotlin
0
0
23dce9413edce6691d464eb9bd245dae51b36d01
84
youtube-dl-android
MIT License
app/src/main/java/com/egoriku/animatedbottomsheet/bottomsheet/expanded/SheetExpanded.kt
egorikftp
393,629,785
false
{"Kotlin": 23199}
package com.example.mymusic.presentation.player import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier @Composable fun SheetExpanded( content: @Composable BoxScope.() -> Unit ) { Box( modifier = Modifier .fillMaxSize() .background(MaterialTheme.colors.primary) ) { content() } }
0
Kotlin
10
54
aa9c664ccee0545879ff7beb098a771aff4bfd52
604
compose-animated-bottomsheet
Apache License 2.0
telegram-bot-core/src/main/kotlin/io/github/dehuckakpyt/telegrambot/model/telegram/SentWebAppMessage.kt
DEHuckaKpyT
670,859,055
false
{"Kotlin": 1719026}
package io.github.dehuckakpyt.telegrambot.model.telegram import com.fasterxml.jackson.`annotation`.JsonProperty import kotlin.String /** * Created on 03.06.2024. * * Describes an inline message sent by a [Web App](https://core.telegram.org/bots/webapps) on behalf * of a user. * * @see [SentWebAppMessage] (https://core.telegram.org/bots/api/#sentwebappmessage) * * @author KScript * * @param inlineMessageId *Optional*. Identifier of the sent inline message. Available only if there * is an [inline keyboard](https://core.telegram.org/bots/api/#inlinekeyboardmarkup) attached to the * message. */ public data class SentWebAppMessage( /** * *Optional*. Identifier of the sent inline message. Available only if there is an [inline * keyboard](https://core.telegram.org/bots/api/#inlinekeyboardmarkup) attached to the message. */ @get:JsonProperty("inline_message_id") @param:JsonProperty("inline_message_id") public val inlineMessageId: String? = null, )
1
Kotlin
3
24
5912e61857da3f63a7bb383490730f47f7f1f8c6
1,000
telegram-bot
Apache License 2.0
core/src/main/kotlin/me/shkschneider/skeleton/javax/Randomizer.kt
shkschneider
11,576,696
false
null
package me.shkschneider.skeleton.javax import androidx.annotation.IntRange import me.shkschneider.skeleton.helperx.Logger import me.shkschneider.skeleton.java.StringHelper import java.util.Random object Randomizer { fun binary(): Boolean { return Math.random() < 0.5 } fun string(@IntRange(from = 0) length: Int, characters: String = StringHelper.HEX): String { val random = Random() val stringBuilder = StringBuilder() for (i in 0 until length) { stringBuilder.append(characters[random.nextInt(characters.length)]) } return stringBuilder.toString() } fun inclusive(min: Int, max: Int): Int { if (min > max) { Logger.warning("MIN was greater than MAX") return -1 } if (min == max) { Logger.info("MIN was equal to MAX") return min } return min + (Math.random() * (max - min + 1)).toInt() } fun exclusive(min: Int, max: Int): Int { return inclusive(min + 1, max - 1) } }
0
Kotlin
12
25
ef82d0b963a7ec7a3210fa396a2ecc6358e42d26
1,064
android_Skeleton
Apache License 2.0
app/src/main/java/com/kumcompany/uptime/presentation/screens/details/DetailsContent.kt
pluzarev-nemanja
769,557,772
false
{"Kotlin": 106416}
package com.kumcompany.uptime.presentation.screens.details import android.app.Activity import androidx.compose.animation.core.animateDpAsState import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.BottomSheetScaffold import androidx.compose.material.BottomSheetScaffoldState import androidx.compose.material.BottomSheetValue import androidx.compose.material.ContentAlpha import androidx.compose.material.ExperimentalMaterialApi import androidx.compose.material.Icon import androidx.compose.material.IconButton import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Close import androidx.compose.material.rememberBottomSheetScaffoldState import androidx.compose.material.rememberBottomSheetState import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.SideEffect import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.alpha import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.lifecycle.Lifecycle import androidx.navigation.NavHostController import coil.compose.AsyncImage import coil.request.ImageRequest import com.kumcompany.uptime.R import com.kumcompany.uptime.domain.model.Watch import com.kumcompany.uptime.presentation.components.InfoBox import com.kumcompany.uptime.presentation.components.SpecificationsBoxes import com.kumcompany.uptime.util.Constants.BASE_URL @OptIn(ExperimentalMaterialApi::class) @Composable fun DetailsContent( navController: NavHostController, selectedWatch: Watch?, colors: Map<String, String> ) { val scaffoldState = rememberBottomSheetScaffoldState( bottomSheetState = rememberBottomSheetState(initialValue = BottomSheetValue.Expanded) ) val currentSheetFraction = scaffoldState.currentSheetFraction val activity = LocalContext.current as Activity var vibrant by remember { mutableStateOf("#000000") } var darkVibrant by remember { mutableStateOf("#000000") } var onDarkVibrant by remember { mutableStateOf("#ffffff") } LaunchedEffect(key1 = selectedWatch) { vibrant = colors["vibrant"]!! darkVibrant = colors["darkVibrant"]!! onDarkVibrant = colors["onDarkVibrant"]!! } SideEffect { activity.window.statusBarColor = Color(android.graphics.Color.parseColor(darkVibrant)).toArgb() } val radiusAnim by animateDpAsState( targetValue = if (currentSheetFraction == 1f) 40.dp else 0.dp, label = "" ) BottomSheetScaffold( sheetContent = { selectedWatch?.let { BottomSheetContent( selectedWatch = it, infoBoxIconColor = Color(android.graphics.Color.parseColor(onDarkVibrant)), sheetBackgroundColor = Color(android.graphics.Color.parseColor(darkVibrant)), contentColor = Color(android.graphics.Color.parseColor(onDarkVibrant)) ) } }, scaffoldState = scaffoldState, sheetPeekHeight = 130.dp, sheetShape = RoundedCornerShape(topStart = radiusAnim, topEnd = radiusAnim), ) { selectedWatch?.let { watch -> BackgroundContent( watchImage = watch.image, imageFraction = currentSheetFraction, onCloseClicked = { if(navController.currentBackStackEntry?.lifecycle?.currentState == Lifecycle.State.RESUMED){ navController.popBackStack() } }, backGroundColor = Color(android.graphics.Color.parseColor(darkVibrant)) ) } } } @Composable fun BackgroundContent( watchImage: String, imageFraction: Float, backGroundColor: Color = MaterialTheme.colors.surface, onCloseClicked: () -> Unit ) { val imageUrl = "$BASE_URL${watchImage}" Box( modifier = Modifier .fillMaxSize() .background(backGroundColor) ) { AsyncImage( model = ImageRequest.Builder(LocalContext.current) .data(imageUrl) .placeholder(R.drawable.placeholder) .build(), contentDescription = "", contentScale = ContentScale.Crop, modifier = Modifier .fillMaxWidth() .fillMaxHeight(fraction = imageFraction + 0.45f) .align(Alignment.TopStart), ) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End ) { IconButton( modifier = Modifier.padding(10.dp), onClick = { onCloseClicked() } ) { Icon( modifier = Modifier.size(32.dp), imageVector = Icons.Filled.Close, contentDescription = "Close icon", tint = Color.White ) } } } } @Composable fun BottomSheetContent( selectedWatch: Watch, infoBoxIconColor: Color = MaterialTheme.colors.primary, sheetBackgroundColor: Color = MaterialTheme.colors.surface, contentColor: Color = MaterialTheme.colors.onBackground ) { Column( modifier = Modifier .background(sheetBackgroundColor) .padding(20.dp) ) { Row( modifier = Modifier .fillMaxWidth() .padding(bottom = 20.dp), verticalAlignment = Alignment.CenterVertically ) { Icon( modifier = Modifier .size(32.dp) .weight(2f), painter = painterResource(id = R.drawable.time), contentDescription = "", tint = contentColor ) Text( modifier = Modifier.weight(8f), text = selectedWatch.model, color = contentColor, fontSize = MaterialTheme.typography.h6.fontSize, fontWeight = FontWeight.Bold, overflow = TextOverflow.Ellipsis, maxLines = 1 ) } Row( modifier = Modifier .fillMaxWidth() .padding(8.dp), horizontalArrangement = Arrangement.SpaceBetween ) { InfoBox( icon = painterResource(id = R.drawable.casediameter), iconColor = infoBoxIconColor, bigText = "${selectedWatch.caseDiameter} mm", smallText = "Diameter", textColor = contentColor ) InfoBox( icon = painterResource(id = R.drawable.powerreserve), iconColor = infoBoxIconColor, bigText = "${selectedWatch.powerReserve} Hours", smallText = "Power", textColor = contentColor ) InfoBox( icon = painterResource(id = R.drawable.waterresistance), iconColor = infoBoxIconColor, bigText = selectedWatch.waterResistance, smallText = "Resistance", textColor = contentColor ) } Spacer(modifier = Modifier.height(4.dp)) Text( modifier = Modifier.fillMaxWidth(), text = "About", fontSize = MaterialTheme.typography.h6.fontSize, color = contentColor, fontWeight = FontWeight.Bold ) Text( modifier = Modifier .alpha(ContentAlpha.medium) .padding(bottom = 10.dp), text = selectedWatch.description, fontSize = MaterialTheme.typography.body1.fontSize, color = contentColor, maxLines = 5, overflow = TextOverflow.Ellipsis ) Spacer(modifier = Modifier.height(8.dp)) SpecificationsBoxes( selectedWatch, infoBoxIconColor, contentColor ) } } @OptIn(ExperimentalMaterialApi::class) val BottomSheetScaffoldState.currentSheetFraction: Float get() { val fraction = bottomSheetState.progress val targetValue = bottomSheetState.targetValue val currentValue = bottomSheetState.currentValue return when { currentValue == BottomSheetValue.Collapsed && targetValue == BottomSheetValue.Collapsed -> 1f currentValue == BottomSheetValue.Expanded && targetValue == BottomSheetValue.Expanded -> 0f currentValue == BottomSheetValue.Collapsed && targetValue == BottomSheetValue.Expanded -> 1f - fraction currentValue == BottomSheetValue.Expanded && targetValue == BottomSheetValue.Collapsed -> 0f + fraction else -> fraction } }
0
Kotlin
0
0
3f623c7f1bc334327b461e1af7026d454efe62dd
10,174
UpTime
MIT License
HdatePicker/src/main/java/com/mgragab/hdatepicker/HorizontalPicker.kt
MGRagab
406,916,461
false
{"Kotlin": 20336}
package com.mgragab.hdatepicker import android.content.Context import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.util.AttributeSet import android.view.View import android.widget.LinearLayout import android.widget.TextView import androidx.annotation.ColorInt import org.joda.time.DateTime /** * Created By MGRagab 15/09/2021 */ class HorizontalPicker : LinearLayout, HorizontalPickerListener { private lateinit var vHover: View private lateinit var tvMonth: TextView private lateinit var tvToday: TextView private lateinit var listener: DatePickerListener private lateinit var monthListener: OnTouchListener private lateinit var rvDays: HorizontalPickerRecyclerView var days = 0 private set var offset = 0 private set private var mDateSelectedColor = -1 private var mDateSelectedTextColor = -1 private var mMonthAndYearTextColor = -1 private var mTodayButtonTextColor = -1 private var showTodayButton = true private var mMonthPattern = "" private var mTodayDateTextColor = -1 private var mTodayDateBackgroundColor = -1 private var mDayOfWeekTextColor = -1 private var mUnselectedDayTextColor = -1 constructor(context: Context) : super(context) { internInit() } constructor(context: Context, attrs: AttributeSet) : super(context, attrs) { internInit() } constructor(context: Context, attrs: AttributeSet, defStyle: Int) : super( context, attrs, defStyle ) { internInit() } private fun internInit() { days = NO_SETTED offset = NO_SETTED } fun setListener(listener: DatePickerListener): HorizontalPicker { this.listener = listener return this } fun setMonthListener(listener: OnTouchListener): HorizontalPicker { monthListener = listener return this } fun setDate(date: DateTime) { rvDays.post { rvDays.setDate(date) } } fun init() { inflate(context, R.layout.horizontal_picker, this) rvDays = findViewById<View>(R.id.rvDays) as HorizontalPickerRecyclerView val DEFAULT_DAYS_TO_PLUS = 120 val finalDays = if (days == NO_SETTED) DEFAULT_DAYS_TO_PLUS else days val DEFAULT_INITIAL_OFFSET = 7 val finalOffset = if (offset == NO_SETTED) DEFAULT_INITIAL_OFFSET else offset vHover = findViewById(R.id.vHover) tvMonth = findViewById<View>(R.id.tvMonth) as TextView if (this::monthListener.isInitialized) { tvMonth.isClickable = true tvMonth.setOnTouchListener(monthListener) } tvToday = findViewById<View>(R.id.tvToday) as TextView rvDays.setListener(this) tvToday.setOnClickListener(rvDays) tvMonth.setTextColor( if (mMonthAndYearTextColor != -1) mMonthAndYearTextColor else getColor( R.color.primaryTextColor ) ) tvToday.visibility = if (showTodayButton) VISIBLE else INVISIBLE tvToday.setTextColor( if (mTodayButtonTextColor != -1) mTodayButtonTextColor else getColor( R.color.colorPrimary ) ) val mBackgroundColor = backgroundColor setBackgroundColor(if (mBackgroundColor != Color.TRANSPARENT) mBackgroundColor else Color.WHITE) mDateSelectedColor = if (mDateSelectedColor == -1) getColor(R.color.colorPrimary) else mDateSelectedColor mDateSelectedTextColor = if (mDateSelectedTextColor == -1) Color.WHITE else mDateSelectedTextColor mTodayDateTextColor = if (mTodayDateTextColor == -1) getColor(R.color.primaryTextColor) else mTodayDateTextColor mDayOfWeekTextColor = if (mDayOfWeekTextColor == -1) getColor(R.color.secundaryTextColor) else mDayOfWeekTextColor mUnselectedDayTextColor = if (mUnselectedDayTextColor == -1) getColor(R.color.primaryTextColor) else mUnselectedDayTextColor rvDays.init( context, finalDays, finalOffset, mBackgroundColor, mDateSelectedColor, mDateSelectedTextColor, mTodayDateTextColor, mTodayDateBackgroundColor, mDayOfWeekTextColor, mUnselectedDayTextColor ) } private fun getColor(colorId: Int): Int { return resources.getColor(colorId) } private val backgroundColor: Int get() { var color = Color.TRANSPARENT val background = background if (background is ColorDrawable) color = background.color return color } override fun post(action: Runnable): Boolean { return rvDays.post(action) } override fun onStopDraggingPicker() { if (vHover.visibility == VISIBLE) vHover.visibility = INVISIBLE } override fun onDraggingPicker() { if (vHover.visibility == INVISIBLE) vHover.visibility = VISIBLE } override fun onDateSelected(item: Day) { tvMonth.text = item.getMonth(mMonthPattern) if (showTodayButton) tvToday.visibility = if (item.isToday()) INVISIBLE else VISIBLE if (this::listener.isInitialized) { listener.onDateSelected(item.getDate()) } } fun setDays(days: Int): HorizontalPicker { this.days = days return this } fun setOffset(offset: Int): HorizontalPicker { this.offset = offset return this } fun setDateSelectedColor(@ColorInt color: Int): HorizontalPicker { mDateSelectedColor = color return this } fun setDateSelectedTextColor(@ColorInt color: Int): HorizontalPicker { mDateSelectedTextColor = color return this } fun setMonthAndYearTextColor(@ColorInt color: Int): HorizontalPicker { mMonthAndYearTextColor = color return this } fun setTodayButtonTextColor(@ColorInt color: Int): HorizontalPicker { mTodayButtonTextColor = color return this } fun showTodayButton(show: Boolean): HorizontalPicker { showTodayButton = show return this } fun setTodayDateTextColor(color: Int): HorizontalPicker { mTodayDateTextColor = color return this } fun setTodayDateBackgroundColor(@ColorInt color: Int): HorizontalPicker { mTodayDateBackgroundColor = color return this } fun setDayOfWeekTextColor(@ColorInt color: Int): HorizontalPicker { mDayOfWeekTextColor = color return this } fun setUnselectedDayTextColor(@ColorInt color: Int): HorizontalPicker { mUnselectedDayTextColor = color return this } fun setMonthPattern(pattern: String): HorizontalPicker { mMonthPattern = pattern return this } companion object { private const val NO_SETTED = -1 } }
0
Kotlin
0
0
6f0b5f32224766d9a6a44d4be51276a17f286ff5
6,989
HorizontalDatePicker
Apache License 2.0
app/src/main/java/com/io/gazette/domain/useCases/MainViewModelUseCases.kt
efe-egbevwie
475,847,896
false
null
package com.io.gazette.domain.useCases import com.io.gazette.data.repositories.NytRepository data class MainViewModelUseCases( val getBusinessUseCase: GetBusinessNewsUseCase, val getHealthNewsUseCase: GetHealthNewsUseCase, val getSportsNewsUseCase: GetSportsNewsUseCase, val getWorldNewsUseCase: GetWorldNewsUseCase )
0
Kotlin
1
0
504e0101a061763e3b8b375ac627b45940601ed8
335
Gazette
The Unlicense
arcade-resource-pack/src/main/kotlin/net/casual/arcade/resources/extensions/PlayerPackExtension.kt
CasualChampionships
621,955,934
false
{"Kotlin": 1016654, "Java": 185854, "GLSL": 4396}
package net.casual.arcade.resources.extensions import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap import net.casual.arcade.events.GlobalEventHandler import net.casual.arcade.extensions.Extension import net.casual.arcade.resources.event.ClientPackSuccessEvent import net.casual.arcade.resources.event.PlayerPackSuccessEvent import net.casual.arcade.resources.pack.PackInfo import net.casual.arcade.resources.pack.PackState import net.casual.arcade.resources.pack.PackStatus import net.casual.arcade.utils.ArcadeUtils import net.casual.arcade.utils.PlayerUtils.player import net.minecraft.network.protocol.common.ClientboundResourcePackPopPacket import net.minecraft.network.protocol.common.ClientboundResourcePackPushPacket import net.minecraft.server.MinecraftServer import java.util.* import java.util.concurrent.CompletableFuture import kotlin.jvm.optionals.getOrNull internal class PlayerPackExtension(private val uuid: UUID): Extension { internal val futures = Object2ObjectOpenHashMap<UUID, CompletableFuture<PackStatus>>() private val packs = Object2ObjectOpenHashMap<UUID, PackState>() internal var allLoadedFuture = CompletableFuture<Void>() internal fun getPackState(uuid: UUID): PackState? { return this.packs[uuid] } internal fun getAllPacks(): Collection<PackState> { return this.packs.values } internal fun addFuture(uuid: UUID): CompletableFuture<PackStatus> { if (this.allLoadedFuture.isDone) { this.allLoadedFuture = CompletableFuture() } return this.futures.getOrPut(uuid) { CompletableFuture() } } internal fun onPackStatus(server: MinecraftServer, uuid: UUID, status: PackStatus) { if (status == PackStatus.REMOVED) { if (this.packs.remove(uuid) != null) { ArcadeUtils.logger.warn("Client removed resource pack without server telling it to!") } this.futures.remove(uuid)?.complete(status) this.checkAllFutures(server) return } val state = this.packs[uuid] if (state == null) { ArcadeUtils.logger.warn("Client is using server resource pack that server is unaware of!?") return } state.setStatus(status) if (!status.isLoadingPack()) { this.futures[uuid]?.complete(status) this.checkAllFutures(server) } } internal fun onPushPack(packet: ClientboundResourcePackPushPacket) { val info = PackInfo(packet.url, packet.hash, packet.required, packet.prompt.getOrNull(), packet.id) val state = PackState(info, PackStatus.WAITING) this.packs[info.uuid] = state this.addFuture(packet.id) } internal fun onPopPack(packet: ClientboundResourcePackPopPacket) { val uuid = packet.id if (uuid.isEmpty) { this.packs.clear() return } this.packs.remove(uuid.get()) } private fun checkAllFutures(server: MinecraftServer) { for (future in this.futures.values) { if (!future.isDone) { return } } this.allLoadedFuture.complete(null) GlobalEventHandler.broadcast(ClientPackSuccessEvent(this.uuid, this.getAllPacks())) val player = server.player(this.uuid) if (player != null) { GlobalEventHandler.broadcast(PlayerPackSuccessEvent(player, this.getAllPacks())) } } }
1
Kotlin
1
2
4f9137a8cedc795a2d01c9fdf1dc292c4f88bced
3,484
arcade
MIT License
app/src/main/java/com/example/appName/common/di/FragmentInjector.kt
kubak89
141,586,462
false
null
package com.example.appName.common.di import com.example.appName.presentation.sum.calculation.CalculationFragment import com.example.appName.presentation.sum.calculation.CalculationModule import dagger.Module import dagger.android.ContributesAndroidInjector @Module abstract class FragmentInjector { @ContributesAndroidInjector(modules = [CalculationModule::class]) abstract fun bindCalculationFragment(): CalculationFragment }
0
Kotlin
1
0
e61f418e10f9a3f4e3a01e6904af13834765e3bb
438
Mvi-Android-Example
MIT License
screenshot/src/main/java/koderlabs/com/screenshot/ScreenShotContentObserver.kt
Anum-Shafiq
212,086,813
false
{"Gradle": 4, "Java Properties": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 2, "Java": 2, "XML": 14, "Kotlin": 5}
package koderlabs.com.screenshotnotifier /** * This class is used to observe the screenShot event triggered and notify the user using LiveData * * @author * <NAME> * Koderlabs * Kotlin Android Developer */ import android.content.Context import android.database.ContentObserver import android.database.Cursor import android.net.Uri import android.os.Handler import android.provider.MediaStore import androidx.lifecycle.MutableLiveData import java.io.File class ScreenShotContentObserver(handler: Handler, private val context: Context?) : ContentObserver(handler) { private var isFromEdit = false private var previousPath: String? = null val screenShot: MutableLiveData<Boolean> = MutableLiveData() override fun onChange(selfChange: Boolean, uri: Uri) { var cursor: Cursor? = null try { cursor = context?.contentResolver?.query( uri, arrayOf(MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATA), null, null, null ) if (cursor != null && cursor.moveToLast()) { val dataColumnIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA) val path = cursor.getString(dataColumnIndex) if (File(path).lastModified() >= System.currentTimeMillis() - 10000) { if (isScreenshot(path) && !isFromEdit && !(previousPath != null && previousPath == path)) { // Timber.i("screenShot Live Event called") screenShot.value = true } previousPath = path isFromEdit = false } else { cursor.close() return } } } catch (t: Throwable) { isFromEdit = true } finally { cursor?.close() } super.onChange(selfChange, uri) } private fun isScreenshot(path: String?): Boolean { return path != null && path.toLowerCase().contains("screenshot") } }
0
Kotlin
0
0
66fd989c703e26ba392644e18c66c45eccddbcd7
2,202
ScreenShotLib
Apache License 2.0
src/main/kotlin/com/arusarka/gfg/kt/ds/Tree.kt
arusarka
151,558,353
false
null
package com.arusarka.gfg.kt.ds class Tree constructor(private val currentVal: Int?, private val leftTree: Tree?, private val rightTree: Tree?) { fun height(): Int { return when (currentVal) { null -> 0 else -> { 1 + maxOf(leftTree?.height() ?: 0, rightTree?.height() ?: 0) } } } internal constructor() : this(currentVal = null, leftTree = null, rightTree = null) }
0
Kotlin
0
0
b2adb74534686693eb1d470ef8d20862dc36e148
447
gfg
MIT License
app/src/main/java/com/fahad/samples/compose_template_ii/data/auth/AuthDataSource.kt
profahad
641,775,395
false
null
package com.fahad.samples.compose_template_ii.data.auth import com.fahad.samples.compose_template_ii.models.requests.auth.ForgotPasswordRequest import com.fahad.samples.compose_template_ii.models.requests.auth.LoginRequest import com.fahad.samples.compose_template_ii.models.requests.auth.SignUpRequest import com.fahad.samples.compose_template_ii.network.middlewares.BaseDataSource import javax.inject.Inject /** * Auth data source * * @property authService * @constructor Create empty Auth data source */ class AuthDataSource @Inject constructor(private val authService: AuthService) : BaseDataSource() { /** * Login * * @param loginRequest */ suspend fun login(loginRequest: LoginRequest?) = getResult { authService.login(loginRequest) } /** * Sign up * * @param signUpRequest */ suspend fun signUp(signUpRequest: SignUpRequest?) = getResult { authService.signUp(signUpRequest) } /** * Forgot password * * @param forgotPasswordRequest */ suspend fun forgotPassword(forgotPasswordRequest: ForgotPasswordRequest?) = getResult { authService.forgotPassword(forgotPasswordRequest) } }
0
Kotlin
0
0
993ecf85cd2411d9c706e63c4a71217d65dc65f4
1,193
composeTemplateV2
MIT License
clients/kotlin-vertx/generated/src/main/kotlin/org/openapitools/server/api/verticle/BerryFirmnessApiVerticle.kt
cliffano
464,411,689
false
{"C++": 5121151, "Java": 4259235, "TypeScript": 3170746, "HTML": 2401291, "C#": 1569306, "Python": 1470207, "PHP": 1250759, "Scala": 1204291, "Rust": 1144006, "Kotlin": 966686, "JavaScript": 896371, "R": 547831, "Erlang": 504910, "Ada": 495819, "F#": 490032, "Shell": 436186, "Objective-C": 431570, "Go": 402480, "PowerShell": 319730, "Crystal": 313970, "C": 311724, "Swift": 273043, "Eiffel": 250745, "Lua": 225344, "Apex": 203102, "Ruby": 191517, "Clojure": 88385, "Nim": 80342, "Groovy": 75156, "Haskell": 73882, "Elm": 70984, "OCaml": 66631, "Perl": 62597, "Dart": 56824, "CMake": 21408, "Batchfile": 13610, "Makefile": 12176, "Dockerfile": 7307, "CSS": 4873, "QMake": 3807, "Elixir": 2312, "Gherkin": 951, "Emacs Lisp": 191}
package org.openapitools.server.api.verticle import io.vertx.core.Vertx import io.vertx.core.AbstractVerticle import io.vertx.serviceproxy.ServiceBinder fun main(){ Vertx.vertx().deployVerticle(BerryFirmnessApiVerticle()) } class BerryFirmnessApiVerticle:AbstractVerticle() { override fun start() { val instance = (javaClass.classLoader.loadClass("org.openapitools.server.api.verticle.BerryFirmnessApiImpl").newInstance() as BerryFirmnessApi) instance.init(vertx,config()) ServiceBinder(vertx) .setAddress(BerryFirmnessApi.address) .register(BerryFirmnessApi::class.java,instance) } }
1
C++
2
4
d2d9531d4febf5f82411f11ea5779aafd21e1bb9
647
pokeapi-clients
MIT License
noober/src/commonMain/kotlin/com/abhi165/noober/model/state/HeaderBodyState.kt
ABHI165
689,673,497
false
{"Kotlin": 107872, "Swift": 765}
package com.abhi165.noober.model.state internal data class HeaderBodyState( val headers: Map<String, String>, val body: String ) { fun matchesQuery(query: String): Boolean { return body.contains(query, ignoreCase = true) || headers.any { it.key.contains(query, ignoreCase = true) || it.value.contains(query, ignoreCase = true) } } }
0
Kotlin
0
3
0776120e3ffb28d857c09aeb8060b5c4ce8e5d22
410
Noober-2.0
Apache License 2.0
kellocharts/src/main/java/co/csadev/kellocharts/model/dsl/ValueDslProviders.kt
gtcompscientist
116,437,926
false
null
package co.csadev.kellocharts.model.dsl import co.csadev.kellocharts.model.* import co.csadev.kellocharts.util.ChartUtils @DslMarker annotation class AxisValueDsl @AxisValueDsl class AXISVALUES: ArrayList<AxisValue>() { fun axis(block: AxisValue.() -> Unit) { add(AxisValue().apply(block)) } } @DslMarker annotation class BubbleValueDsl @BubbleValueDsl class BubbleValueBuilder { var x: Float = 0f var y: Float = 0f var z: Float = 0f var color: Int = ChartUtils.DEFAULT_COLOR var label: CharArray? = null var shape: ValueShape? = ValueShape.CIRCLE fun build() = BubbleValue(x, y, z, color, label, shape) } @BubbleValueDsl class BUBBLEVALUES: ArrayList<BubbleValue>() { fun bubble(block: BubbleValueBuilder.() -> Unit) { add(BubbleValueBuilder().apply(block).build()) } } @DslMarker annotation class PointValueDsl @PointValueDsl class PointValueBuilder { var x: Float = 0f var y: Float = 0f var label: CharArray? = null fun build() = PointValue(x, y, label) } @PointValueDsl class POINTVALUES: ArrayList<PointValue>() { fun point(block: PointValueBuilder.() -> Unit) { add(PointValueBuilder().apply(block).build()) } } @DslMarker annotation class SelectedValueDsl @SelectedValueDsl class SELECTEDVALUES: ArrayList<SelectedValue>() { fun point(block: SelectedValue.() -> Unit) { add(SelectedValue().apply(block)) } } @DslMarker annotation class SliceValueDsl fun sliceValue(block: SliceValue.() -> Unit): SliceValue = SliceValue().apply(block) @SliceValueDsl class SLICEVALUES: ArrayList<SliceValue>() { fun slice(block: SliceValue.() -> Unit) { add(SliceValue().apply(block)) } } @DslMarker annotation class SubcolumnValueDsl @SubcolumnValueDsl class SUBCOLUMNVALUES: ArrayList<SubcolumnValue>() { fun subcolumn(block: SubcolumnValue.() -> Unit) { add(SubcolumnValue().apply(block)) } }
6
Kotlin
6
50
c78ce8c4ba1991f30f379ec47cf4c38749341c57
1,941
KelloCharts
Apache License 2.0
shared/data/src/main/java/com/example/prodlist/data/product/like/ProdLike.kt
bsscco
482,714,624
false
null
package com.example.prodlist.data.product.like data class ProdLike( val productKey: String, val liked: Boolean, )
0
Kotlin
0
1
eacb6427f12f953bce62e4a72c31e2300918bd20
122
prodlist
Apache License 2.0
app/src/main/java/com/github/jaydeepw/pokemondirectory/models/dataclasses/Pokemon2.kt
jaydeepw
188,834,774
false
null
package com.github.jaydeepw.pokemondirectory.models.dataclasses import androidx.room.PrimaryKey data class Pokemon2( @PrimaryKey(autoGenerate = true) val id: Int = 0, val title: String = "", val userId: Int = 0 )
0
Kotlin
0
0
0891561a10d4a4d277ad6cef1bc4b293f8cd3607
238
pokemon-directory
MIT License
app/src/main/kotlin/example/maester/ui/home/presenter/HomePresenter.kt
andresciceri
205,940,960
true
{"Kotlin": 71817}
package example.maester.ui.home.presenter import example.maester.api.Endpoints import example.maester.base.mvp.BasePresenter import example.maester.utils.SchedulerProvider import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject class HomePresenter @Inject constructor(disposable: CompositeDisposable, scheduler: SchedulerProvider) : BasePresenter<MoviesView>(disposable, scheduler) { //TODO Methods from presenter }
0
Kotlin
0
0
dbfde5ea9155c0d0f3f773c74a7c2e9252501886
445
maester
Apache License 2.0
app/src/main/java/com/notes/app/feature_note/presentation/add_edit_note/AddEditNoteScreen.kt
ayyappankarunan
540,853,446
false
{"Kotlin": 65730}
package com.notes.app.feature_note.presentation.add_edit_note import android.annotation.SuppressLint import android.content.Intent import android.net.Uri import androidx.activity.compose.BackHandler import androidx.compose.animation.Animatable import androidx.compose.animation.core.tween import androidx.compose.foundation.* import androidx.compose.foundation.layout.* import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.KeyboardActions import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.* import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.toArgb import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextDecoration import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import androidx.navigation.NavController import com.notes.app.R import com.notes.app.feature_note.domain.model.Note import com.notes.app.feature_note.presentation.add_edit_note.components.BasicDialog import com.notes.app.feature_note.presentation.add_edit_note.components.TextFieldDialog import com.notes.app.feature_note.presentation.add_edit_note.components.TransparentTextFields import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch @SuppressLint("UnusedMaterialScaffoldPaddingParameter") @OptIn(ExperimentalComposeUiApi::class, ExperimentalMaterialApi::class) @Composable fun AddEditNoteScreen( navController: NavController, noteColor: Int, viewModel: AddEditNoteViewModel = hiltViewModel(), ) { val titleState = viewModel.noteTitle.value val contentState = viewModel.noteContent.value val urlState = viewModel.noteUrl.value val keyboardController = LocalSoftwareKeyboardController.current val context = LocalContext.current val scaffoldState = rememberScaffoldState() val scope = rememberCoroutineScope() val sheetState = rememberModalBottomSheetState( initialValue = ModalBottomSheetValue.Hidden, confirmStateChange = { it != ModalBottomSheetValue.HalfExpanded } ) val noteColorAnimated = remember { Animatable( Color(if (noteColor != -1) noteColor else viewModel.noteColor.value) ) } var exitDialogState by remember { mutableStateOf(false) } var deleteDialogState by remember { mutableStateOf(false) } var addEditUrlDialogState by remember { mutableStateOf(false) } LaunchedEffect(key1 = true) { viewModel.eventFlow.collectLatest { event -> when (event) { is AddEditNoteViewModel.UiEvent.ShowSnackBar -> { scaffoldState.snackbarHostState.showSnackbar(message = event.message) } is AddEditNoteViewModel.UiEvent.SaveNote -> { navController.navigateUp() } } } } ModalBottomSheetLayout( sheetState = sheetState, sheetContent = { Column( modifier = Modifier .fillMaxWidth() .padding(6.dp, 0.dp, 6.dp, 6.dp) ) { Box( modifier = Modifier .padding(vertical = 10.dp) .width(100.dp) .height(4.dp) .background(MaterialTheme.colors.secondaryVariant, RoundedCornerShape(2.dp)) .align(Alignment.CenterHorizontally) ) Row( modifier = Modifier .fillMaxWidth() .padding(vertical = 8.dp), horizontalArrangement = Arrangement.SpaceEvenly ) { Note.noteColors.forEach { val color = it.toArgb() val shape = RoundedCornerShape(5.dp) Box( modifier = Modifier .size(40.dp) .shadow(4.dp, shape) .clip(shape) .background(it) .border( width = 2.dp, color = if (color == viewModel.noteColor.value) MaterialTheme.colors.primary else Color.Transparent, shape = shape ) .clickable { scope.launch { noteColorAnimated.animateTo( targetValue = Color(color), animationSpec = tween( durationMillis = 500 ) ) } viewModel.onEvent(AddEditNoteEvent.ChangeNoteColor(color)) } ) { if (color == viewModel.noteColor.value) Icon( imageVector = Icons.Default.Done, contentDescription = stringResource(id = R.string.selected_color), tint = MaterialTheme.colors.primary, modifier = Modifier.align( Alignment.Center ) ) } } } Row( modifier = Modifier .fillMaxWidth() .clickable { addEditUrlDialogState = true }, verticalAlignment = Alignment.CenterVertically ) { Icon( Icons.Default.Link, stringResource(id = R.string.add_url), modifier = Modifier .padding(14.dp) .size(20.dp), tint = MaterialTheme.colors.primary, ) Text( if (urlState.isEmpty()) stringResource(id = R.string.add_url) else stringResource( id = R.string.edit_url ), style = TextStyle( color = MaterialTheme.colors.primary, fontWeight = FontWeight.SemiBold, fontSize = 16.sp ) ) } Row( modifier = Modifier .fillMaxWidth() .clickable { deleteDialogState = true }, verticalAlignment = Alignment.CenterVertically ) { Icon( Icons.Default.Delete, stringResource(id = R.string.delete_note), modifier = Modifier .padding(14.dp) .size(20.dp), tint = Color.Red, ) Text( stringResource(id = R.string.delete_note), style = TextStyle( color = Color.Red, fontWeight = FontWeight.SemiBold, fontSize = 16.sp ) ) } Spacer(modifier = Modifier.width(20.dp)) } }, sheetBackgroundColor = MaterialTheme.colors.secondary, sheetShape = RoundedCornerShape(20.dp, 20.dp, 0.dp, 0.dp) ) { BackHandler(true) { if (sheetState.isVisible) { scope.launch { sheetState.hide() } } else if (viewModel.checkIsNoteUnSaved()) { exitDialogState = true } else navController.navigateUp() } Scaffold( floatingActionButton = { FloatingActionButton( onClick = { viewModel.onEvent(AddEditNoteEvent.SaveNote) }, backgroundColor = MaterialTheme.colors.secondary ) { Icon( imageVector = Icons.Default.Done, contentDescription = stringResource(id = R.string.save_note), tint = MaterialTheme.colors.primary ) } }, scaffoldState = scaffoldState ) { Column( modifier = Modifier .fillMaxSize() .verticalScroll(rememberScrollState()) ) { TopAppBar(title = {}, actions = { IconButton(onClick = { scope.launch { keyboardController?.hide() sheetState.show() } }) { Icon( imageVector = Icons.Default.Menu, contentDescription = stringResource(id = R.string.menu), tint = MaterialTheme.colors.primary ) } }, navigationIcon = { IconButton(onClick = { if (viewModel.checkIsNoteUnSaved().not()) navController.navigateUp() else exitDialogState = true }) { Icon( imageVector = Icons.Default.ArrowBack, contentDescription = stringResource(id = R.string.go_back), tint = MaterialTheme.colors.primary ) } }, backgroundColor = MaterialTheme.colors.background, elevation = 0.dp) Spacer(modifier = Modifier.height(8.dp)) Row( modifier = Modifier .height(IntrinsicSize.Max) .fillMaxWidth() ) { Box( modifier = Modifier .fillMaxHeight() .width(8.dp) .padding(start = 4.dp) .background(noteColorAnimated.value, shape = RoundedCornerShape(4.dp)) ) Column { if (viewModel.showDateModified.value) { Text( text = viewModel.dateModified!!, style = TextStyle( color = MaterialTheme.colors.secondaryVariant, fontSize = 10.sp ), modifier = Modifier.padding(horizontal = 10.dp, 4.dp) ) } TransparentTextFields( text = titleState.text, hint = titleState.hint, onValueChange = { viewModel.onEvent(AddEditNoteEvent.EnteredTitle(it)) }, onFocusChange = { viewModel.onEvent(AddEditNoteEvent.ChangeTitleFocus(it)) }, singleLine = false, textStyle = MaterialTheme.typography.h6.copy(color = MaterialTheme.colors.primary), isHintVisible = titleState.isHintVisible, modifier = Modifier .fillMaxWidth() .padding(horizontal = 8.dp), keyboardActions = KeyboardActions(onDone = { keyboardController?.hide() }), ) } } if (urlState.isNotEmpty()) { Spacer(modifier = Modifier.height(8.dp)) Row( modifier = Modifier .padding(horizontal = 8.dp) ) { Icon( imageVector = Icons.Default.Link, contentDescription = stringResource(id = R.string.link), tint = noteColorAnimated.value ) Text( text = urlState, modifier = Modifier .padding(horizontal = 4.dp) .clickable { var webpage = Uri.parse(urlState) if (!urlState.startsWith("http://") && !urlState.startsWith("https://")) { Uri .parse("http://$urlState") .also { webpage = it } } val urlIntent = Intent( Intent.ACTION_VIEW, webpage ) context.startActivity(urlIntent) }, style = TextStyle( color = noteColorAnimated.value, textDecoration = TextDecoration.Underline, fontSize = 16.sp ) ) } } Spacer(modifier = Modifier.height(8.dp)) TransparentTextFields( text = contentState.text, hint = contentState.hint, onValueChange = { viewModel.onEvent(AddEditNoteEvent.EnteredContent(it)) }, onFocusChange = { viewModel.onEvent(AddEditNoteEvent.ChangeContentFocus(it)) }, singleLine = false, textStyle = MaterialTheme.typography.body1.copy(color = MaterialTheme.colors.primary), modifier = Modifier .fillMaxSize() .padding(horizontal = 10.dp), isHintVisible = contentState.isHintVisible, keyboardActions = KeyboardActions(onDone = { keyboardController?.hide() }) ) } } } if (exitDialogState) { BasicDialog( onDismissRequest = { exitDialogState = false }, title = stringResource(id = R.string.leave_note), description = stringResource(id = R.string.leave_note_desc), confirmText = stringResource(id = R.string.leave), dismissText = stringResource(id = R.string.cancel), confirmRequest = { exitDialogState = false navController.navigateUp() } ) } if (addEditUrlDialogState) { TextFieldDialog( onDismissRequest = { addEditUrlDialogState = false }, defaultText = urlState, title = if (urlState.isEmpty()) stringResource(id = R.string.add_url) else stringResource( id = R.string.edit_url ), icon = Icons.Default.Link, confirmText = stringResource(id = R.string.add), dismissText = stringResource(id = R.string.cancel), confirmRequest = { viewModel.onEvent(AddEditNoteEvent.EnteredUrl(it)) addEditUrlDialogState = false } ) } if (deleteDialogState) { BasicDialog( onDismissRequest = { deleteDialogState = false }, title = stringResource(id = R.string.delete_note_qn), description = stringResource(id = R.string.delete_note_desc), confirmText = stringResource(id = R.string.delete), dismissText = stringResource(id = R.string.no), confirmRequest = { viewModel.onEvent(AddEditNoteEvent.DeleteNote) deleteDialogState = false navController.navigateUp() } ) } }
0
Kotlin
0
0
5636f061dc8614436310090ff32f34e8e04990d8
17,362
Notes_Note_it
MIT License
Tareas/Tarea1/app/src/main/java/com/cuaspro/tarea1/Excercise8.kt
MiguelIslasH
343,788,587
false
null
package com.cuaspro.tarea1 import android.content.Context import android.content.Intent import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.view.View import android.view.inputmethod.InputMethodManager import android.widget.Button import android.widget.EditText class Excercise8: AppCompatActivity() { private lateinit var btnNext : Button private lateinit var txtEj8 : EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_excercise8) setTitle("Tarea 1 : Ej. 8") val actionBar = supportActionBar actionBar?.setDisplayHomeAsUpEnabled(true) actionBar?.setDisplayHomeAsUpEnabled(true) setup() } private fun setup() { btnNext = findViewById(R.id.btnNextActivity8_9) txtEj8 = findViewById(R.id.txtEj8) btnNext.setOnClickListener({ val intent = Intent(this, Excercise9::class.java) startActivity(intent) }) txtEj8.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) { closeKeyBoard() } override fun afterTextChanged(s: Editable?) { closeKeyBoard() } }) } private fun closeKeyBoard() { val view = this.currentFocus if (view != null) { val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view.windowToken, 0) } } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } }
0
Kotlin
0
1
31590a1f647a7ece52236e5bf740c0999923fdcb
1,923
Clases-Desarollo-de-Apps-Moviles---ESCOM-IPN
MIT License
backend/search-data/src/commonMain/kotlin/com/gchristov/thecodinglove/searchdata/domain/SearchSession.kt
gchristov
533,472,792
false
null
package com.gchristov.thecodinglove.searchdata.model import com.gchristov.thecodinglove.searchdata.db.DbSearchSession data class SearchSession( val id: String, val query: String, val totalPosts: Int?, // Contains visited page numbers mapped to visited post indexes on those pages val searchHistory: Map<Int, List<Int>>, val currentPost: Post?, val preloadedPost: Post?, val state: State ) { sealed class State { object Searching : State() } } internal fun DbSearchSession.toSearchSession() = SearchSession( id = id, query = query, totalPosts = totalPosts, searchHistory = mutableMapOf<Int, List<Int>>().apply { searchHistory.keys.forEach { page -> searchHistory[page]?.let { itemIndex -> put(page.toInt(), itemIndex) } } }, currentPost = currentPost?.toPost(), preloadedPost = preloadedPost?.toPost(), state = state.toSearchSessionState() ) private fun DbSearchSession.DbState.toSearchSessionState() = when (this) { is DbSearchSession.DbState.DbSearching -> SearchSession.State.Searching }
1
null
0
3
c674df658a0787f9254bd8ce240cddb25b25fff8
1,133
thecodinglove-kmp
Apache License 2.0
app/src/main/java/io/r_a_d/radio2/ui/songs/SongsPagerAdapter.kt
yattoz
216,435,573
false
{"Kotlin": 201754, "HTML": 723}
package io.r_a_d.radio2.ui.songs import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentPagerAdapter import androidx.fragment.app.FragmentManager class SongsPagerAdapter(f: FragmentManager, t: Int) : FragmentPagerAdapter(f, t){ private val fragmentList = ArrayList<Fragment>() private val fragmentTitleList = ArrayList<String>() override fun getItem(position: Int): Fragment { return fragmentList[position] } override fun getCount(): Int { return fragmentList.size } fun addFragment(fragment: Fragment, title: String) { fragmentList.add(fragment) fragmentTitleList.add(title) } override fun getPageTitle(position: Int): CharSequence? { return fragmentTitleList[position] } }
4
Kotlin
2
5
d2604faa6a085e274c7afceb43e42ed7dc859021
782
Radio2
MIT License
coil-core/src/jvmCommonMain/kotlin/coil3/map/FileMapper.kt
coil-kt
201,684,760
false
{"Kotlin": 955603, "Shell": 2360, "JavaScript": 209}
package coil3.map import coil3.Uri import coil3.request.Options import coil3.toUri import coil3.util.SCHEME_FILE import java.io.File class FileMapper : Mapper<File, Uri> { override fun map(data: File, options: Options): Uri { return "$SCHEME_FILE://$data".toUri() } }
39
Kotlin
626
9,954
9b3f851b2763b4c72a3863f8273b8346487b363b
286
coil
Apache License 2.0
Mitori-Satori/src/main/kotlin/xyz/xasmc/mitori/satori/util/StringEnumSelizer.kt
XAS-Dev
832,216,378
false
{"Kotlin": 71553, "Java": 179}
import kotlinx.serialization.KSerializer import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder import kotlin.enums.EnumEntries // 通用的枚举序列化器 abstract class StringEnumSerializer<T : Enum<T>>( private val serialName: String, private val values: EnumEntries<T>, private val valueToString: (T) -> String ) : KSerializer<T> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor(serialName, PrimitiveKind.INT) override fun serialize(encoder: Encoder, value: T) { encoder.encodeString(valueToString(value)) } override fun deserialize(decoder: Decoder): T { val stringVal = decoder.decodeString() return values.find { valueToString(it) == stringVal } ?: throw IllegalArgumentException("Unknown $serialName value: $stringVal") } }
0
Kotlin
0
1
ba84efef3d336ead22ddcb266063fc682ccdd925
1,027
Mitori
MIT License
tgbotapi.api/src/commonMain/kotlin/dev/inmo/tgbotapi/extensions/api/bot/DeleteMyCommands.kt
InsanusMokrassar
163,152,024
false
null
package dev.inmo.tgbotapi.extensions.api.bot import dev.inmo.micro_utils.language_codes.IetfLanguageCode import dev.inmo.tgbotapi.bot.TelegramBot import dev.inmo.tgbotapi.requests.bot.DeleteMyCommands import dev.inmo.tgbotapi.types.commands.BotCommandScope import dev.inmo.tgbotapi.types.commands.BotCommandScopeDefault suspend fun TelegramBot.deleteMyCommands( scope: BotCommandScope = BotCommandScopeDefault, languageCode: IetfLanguageCode? ) = execute(DeleteMyCommands(scope, languageCode)) suspend fun TelegramBot.deleteMyCommands( scope: BotCommandScope = BotCommandScopeDefault, languageCode: String? = null ) = deleteMyCommands(scope, languageCode ?.let(::IetfLanguageCode))
9
Kotlin
10
99
8206aefbb661db936d4078a8ef7cc9cecb5384e4
701
TelegramBotAPI
Apache License 2.0
features/setting/map/src/main/kotlin/com/egoriku/grodnoroads/setting/map/ui/MapStyleSection.kt
egorikftp
485,026,420
false
null
package com.egoriku.grodnoroads.settings.map.ui import androidx.compose.foundation.layout.* import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.egoriku.grodnoroads.foundation.CheckableCard import com.egoriku.grodnoroads.foundation.SettingsHeader import com.egoriku.grodnoroads.foundation.list.CheckboxSettings import com.egoriku.grodnoroads.foundation.theme.GrodnoRoadsPreview import com.egoriku.grodnoroads.foundation.theme.GrodnoRoadsTheme import com.egoriku.grodnoroads.resources.R import com.egoriku.grodnoroads.settings.map.domain.component.MapSettingsComponent.MapPref import com.egoriku.grodnoroads.settings.map.domain.component.MapSettingsComponent.MapSettings.MapStyle import com.egoriku.grodnoroads.shared.appsettings.types.map.mapstyle.Style @Composable internal fun MapStyleSection( mapStyle: MapStyle, onCheckedChange: (MapPref) -> Unit ) { Column(modifier = Modifier.fillMaxWidth()) { SettingsHeader(title = stringResource(id = R.string.map_header_appearance)) GoogleMapStyle(mapStyle, onCheckedChange) TrafficJam(mapStyle, onCheckedChange) } } @Composable private fun GoogleMapStyle( mapStyle: MapStyle, onCheckedChange: (MapPref) -> Unit ) { val googleMapStyle = mapStyle.googleMapStyle Row( horizontalArrangement = Arrangement.SpaceEvenly, modifier = Modifier .fillMaxWidth() .padding(vertical = 16.dp) ) { CheckableCard( title = R.string.map_google_map_style_minimal, selected = googleMapStyle.style == Style.Minimal, iconId = R.drawable.ic_map_style_minimal, onClick = { onCheckedChange(googleMapStyle.copy(style = Style.Minimal)) } ) CheckableCard( title = R.string.map_google_map_style_detailed, selected = googleMapStyle.style == Style.Detailed, iconId = R.drawable.ic_map_style_detailed, onClick = { onCheckedChange(googleMapStyle.copy(style = Style.Detailed)) } ) } } @Composable private fun TrafficJam( mapStyle: MapStyle, onCheckedChange: (MapPref) -> Unit ) { val trafficJamOnMap = mapStyle.trafficJamOnMap CheckboxSettings( iconRes = R.drawable.ic_traffic_light, stringResId = R.string.map_traffic_jam_appearance, isChecked = trafficJamOnMap.isShow, onCheckedChange = { onCheckedChange(trafficJamOnMap.copy(isShow = it)) } ) } @GrodnoRoadsPreview @Composable fun PreviewMapStyleSection() { GrodnoRoadsTheme { MapStyleSection(mapStyle = MapStyle()) { } } }
2
Kotlin
1
9
43fcdea90af3233a29912d196d2ae53e5323855f
2,787
GrodnoRoads
Apache License 2.0
quarkus-workshop-super-heroes/super-heroes/app_superheroes/android/app/src/main/kotlin/com/example/app_superheroes/MainActivity.kt
buehren
322,656,780
true
{"HTML": 11403450, "Java": 141450, "CSS": 102686, "Shell": 74112, "HCL": 30948, "TypeScript": 26940, "C++": 24562, "CMake": 14989, "Dart": 13361, "C": 1102, "Swift": 404, "Kotlin": 132, "Objective-C": 38}
package com.example.app_superheroes import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() { }
0
HTML
0
0
bf92ad680511cf2d843ef7ebc01d548d29f4cafc
132
quarkus-workshops
Apache License 2.0
library/core/stereotyped/src/test/kotlin/de/lise/fluxflow/stereotyped/job/ReflectedJobDefinitionTest.kt
lisegmbh
740,936,659
false
{"Kotlin": 732949}
package de.lise.fluxflow.stereotyped.job import de.lise.fluxflow.api.job.JobIdentifier import de.lise.fluxflow.api.job.JobKind import de.lise.fluxflow.api.job.JobStatus import de.lise.fluxflow.api.workflow.Workflow import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test import org.mockito.kotlin.mock import java.time.Instant class ReflectedJobDefinitionTest { @Test fun `createJob should return a job with the provided information`() { // Arrange val instance = Any() val jobCaller = mock<JobCaller<Any>> { } val metadata = mapOf<String, Any>( "test" to 4 ) val reflectedJobDefinition = ReflectedJobDefinition( JobKind("kind"), emptyList(), metadata, instance, jobCaller ) val jobIdentifier = JobIdentifier("id") val workflow = mock<Workflow<*>> {} val instant = Instant.now() // Act val job = reflectedJobDefinition.createJob( jobIdentifier, workflow, instant, null, JobStatus.Scheduled ) // Assert assertThat(job.identifier).isEqualTo(jobIdentifier) assertThat(job.definition).isEqualTo(reflectedJobDefinition) assertThat(job.workflow).isEqualTo(workflow) assertThat(job.scheduledTime).isEqualTo(instant) assertThat(job.metadata).isEqualTo(metadata) } }
20
Kotlin
0
7
053a926f73ca6c77a93d173a416c8d45e12d4ad0
1,487
fluxflow
Apache License 2.0
sdk/src/main/java/io/wso2/android/api_authenticator/sdk/models/autheniticator_type/AuthenticatorTypeFactory.kt
Achintha444
731,559,375
false
{"Kotlin": 10524}
package io.wso2.android.api_authenticator.sdk.models.autheniticator_type class AuthenticatorTypeFactory { }
0
Kotlin
0
0
4fe2edcd0013cfe27457492eeaa931e70dddbbe0
108
wso2-android-api-authenticator-sdk
Apache License 2.0
ExternalConnection/src/main/java/com/payz/externalconnection/communication/model/applist/AppListResponse.kt
burhanaras
327,103,273
false
null
package com.payz.externalconnection.communication.model.applist data class AppListResponse( var appList: List<AppInfo> = listOf(), var type: String = "AppListResponse" )
0
Kotlin
3
6
bf9e00e5e4cab7d6b81ed4b805d9b7bcf67572aa
186
SoftPos
Apache License 2.0
kotlin-node/src/jsMain/generated/node/os/namespace.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Generated by Karakum - do not modify it manually! @file:JsModule("node:os") package node.os external val devNull: String /** * The operating system-specific end-of-line marker. * * `\n` on POSIX * * `\r\n` on Windows */ external val EOL: String
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
257
kotlin-wrappers
Apache License 2.0
src/test/kotlin/ee/nx01/tonclient/TestConstants.kt
mdorofeev
305,637,520
false
null
package ee.nx01.tonclient object TestConstants { val WALLET_PHRASE = "defense talent layer admit setup virus deer buffalo timber ethics symbol cover" val WALLET_ADDRESS = "0:7f458ae01e28573a181e2227dc77710d6421d4e103fdd3e023200aa4bce83950" val MESSAGE_ID = "240e0219663b7253c41e76d581919a62cf447d0b8b5330b6da133b77acabc64b" val BLOCK_ID = 35664f val TRANSACTION_ID = "c289bae33734e680b73d5ec61c98baa6c8bc929b4536a2d43e7940d193d87e3c" val KEY_BLOCK_ID = "3fbe311e2bb04c758d041e6890a000039039de3177f13aff0897587aeb25bb0e" val WALLET_SECRET = "db16e21ee91b5064f6e31d9a2fb4771ce7f8acf14fe6d6ffade8ffcbeec31d69" val WALLET_PUBLIC = "<KEY>" }
0
Kotlin
3
6
b3a66d6ee9f117091805ed9ed660ef58d799fb8c
670
ton-client-kotlin
Apache License 2.0
src/main/kotlin/com/jahnelgroup/domain/notification/Notification.kt
JahnelGroup
168,455,772
false
{"HTML": 130381, "Kotlin": 99201, "JavaScript": 23425, "TSQL": 17712, "CSS": 5254, "Dockerfile": 544}
package com.jahnelgroup.domain.notification import com.jahnelgroup.domain.AbstractEntity import java.io.Serializable import javax.persistence.Entity import javax.persistence.Table @Table(name = "notifications") @Entity data class Notification( var recipient: String? = null, var sender: String? = null, var content: String? = null, var isRead: Boolean = false ): AbstractEntity()
0
HTML
2
1
d97822fd4a348d83a984c031a55b2b0b523f2f04
414
thymeleaf-starter
MIT License
app/src/main/java/com/lighttigerxiv/simple/mp/compose/frontend/screens/main/library/playlists/playlist/PlaylistScreenVM.kt
jpbandroid
733,977,750
false
{"Kotlin": 458602}
package com.jpb.music.compose.frontend.screens.main.library.playlists.playlist import android.graphics.Bitmap import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProvider.AndroidViewModelFactory.Companion.APPLICATION_KEY import androidx.lifecycle.viewModelScope import androidx.lifecycle.viewmodel.initializer import androidx.lifecycle.viewmodel.viewModelFactory import com.jpb.music.compose.MusicApplication import com.jpb.music.compose.backend.realm.Queries import com.jpb.music.compose.backend.realm.collections.Playlist import com.jpb.music.compose.backend.realm.collections.Song import com.jpb.music.compose.backend.realm.getRealm import com.jpb.music.compose.backend.repositories.LibraryRepository import com.jpb.music.compose.backend.repositories.PlaybackRepository import com.jpb.music.compose.backend.repositories.PlaylistsRepository import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.mongodb.kbson.ObjectId class PlaylistScreenVM( private val playbackRepository: PlaybackRepository, private val playlistsRepository: PlaylistsRepository, private val libraryRepository: LibraryRepository ) : ViewModel() { companion object Factory { val Factory: ViewModelProvider.Factory = viewModelFactory { initializer { val app = (this[APPLICATION_KEY] as MusicApplication) val playbackRepository = app.container.playbackRepository val playlistsRepository = app.container.playlistsRepository val libraryRepository = app.container.libraryRepository PlaylistScreenVM(playbackRepository, playlistsRepository, libraryRepository) } } } data class UiState( val requestedLoading: Boolean = false, val loading: Boolean = true, val playlistId: ObjectId? = null, val playlistArt: Bitmap? = null, val playlistName: String = "", val editNameText: String = "", val songs: List<Song> = ArrayList(), val showMenu: Boolean = false, val inEditMode: Boolean = false, val showEditNameDialog: Boolean = false, val showEditImageDialog: Boolean = false, val showDeletePlaylistDialog: Boolean = false, val currentSong: Song? = null ) private val _uiState = MutableStateFlow(UiState()) val uiState = _uiState.asStateFlow() private lateinit var playlist: Playlist private lateinit var songs: List<Song> private val queries = Queries(getRealm()) init { viewModelScope.launch(Dispatchers.Main) { playbackRepository.currentSongState.collect { currentSongState -> _uiState.update { uiState.value.copy(currentSong = currentSongState?.currentSong) } } } viewModelScope.launch(Dispatchers.Main) { playlistsRepository.userPlaylists.collect { uiState.value.playlistId?.let { playlistId -> val newPlaylist = playlistsRepository.getUserPlaylist(playlistId) newPlaylist?.let { playlist = newPlaylist _uiState.update { uiState.value.copy(songs = playlistsRepository.getPlaylistSongs(playlist.songs)) } } } } } } fun load(playlistId: ObjectId) { viewModelScope.launch(Dispatchers.Main) { _uiState.update { uiState.value.copy(requestedLoading = true) } val newPlaylist = playlistsRepository.getUserPlaylist(playlistId) newPlaylist?.let { playlist = newPlaylist songs = playlistsRepository.getPlaylistSongs(playlist.songs) _uiState.update { uiState.value.copy( loading = false, playlistId = playlistId, playlistName = playlist.name, songs = songs ) } } } } fun updateShowMenu(v: Boolean) { _uiState.update { uiState.value.copy(showMenu = v) } } fun getArtistName(artistId: Long): String { return libraryRepository.getArtistName(artistId) } fun getAlbumArt(albumId: Long): Bitmap? { return libraryRepository.getSmallAlbumArt(albumId) } fun playSong(song: Song) { playbackRepository.playSelectedSong(song, uiState.value.songs) } fun updateShowDeleteDialog(v: Boolean) { _uiState.update { uiState.value.copy(showDeletePlaylistDialog = v) } } fun updateShowEditNameDialog(v: Boolean) { _uiState.update { uiState.value.copy( showEditNameDialog = v, editNameText = if(v) uiState.value.playlistName else uiState.value.editNameText ) } } fun updateEditNameText(text: String) { _uiState.update { uiState.value.copy(editNameText = text) } } fun updatePlaylistName() { _uiState.update { uiState.value.copy( playlistName = uiState.value.editNameText, showEditNameDialog = false ) } } fun deletePlaylist(playlistId: ObjectId) { viewModelScope.launch(Dispatchers.Main) { queries.deletePlaylist(playlistId) playlistsRepository.loadPlaylists(libraryRepository.songs.value) } } fun shuffleAndPlay() { playbackRepository.shuffleAndPlay(uiState.value.songs) } fun updateEditMode(v: Boolean) { _uiState.update { uiState.value.copy(inEditMode = v) } } fun cancelEditMode() { _uiState.update { uiState.value.copy( playlistName = playlist.name, songs = songs, inEditMode = false, showMenu = false ) } } fun save() { viewModelScope.launch(Dispatchers.Main) { queries.updatePlaylistName(playlist._id, uiState.value.playlistName) queries.updatePlaylistSongs(playlist._id, uiState.value.songs.map { it.id }) _uiState.update { uiState.value.copy( showMenu = false, inEditMode = false, ) } playlistsRepository.loadPlaylists(libraryRepository.songs.value) } } fun removeSong(songId: Long) { _uiState.update { uiState.value.copy( songs = uiState.value.songs.filter { it.id != songId } ) } } }
0
Kotlin
0
0
e53569c3ebe0cba05a70519805ffb6c97137fe1e
6,880
jpbMusic-Compose
MIT License
app/src/main/java/com/example/rental_mobil/View/Pelanggan/PdfActivity.kt
mrAldirs
691,938,449
false
{"Kotlin": 333860}
package com.example.rental_mobil.View.Pelanggan import android.Manifest import android.R.attr.rowCount import android.content.Intent import android.os.Build import android.os.Bundle import android.os.Environment import android.text.TextUtils import android.util.Log import android.widget.Toast import androidx.activity.result.contract.ActivityResultContracts import androidx.appcompat.app.AppCompatActivity import com.example.rental_mobil.Model.Mobil import com.example.rental_mobil.Model.Pelanggan import com.example.rental_mobil.Model.Riwayat import com.example.rental_mobil.R import com.example.rental_mobil.Utils.PdfUtility import com.example.rental_mobil.Utils.TemplatePdf import com.example.rental_mobil.databinding.ActivityPdfBinding import java.io.File import java.util.ArrayList import java.util.List class PdfActivity : AppCompatActivity(), PdfUtility.OnDocumentClose { private lateinit var b: ActivityPdfBinding private lateinit var mobil:Mobil private lateinit var pelanggan:Pelanggan private lateinit var riwayat:Riwayat override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) b = ActivityPdfBinding.inflate(layoutInflater) setContentView(b.root) supportActionBar?.setDisplayHomeAsUpEnabled(true) mobil = intent.getSerializableExtra("mobil") as Mobil pelanggan = intent.getSerializableExtra("pelanggan") as Pelanggan riwayat = intent.getSerializableExtra("riwayat") as Riwayat showPreview() b.fabDownload.setOnClickListener { var file:File = if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.S){ File(Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_DOCUMENTS),"/${System.currentTimeMillis()}.pdf") }else{ File(Environment.getExternalStorageDirectory(), "/${System.currentTimeMillis()}.pdf") } // var templatePdf = TemplatePdf(this@PdfActivity) // templatePdf.generatePdf(pelanggan,mobil,riwayat, file, b.templatePdf.width, b.templatePdf.height) try { PdfUtility.createPdf(this@PdfActivity,this,getSampleData(),file.path,true); } catch (e:Exception) { e.printStackTrace(); Log.e("TAG","Error Creating Pdf"); Toast.makeText(this,"Error Creating Pdf",Toast.LENGTH_SHORT).show(); } } requestAllPermissions(); } private fun getSampleData(): MutableList<Array<String>> { var count = 20 var temp: MutableList<Array<String>> = mutableListOf() for (i in 0 until count) { temp.add(arrayOf("C1-R" + (i + 1), "C2-R" + (i + 1))) } return temp } private val multiPermissionCallback = registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { map -> if ( map.entries.size <3){ Toast.makeText(this, "Please Accept all the permissions", Toast.LENGTH_SHORT).show() } } private fun requestAllPermissions(){ multiPermissionCallback.launch( arrayOf( Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA ) ) } override fun onPDFDocumentClose(file: File?) { Toast.makeText(this,"Sample Pdf Created",Toast.LENGTH_SHORT).show(); } override fun onSupportNavigateUp(): Boolean { onBackPressed() overridePendingTransition(R.anim.slide_in_left, android.R.anim.slide_out_right) return true } override fun onBackPressed() { super.onBackPressed() overridePendingTransition(R.anim.slide_in_left, android.R.anim.slide_out_right) } private fun showPreview() { b.templatePdf.setBackgroundPaint(1) b.templatePdf.setData(pelanggan,riwayat,mobil) b.templatePdf.invalidate() } }
1
Kotlin
0
2
624e82b43797c514a0f424ef025d66c4eab53ee8
4,087
kotlin-rent-car-app
Apache License 2.0
src/test/kotlin/com/github/kerubistan/kerub/services/impl/AuditServiceIT.kt
kerubistan
19,528,622
false
null
package com.github.kerubistan.kerub.services.impl import com.github.kerubistan.kerub.RestException import com.github.kerubistan.kerub.createClient import com.github.kerubistan.kerub.expect import com.github.kerubistan.kerub.login import com.github.kerubistan.kerub.runRestAction import com.github.kerubistan.kerub.services.AuditService import org.junit.Test import java.util.UUID import kotlin.test.assertEquals class AuditServiceIT { @Test fun security() { createClient().runRestAction(AuditService::class) { expect(RestException::class, action = { it.listById(UUID.randomUUID()) }, check = { assertEquals("AUTH1", it.code) }) } val endUser = createClient() endUser.login("enduser", "<PASSWORD>") endUser.runRestAction(AuditService::class) { expect(RestException::class, action = { it.listById(UUID.randomUUID()) }, check = { assertEquals("SEC1", it.code) }) } } }
109
Kotlin
4
14
99cb43c962da46df7a0beb75f2e0c839c6c50bda
911
kerub
Apache License 2.0
save-core/src/commonNonJsTest/kotlin/org/cqfn/save/core/test/utils/TestUtilsCommon.kt
cqfn
340,654,529
false
null
/** * MPP test Utils for integration tests, especially for downloading of tested tools, like diktat and ktlint */ @file:Suppress("FILE_NAME_MATCH_CLASS") package org.cqfn.save.core.test.utils import org.cqfn.save.core.Save import org.cqfn.save.core.config.LogType import org.cqfn.save.core.config.OutputStreamType import org.cqfn.save.core.config.ReportType import org.cqfn.save.core.config.SaveProperties import org.cqfn.save.core.result.Fail import org.cqfn.save.core.result.Ignored import org.cqfn.save.core.result.Pass import org.cqfn.save.reporter.test.TestReporter import okio.FileSystem import okio.Path import kotlin.test.assertEquals import kotlin.test.assertTrue /** * @property testName * @property reason */ data class ExpectedFail(val testName: String, val reason: String) /** * @param testDir `testFiles` as accepted by save-cli * @param numberOfTests expected number of executed tests with this configuration * @param expectedFail list of expected failed tests * @param addProperties lambda to add/override SaveProperties during test * @return TestReporter */ @Suppress( "COMPLEX_EXPRESSION", "TOO_LONG_FUNCTION", ) fun runTestsWithDiktat( testDir: List<String>?, numberOfTests: Int, expectedFail: List<ExpectedFail> = listOf(), addProperties: SaveProperties.() -> Unit = {}, ): TestReporter { val mutableTestDir: MutableList<String> = mutableListOf() testDir?.let { mutableTestDir.addAll(testDir) } mutableTestDir.add(0, "../examples/kotlin-diktat/") val saveProperties = SaveProperties( logType = LogType.ALL, testFiles = mutableTestDir, reportType = ReportType.TEST, resultOutput = OutputStreamType.STDOUT, ).apply { addProperties() } // In this test we need to merge with emulated empty save.properties file in aim to use default values, // since initially all fields are null val testReporter = Save(saveProperties.mergeConfigWithPriorityToThis(SaveProperties()), FileSystem.SYSTEM) .performAnalysis() as TestReporter assertEquals(numberOfTests, testReporter.results.size) testReporter.results.forEach { test -> // FixMe: if we will have other failing tests - we will make the logic less hardcoded if (test.resources.test.name == "ThisShouldAlwaysFailTest.kt") { assertEquals( Fail( "(MISSING WARNINGS):" + " [Warning(message=[DUMMY_ERROR] this error should not match, line=8, column=1," + " fileName=ThisShouldAlwaysFailTest.kt)]", "(MISSING WARNINGS): (1). (MATCHED WARNINGS): (1)" ), test.status ) } else if (test.resources.test.toString().contains("warn${Path.DIRECTORY_SEPARATOR}chapter2")) { assertEquals(Fail("ProcessTimeoutException: Timeout is reached: 2", "ProcessTimeoutException: Timeout is reached: 2"), test.status) } else { assertTrue("test.status is actually ${test.status::class.simpleName}: $test") { test.status is Pass || test.status is Ignored } if (test.status is Ignored) { assertEquals(Ignored("Excluded by configuration"), test.status) } else { assertTrue(test.status is Pass) } } } return testReporter }
35
Kotlin
2
24
b2ad9025696cdbcd10fdc6fc7f4c79d5bbb5381e
3,394
save
MIT License