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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
core/src/test/kotlin/org/coepi/api/Fixtures.kt | TCNCoalition | 260,516,846 | true | {"Kotlin": 26416, "HCL": 6080, "Shell": 289} | package org.coepi.api
import io.mockk.every
import io.mockk.mockk
import org.assertj.core.api.ObjectAssert
import org.coepi.api.v4.dao.TCNReportRecord
object Fixtures {
fun someBytes() = ByteArray(42) { it.toByte() }
fun mockSavedReport(): TCNReportRecord = mockk {
every { reportId } returns "<mock report id>"
}
}
| 0 | Kotlin | 4 | 0 | fb4646621a0f32614e5c58eb601adc802732b4eb | 344 | tcn-backend-aws | MIT License |
app/src/main/java/uk/nhs/nhsx/sonar/android/app/onboarding/PostCodeNavigation.kt | Ecosify | 268,914,468 | true | {"Kotlin": 472891, "Dockerfile": 4405, "Shell": 4052} | /*
* Copyright © 2020 NHSX. All rights reserved.
*/
package uk.nhs.nhsx.sonar.android.app.onboarding
sealed class PostCodeNavigation {
object Permissions : PostCodeNavigation()
}
| 0 | Kotlin | 0 | 0 | 498c8eb194a6db7fcb92c82ff0b51eb7485bc391 | 187 | COVID-19-app-Android-BETA | MIT License |
app/src/main/java/com/horsefarmer/asm/AsmApplication.kt | HorseFarmer-Ma | 294,121,291 | false | null | package com.horsefarmer.asm
import android.app.Application
import android.content.Context
class AsmApplication : Application() {
override fun onCreate() {
super.onCreate()
context = this
}
companion object {
@JvmStatic
lateinit var context: Context
}
} | 0 | Kotlin | 0 | 1 | 73125955610934fe90b8421c02a6bcddfcf35679 | 303 | HorseFarmer-ASM | Apache License 2.0 |
app/src/main/java/com/appcake/modsforvalheim/core/model/seeds/SeedData.kt | zainshah412-eng | 639,874,991 | false | null | package com.appcake.modsforvalheim.core.model.seeds
data class SeedData(
val itemTitle: String? = null,
val itemDes: String? = null,
val ImageId: String? = null,
val favourite: Boolean? = false,
) | 0 | Kotlin | 0 | 0 | 507940ba15a7953de07fbab9e0fe992036b731ff | 213 | ModsOfValhiem | Apache License 2.0 |
app/demo-adapter/src/main/java/com/gmail/jiangyang5157/demo_adapter/recycleview/TextItemDelegate.kt | jiangyang5157 | 553,993,370 | false | null | package com.gmail.jiangyang5157.demo_adapter.recycleview
import android.content.Context
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.gmail.jiangyang5157.adapter.recycleview.RecycleViewItemDelegate
import com.gmail.jiangyang5157.demo_adapter.databinding.ItemTextBinding
import com.gmail.jiangyang5157.demo_adapter.item.TextItem
class TextItemDelegate :
RecycleViewItemDelegate<TextItem, TextItemDelegate.ViewHolder>() {
override fun onCreateViewHolder(context: Context, parent: ViewGroup): ViewHolder {
return ViewHolder(ItemTextBinding.inflate(LayoutInflater.from(context), parent, false))
}
override fun onBindViewHolder(viewHolder: ViewHolder, item: TextItem) {
viewHolder.binding.tv.text = item.title
}
class ViewHolder(val binding: ItemTextBinding) : RecyclerView.ViewHolder(binding.root)
}
| 0 | Kotlin | 0 | 0 | bd3252ce62e592405fa2ffa4ce82e3dbab339df2 | 920 | kotlin-multiplatform-mobile | MIT License |
app/src/main/java/pl/ravine/jumpingtiger/TigerScreenState.kt | circusmagnus | 637,764,357 | false | null | package pl.ravine.jumpingtiger
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.geometry.Offset
import kotlin.random.Random
import kotlin.random.nextInt
private const val tigerBaseX = 400f
private const val tigerBaseY = 1800f
internal enum class HeadTo { RIGHT, LEFT }
private const val errorMargin = 30
@Composable
internal fun rememberTigerScreen() = remember {
TigerScreenState()
}
internal class TigerScreenState {
var tigerOffset by mutableStateOf(Offset(tigerBaseX, tigerBaseY))
private set
var headTo: HeadTo by mutableStateOf(HeadTo.RIGHT)
private set
var hamburgerOffset by mutableStateOf(calculateHamburgerOffset())
private set
var isCatchingHamburger by mutableStateOf(false)
private fun calculateHamburgerOffset(): Offset {
val randomX = Random.nextInt(-350..350)
val randomY = Random.nextInt(-1750..-300)
return Offset(
x = tigerBaseX + randomX,
y = tigerBaseY + randomY
)
}
fun onTap(offset: Offset) {
headTo = if (offset.x < tigerOffset.x) HeadTo.LEFT else HeadTo.RIGHT
tigerOffset = offset
}
fun checkHamburgerCatched(currentPosition: Offset) {
if (isCatchingHamburger) return
val xHamburgerRange = hamburgerOffset.x - errorMargin..hamburgerOffset.x + errorMargin
val yHamburgerRange = hamburgerOffset.y - errorMargin..hamburgerOffset.y + errorMargin
isCatchingHamburger = currentPosition.x in xHamburgerRange && currentPosition.y in yHamburgerRange
}
fun hamburgerConsumed(){
isCatchingHamburger = false
hamburgerOffset = calculateHamburgerOffset()
}
fun onJumpHighpoint() {
tigerOffset = tigerOffset.copy(y = tigerBaseY)
}
} | 0 | Kotlin | 0 | 0 | 5f302c385ed07bdfd36c5f1b9686071607b20c4e | 1,964 | JumpingTiger | MIT License |
notary-commons/src/test/kotlin/com/d3/commons/config/ConfigsPriorityTest.kt | d3ledger | 129,921,969 | false | null | /*
* Copyright D3 Ledger, Inc. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
package com.d3.commons.config
import org.junit.Assert.assertEquals
import org.junit.Rule
import org.junit.Test
import org.junit.contrib.java.lang.system.EnvironmentVariables
class ConfigsPriorityTest {
@Rule
@JvmField
//For environment variables dependent code testing
val environmentVariables = EnvironmentVariables()
/**
* @given environment variables full of passwords
* @when properties file is passed to loadEthPasswords()
* @then EthPasswordsConfig is constructed based on environment variables
*/
@Test
fun testLoadEthPasswordsEnv() {
setEthEnvVariables()
val envCredentialsPassword = System.getenv(ETH_CREDENTIALS_PASSWORD_ENV)
val envNodeLogin = System.getenv(ETH_NODE_LOGIN_ENV)
val envNodePassword = System.getenv(ETH_NODE_PASSWORD_ENV)
val ethPasswords = loadEthPasswords("test", "/eth/ethereum_password.properties").get()
assertEquals(envCredentialsPassword, ethPasswords.credentialsPassword)
assertEquals(envNodeLogin, ethPasswords.nodeLogin)
assertEquals(envNodePassword, ethPasswords.nodePassword)
}
/**
* @given environment variables containing account id property
* @when test properties file is passed to loadConfigs
* @then MixedConfig is constructed based on both environment variables and file
*/
@Test
fun testTestConfigEnvPartially() {
val envAccountId = "envAccountId"
val testConfig = loadConfigs("test", TestConfig::class.java, "/test.properties").get()
environmentVariables.set("TEST_TESTCREDENTIALCONFIG_ACCOUNTID", envAccountId)
val mixedConfig = loadConfigs("test", TestConfig::class.java, "/test.properties").get()
assertEquals(envAccountId, mixedConfig.testCredentialConfig.accountId)
assertEquals(
testConfig.testCredentialConfig.pubkeyPath,
mixedConfig.testCredentialConfig.pubkeyPath
)
assertEquals(
testConfig.testCredentialConfig.privkeyPath,
mixedConfig.testCredentialConfig.privkeyPath
)
}
/**
* @given environment variables containing test properties
* @when wrong test properties file is passed to loadConfigs
* @then EnvConfig is constructed based on environment variables values
*/
@Test
fun testTestConfigEnv() {
val testConfig = loadConfigs("test", TestConfig::class.java, "/test.properties").get()
environmentVariables.set("ENV_ETHTESTACCOUNT", testConfig.ethTestAccount)
environmentVariables.set("ENV_IROHA_HOSTNAME", testConfig.iroha.hostname)
environmentVariables.set("ENV_IROHA_PORT", testConfig.iroha.port.toString())
environmentVariables.set("ENV_ETHEREUM_URL", testConfig.ethereum.url)
environmentVariables.set(
"ENV_ETHEREUM_CONFIRMATIONPERIOD",
testConfig.ethereum.confirmationPeriod.toString()
)
environmentVariables.set(
"ENV_ETHEREUM_CREDENTIALSPATH",
testConfig.ethereum.credentialsPath
)
environmentVariables.set("ENV_ETHEREUM_GASPRICE", testConfig.ethereum.gasPrice.toString())
environmentVariables.set("ENV_ETHEREUM_GASLIMIT", testConfig.ethereum.gasLimit.toString())
environmentVariables.set(
"ENV_TESTCREDENTIALCONFIG_ACCOUNTID",
testConfig.testCredentialConfig.accountId
)
environmentVariables.set(
"ENV_TESTCREDENTIALCONFIG_PUBKEYPATH",
testConfig.testCredentialConfig.pubkeyPath
)
environmentVariables.set(
"ENV_TESTCREDENTIALCONFIG_PRIVKEYPATH",
testConfig.testCredentialConfig.privkeyPath
)
// Pass an nonexistent file to be sure all values are loaded from the environment
val envConfig = loadConfigs("env", TestConfig::class.java, "/NOSUCHFILE.properties").get()
assertEquals(testConfig.ethTestAccount, envConfig.ethTestAccount)
assertEquals(testConfig.iroha.hostname, envConfig.iroha.hostname)
assertEquals(testConfig.iroha.port, envConfig.iroha.port)
assertEquals(testConfig.ethereum.url, envConfig.ethereum.url)
assertEquals(testConfig.ethereum.confirmationPeriod, envConfig.ethereum.confirmationPeriod)
assertEquals(testConfig.ethereum.credentialsPath, envConfig.ethereum.credentialsPath)
assertEquals(testConfig.ethereum.gasPrice, envConfig.ethereum.gasPrice)
assertEquals(testConfig.ethereum.gasLimit, envConfig.ethereum.gasLimit)
assertEquals(
testConfig.testCredentialConfig.accountId,
envConfig.testCredentialConfig.accountId
)
assertEquals(
testConfig.testCredentialConfig.pubkeyPath,
envConfig.testCredentialConfig.pubkeyPath
)
assertEquals(
testConfig.testCredentialConfig.privkeyPath,
envConfig.testCredentialConfig.privkeyPath
)
}
private fun setEthEnvVariables() {
environmentVariables.set(ETH_CREDENTIALS_PASSWORD_ENV, "env_credentialsPassword")
environmentVariables.set(ETH_NODE_LOGIN_ENV, "env_nodeLogin")
environmentVariables.set(ETH_NODE_PASSWORD_ENV, "env_nodePassword")
}
}
| 2 | Kotlin | 5 | 15 | 0e719a1a8fcdce23933df68749028befe40cbc50 | 5,367 | notary | Apache License 2.0 |
idea/testData/refactoring/rename/quotedToNonQuoted/before/test.kt | JakeWharton | 99,388,807 | false | null | fun /*rename*/`fun`(n: Int) {
}
fun test() {
`fun`(1)
`fun`(2)
} | 0 | null | 28 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 74 | kotlin | Apache License 2.0 |
app/src/main/java/com/example/mywiki/data/remote/response/SearchResponse.kt | uditbhaskar | 368,022,314 | false | null | package com.example.mywiki.data.remote.response
import com.example.mywiki.data.model.Continues
import com.example.mywiki.data.model.Pages
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
data class SearchResponse(
@Expose
@SerializedName("batchcomplete")
var batchcomplete: Boolean?,
@Expose
@SerializedName("continue")
var total: Continues?,
@Expose
@SerializedName("query")
var query : Pages?
)
| 0 | Kotlin | 6 | 8 | 952fe8a9493d5821cb3a2584f0a3ae21dfb9cec0 | 479 | MyWiki | MIT License |
packages/amplify_auth_cognito/android/src/main/kotlin/com/amazonaws/amplify/amplify_auth_cognito/types/FlutterResetPasswordResult.kt | aws-amplify | 253,571,453 | false | null | /*
* Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.amazonaws.amplify.amplify_auth_cognito.types
import com.amplifyframework.auth.result.AuthResetPasswordResult
import com.amazonaws.amplify.amplify_auth_cognito.setNextStep
data class FlutterResetPasswordResult(private val raw: AuthResetPasswordResult) {
val isPasswordReset: Boolean = raw.isPasswordReset
val nextStep: Map<String, Any> = setNextStep(
"resetPasswordStep",
raw.nextStep.resetPasswordStep.toString(),
raw.nextStep.codeDeliveryDetails,
raw.nextStep.additionalInfo)
fun toValueMap(): Map<String, Any> {
return mapOf(
"isPasswordReset" to this.isPasswordReset,
"nextStep" to this.nextStep
)
}
}
| 172 | Dart | 128 | 953 | ca3790498eae4e027aa0579cd6148f3ae7d6cebe | 1,247 | amplify-flutter | Apache License 2.0 |
libs/lib_database/src/main/java/com/bael/dads/lib/database/repository/DefaultDadsRepository.kt | virendersran01 | 356,644,618 | true | {"Kotlin": 200059} | package com.bael.dads.lib.database.repository
import com.bael.dads.lib.database.DadsDatabase
import com.bael.dads.lib.database.dao.DadJokeDao
import javax.inject.Inject
/**
* Created by ErickSumargo on 01/04/21.
*/
internal class DefaultDadsRepository @Inject constructor(database: DadsDatabase) :
DadsRepository,
DadJokeDao by database.dadJoke
| 0 | null | 0 | 1 | 0dab6bcc5d7a6f726140e80fc21f503ab8b07c07 | 358 | Dads | MIT License |
app/src/main/java/com/babylon/wallet/android/presentation/dapp/authorized/personaonetime/PersonaDataOnetimeViewModel.kt | radixdlt | 513,047,280 | false | {"Kotlin": 4341361, "HTML": 215350, "Java": 18496, "Ruby": 2757, "Shell": 1962} | package com.babylon.wallet.android.presentation.dapp.authorized.personaonetime
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.viewModelScope
import com.babylon.wallet.android.domain.model.RequiredPersonaFields
import com.babylon.wallet.android.presentation.common.OneOffEvent
import com.babylon.wallet.android.presentation.common.OneOffEventHandler
import com.babylon.wallet.android.presentation.common.OneOffEventHandlerImpl
import com.babylon.wallet.android.presentation.common.StateViewModel
import com.babylon.wallet.android.presentation.common.UiState
import com.babylon.wallet.android.presentation.dapp.authorized.selectpersona.PersonaUiModel
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.collections.immutable.ImmutableList
import kotlinx.collections.immutable.persistentListOf
import kotlinx.collections.immutable.toImmutableList
import kotlinx.collections.immutable.toPersistentList
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import rdx.works.core.preferences.PreferencesManager
import rdx.works.profile.data.model.pernetwork.Network
import rdx.works.profile.domain.GetProfileUseCase
import rdx.works.profile.domain.personasOnCurrentNetwork
import javax.inject.Inject
@HiltViewModel
class PersonaDataOnetimeViewModel @Inject constructor(
savedStateHandle: SavedStateHandle,
private val getProfileUseCase: GetProfileUseCase,
private val preferencesManager: PreferencesManager
) : StateViewModel<PersonaDataOnetimeUiState>(), OneOffEventHandler<PersonaDataOnetimeEvent> by OneOffEventHandlerImpl() {
private val args = PersonaDataOnetimeArgs(savedStateHandle)
override fun initialState(): PersonaDataOnetimeUiState {
return PersonaDataOnetimeUiState()
}
init {
viewModelScope.launch {
getProfileUseCase.personasOnCurrentNetwork.collect { personas ->
_state.update { state ->
state.copy(
personaListToDisplay = personas.map {
PersonaUiModel(it, requiredPersonaFields = args.requiredPersonaFields)
}.toImmutableList()
)
}
}
}
}
fun onSelectPersona(persona: Network.Persona) {
val updatedPersonas = state.value.personaListToDisplay.map {
it.copy(selected = it.persona.address == persona.address)
}.toPersistentList()
_state.update { it.copy(personaListToDisplay = updatedPersonas, continueButtonEnabled = true) }
}
fun onCreatePersona() {
viewModelScope.launch {
sendEvent(PersonaDataOnetimeEvent.CreatePersona(preferencesManager.firstPersonaCreated.first()))
}
}
fun onEditClick(personaAddress: String) {
viewModelScope.launch {
sendEvent(PersonaDataOnetimeEvent.OnEditPersona(personaAddress, args.requiredPersonaFields))
}
}
}
sealed interface PersonaDataOnetimeEvent : OneOffEvent {
data class OnEditPersona(
val personaAddress: String,
val requiredPersonaFields: RequiredPersonaFields
) : PersonaDataOnetimeEvent
data class CreatePersona(val firstPersonaCreated: Boolean) : PersonaDataOnetimeEvent
}
data class PersonaDataOnetimeUiState(
val personaListToDisplay: ImmutableList<PersonaUiModel> = persistentListOf(),
val continueButtonEnabled: Boolean = false
) : UiState {
fun selectedPersona(): Network.Persona {
return personaListToDisplay.first { it.selected }.persona
}
}
| 6 | Kotlin | 11 | 6 | 2509c9bd9b5db75bc4d793f98d3ac055a8ae4730 | 3,597 | babylon-wallet-android | Apache License 2.0 |
app/src/main/java/com/renamecompanyname/renameappname/ui/navigation/destinations/profile/EditProfileNavigation.kt | pim-developer | 839,680,760 | false | {"Kotlin": 31883} | package com.renamecompanyname.renameappname.ui.navigation.destinations.profile
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import androidx.navigation.compose.composable
import androidx.navigation.toRoute
import com.renamecompanyname.renameappname.presentation.profile.EditProfileViewModel
import com.renamecompanyname.renameappname.ui.profile.EditProfileScreen
import kotlinx.serialization.Serializable
@Serializable
internal data class EditProfile(val id: String)
internal fun NavController.navigateToEditProfile(id: String) {
navigate(route = EditProfile(id = id))
}
internal fun NavGraphBuilder.editProfileDestination(
onNavigateToProfile: (id: String) -> Unit,
) {
composable<EditProfile> { navBackStackEntry ->
val editProfile: EditProfile = navBackStackEntry.toRoute() // get arguments from route
val viewModel: EditProfileViewModel = hiltViewModel()
EditProfileScreen(
editProfileUiState = viewModel.uiState.value,
onNavigateToProfile = { onNavigateToProfile(editProfile.id) }
)
}
}
| 10 | Kotlin | 1 | 1 | 107873a3b38786386837ab1cc014d7cbe123b3dd | 1,162 | modern-android-template-quick-start | MIT License |
core/presentation/src/main/java/com/gigauri/reptiledb/module/core/presentation/Theme.kt | george-gigauri | 758,816,993 | false | {"Kotlin": 306896} | package com.gigauri.reptiledb.module.core.presentation
import androidx.compose.foundation.isSystemInDarkTheme
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.lightColorScheme
import androidx.compose.runtime.Composable
import androidx.compose.runtime.SideEffect
import androidx.compose.ui.platform.LocalView
import com.google.accompanist.systemuicontroller.rememberSystemUiController
private val LightColorScheme = lightColorScheme(
primary = HerpiColors.DarkGreenMain,
secondary = HerpiColors.LightGreen,
tertiary = HerpiColors.CreamyYellow
/* Other default colors to override
background = Color(0xFFFFFBFE),
surface = Color(0xFFFFFBFE),
onPrimary = Color.White,
onSecondary = Color.White,
onTertiary = Color.White,
onBackground = Color(0xFF1C1B1F),
onSurface = Color(0xFF1C1B1F),
*/
)
@Composable
fun HerpiDefaultTheme(
darkTheme: Boolean = isSystemInDarkTheme(),
dynamicColor: Boolean = false,
content: @Composable () -> Unit
) {
val colorScheme = LightColorScheme
val systemUi = rememberSystemUiController()
val statusBarColor = HerpiColors.DarkGreenMain
val view = LocalView.current
if (!view.isInEditMode) {
SideEffect {
systemUi.setSystemBarsColor(statusBarColor)
}
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
} | 0 | Kotlin | 0 | 2 | 8e9805993309c5a11b3d549bb591254413a595a4 | 1,448 | herpi-android | Apache License 2.0 |
instantsearch/src/androidMain/kotlin/com/algolia/instantsearch/helper/android/stats/StatsTextViewSpanned.kt | algolia | 55,971,521 | false | null | package com.algolia.instantsearch.helper.android.stats
import com.algolia.instantsearch.helper.android.item.StatsTextViewSpanned
public typealias StatsTextViewSpanned = StatsTextViewSpanned
| 5 | Kotlin | 21 | 140 | 5bf5512ffeebc61b064966ef64bc3baea49b6d9f | 192 | instantsearch-android | Apache License 2.0 |
src/commonMain/kotlin/net/ntworld/kotlin/validator/AlwaysPremierRule.kt | nhat-phan | 192,342,101 | false | null | package net.ntworld.kotlin.validator
interface AlwaysPremierRule: PremierRule {} | 0 | Kotlin | 1 | 3 | ece8335fb92772b1f199475400737ea0bf247c6b | 81 | kotlin-validator | MIT License |
project/module-editor/src/main/kotlin/ink/ptms/adyeshach/module/command/subcommand/Move.kt | TabooLib | 284,936,010 | false | {"Kotlin": 1050024, "Java": 35966} | @file:Suppress("DuplicatedCode")
package ink.ptms.adyeshach.module.command.subcommand
import ink.ptms.adyeshach.core.util.sendLang
import ink.ptms.adyeshach.module.command.*
import org.bukkit.Location
import org.bukkit.command.CommandSender
import org.bukkit.entity.Player
import taboolib.common.platform.command.*
import taboolib.platform.util.toProxyLocation
private const val STANDARD_MOVE_TRACKER = "move"
/**
* npc move (id)? (method) (...)?
*
* npc move 1 here
* npc move 1 to 0 0 0 —— 移动到指定位置
* npc move 1 to ~1 ~ ~ —— 向 x 方向移动 1 格
*/
val moveSubCommand = subCommand {
dynamic("id") {
suggestEntityList()
// 移动到当前位置
literal("here") {
execute<Player> { sender, ctx, _ ->
multiControl<EntitySource.Empty>(sender, ctx["id"], STANDARD_MOVE_TRACKER, unified = false) {
if (it.world != sender.world) {
sender.sendLang("command-world-different", ctx["id"])
return@multiControl
}
if (it.hasVehicle()) {
sender.sendLang("command-move-has-vehicle", ctx["id"], it.getVehicle()!!.id)
return@multiControl
}
it.moveTarget = sender.location
if (!sender.isIgnoreNotice()) {
sender.sendLang("command-move-to-here", it.id)
}
}
}
}
// 移动到指定位置
literal("to").xyz {
execute<CommandSender> { sender, ctx, _ ->
multiControl<EntitySource.Empty>(sender, ctx["id"], STANDARD_MOVE_TRACKER, unified = false) {
if (it.hasVehicle()) {
sender.sendLang("command-move-has-vehicle", ctx["id"], it.getVehicle()!!.id)
return@multiControl
}
val origin = it.getLocation().toProxyLocation()
val loc = Location(it.world, ctx.x("x", origin), ctx.y("y", origin), ctx.z("z", origin))
it.moveTarget = loc
if (!sender.isIgnoreNotice()) {
sender.sendLang("command-move-to-location", it.id, format(loc.x), format(loc.y), format(loc.z))
}
}
}
}
}
} | 13 | Kotlin | 86 | 98 | ac7098b62db19308c9f14182e33181c079b9e561 | 2,367 | adyeshach | MIT License |
src/main/kotlin/org/universal_markup_converter/api/FlexmarkMarkdownToHtmlConverter.kt | andreas-oberheim | 65,896,281 | false | null | /*
* MIT License
* Copyright (c) 2016 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.universal_markup_converter.api
import com.vladsch.flexmark.html.HtmlRenderer
import com.vladsch.flexmark.parser.Parser
import com.vladsch.flexmark.profiles.pegdown.Extensions
import com.vladsch.flexmark.profiles.pegdown.PegdownOptionsAdapter
import java.io.File
class FlexmarkMarkdownToHtmlConverter(fromFile: String,
toFile: String) : AbstractMarkupConverter(fromFile, toFile) {
override fun convert() {
val options = PegdownOptionsAdapter.flexmarkOptions(Extensions.ALL)
val parser = Parser.builder(options).build()
val document = parser.parse(File(fromFile).readText())
val renderer = HtmlRenderer.builder(options).build()
val html = renderer.render(document)
File(toFile).writeText(html)
}
}
| 0 | Kotlin | 0 | 1 | 4c46a1d54b55d6ad92efe2574eddc19ad24101d9 | 1,931 | universal-markup-converter | MIT License |
examples/imageviewer/android/src/main/java/imageviewer/MainActivity.kt | sharklet | 312,652,752 | true | {"Kotlin": 68341, "Dockerfile": 3451, "Shell": 3024, "PowerShell": 1708} | package example.imageviewer
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.ui.platform.setContent
import example.imageviewer.view.BuildAppUI
import example.imageviewer.model.ContentState
import example.imageviewer.model.ImageRepository
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val content = ContentState.applyContent(
this@MainActivity,
"https://spvessel.com/iv/images/fetching.list"
)
setContent {
BuildAppUI(content)
}
}
} | 0 | null | 0 | 1 | bef34ad7d2fc484b6c28398893158a1ea038137b | 660 | compose-jb | Apache License 2.0 |
ontrack-job/src/main/java/net/nemerosa/ontrack/job/JobKey.kt | nemerosa | 19,351,480 | false | null | package net.nemerosa.ontrack.job
import io.micrometer.core.instrument.Tag
data class JobKey(
val type: JobType,
val id: String
) {
fun sameType(type: JobType): Boolean {
return this.type == type
}
fun sameCategory(category: JobCategory): Boolean {
return this.type.category == category
}
override fun toString(): String {
return "$type[$id]"
}
val metricTags: List<Tag>
get() = listOf(
Tag.of("job-type", type.key),
Tag.of("job-category", type.category.key)
)
companion object {
@JvmStatic
fun of(type: JobType, id: String): JobKey {
return JobKey(type, id)
}
}
}
| 57 | null | 27 | 97 | 7c71a3047401e088ba0c6d43aa3a96422024857f | 732 | ontrack | MIT License |
data/data-sources/remote/src/main/java/com/mobdao/remote/internal/services/AuthService.kt | diegohkd | 764,734,288 | false | {"Kotlin": 275910} | package com.mobdao.remote.internal.services
import com.mobdao.remote.internal.responses.AccessTokenResponse
import retrofit2.http.Field
import retrofit2.http.FormUrlEncoded
import retrofit2.http.POST
internal interface AuthService {
@FormUrlEncoded
@POST("oauth2/token")
suspend fun getAccessToken(
@Field("grant_type")
grantType: String,
@Field("client_id")
clientId: String,
@Field("client_secret")
clientSecret: String
): AccessTokenResponse
}
| 0 | Kotlin | 0 | 0 | 0bf628c83f6c645a41188e707413706770591739 | 513 | AdoptAPet | Apache License 2.0 |
backend/app/src/main/kotlin/io/tolgee/component/rateLimits/UserRateLimit.kt | tolgee | 303,766,501 | false | null | package io.tolgee.component.rateLimits
import io.tolgee.security.AuthenticationFacade
import io.tolgee.security.rateLimis.RateLimit
import io.tolgee.security.rateLimis.RateLimitLifeCyclePoint
import org.springframework.context.ApplicationContext
import org.springframework.stereotype.Component
import javax.servlet.http.HttpServletRequest
/**
* User rate limit according to pricing
*/
@Component
class UserRateLimit : RateLimit {
override val urlMatcher: Regex
get() = Regex("/.*")
override val condition: (
request: HttpServletRequest,
applicationContext: ApplicationContext
) -> Boolean = { _, context ->
val authenticationFacade = context.getBean(AuthenticationFacade::class.java)
authenticationFacade.userAccountOrNull?.let { true } ?: false
}
override val keyPrefix: String = "user_id"
override val keyProvider: (
request: HttpServletRequest,
applicationContext: ApplicationContext
) -> String = { _, context ->
val authenticationFacade = context.getBean(AuthenticationFacade::class.java)
authenticationFacade.userAccount.id.toString()
}
override val bucketSizeProvider = { 400 }
override val timeToRefillInMs = 60000
override val lifeCyclePoint: RateLimitLifeCyclePoint = RateLimitLifeCyclePoint.AFTER_AUTHORIZATION
}
| 100 | Kotlin | 40 | 666 | 38c1064783f3ec5d60d0502ec0420698395af539 | 1,292 | tolgee-platform | Apache License 2.0 |
core/src/main/kotlin/ca/allanwang/kau/utils/ActivityUtils.kt | bobby-walle | 115,142,126 | true | {"Kotlin": 370279, "Java": 118232, "HTML": 3366, "Shell": 566, "Ruby": 25} | package ca.allanwang.kau.utils
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.os.Bundle
import android.support.annotation.ColorInt
import android.support.annotation.StringRes
import android.support.design.widget.Snackbar
import android.view.Menu
import android.view.View
import ca.allanwang.kau.R
import com.mikepenz.iconics.typeface.IIcon
import org.jetbrains.anko.contentView
/**
* Created by <NAME> on 2017-06-21.
*/
@DslMarker
@Target(AnnotationTarget.CLASS, AnnotationTarget.TYPE, AnnotationTarget.FUNCTION)
annotation class KauActivity
/**
* Helper class to launch an activity for result
* Counterpart of [Activity.startActivityForResult]
* For starting activities without result, see [startActivity]
*/
inline fun Activity.startActivityForResult(
clazz: Class<out Activity>,
requestCode: Int,
bundleBuilder: Bundle.() -> Unit = {},
intentBuilder: Intent.() -> Unit = {}) {
val intent = Intent(this, clazz)
intent.intentBuilder()
val bundle = Bundle()
bundle.bundleBuilder()
startActivityForResult(intent, requestCode, bundle)
}
/**
* Restarts an activity from itself with a fade animation
* Keeps its existing extra bundles and has a intentBuilder to accept other parameters
*/
inline fun Activity.restart(intentBuilder: Intent.() -> Unit = {}) {
val i = Intent(this, this::class.java)
i.putExtras(intent.extras)
i.intentBuilder()
startActivity(i)
overridePendingTransition(R.anim.kau_fade_in, R.anim.kau_fade_out) //No transitions
finish()
overridePendingTransition(R.anim.kau_fade_in, R.anim.kau_fade_out)
}
fun Activity.finishSlideOut() {
finish()
overridePendingTransition(R.anim.kau_fade_in, R.anim.kau_slide_out_right_top)
}
inline var Activity.navigationBarColor: Int
@SuppressLint("NewApi")
get() = if (buildIsLollipopAndUp) window.navigationBarColor else Color.BLACK
@SuppressLint("NewApi")
set(value) {
if (buildIsLollipopAndUp) window.navigationBarColor = value
}
inline var Activity.statusBarColor: Int
@SuppressLint("NewApi")
get() = if (buildIsLollipopAndUp) window.statusBarColor else Color.BLACK
@SuppressLint("NewApi")
set(value) {
if (buildIsLollipopAndUp) window.statusBarColor = value
}
inline var Activity.statusBarLight: Boolean
@SuppressLint("InlinedApi")
get() = if (buildIsMarshmallowAndUp) window.decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR > 0 else false
@SuppressLint("InlinedApi")
set(value) {
if (buildIsMarshmallowAndUp) {
val flags = window.decorView.systemUiVisibility
window.decorView.systemUiVisibility =
if (value) flags or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
else flags and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR.inv()
}
}
/**
* Themes the base menu icons and adds iicons programmatically based on ids
*
* Call in [Activity.onCreateOptionsMenu]
*/
fun Context.setMenuIcons(menu: Menu, @ColorInt color: Int = Color.WHITE, vararg iicons: Pair<Int, IIcon>) {
iicons.forEach { (id, iicon) ->
menu.findItem(id).icon = iicon.toDrawable(this, sizeDp = 18, color = color)
}
}
fun Activity.hideKeyboard() = currentFocus.hideKeyboard()
fun Activity.showKeyboard() = currentFocus.showKeyboard()
fun Activity.snackbar(text: String, duration: Int = Snackbar.LENGTH_LONG, builder: Snackbar.() -> Unit = {})
= contentView!!.snackbar(text, duration, builder)
fun Activity.snackbar(@StringRes textId: Int, duration: Int = Snackbar.LENGTH_LONG, builder: Snackbar.() -> Unit = {})
= contentView!!.snackbar(textId, duration, builder) | 0 | Kotlin | 0 | 0 | fb9ca21757068c0fb4123a5e30b1471ae4c32cf3 | 3,811 | KAU | Apache License 2.0 |
app/src/main/java/com/istu/schedule/domain/repository/schedule/ClassroomsRepository.kt | imysko | 498,018,609 | false | {"Kotlin": 702754} | package com.istu.schedule.domain.repository.schedule
import com.istu.schedule.domain.model.schedule.Classroom
interface ClassroomsRepository {
suspend fun getClassrooms(): Result<List<Classroom>>
}
| 1 | Kotlin | 0 | 2 | 0d7542e7d2864c8fe2edb4b266f48b89fcf01335 | 204 | Schedule-ISTU | MIT License |
sdk/src/main/kotlin/com/processout/sdk/ui/web/customtab/POCustomTabRedirectActivity.kt | processout | 117,821,122 | false | {"Kotlin": 1097497, "Java": 85526, "Shell": 696} | package com.processout.sdk.ui.web.customtab
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
/**
* Redirect activity that receives deep link and starts [POCustomTabAuthorizationActivity] providing return URL.
* This ensures that back stack is cleared after redirection and that Custom Chrome Tabs activity is finished.
*/
class POCustomTabRedirectActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Intent(this, POCustomTabAuthorizationActivity::class.java).let {
it.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP or Intent.FLAG_ACTIVITY_SINGLE_TOP
intent.data?.let { uri -> it.data = uri }
startActivity(it)
}
finish()
}
}
| 0 | Kotlin | 5 | 2 | 8729dd5e48d4cd4b15268dcaaa295f9e248df4db | 821 | processout-android | MIT License |
commands/src/main/kotlin/tech/carcadex/kotlinbukkitkit/commands/CommandBase.kt | CarcadeX | 681,093,300 | false | null | package tech.carcadex.kotlinbukkitkit.commands
open class CommandBase{} | 0 | Kotlin | 0 | 0 | 51ae06d7cdf27e37473e2ab208110db8c5d57004 | 72 | KotlinBukkitKit | MIT License |
collections-immutable/src/commonMain/kotlin/implementations/persistentOrderedSet/PersistentOrderedSetIterator.kt | msink | 238,201,045 | false | null | /*
* Copyright 2016-2019 JetBrains s.r.o.
* Use of this source code is governed by the Apache 2.0 License that can be found in the LICENSE.txt file.
*/
package kotlinx.collections.immutable.implementations.persistentOrderedSet
internal open class PersistentOrderedSetIterator<E>(private var nextElement: Any?,
internal val map: Map<E, Links>) : Iterator<E> {
internal var index = 0
override fun hasNext(): Boolean {
return index < map.size
}
override fun next(): E {
checkHasNext()
@Suppress("UNCHECKED_CAST")
val result = nextElement as E
index++
nextElement = map[result]!!.next
return result
}
private fun checkHasNext() {
if (!hasNext())
throw NoSuchElementException()
}
}
| 0 | Kotlin | 0 | 3 | f6531d57503e59548edb505c9828158e9c2cd20a | 842 | kotlin-compose-sdl | Apache License 2.0 |
src/test/kotlin/com/muhron/kotlinq/ElementAtTest.kt | RyotaMurohoshi | 53,187,022 | false | null | package com.muhron.kotlinq
import org.junit.Assert
import org.junit.Test
class ElementAtTest {
@Test
fun test0() {
val result = sequenceOf(1, 2, 3).elementAt(0)
Assert.assertEquals(result, 1)
}
@Test(expected = IndexOutOfBoundsException::class)
fun test1() {
sequenceOf(1, 2, 3).elementAt(3)
}
@Test(expected = IndexOutOfBoundsException::class)
fun test2() {
emptySequence<Int>().elementAt(0)
}
}
| 1 | Kotlin | 0 | 5 | 1bb201d7032cdcc302f342bc771ab356f1d96db2 | 470 | KotLinq | MIT License |
widgets/src/iosMain/kotlin/dev/icerock/moko/widgets/units/WidgetsCollectionUnitItem.kt | stevesoltys | 268,716,583 | true | {"Kotlin": 554126, "Swift": 6296, "Ruby": 3029, "Shell": 372} | /*
* Copyright 2019 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license.
*/
package dev.icerock.moko.widgets.units
import dev.icerock.moko.mvvm.livedata.LiveData
import dev.icerock.moko.units.CollectionUnitItem
import platform.UIKit.UICollectionView
import platform.UIKit.UICollectionViewCell
import platform.UIKit.translatesAutoresizingMaskIntoConstraints
import dev.icerock.moko.widgets.core.Widget
import dev.icerock.moko.widgets.style.view.WidgetSize
actual abstract class WidgetsCollectionUnitItem<T> actual constructor(
override val itemId: Long,
private val data: T
) : CollectionUnitItem {
actual abstract val reuseId: String
actual abstract fun createWidget(data: LiveData<T>): Widget<out WidgetSize>
override val reusableIdentifier: String get() = reuseId
override fun register(intoView: UICollectionView) {
intoView.registerClass(
cellClass = UICollectionViewCell().`class`(),
forCellWithReuseIdentifier = reusableIdentifier
)
}
override fun bind(collectionViewCell: UICollectionViewCell) {
collectionViewCell.contentView.setupWidgetContent(data, ::createWidget)
}
}
| 0 | null | 0 | 0 | 751235e5023c8d1f97f96abf4e6f436eaabd79df | 1,197 | moko-widgets | Apache License 2.0 |
Jetchat/app/src/main/java/com/example/compose/jetchat/DroidconEmbeddingsWrapper.kt | conceptdev | 648,744,747 | false | null | package com.example.compose.jetchat
import android.os.Build
import android.util.Log
import androidx.annotation.RequiresApi
import com.aallam.openai.api.BetaOpenAI
import com.aallam.openai.api.chat.ChatCompletion
import com.aallam.openai.api.chat.ChatCompletionRequest
import com.aallam.openai.api.chat.ChatMessage
import com.aallam.openai.api.chat.ChatRole
import com.aallam.openai.api.chat.FunctionMode
import com.aallam.openai.api.chat.chatCompletionRequest
import com.aallam.openai.api.embedding.EmbeddingRequest
import com.aallam.openai.api.image.ImageCreation
import com.aallam.openai.api.image.ImageURL
import com.aallam.openai.api.model.ModelId
import com.aallam.openai.client.OpenAI
import com.example.compose.jetchat.data.DroidconSessionData
import com.google.api.client.util.DateTime
import kotlinx.serialization.json.jsonPrimitive
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.SortedMap
/** dot product for comparing vector similarity */
infix fun DoubleArray.dot(other: DoubleArray): Double {
var out = 0.0
for (i in indices) out += this[i] * other[i]
return out
}
/** THIS IS A COPY OF OpenAIWrapper
*
* Adds embeddings to allow grounding in droidcon SF 2023 conference data
* */
@OptIn(BetaOpenAI::class)
class DroidconEmbeddingsWrapper {
private val openAIToken: String = Constants.OPENAI_TOKEN
private var conversation: MutableList<ChatMessage>
private var openAI: OpenAI = OpenAI(openAIToken)
init {
conversation = mutableListOf(
ChatMessage(
role = ChatRole.System,
content = """You are a personal assistant called JetchatAI.
You will answer questions about the speakers and sessions at the droidcon SF conference.
The conference is on June 8th and 9th, 2023 on the UCSF campus in Mission Bay.
It starts at 8am and finishes by 6pm.
Your answers will be short and concise, since they will be required to fit on
a mobile device display.
When showing session information, always include the subject, speaker, location, and time.
ONLY show the description when responding about a single session.
Only use the functions you have been provided with.""".trimMargin()
)
)
}
suspend fun chat(message: String): String {
initVectorCache() // should only run once (HACK: wait to finish)
val messagePreamble = grounding(message)
// add the user's message to the chat history
conversation.add(
ChatMessage(
role = ChatRole.User,
content = messagePreamble + message
)
)
// build the OpenAI network request
val chatCompletionRequest = chatCompletionRequest {
model = ModelId(Constants.OPENAI_CHAT_MODEL)
messages = conversation
// hardcoding functions every time (for now)
functions {
function {
name = SessionsByTimeFunction.name()
description = SessionsByTimeFunction.description()
parameters = SessionsByTimeFunction.params()
}
// function {
// name = TimeForSessionFunctions.name()
// description = TimeForSessionFunctions.description()
// parameters = TimeForSessionFunctions.params()
// }
function {
name = AddFavoriteFunction.name()
description = AddFavoriteFunction.description()
parameters = AddFavoriteFunction.params()
}
function {
name = RemoveFavoriteFunction.name()
description = RemoveFavoriteFunction.description()
parameters = RemoveFavoriteFunction.params()
}
function {
name = ListFavoritesFunction.name()
description = ListFavoritesFunction.description()
parameters = ListFavoritesFunction.params()
}
}
functionCall = FunctionMode.Auto
}
val completion: ChatCompletion = openAI.chatCompletion(chatCompletionRequest)
val completionMessage = completion.choices.first().message ?: error("no response found!")
// extract the response to show in the app
var chatResponse = completion.choices[0].message?.content ?: ""
if (completionMessage.functionCall == null) {
// no function, add the response to the conversation history
Log.i("LLM", "No function call was made")
conversation.add(
ChatMessage(
role = ChatRole.Assistant,
content = chatResponse
)
)
} else { // handle function
val function = completionMessage.functionCall
Log.i("LLM", "Function ${function!!.name} was called")
var functionResponse = ""
var handled = true
when (function.name) {
SessionsByTimeFunction.name() -> {
val functionArgs = function.argumentsAsJson() ?: error("arguments field is missing")
var optionalEarliestTime = ""
var optionalLatestTime = ""
if (functionArgs.containsKey("earliestTime")) {
optionalEarliestTime = functionArgs.getValue("earliestTime").jsonPrimitive.content
}
if (functionArgs.containsKey("latestTime")) {
optionalLatestTime = functionArgs.getValue("latestTime").jsonPrimitive.content
}
functionResponse = SessionsByTimeFunction.function(
functionArgs.getValue("date").jsonPrimitive.content,
optionalEarliestTime,
optionalLatestTime
)
}
TimeForSessionFunctions.name() -> {
val functionArgs =
function.argumentsAsJson() ?: error("arguments field is missing")
functionResponse = TimeForSessionFunctions.function(
functionArgs.getValue("subject").jsonPrimitive.content
)
}
AddFavoriteFunction.name() -> {
val functionArgs =
function.argumentsAsJson() ?: error("arguments field is missing")
functionResponse = AddFavoriteFunction.function(
functionArgs.getValue("id").jsonPrimitive.content
)
}
RemoveFavoriteFunction.name() -> {
val functionArgs =
function.argumentsAsJson() ?: error("arguments field is missing")
functionResponse = RemoveFavoriteFunction.function(
functionArgs.getValue("id").jsonPrimitive.content
)
}
ListFavoritesFunction.name() -> {
// val functionArgs =
// function.argumentsAsJson() ?: error("arguments field is missing")
functionResponse = ListFavoritesFunction.function()
}
else -> {
Log.i("LLM", "Function ${function!!.name} does not exist")
handled = false
chatResponse += " " + function.name + " " + function.arguments
conversation.add(
ChatMessage(
role = ChatRole.Assistant,
content = chatResponse
)
)
}
}
if (handled) {
// add the 'call a function' response to the history
conversation.add(
ChatMessage(
role = completionMessage.role,
content = completionMessage.content
?: "", // required to not be empty in this case
functionCall = completionMessage.functionCall
)
)
// add the response to the 'function' call to the history
conversation.add(
ChatMessage(
role = ChatRole.Function,
name = function.name,
content = functionResponse
)
)
// send the function request/response back to the model
val functionCompletionRequest = chatCompletionRequest {
model = ModelId(Constants.OPENAI_CHAT_MODEL)
messages = conversation
}
val functionCompletion: ChatCompletion =
openAI.chatCompletion(functionCompletionRequest)
// show the interpreted function response as chat completion
chatResponse = functionCompletion.choices.first().message?.content!!
conversation.add(
ChatMessage(
role = ChatRole.Assistant,
content = chatResponse
)
)
}
}
return chatResponse
}
/** Provide grounding for user query by checking
* message against embeddings.
*
* Also calculates current date and time
* (or uses `Constant` value for testing if supplied)
*
* @return the relevant data to add to the query,
* along with additional prompt instructions.
* Empty string if no matching embeddings found. */
@RequiresApi(Build.VERSION_CODES.O)
private suspend fun grounding(message: String): String {
var messagePreamble = ""
val embeddingRequest = EmbeddingRequest(
model = ModelId(Constants.OPENAI_EMBED_MODEL),
input = listOf(message)
)
val embedding = openAI.embeddings(embeddingRequest)
val messageVector = embedding.embeddings[0].embedding.toDoubleArray()
Log.i("LLM", "messageVector: $messageVector")
var sortedVectors: SortedMap<Double, String> = sortedMapOf()
// find the best match sessions
for (session in vectorCache) {
val v = messageVector dot session.value
sortedVectors[v] = session.key
Log.v("LLM", "Comparing input to ${session.key} dot $v")
}
if (sortedVectors.lastKey() > 0.8) { // arbitrary match threshold
Log.i("LLM", "Top match is ${sortedVectors.lastKey()}")
messagePreamble =
"Following are some talks/sessions scheduled for the droidcon San Francisco conference in June 2023:\n\n"
for (dpKey in sortedVectors.tailMap(0.8)) {
Log.i("LLM", "Add to preamble: ${dpKey.key} -> ${dpKey.value}")
messagePreamble += DroidconSessionData.droidconSessions[dpKey.value] + "\n\n"
}
messagePreamble += "\n\nUse the above information to answer the following question. Summarize and provide date/time and location if appropriate.\n\n"
Log.v("LLM", "$messagePreamble")
} else {
Log.i("LLM", "Top match was ${sortedVectors.lastKey()} which was below 0.8 and failed to meet criteria for grounding data")
}
// ALWAYS add the date and time to every prompt
var date = Constants.TEST_DATE
var time = Constants.TEST_TIME
if (date == "") {
date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
}
if (time == "") {
time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm"))
}
messagePreamble =
"The current date is $date and the time (in 24 hour format) is $time.\n\n$messagePreamble"
return messagePreamble
}
suspend fun imageURL(prompt: String): String {
val imageRequest = ImageCreation(prompt)
// OpenAI network request
val images: List<ImageURL> = openAI.imageURL(imageRequest)
return if (images.isEmpty()) "" else images[0].url
}
/** key'd map of session to vector */
private var vectorCache: MutableMap<String, DoubleArray> = mutableMapOf()
/** make embedding requests for each session, populate vectorCache */
suspend fun initVectorCache () {
if (vectorCache.isEmpty()) {
for (session in DroidconSessionData.droidconSessions) {
val embeddingRequest = EmbeddingRequest(
model = ModelId(Constants.OPENAI_EMBED_MODEL),
input = listOf(session.value)
)
val embedding = openAI.embeddings(embeddingRequest)
val vector = embedding.embeddings[0].embedding.toDoubleArray()
vectorCache[session.key] = vector
Log.i("LLM", "$session.key vector: $vector")
}
}
}
} | 0 | Kotlin | 0 | 5 | 942abb8512a04d90661fa796668f1e7062ea5a42 | 13,375 | droidcon-sf-23 | Apache License 2.0 |
android4337/src/test/java/io/cometh/android4337/gasprice/RPCGasEstimatorTests.kt | cometh-hq | 813,532,041 | false | {"Kotlin": 152124, "Java": 18433} | package io.cometh.android4337.gasprice
import io.cometh.android4337.web3j.EthFeeHistory
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.mockk
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.web3j.protocol.Web3jService
import org.web3j.protocol.core.Request
class RPCGasEstimatorTests {
@MockK
lateinit var web3jService: Web3jService
@MockK
lateinit var web3jPort: Web3jPort
@Before
fun before() {
MockKAnnotations.init(this)
}
@Test
fun getGasFeesWithBaseMultiplier100AndPriorityMultiplier100() {
val rpcGasEstimator = RPCGasEstimator(
web3jService,
baseFeePercentMultiplier = 100L,
priorityFeePercentMultiplier = 100L,
web3jPort
)
val request = mockk<Request<Any, EthFeeHistory>>()
val ethFeeHistory = EthFeeHistory().apply {
result = EthFeeHistory.FeeHistory(
"0x531c",
listOf(listOf("0x155a4548"), listOf("0x59682f00"), listOf("0x3b9aca00"), listOf("0x59682f00"), listOf("0x59682f00")),
listOf("0xc876a5b8", "0xc5b2834c", "0xbb3a432a", "0xc3f3bbac", "0xc6617c5e", "0xc816c3d2"),
listOf(0.4448049, 0.2881665, 0.6863933666666666, 0.5495778666666666, 0.5344412666666667)
)
}
every { request.send() } returns ethFeeHistory
every { web3jPort.ethFeeHistory(any(), any(), any()) } returns request
val gasPrice = rpcGasEstimator.getGasPrice()
Assert.assertEquals(1171647502.toBigInteger(), gasPrice.maxPriorityFeePerGas)
Assert.assertEquals(3356935122.toBigInteger() + gasPrice.maxPriorityFeePerGas, gasPrice.maxFeePerGas)
}
} | 0 | Kotlin | 0 | 0 | ad59bdcff3338e49728d119be374a1e61f6865d5 | 1,789 | android4337 | Apache License 2.0 |
arrow-libs/core/arrow-core/src/main/kotlin/arrow/core/extensions/mapk/unalign/MapKUnalign.kt | clojj | 343,913,289 | true | {"Kotlin": 6274993, "SCSS": 78040, "JavaScript": 77812, "HTML": 21200, "Scala": 8073, "Shell": 2474, "Ruby": 83} | package arrow.core.extensions.mapk.unalign
import arrow.Kind
import arrow.core.ForMapK
import arrow.core.Ior
import arrow.core.MapK.Companion
import arrow.core.Tuple2
import arrow.core.extensions.MapKUnalign
import kotlin.Any
import kotlin.Deprecated
import kotlin.Function1
import kotlin.PublishedApi
import kotlin.Suppress
import kotlin.jvm.JvmName
/**
* cached extension
*/
@PublishedApi()
internal val unalign_singleton: MapKUnalign<Any?> = object : MapKUnalign<Any?> {}
@JvmName("unalign")
@Suppress(
"UNCHECKED_CAST",
"USELESS_CAST",
"EXTENSION_SHADOWED_BY_MEMBER",
"UNUSED_PARAMETER"
)
@Deprecated(
"@extension kinded projected functions are deprecated",
ReplaceWith(
"arg0.unalign()",
"arrow.core.unalign"
),
DeprecationLevel.WARNING
)
fun <K, A, B> unalign(arg0: Kind<Kind<ForMapK, K>, Ior<A, B>>): Tuple2<Kind<Kind<ForMapK, K>, A>,
Kind<Kind<ForMapK, K>, B>> = arrow.core.MapK
.unalign<K>()
.unalign<A, B>(arg0) as arrow.core.Tuple2<arrow.Kind<arrow.Kind<arrow.core.ForMapK, K>, A>,
arrow.Kind<arrow.Kind<arrow.core.ForMapK, K>, B>>
@JvmName("unalignWith")
@Suppress(
"UNCHECKED_CAST",
"USELESS_CAST",
"EXTENSION_SHADOWED_BY_MEMBER",
"UNUSED_PARAMETER"
)
@Deprecated(
"@extension kinded projected functions are deprecated",
ReplaceWith(
"arg0.unalign { (_, c) -> arg1(c) }",
"arrow.core.unalign"
),
DeprecationLevel.WARNING
)
fun <K, A, B, C> unalignWith(arg0: Kind<Kind<ForMapK, K>, C>, arg1: Function1<C, Ior<A, B>>):
Tuple2<Kind<Kind<ForMapK, K>, A>, Kind<Kind<ForMapK, K>, B>> = arrow.core.MapK
.unalign<K>()
.unalignWith<A, B, C>(arg0, arg1) as arrow.core.Tuple2<arrow.Kind<arrow.Kind<arrow.core.ForMapK,
K>, A>, arrow.Kind<arrow.Kind<arrow.core.ForMapK, K>, B>>
@Suppress(
"UNCHECKED_CAST",
"NOTHING_TO_INLINE"
)
@Deprecated("Unalign typeclasses is deprecated. Use concrete methods on Map")
inline fun <K> Companion.unalign(): MapKUnalign<K> = unalign_singleton as
arrow.core.extensions.MapKUnalign<K>
| 0 | null | 0 | 0 | 5eae605bbaeb2b911f69a5bccf3fa45c42578416 | 2,005 | arrow | Apache License 2.0 |
mbmobilesdk/src/main/java/com/daimler/mbmobilesdk/vehicleassignment/AssignVehicleHelpViewModel.kt | rafalzawadzki | 208,997,288 | true | {"Kotlin": 1297852, "Groovy": 4489} | package com.daimler.mbmobilesdk.vehicleassignment
import androidx.lifecycle.ViewModel
internal class AssignVehicleHelpViewModel : ViewModel() | 0 | null | 0 | 0 | 1a924f70fbde5d731cdfde275e724e6343ee6ebe | 143 | MBSDK-Mobile-Android | MIT License |
app/src/main/java/com/example/passwordmanager/usecases/GeneratePasswordUseCase.kt | PerfectCoder123 | 795,968,358 | false | {"Kotlin": 26175} | package com.example.passwordmanager.usecases
import com.example.passwordmanager.PasswordGeneratorViewState
class GeneratePasswordUseCase {
fun execute(state: PasswordGeneratorViewState): String {
val characterLength = state.characterLength.toInt()
val selectedCharacters = mutableListOf<Char>()
if (state.isLowerCaseSelected) {
selectedCharacters.addAll('a'..'z')
}
if (state.isUpperCaseSelected) {
selectedCharacters.addAll('A'..'Z')
}
if (state.isNumbersSelected) {
selectedCharacters.addAll('0'..'9')
}
if (state.isSymbolsSelected) {
selectedCharacters.addAll("!@#$%^&*()_+{}[];:,.<>?".toList())
}
if(selectedCharacters.size == 0)selectedCharacters.add(' ')
return buildString {
repeat(characterLength) {
append(selectedCharacters.random())
}
}
}
}
| 0 | Kotlin | 0 | 0 | 44c1b5921ad858a08efc887f505bf4e11d539e5f | 957 | PassGen | MIT License |
app/src/main/java/com/elshafee/androiden/breakingbadapp/ui/BreakingBadActivity.kt | madahetooo | 591,076,051 | false | {"Kotlin": 78600} | package com.elshafee.androiden.breakingbadapp.ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.navigation.NavController
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.NavigationUI
import androidx.navigation.ui.setupActionBarWithNavController
import com.elshafee.androiden.R
import com.elshafee.androiden.databinding.ActivityBreakingBadBinding
class BreakingBadActivity : AppCompatActivity() {
private lateinit var navController: NavController
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityBreakingBadBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityBreakingBadBinding.inflate(layoutInflater)
setContentView(binding.root)
navController = findNavController(R.id.nav_host_fragment)
appBarConfiguration = AppBarConfiguration(setOf())
setupActionBarWithNavController(navController)
}
override fun onSupportNavigateUp(): Boolean {
return NavigationUI.navigateUp(navController,appBarConfiguration)
}
} | 0 | Kotlin | 0 | 1 | effdf4a3df84c0db50f4a844a3f7c84fab0f5e6d | 1,225 | BreakingBadApp | Apache License 2.0 |
app/src/main/java/com/brins/lightmusic/model/artist/HotSongBean.kt | BrinsLee | 193,304,333 | false | null | package com.brins.lightmusic.model.artist
class HotSongBean {
} | 1 | Kotlin | 3 | 20 | f0be073b901efdee40d38824bc3c0cc4d6aa426d | 64 | LightMusic | Apache License 2.0 |
android/sdk/src/main/java/io/violas/sdk/Token.kt | HunterSun2018 | 459,510,904 | true | {"C++": 2042241, "Rust": 294180, "Java": 25520, "CMake": 23944, "Kotlin": 21734, "Makefile": 20437, "C": 20271, "Shell": 14588, "Python": 4239, "M4": 2035} | package io.violas.sdk
class Token {
} | 0 | C++ | 0 | 0 | e44b0ecbdcd1096f21ab6f7cc8bd717e10e9fd67 | 39 | violas-client-sdk | MIT License |
app/src/main/java/com/avi5hek/surveys/data/model/Theme.kt | AVI5HEK | 284,445,957 | false | null | package com.avi5hek.surveys.data.model
import com.google.gson.annotations.SerializedName
data class Theme(
@SerializedName("color_active")
val colorActive: String,
@SerializedName("color_answer_inactive")
val colorAnswerInactive: String,
@SerializedName("color_answer_normal")
val colorAnswerNormal: String,
@SerializedName("color_inactive")
val colorInactive: String,
@SerializedName("color_question")
val colorQuestion: String
) | 2 | Kotlin | 0 | 1 | 4b453b3a8be9c7a61b6c5a79477a0d779c001a6a | 453 | surveys | MIT License |
zowe-imperative/src/jsMain/kotlin/zowe/imperative/cmd/doc/profiles/definition/ICommandProfileProperty.kt | lppedd | 761,812,661 | false | {"Kotlin": 1887051} | package zowe.imperative.cmd.doc.profiles.definition
import zowe.imperative.cmd.doc.option.ICommandOptionDefinition
import zowe.imperative.profiles.doc.definition.IProfileProperty
import kotlin.js.plain.JsPlainObject
/**
* Extended version of a team profile schema property that can include option definitions for
* auto-generated commands.
*/
@JsPlainObject
external interface ICommandProfileProperty : IProfileProperty {
/**
* This option definition will be used to auto-generate profile commands. This is the same type
* used by normal Imperative command definitions.
*/
var optionDefinition: ICommandOptionDefinition?
var optionDefinitions: Array<ICommandOptionDefinition>?
}
| 0 | Kotlin | 0 | 3 | 0f493d3051afa3de2016e5425a708c7a9ed6699a | 699 | kotlin-externals | MIT License |
app/src/main/java/com/droidafricana/moveery/mappers/FavMovieMapper.kt | Fbada006 | 240,091,360 | false | null | package com.droidafricana.moveery.mappers
import com.droidafricana.moveery.models.favourites.movies.FavMovie
import com.droidafricana.moveery.models.movies.Movie
/**Map a [Movie] to a [FavMovie]*/
fun Movie.toFavMovieDataModel() = FavMovie(
id = this.id,
backdrop_path = this.backdrop_path,
genre_ids = this.genre_ids,
original_language = this.original_language,
original_title = this.original_title,
overview = this.overview,
poster_path = this.poster_path,
release_date = this.release_date,
title = this.title,
vote_average = this.vote_average
)
/**Map a [FavMovie] to a [Movie].*/
fun FavMovie.toMovieDomainModel() = Movie(
id = this.id,
backdrop_path = this.backdrop_path,
genre_ids = this.genre_ids,
original_language = this.original_language,
original_title = this.original_title,
overview = this.overview,
poster_path = this.poster_path,
release_date = this.release_date,
title = this.title,
vote_average = this.vote_average,
hasVideo = null,
isForAdult = null
) | 0 | Kotlin | 0 | 2 | 92b175690eac0333ecbe0d87c9f07084f6099459 | 1,060 | Moveery | Apache License 2.0 |
platform/core-impl/src/com/intellij/openapi/application/impl/modality.kt | JetBrains | 2,489,216 | false | null | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.application.impl
import com.intellij.openapi.application.EDT
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.asContextElement
import kotlinx.coroutines.*
import org.jetbrains.annotations.ApiStatus.Internal
import org.jetbrains.annotations.VisibleForTesting
import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.ContinuationInterceptor
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.coroutineContext
internal class ModalityStateElement(
val modalityState: ModalityState,
) : AbstractCoroutineContextElement(ModalityStateElement) {
companion object : CoroutineContext.Key<ModalityStateElement>
}
@VisibleForTesting
@Internal
fun CoroutineContext.contextModality(): ModalityState {
return this[ModalityStateElement]?.modalityState
?: ModalityState.any()
}
@Internal
suspend fun <X> withModalContext(
action: suspend CoroutineScope.() -> X,
): X = coroutineScope {
val originalDispatcher = requireNotNull(coroutineContext[ContinuationInterceptor])
val contextModality = coroutineContext.contextModality()
if (Dispatchers.EDT === originalDispatcher) {
if (contextModality == ModalityState.any()) {
// Force NON_MODAL, otherwise another modality could be entered concurrently.
withContext(ModalityState.NON_MODAL.asContextElement()) {
yield() // Force re-dispatch in the proper modality.
withModalContextEDT(action)
}
}
else {
withModalContextEDT(action)
}
}
else {
val enterModalModality = if (contextModality == ModalityState.any()) ModalityState.NON_MODAL else contextModality
withContext(Dispatchers.EDT + enterModalModality.asContextElement()) {
withModalContextEDT {
withContext(originalDispatcher, action)
}
}
}
}
private suspend fun <X> withModalContextEDT(action: suspend CoroutineScope.() -> X): X {
val ctx = coroutineContext
val job = ctx.job
val newModalityState = (ctx.contextModality() as ModalityStateEx).appendJob(job) as ModalityStateEx
LaterInvocator.enterModal(job, newModalityState)
try {
return withContext(newModalityState.asContextElement(), action)
}
finally {
LaterInvocator.leaveModal(job)
}
}
| 191 | null | 4372 | 13,319 | 4d19d247824d8005662f7bd0c03f88ae81d5364b | 2,406 | intellij-community | Apache License 2.0 |
app/src/main/java/com/guru/cocktails/ui/bar/myingredients/di/MyIngredientListModule.kt | morristech | 143,734,527 | false | null | package com.guru.cocktails.ui.bar.myingredients.di
import com.guru.cocktails.di.scope.ViewScope
import com.guru.cocktails.domain.interactor.definition.MyIngredientsUseCase
import com.guru.cocktails.ui.bar.myingredients.MyIngredientListContract
import com.guru.cocktails.ui.bar.myingredients.MyIngredientListPresenter
import com.guru.cocktails.ui.bar.myingredients.MyIngredientListType
import dagger.Module
import dagger.Provides
import javax.inject.Named
@Module
class MyIngredientListModule(private val type: MyIngredientListType) {
@ViewScope
@Provides
@Named("myIngredientListType")
internal fun myIngredientListType(): MyIngredientListType {
return type
}
@ViewScope
@Provides
internal fun ingredientsPresenter(
myIngredientsUseCase: MyIngredientsUseCase,
@Named("myIngredientListType") myIngredientListType: MyIngredientListType
): MyIngredientListContract.Presenter {
return MyIngredientListPresenter(myIngredientsUseCase, myIngredientListType)
}
} | 0 | Kotlin | 0 | 0 | f3feac05ebb51a7a30c2d37ccf76f4269da92f07 | 1,030 | client-android | MIT License |
src/main/kotlin/cn/therouter/idea/about/VersionAction.kt | kymjs | 700,777,348 | false | {"Kotlin": 74273} | package cn.therouter.idea.about
import cn.therouter.idea.utils.getVersion
import cn.therouter.idea.utils.gotoUrl
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.ui.MessageDialogBuilder
import com.intellij.openapi.ui.Messages
import java.io.File
import java.util.regex.Pattern
class VersionAction : AnAction() {
override fun actionPerformed(event: AnActionEvent) {
val currentVersion = event.project?.basePath?.let { foundCurrentVersion(File(it)) } ?: "UnKnow"
val version = getVersion(currentVersion)
if (MessageDialogBuilder
.okCancel(
"TheRouter",
"最新稳定版本为:${version.latestRelease} \n最新预览版为:${version.latestVersion}\n当前项目版本:$currentVersion \n\n${version.upgradeText}"
)
.noText("关闭")
.yesText("版本日志")
.icon(Messages.getInformationIcon())
.ask(event.project)
) {
gotoUrl("https://github.com/HuolalaTech/hll-wp-therouter-android/releases")
}
}
}
private val theRouterVersionStrSet = HashSet<String>()
private val versionSet = HashSet<String>()
fun foundCurrentVersion(projectFile: File): String {
createIndex(projectFile) { root ->
foundTheRouterVersionStr(
root.readText()
.replace(" ", "")
.replace("\n", "")
)
}
foundVersion(projectFile)
if (versionSet.isEmpty()) {
return "unknow"
}
var max = ""
versionSet.forEach {
if (max < it) {
max = it
}
}
return max
}
private fun createIndex(root: File, action: (File) -> Unit) {
if (root.isFile) {
if (root.name.endsWith(".gradle")
|| root.name.endsWith(".kts")
) {
action(root)
}
} else {
root.listFiles()?.forEach { file ->
createIndex(file, action)
}
}
}
private fun foundTheRouterVersionStr(content: String) {
val pattern = Pattern.compile("cn.therouter:router:[A-Za-z0-9_\\-\\.\\{\\}$]+[\"']")
val m = pattern.matcher(content)
while (m.find()) {
val version = m.group()
.replace("cn.therouter:router:", "")
.replace("'", "")
.replace("\"", "")
.replace("\$", "")
.replace("{", "")
.replace("}", "")
theRouterVersionStrSet.add(version)
}
}
private fun foundVersion(projectFile: File) {
val versionFieldSet = HashSet<String>()
theRouterVersionStrSet.forEach { versionStr ->
if (versionStr.contains("[0-9]\\.[0-9]\\.[0-9](-rc\\d)?".toRegex())) {
versionSet.add(versionStr)
} else {
versionFieldSet.add(versionStr)
}
}
createIndex(projectFile) { root ->
versionFieldSet.forEach { field ->
foundTheRouterVersionField(
field,
root.readText()
.replace(" ", "")
.replace("\n", "")
)
}
}
}
private fun foundTheRouterVersionField(versionStr: String, content: String) {
val pattern = Pattern.compile("$versionStr=[0-9]\\.[0-9]+\\.[0-9]+(-rc[0-9]+)?")
val m = pattern.matcher(content)
while (m.find()) {
val version = m.group()
.replace("$versionStr=", "")
versionSet.add(version)
}
}
| 0 | Kotlin | 0 | 9 | 0c407ff2d6a4a95ad5a551dc89e751ed0968c47c | 3,464 | TheRouterIdeaPlugin | Apache License 2.0 |
model-server/src/test/kotlin/org/modelix/model/server/handlers/ContentExplorerTest.kt | modelix | 533,211,353 | false | {"Kotlin": 2175823, "JetBrains MPS": 274458, "TypeScript": 47718, "Java": 25036, "Gherkin": 7693, "JavaScript": 5004, "Mustache": 2915, "CSS": 2812, "Shell": 2541, "Dockerfile": 378, "Procfile": 76} | /*
* Copyright (c) 2024.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.modelix.model.server.handlers
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import io.ktor.client.statement.bodyAsText
import io.ktor.http.ContentType
import io.ktor.http.contentType
import io.ktor.serialization.kotlinx.json.json
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
import io.ktor.server.resources.Resources
import io.ktor.server.routing.IgnoreTrailingSlash
import io.ktor.server.testing.ApplicationTestBuilder
import io.ktor.server.testing.testApplication
import io.ktor.server.websocket.WebSockets
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import org.jsoup.select.Evaluator
import org.modelix.model.client.successful
import org.modelix.model.lazy.CLVersion
import org.modelix.model.server.api.v2.VersionDelta
import org.modelix.model.server.store.InMemoryStoreClient
import org.modelix.model.server.store.LocalModelClient
import kotlin.test.Test
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import io.ktor.client.plugins.contentnegotiation.ContentNegotiation as ClientContentNegotiation
class ContentExplorerTest {
private val modelClient = LocalModelClient(InMemoryStoreClient())
private val repoManager = RepositoriesManager(modelClient)
private fun runTest(body: suspend (ApplicationTestBuilder.() -> Unit)) {
testApplication {
install(WebSockets)
install(ContentNegotiation) { json() }
install(Resources)
install(IgnoreTrailingSlash)
application {
ModelReplicationServer(repoManager).init(this)
ContentExplorer(modelClient, repoManager).init(this)
}
body()
}
}
@Test
fun `node inspector finds root node`() = runTest {
val client = createClient {
install(ClientContentNegotiation) { json() }
}
val delta: VersionDelta = client.post("/v2/repositories/node-inspector/init").body()
val versionHash = delta.versionHash
val version = CLVersion.loadFromHash(versionHash, modelClient.storeCache)
val nodeId = checkNotNull(version.getTree().root?.id)
val response = client.get("/content/$versionHash/$nodeId/")
assertTrue(response.successful)
}
@Test
fun `nodes can be expanded`() = runTest {
val client = createClient {
install(ClientContentNegotiation) { json() }
}
val delta: VersionDelta = client.post("/v2/repositories/node-expansion/init").body()
val versionHash = delta.versionHash
val version = CLVersion.loadFromHash(versionHash, modelClient.storeCache)
val nodeId = checkNotNull(version.getTree().root?.id)
val expandedNodes = ContentExplorerExpandedNodes(setOf(nodeId.toString()), false)
val response = client.post("/content/$versionHash/") {
contentType(ContentType.Application.Json)
setBody(expandedNodes)
}
val html = Jsoup.parse(response.bodyAsText())
val root: Element? = html.body().firstElementChild()
assertTrue { response.successful }
assertNotNull(root)
assertTrue { root.`is`(Evaluator.Tag("ul")) }
assertTrue { root.`is`(Evaluator.Class("treeRoot")) }
assertTrue { root.childrenSize() > 0 }
}
}
| 52 | Kotlin | 10 | 6 | d0855f41775775f7fb4478729a2f481d1dfe40b7 | 3,995 | modelix.core | Apache License 2.0 |
app/src/main/java/com/hegesoftware/snookerscore/domain/usecases/GetLegalBallsStream.kt | Henkkagg | 611,836,646 | false | null | package com.hegesoftware.snookerscore.domain.usecases
import com.hegesoftware.snookerscore.domain.BreakRepository
import com.hegesoftware.snookerscore.domain.models.LegalBalls
import com.hegesoftware.snookerscore.domain.models.toBreakUi
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOn
import javax.inject.Inject
class GetLegalBallsStream @Inject constructor(
private val repository: BreakRepository,
private val getScoreStream: GetScoreStream
) {
private sealed class LastPotted {
object Nothing : LastPotted()
object Red : LastPotted()
object NonRed : LastPotted()
}
operator fun invoke() = flow {
repository.getAll().collect { breakList ->
if (breakList.isEmpty()) return@collect
var lastPotted: LastPotted = LastPotted.Nothing
var redsRemaining = 15
var lowestPointRemaining = 1
var lastShotStartedPhase2 = false
for (breakDb in breakList) {
if (breakDb.redsLost >= 1 && redsRemaining - breakDb.redsLost == 0) {
lowestPointRemaining += 1
}
redsRemaining -= breakDb.redsLost
lastPotted = LastPotted.Nothing
lastShotStartedPhase2 = false
val breakPoints = breakDb.toBreakUi().breakPoints
for (pointIndex in breakPoints.indices) {
val point = breakPoints[pointIndex]
val pointWasFreeBall = pointIndex == 0 && breakDb.freeBallStatus == 2
if (pointWasFreeBall) {
lastPotted = LastPotted.Red
continue
}
if (redsRemaining > 0) {
if (point == 1) {
lastPotted = LastPotted.Red
redsRemaining -= 1
if (redsRemaining == 0) {
lastShotStartedPhase2 = true
lowestPointRemaining += 1
}
} else {
lastPotted = LastPotted.NonRed
}
} else {
if (lastShotStartedPhase2) {
lastShotStartedPhase2 = false
} else {
val score = getScoreStream().first()
//To prevent frame ending in draw, black is put back to table if scores equal
if (lowestPointRemaining != 7 || score.player1Score != score.player2Score) {
lowestPointRemaining += 1
}
}
}
}
}
val lastBreak = breakList.last()
val isFirstOfBreak = lastBreak.toBreakUi().breakPoints.isEmpty()
val isShootingFreeBall = lastBreak.freeBallStatus == 1 && isFirstOfBreak
val legalBalls = if (isShootingFreeBall || lastShotStartedPhase2) {
LegalBalls(
red = lowestPointRemaining <= 1,
yellow = lowestPointRemaining <= 2,
green = lowestPointRemaining <= 3,
brown = lowestPointRemaining <= 4,
blue = lowestPointRemaining <= 5,
pink = lowestPointRemaining <= 6,
black = lowestPointRemaining <= 7,
isFreeBall = isShootingFreeBall
)
} else {
if (redsRemaining > 0) {
LegalBalls(
//Red is always true because it's legal to pot multiple reds with same shot
red = true,
yellow = lastPotted == LastPotted.Red,
green = lastPotted == LastPotted.Red,
brown = lastPotted == LastPotted.Red,
blue = lastPotted == LastPotted.Red,
pink = lastPotted == LastPotted.Red,
black = lastPotted == LastPotted.Red
)
} else {
LegalBalls(
red = false,
yellow = lowestPointRemaining == 2,
green = lowestPointRemaining == 3,
brown = lowestPointRemaining == 4,
blue = lowestPointRemaining == 5,
pink = lowestPointRemaining == 6,
black = lowestPointRemaining == 7
)
}
}
emit(legalBalls)
}
}.flowOn(Dispatchers.IO)
} | 0 | Kotlin | 0 | 0 | 4c2a96c64c9edea1f44689e75697a8af3cb47588 | 4,888 | SnookerScore | Apache License 2.0 |
test-lib/src/main/java/com/flyjingfish/test_lib/LoginUtils.kt | FlyJingFish | 722,020,803 | false | {"Kotlin": 166067, "Java": 40881} | package com.flyjingfish.test_lib
object LoginUtils {
var login:Boolean = true
} | 0 | Kotlin | 3 | 84 | dbda228d57afd1d0dc122d1bce6377e83616ca20 | 84 | AndroidAOP | Apache License 2.0 |
autofill/autofill-impl/src/main/java/com/duckduckgo/autofill/sync/persister/CrendentialsDedupStrategy.kt | hojat72elect | 822,396,044 | false | {"Kotlin": 11627106, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784} |
package com.duckduckgo.autofill.sync.persister
import com.duckduckgo.autofill.api.domain.app.LoginCredentials
import com.duckduckgo.autofill.sync.*
import com.duckduckgo.autofill.sync.isDeleted
import com.duckduckgo.common.utils.DispatcherProvider
import com.duckduckgo.sync.api.engine.SyncMergeResult
import com.duckduckgo.sync.api.engine.SyncMergeResult.Error
import com.duckduckgo.sync.api.engine.SyncMergeResult.Success
import kotlinx.coroutines.runBlocking
import timber.log.Timber
class CredentialsDedupStrategy(
private val credentialsSync: CredentialsSync,
private val credentialsSyncMapper: CredentialsSyncMapper,
private val dispatchers: DispatcherProvider,
) : CredentialsMergeStrategy {
override fun processEntries(
credentials: credentialsSyncEntries,
clientModifiedSince: String,
): SyncMergeResult {
Timber.d("Sync-autofill-Persist: ======= MERGING DEDUPLICATION =======")
return kotlin.runCatching {
runBlocking(dispatchers.io()) {
credentials.entries.forEach { remoteEntry ->
if (remoteEntry.isDeleted()) return@forEach
val remoteLoginCredential = mapRemoteToLocalLoginCredential(remoteEntry, credentials.last_modified)
val localMatchesForDomain = credentialsSync.getCredentialsForDomain(remoteLoginCredential.domain)
if (localMatchesForDomain.isEmpty()) {
Timber.d("Sync-autofill-Persist: >>> no duplicate found, save remote $remoteLoginCredential")
credentialsSync.saveCredential(remoteLoginCredential, remoteId = remoteEntry.id)
} else {
val duplicateFound = findDuplicates(localMatchesForDomain, remoteLoginCredential, remoteEntry.id)
if (duplicateFound) return@forEach
Timber.d("Sync-autofill-Persist: >>> no duplicate found, save remote $remoteLoginCredential")
credentialsSync.saveCredential(remoteLoginCredential, remoteId = remoteEntry.id)
}
}
}
}.getOrElse {
Timber.d("Sync-autofill-Persist: merging failed with error $it")
return Error(reason = "DeDup merge failed with error $it")
}.let {
Timber.d("Sync-autofill-Persist: merging completed")
Success()
}
}
private suspend fun findDuplicates(
localMatchesForDomain: List<LoginCredentials>,
remoteLoginCredential: LoginCredentials,
remoteId: String,
): Boolean {
var duplicateFound = false
localMatchesForDomain.forEach { localMatch ->
val result = compareCredentials(localMatch, remoteLoginCredential)
when {
result == null -> {}
result <= 0 -> {
Timber.d("Sync-autofill-Persist: >>> duplicate found $localMatch, update remote $remoteLoginCredential")
remoteLoginCredential.copy(id = localMatch.id).also {
credentialsSync.updateCredentials(it, remoteId = remoteId)
}
duplicateFound = true
}
result > 0 -> {
Timber.d("Sync-autofill-Persist: >>> duplicate found $localMatch, update local $localMatch")
val localCredential = credentialsSync.getCredentialWithId(localMatch.id!!)!!
credentialsSync.updateCredentials(
loginCredential = localCredential,
remoteId = remoteId,
)
duplicateFound = true
}
}
}
return duplicateFound
}
private fun compareCredentials(
localCredential: LoginCredentials,
loginCredential: LoginCredentials,
): Int? {
Timber.i("Duplicate: compareCredentials local $localCredential vs remote $loginCredential")
val isDuplicated = with(localCredential) {
domain.orEmpty() == loginCredential.domain.orEmpty() &&
username.orEmpty() == loginCredential.username.orEmpty() &&
password.orEmpty() == loginCredential.password.orEmpty() &&
notes.orEmpty() == loginCredential.notes.orEmpty()
}
val comparison = when (isDuplicated) {
true -> localCredential.lastUpdatedMillis?.compareTo(loginCredential.lastUpdatedMillis ?: 0) ?: 0
false -> null
}
return comparison
}
private fun mapRemoteToLocalLoginCredential(
remoteEntry: CredentialsSyncEntryResponse,
clientModifiedSince: String,
): LoginCredentials {
return credentialsSyncMapper.toLoginCredential(
remoteEntry = remoteEntry,
localId = null,
lastModified = clientModifiedSince,
)
}
}
| 0 | Kotlin | 0 | 0 | 54351d039b85138a85cbfc7fc3bd5bc53637559f | 4,956 | DuckDuckGo | Apache License 2.0 |
data/src/main/java/com/amaringo/data/carecenter/network/model/Location.kt | AdrianMarinGonzalez | 329,634,066 | false | null | package com.amaringo.data.carecenter.network.model
data class Location(
val latitude: Double,
val longitude: Double
) | 0 | Kotlin | 0 | 0 | 23375a1c62cdce702d81b65f1b70e0c198bd144b | 126 | CAM-care | The Unlicense |
app/src/main/java/com/techflow/materialcolor/activity/HomeActivity.kt | dilipsuthar97 | 199,159,898 | false | null | /*
* Copyright 2020 Dilip Suthar
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.techflow.materialcolor.activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.ImageButton
import android.widget.LinearLayout
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import com.afollestad.materialdialogs.LayoutMode
import com.afollestad.materialdialogs.MaterialDialog
import com.afollestad.materialdialogs.bottomsheets.BottomSheet
import com.afollestad.materialdialogs.customview.customView
import com.afollestad.materialdialogs.customview.getCustomView
import com.facebook.ads.*
import com.google.android.material.appbar.MaterialToolbar
import com.google.android.material.button.MaterialButton
import com.google.android.material.snackbar.Snackbar
import com.google.android.play.core.appupdate.AppUpdateManagerFactory
import com.google.android.play.core.install.InstallStateUpdatedListener
import com.google.android.play.core.install.model.AppUpdateType
import com.google.android.play.core.install.model.InstallStatus
import com.google.android.play.core.install.model.UpdateAvailability
import com.techflow.materialcolor.MaterialColor
import com.techflow.materialcolor.MaterialColor.AdType
import com.techflow.materialcolor.R
import com.techflow.materialcolor.databinding.ActivityHomeBinding
import com.techflow.materialcolor.fragment.BookmarkedColorFragment
import com.techflow.materialcolor.fragment.ColorPickerFragment
import com.techflow.materialcolor.fragment.GradientFragment
import com.techflow.materialcolor.fragment.HomeFragment
import com.techflow.materialcolor.helpers.AnalyticsHelper
import com.techflow.materialcolor.helpers.displaySnackbar
import com.techflow.materialcolor.helpers.displayToast
import com.techflow.materialcolor.helpers.isDebug
import com.techflow.materialcolor.utils.SharedPref
import com.techflow.materialcolor.utils.StorageKey
import com.techflow.materialcolor.utils.ThemeUtils
import com.techflow.materialcolor.utils.Tools
/**
* @author Dilip Suthar
* Modified by Dilip Suthar on 29/05/2020
*/
class HomeActivity : BaseActivity(), SharedPreferences.OnSharedPreferenceChangeListener {
private val TAG = HomeActivity::class.java.simpleName
private val HIGH_PRIORITY_UPDATE = 5
val REQUEST_CODE_UPDATE = 201
// STATIC
companion object {
// Audience network
private lateinit var interstitialAd: InterstitialAd
fun showInterstitialAd(context: Context) {
if (!MaterialColor.getInstance().isDebug()) {
if (SharedPref.getInstance(context).actionShowInterstitialAd()) {
Log.d(HomeActivity::class.java.simpleName, "serving ads")
if (interstitialAd.isAdLoaded)
interstitialAd.show()
else if (Tools.hasNetwork(context))
interstitialAd.loadAd()
} else
SharedPref.getInstance(context).increaseInterstitialAdCounter()
}
}
}
private lateinit var binding: ActivityHomeBinding
private lateinit var sharedPref: SharedPref
private lateinit var homeFragment: HomeFragment
private lateinit var gradientFragment: GradientFragment
private lateinit var colorPickerFragment: ColorPickerFragment
private lateinit var bookmarkedColorFragment: BookmarkedColorFragment
private lateinit var activeFragment: Fragment
private var bottomSheet: MaterialDialog? = null
private var adView: AdView? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.activity_home)
sharedPref = SharedPref.getInstance(this)
initToolbar()
initComponent()
initIntro()
initBottomNavigation()
initMenuSheet()
if (!this.isDebug()) initAd()
initInAppUpdate() // Init in-app update
}
override fun onStart() {
super.onStart()
this.getSharedPreferences(packageName, Context.MODE_PRIVATE)
.registerOnSharedPreferenceChangeListener(this)
}
override fun onPause() {
super.onPause()
if (!sharedPref.getBoolean(StorageKey.BOTTOM_SHEET_CONFIG, false))
bottomSheet?.cancel()
}
override fun onDestroy() {
if (adView != null)
adView?.destroy()
super.onDestroy()
this.getSharedPreferences(packageName, Context.MODE_PRIVATE)
.unregisterOnSharedPreferenceChangeListener(this)
}
override fun onBackPressed() {
if (activeFragment != homeFragment) {
binding.justBar.setSelected(0)
displayFragment(homeFragment)
activeFragment = homeFragment
} else
appCloser()
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.menu_home, menu)
Tools.changeMenuIconColor(menu!!, ThemeUtils.getThemeAttrColor(this, R.attr.colorTextPrimary))
return super.onCreateOptionsMenu(menu)
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
if (item.itemId == R.id.action_menu) {
bottomSheet?.show()
return true
}
return super.onOptionsItemSelected(item)
}
override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
if (key!! == StorageKey.THEME)
recreate()
}
/**
* @func init toolbar config
*/
private fun initToolbar() {
setSupportActionBar(binding.toolbar as MaterialToolbar)
supportActionBar?.title = resources.getString(R.string.app_name)
}
/**
* @func init all component's config
*/
private fun initComponent() {
homeFragment = HomeFragment.getInstance()
gradientFragment = GradientFragment.getInstance()
colorPickerFragment = ColorPickerFragment.getInstance()
bookmarkedColorFragment = BookmarkedColorFragment.getInstance()
displayFragment(homeFragment)
}
/**
* @func init app intro for first use
*/
private fun initIntro() {
if (sharedPref.getBoolean(StorageKey.isFirstRun, true)) {
Snackbar.make(binding.rootLayout, "Long press on card to copy code", Snackbar.LENGTH_INDEFINITE).apply {
setAction("NEXT") {
Snackbar.make(binding.rootLayout, "Tap on card to see different shades", Snackbar.LENGTH_INDEFINITE).apply {
setAction("CLOSE") {}
show()
}
}
show()
}
sharedPref.saveData(StorageKey.isFirstRun, false)
}
}
/**
* @func init bottom navigation config
*/
private fun initBottomNavigation() {
binding.justBar.setOnBarItemClickListener { barItem, position ->
// Load ad
if (SharedPref.getInstance(this).getBoolean(StorageKey.SHOW_AD, true))
showInterstitialAd(this)
when(barItem.id) {
R.id.nav_home -> {
AnalyticsHelper.getInstance()?.logEvent(MaterialColor.FIREBASE_EVENT_TAB_COLOR, null)
displayFragment(homeFragment)
supportActionBar?.title = "MaterialColor"
}
R.id.nav_gradients -> {
AnalyticsHelper.getInstance()?.logEvent(MaterialColor.FIREBASE_EVENT_TAB_GRADIENT, null)
displayFragment(gradientFragment)
supportActionBar?.title = "Gradients"
}
R.id.nav_color_picker -> {
AnalyticsHelper.getInstance()?.logEvent(MaterialColor.FIREBASE_EVENT_TAB_COLOR_PICKER, null)
displayFragment(colorPickerFragment)
supportActionBar?.title = "Color Picker"
}
R.id.nav_bookmarked_color -> {
AnalyticsHelper.getInstance()?.logEvent(MaterialColor.FIREBASE_EVENT_TAB_BOOKMARKED_COLOR, null)
displayFragment(bookmarkedColorFragment)
supportActionBar?.title = "Bookmarked Color"
}
}
}
}
/**
* @func change fragment in frame layout
* @param fragment fragment value
*/
private fun displayFragment(fragment: Fragment?) {
val fragmentManager = supportFragmentManager
if (fragment != null) {
activeFragment = fragment
val transaction = fragmentManager.beginTransaction()
transaction.setCustomAnimations(R.anim.anim_fragment_enter, R.anim.anim_fragment_exit)
transaction.replace(R.id.host_fragment, fragment)
transaction.commit()
}
}
/**
* @func init bottom sheet menu config
*/
private fun initMenuSheet() {
bottomSheet = MaterialDialog(this, BottomSheet(LayoutMode.WRAP_CONTENT))
.cornerRadius(16f)
.customView(R.layout.bottom_sheet_menu, scrollable = true)
val view = bottomSheet?.getCustomView()
view?.findViewById<ImageButton>(R.id.btn_settings)?.setOnClickListener {
startActivity(Intent(this, SettingsActivity::class.java))
}
view?.findViewById<LinearLayout>(R.id.btn_custom_color_maker)?.setOnClickListener {
AnalyticsHelper.getInstance()?.logEvent(MaterialColor.FIREBASE_EVENT_CUSTOM_COLOR_MAKER, null)
startActivity(Intent(this, CustomColorActivity::class.java))
}
view?.findViewById<LinearLayout>(R.id.btn_gradient_maker)?.setOnClickListener {
AnalyticsHelper.getInstance()?.logEvent(MaterialColor.FIREBASE_EVENT_CUSTOM_GRADIENT_MAKER, null)
startActivity(Intent(this, CustomGradientActivity::class.java))
}
view?.findViewById<LinearLayout>(R.id.btn_material_design_tool)?.setOnClickListener {
AnalyticsHelper.getInstance()?.logEvent(MaterialColor.FIREBASE_EVENT_MATERIAL_DESIGN_TOOL, null)
startActivity(Intent(this, DesignToolActivity::class.java))
}
view?.findViewById<LinearLayout>(R.id.btn_flat_ui_colors)?.setOnClickListener {
AnalyticsHelper.getInstance()?.logEvent(MaterialColor.FIREBASE_EVENT_FLAT_UI_COLORS, null)
startActivity(Intent(this, FlatUIColorsActivity::class.java))
}
view?.findViewById<LinearLayout>(R.id.btn_social_colors)?.setOnClickListener {
AnalyticsHelper.getInstance()?.logEvent(MaterialColor.FIREBASE_EVENT_SOCIAL_COLORS, null)
startActivity(Intent(this, SocialColorsActivity::class.java))
}
view?.findViewById<LinearLayout>(R.id.btn_metro_colors)?.setOnClickListener {
AnalyticsHelper.getInstance()?.logEvent(MaterialColor.FIREBASE_EVENT_METRO_COLORS, null)
startActivity(Intent(this, MetroColorsActivity::class.java))
}
view?.findViewById<MaterialButton>(R.id.btn_support_development)?.setOnClickListener {
AnalyticsHelper.getInstance()?.logEvent(MaterialColor.FIREBASE_EVENT_SUPPORT_DEVELOPMENT, null)
startActivity(Intent(this, SupportDevelopmentActivity::class.java))
}
}
/**
* @func app closer functionality
*/
private var exitTime: Long = 0
private fun appCloser() {
if (System.currentTimeMillis() - exitTime > 2000) {
this.displayToast("Press again to close app")
exitTime = System.currentTimeMillis()
return
}
finish()
}
/**
* @func init audience network config for ad ---------------------------------------------------
*/
private fun initAd() {
Log.d(TAG, "initAd: called")
// Interstitial Ad
interstitialAd = InterstitialAd(this, MaterialColor.getAdId(AdType.INTERSTITIAL))
if (Tools.hasNetwork(this))
interstitialAd.loadAd()
interstitialAd.setAdListener(object : InterstitialAdListener {
override fun onInterstitialDisplayed(p0: Ad?) {
}
override fun onInterstitialDismissed(p0: Ad?) {
}
override fun onAdLoaded(p0: Ad?) {
Log.d(TAG, "onAdLoaded: called")
}
override fun onError(p0: Ad?, p1: AdError?) {
Log.d(TAG, "onError: called: ${p1?.errorMessage}")
/*if (Tools.hasNetwork(this@HomeActivity))
interstitialAd.loadAd()*/
}
override fun onAdClicked(p0: Ad?) {
}
override fun onLoggingImpression(p0: Ad?) {
}
})
// Banner Ad
adView = AdView(this, MaterialColor.getAdId(AdType.BANNER), AdSize.BANNER_HEIGHT_50)
if (Tools.hasNetwork(this))
if (SharedPref.getInstance(this).getBoolean(StorageKey.SHOW_AD, true))
adView?.loadAd()
adView?.setAdListener(object : AdListener {
override fun onAdLoaded(p0: Ad?) {
Tools.visibleViews(binding.bannerContainer)
binding.bannerContainer.addView(adView)
}
override fun onAdClicked(p0: Ad?) {
}
override fun onError(p0: Ad?, p1: AdError?) {
if (Tools.hasNetwork(this@HomeActivity))
if (SharedPref.getInstance(this@HomeActivity).getBoolean(StorageKey.SHOW_AD, true))
adView?.loadAd()
}
override fun onLoggingImpression(p0: Ad?) {
}
})
}
/**
* @func in-app update functionality -----------------------------------------------------------
*/
private var updateStarted = false
private fun initInAppUpdate() {
val appUpdateManager = AppUpdateManagerFactory.create(this)
val appUpdateInfoTask = appUpdateManager.appUpdateInfo
val listener = InstallStateUpdatedListener { state ->
// Show update downloading...
if (state.installStatus() == InstallStatus.DOWNLOADING && !updateStarted) {
/*val bytesDownloaded = state.bytesDownloaded()
val totalBytesToDownload = state.totalBytesToDownload()*/
binding.rootLayout.displaySnackbar(
"Downloading update...",
Snackbar.LENGTH_LONG
)
updateStarted = true
}
// If the process of downloading is finished, start the completion flow.
if (state.installStatus() == InstallStatus.DOWNLOADED) {
Snackbar.make(binding.rootLayout,
"An update has just been downloaded from Google Play",
Snackbar.LENGTH_INDEFINITE
).apply {
setAction("RESTART") { appUpdateManager.completeUpdate() }
show()
}
}
// If the downloading is failed
if (state.installStatus() == InstallStatus.FAILED) {
binding.rootLayout.displaySnackbar(
"Update downloading failed!",
Snackbar.LENGTH_LONG
)
}
}
// Register update listener
appUpdateManager.registerListener(listener)
appUpdateInfoTask.addOnSuccessListener { appUpdateInfo ->
if ((appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
&& appUpdateInfo.updatePriority() >= HIGH_PRIORITY_UPDATE
// For a flexible update, use AppUpdateType.FLEXIBLE
&& appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE))) {
this.displayToast("Update available")
// Start update flow dialog
appUpdateManager.startUpdateFlowForResult(
appUpdateInfo,
AppUpdateType.FLEXIBLE,
this,
REQUEST_CODE_UPDATE)
}
// If update is already download but, not installed
if (appUpdateInfo.installStatus() == InstallStatus.DOWNLOADED) {
Snackbar.make(binding.rootLayout,
"An update has been downloaded from Google Play",
Snackbar.LENGTH_INDEFINITE
).apply {
setAction("RESTART") { appUpdateManager.completeUpdate() }
show()
}
}
}.addOnFailureListener { e ->
e.printStackTrace()
}
}
}
| 0 | Kotlin | 0 | 2 | 6bf777391ba70869507b1f57a2486c7c00170abf | 17,439 | MaterialColor | Apache License 2.0 |
app/src/main/java/com/lloyds/media/infra/database/entity/MediaFavouritesEntity.kt | gokulkalagara | 811,753,503 | false | {"Kotlin": 114582} | package com.lloyds.media.infra.database.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import java.util.Date
/**
* @Author: <NAME>
* copyright (c) 2024, All rights reserved.
*
*/
@Entity(tableName = "media_favourites")
data class MediaFavouritesEntity(
@PrimaryKey
val id: Int,
val name: String,
val mediaType: String? = null,
val overview: String? = null,
val imageUrl: String? = null,
@ColumnInfo(name = "createdAt") val createdAt: Date = Date(System.currentTimeMillis())
) | 0 | Kotlin | 0 | 0 | b28eb8a44e52e092394ddc7fc5e996a24d8e74df | 563 | Movies | Apache License 2.0 |
src/me/anno/gpu/shader/Shader.kt | won21kr | 351,713,352 | true | {"Kotlin": 1983578, "Java": 301507, "C": 75596, "GLSL": 9436} | package me.anno.gpu.shader
import me.anno.cache.data.ICacheData
import me.anno.gpu.GFX
import me.anno.gpu.framebuffer.Frame
import me.anno.ui.editor.files.toAllowedFilename
import me.anno.utils.OS
import me.anno.utils.structures.arrays.FloatArrayList
import org.apache.logging.log4j.LogManager
import org.joml.*
import org.lwjgl.BufferUtils
import org.lwjgl.opengl.GL20.*
import org.lwjgl.opengl.GL21.glUniformMatrix4x3fv
import java.io.File
import java.nio.FloatBuffer
open class Shader(
val shaderName: String,
val vertex: String,
val varying: String,
val fragment: String,
private val disableShorts: Boolean = false
) : ICacheData {
companion object {
private var logShaders = true
private val LOGGER = LogManager.getLogger(Shader::class)
private const val attributeName = "in"
private val matrixBuffer = BufferUtils.createFloatBuffer(16)
private val identity3 = Matrix3f() as Matrix3fc
private val identity4 = Matrix4f() as Matrix4fc
private val identity4x3 = Matrix4x3f() as Matrix4x3fc
const val DefaultGLSLVersion = 150
var lastProgram = -1
}
var glslVersion = DefaultGLSLVersion
private var program = -1
private val uniformLocations = HashMap<String, Int>()
private val attributeLocations = HashMap<String, Int>()
private val uniformCache = FloatArrayList(128, Float.NaN)
val pointer get() = program
private val ignoredNames = HashSet<String>()
// shader compile time doesn't really matter... -> move it to the start to preserve ram use?
// isn't that much either...
fun init() {
// LOGGER.debug("$shaderName\nVERTEX:\n$vertex\nVARYING:\n$varying\nFRAGMENT:\n$fragment")
program = glCreateProgram()
// the shaders are like a C compilation process, .o-files: after linking, they can be removed
val vertexSource = ("" +
"#version $glslVersion\n" +
"${varying.replace("varying", "out")} $vertex").replaceShortCuts()
val vertexShader = compile(GL_VERTEX_SHADER, vertexSource)
val fragmentSource = ("" +
"#version $glslVersion\n" +
"precision mediump float; ${varying.replace("varying", "in")} ${
if (fragment.contains("gl_FragColor") && glslVersion == DefaultGLSLVersion) {
"out vec4 glFragColor;" +
fragment.replace("gl_FragColor", "glFragColor")
} else fragment}").replaceShortCuts()
val fragmentShader = compile(GL_FRAGMENT_SHADER, fragmentSource)
glLinkProgram(program)
glDeleteShader(vertexShader)
glDeleteShader(fragmentShader)
logShader(vertexSource, fragmentSource)
}
fun logShader(vertex: String, fragment: String) {
if (logShaders) {
val folder = File(OS.desktop, "shaders")
folder.mkdirs()
fun print(ext: String, data: String) {
val name = "$shaderName.$ext".toAllowedFilename() ?: return
File(folder, name).writeText(data)
}
print("vert", vertex)
print("frag", fragment)
}
}
fun String.replaceShortCuts() = if (disableShorts) this else this
.replace("\n", " \n ")
.replace(";", " ; ")
.replace(" u1 ", " uniform float ")
.replace(" u2 ", " uniform vec2 ")
.replace(" u3 ", " uniform vec3 ")
.replace(" u4 ", " uniform vec4 ")
.replace(" u2x2 ", " uniform mat2 ")
.replace(" u3x3 ", " uniform mat3 ")
.replace(" u4x4 ", " uniform mat4 ")
.replace(" u4x3 ", " uniform mat4x3 ")
.replace(" u3x4 ", " uniform mat3x4 ")
.replace(" a1 ", " $attributeName float ")
.replace(" a2 ", " $attributeName vec2 ")
.replace(" a3 ", " $attributeName vec3 ")
.replace(" a4 ", " $attributeName vec4 ")
.replace(" v1 ", " float ")
.replace(" v2 ", " vec2 ")
.replace(" v3 ", " vec3 ")
.replace(" v4 ", " vec4 ")
.replace(" m2 ", " mat2 ")
.replace(" m3 ", " mat3 ")
.replace(" m4 ", " mat4 ")
private fun compile(type: Int, source: String): Int {
// ("$shaderName/$type: $source")
val shader = glCreateShader(type)
glShaderSource(shader, source)
glCompileShader(shader)
glAttachShader(program, shader)
postPossibleError(shader, source)
return shader
}
private fun postPossibleError(shader: Int, source: String) {
val log = glGetShaderInfoLog(shader)
if (log.isNotBlank()) {
LOGGER.warn(
"$log by\n\n${
source
.split('\n')
.mapIndexed { index, line ->
"${"%1\$3s".format(index + 1)}: $line"
}.joinToString("\n")}"
)
/*if(!log.contains("deprecated", true)){
throw RuntimeException()
}*/
}
}
fun ignoreUniformWarnings(names: List<String>) {
ignoredNames += names
}
fun getUniformLocation(name: String): Int {
val old = uniformLocations.getOrDefault(name, -100)
if (old != -100) return old
use()
val loc = glGetUniformLocation(program, name)
uniformLocations[name] = loc
if (loc < 0 && name !in ignoredNames) {
LOGGER.warn("Uniform location \"$name\" not found in shader $shaderName")
}
return loc
}
fun getAttributeLocation(name: String): Int {
val old = attributeLocations.getOrDefault(name, -100)
if (old != -100) return old
val loc = glGetAttribLocation(program, name)
attributeLocations[name] = loc
if (loc < 0 && name !in ignoredNames) {
LOGGER.warn("Attribute location \"$name\" not found in shader $shaderName")
}
return loc
}
fun use() {
Frame.currentFrame?.bind()
if (program == -1) init()
if (program != lastProgram) {
glUseProgram(program)
lastProgram = program
}
}
fun v1(name: String, x: Int) {
val loc = getUniformLocation(name)
if (loc > -1) {
val asFloat = x.toFloat()
if (asFloat.toInt() != x) {
// cannot be represented as a float -> cannot currently be cached
uniformCache[loc * 4] = Float.NaN
use()
glUniform1i(loc, x)
} else if (uniformCache[loc * 4, Float.NaN] != asFloat) {
// it has changed
uniformCache[loc * 4] = asFloat
use()
glUniform1i(loc, x)
}
}
}
fun v1(name: String, x: Float) {
val loc = getUniformLocation(name)
if (loc > -1) {
val index0 = loc * 4
if (uniformCache[index0 + 0, Float.NaN] != x) {
uniformCache[index0 + 0] = x
use()
glUniform1f(loc, x)
}
}
}
fun v2(name: String, x: Float, y: Float) {
val loc = getUniformLocation(name)
if (loc > -1) {
val index0 = loc * 4
if (
uniformCache[index0 + 0, Float.NaN] != x ||
uniformCache[index0 + 1, Float.NaN] != y
) {
uniformCache[index0 + 0] = x
uniformCache[index0 + 1] = y
use()
glUniform2f(loc, x, y)
}
}
}
fun v3(name: String, x: Float, y: Float, z: Float) {
val loc = getUniformLocation(name)
if (loc > -1) {
val index0 = loc * 4
if (
uniformCache[index0 + 0, Float.NaN] != x ||
uniformCache[index0 + 1, Float.NaN] != y ||
uniformCache[index0 + 2, Float.NaN] != z
) {
uniformCache[index0 + 0] = x
uniformCache[index0 + 1] = y
uniformCache[index0 + 2] = z
use()
glUniform3f(loc, x, y, z)
}
}
}
fun v3X(name: String, v: Vector4f) {
v3(name, v.x / v.w, v.y / v.w, v.z / v.w)
}
fun v3(name: String, color: Int) {
v3(
name,
(color.shr(16) and 255) / 255f,
(color.shr(8) and 255) / 255f,
color.and(255) / 255f
)
}
fun v4(name: String, x: Float, y: Float, z: Float, w: Float) {
val loc = getUniformLocation(name)
if (loc > -1) glUniform4f(loc, x, y, z, w)
}
fun v4(name: String, color: Int) {
v4(
name,
(color.shr(16) and 255) / 255f,
(color.shr(8) and 255) / 255f,
color.and(255) / 255f,
(color.shr(24) and 255) / 255f
)
}
fun v4(name: String, color: Int, alpha: Float) {
v4(
name,
color.shr(16).and(255) / 255f,
color.shr(8).and(255) / 255f,
color.and(255) / 255f, alpha
)
}
fun v2(name: String, all: Float) = v2(name, all, all)
fun v3(name: String, all: Float) = v3(name, all, all, all)
fun v4(name: String, all: Float) = v4(name, all, all, all, all)
fun v2(name: String, v: Vector2fc) = v2(name, v.x(), v.y())
fun v3(name: String, v: Vector3fc) = v3(name, v.x(), v.y(), v.z())
fun v4(name: String, v: Vector4fc) = v4(name, v.x(), v.y(), v.z(), v.w())
fun m3x3(name: String, value: Matrix3fc = identity3) {
use()
val loc = this[name]
if (loc > -1) {
value.get(matrixBuffer)
glUniformMatrix3fv(loc, false, matrixBuffer)
}
}
fun m4x3(name: String, value: Matrix4x3fc = identity4x3) {
use()
val loc = this[name]
if (loc > -1) {
value.get(matrixBuffer)
glUniformMatrix4x3fv(loc, false, matrixBuffer)
}
}
fun m4x4(name: String, value: Matrix4fc = identity4) {
use()
val loc = this[name]
if (loc > -1) {
value.get(matrixBuffer)
glUniformMatrix4fv(loc, false, matrixBuffer)
}
}
fun v1Array(name: String, value: FloatBuffer) {
use()
val loc = this[name]
if (loc > -1) {
glUniform1fv(loc, value)
}
}
fun v2Array(name: String, value: FloatBuffer) {
use()
val loc = this[name]
if (loc > -1) {
glUniform2fv(loc, value)
}
}
fun v3Array(name: String, value: FloatBuffer) {
use()
val loc = this[name]
if (loc > -1) {
glUniform3fv(loc, value)
}
}
fun v4Array(name: String, value: FloatBuffer) {
use()
val loc = this[name]
if (loc > -1) {
glUniform4fv(loc, value)
}
}
fun check() = GFX.check()
operator fun get(name: String) = getUniformLocation(name)
override fun destroy() {
if (program > -1) glDeleteProgram(program)
}
} | 0 | null | 0 | 0 | b85295f59ddfa9fc613a384d439fd1b30b06a5a4 | 11,152 | RemsStudio | Apache License 2.0 |
src/main/kotlin/dev/slint/ideaplugin/ide/folding/SlintImportFoldingBuilder.kt | kizeevov | 700,879,080 | false | {"Kotlin": 39285, "Lex": 4139, "HTML": 63} | package dev.slint.ideaplugin.ide.folding
import com.intellij.lang.ASTNode
import com.intellij.lang.folding.CustomFoldingBuilder
import com.intellij.lang.folding.FoldingDescriptor
import com.intellij.openapi.editor.Document
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.refactoring.suggested.endOffset
import com.intellij.refactoring.suggested.startOffset
import dev.slint.ideaplugin.lang.psi.SlintFile
import dev.slint.ideaplugin.lang.psi.SlintImportDefinition
import dev.slint.ideaplugin.util.parser.childrenOfType
class SlintImportFoldingBuilder : CustomFoldingBuilder(), DumbAware {
override fun buildLanguageFoldRegions(
descriptors: MutableList<FoldingDescriptor>,
root: PsiElement,
document: Document,
quick: Boolean
) {
if (root !is SlintFile) {
return
}
val covered = HashSet<SlintImportDefinition>()
val imports = root.allImports()
for (import in imports) {
if (import in covered) {
continue
}
var next: SlintImportDefinition? = import
var last: SlintImportDefinition = import
while (next != null) {
covered += next
last = next
next = next.nextImport()
}
descriptors += FoldingDescriptor(import, TextRange(import.startOffset, last.endOffset))
}
}
override fun getLanguagePlaceholderText(node: ASTNode, textRange: TextRange): String = "import ..."
override fun isRegionCollapsedByDefault(node: ASTNode): Boolean = false
}
private fun PsiElement.allImports() = childrenOfType(SlintImportDefinition::class).toList()
private fun PsiElement.nextImport(): SlintImportDefinition? {
val next = this.nextSibling
if (next is PsiWhiteSpace) {
return next.nextImport()
}
if (next is PsiComment) {
return next.nextImport()
}
return next as? SlintImportDefinition
} | 3 | Kotlin | 0 | 9 | efd8d05d1e6ca4369e86476c3b647ec0759d7103 | 2,146 | slint-idea-plugin | MIT License |
src/main/kotlin/no/nav/cv/eures/cv/dto/cv/CvEndretInternWorkExperience.kt | navikt | 245,109,239 | false | {"Kotlin": 214845, "Shell": 356, "Dockerfile": 110} | package no.nav.cv.dto.cv
import com.fasterxml.jackson.annotation.JsonIgnoreProperties
import java.time.ZonedDateTime
@JsonIgnoreProperties(ignoreUnknown = true)
data class CvEndretInternWorkExperience(
val employer: String?,
val jobTitle: String?,
val alternativeJobTitle: String?,
val conceptId: String?,
val location: String?,
val description: String?,
val fromDate: ZonedDateTime?,
val toDate: ZonedDateTime?,
val styrkkode: String?,
val ikkeAktueltForFremtiden: Boolean
) | 0 | Kotlin | 0 | 2 | a18ec24f896bba24c477fa652667ae01b811ed89 | 517 | pam-eures-cv-eksport | MIT License |
feature/metis/src/main/kotlin/de/tum/informatics/www1/artemis/native_app/feature/metis/ui/view_post/ReplyState.kt | ls1intum | 537,104,541 | false | null | package de.tum.informatics.www1.artemis.native_app.feature.metis.ui.view_post
internal sealed class ReplyState {
data class CanCreate(val onCreateReply: (String) -> Unit) : ReplyState()
data class IsSendingReply(val onCancelSendReply: () -> Unit) : ReplyState()
object HasSentReply : ReplyState()
} | 2 | Kotlin | 0 | 2 | d9a0833905cdad14da0f9cf4863b6cf85747941d | 311 | artemis-android | Apache License 2.0 |
runtime/src/main/java/com/edgeverse/wallet/runtime/multiNetwork/ChainGradientParser.kt | finn-exchange | 512,140,809 | false | null | package com.dfinn.wallet.runtime.multiNetwork
import com.dfinn.wallet.runtime.multiNetwork.chain.model.Chain
/**
* Definition format: linear-gradient(<degrees>deg, #<color1> <percent1>%, ...);
*/
object ChainGradientParser {
private val MAIN_REGEX by lazy {
"linear-gradient\\(([0-9.]*)deg,([^)]+)\\)".toRegex()
}
private val COLORS_REGEX by lazy {
"\\s?(#[0-9A-F]*) ([0-9.]*)%".toRegex()
}
fun parse(definition: String?): Chain.Gradient? {
if (definition == null) return null
return runCatching {
val (_, degreeRaw, colorsAndPositionsRaw) = MAIN_REGEX.find(definition)!!.groupValues
val colorsAndPositions = COLORS_REGEX.findAll(colorsAndPositionsRaw).map { match ->
match.groupValues[1] to match.groupValues[2]
}.toList()
val colors = colorsAndPositions.map { it.first }
val positions = colorsAndPositions.map { it.second.toFloat() }
Chain.Gradient(
angle = degreeRaw.toFloat(),
colors = colors,
positionsPercent = positions
)
}.getOrThrow()
}
fun encode(gradient: Chain.Gradient?): String? = gradient?.let {
gradient.colors.zip(gradient.positionsPercent).joinToString(
prefix = "linear-gradient(${gradient.angle}deg, ",
separator = ", ",
postfix = ")"
) { (color, position) ->
"$color $position%"
}
}
}
| 0 | Kotlin | 1 | 0 | 6cc7a0a4abb773daf3da781b7bd1dda5dbf9b01d | 1,509 | edgeverse-wallet | Apache License 2.0 |
bytecode/samples/src/main/kotlin/io/redgreen/tumbleweed/samples/ActionConsumerExtensions.kt | redgreenio | 546,118,669 | false | null | package io.redgreen.tumbleweed.samples
import io.redgreen.tumbleweed.samples.listener.ActionConsumer
inline fun ActionConsumer.doIt(crossinline block: (Any) -> Unit) {
block(this)
}
| 0 | Kotlin | 3 | 57 | 081c03666190a16a6845c5cf642b7d3d1b8d6959 | 186 | tumbleweed | Apache License 2.0 |
compose/foundation/foundation/src/desktopMain/kotlin/androidx/compose/foundation/text/ContextMenu.desktop.kt | VexorMC | 838,305,267 | false | {"Kotlin": 104238872, "Java": 66757679, "C++": 9111230, "AIDL": 628952, "Python": 306842, "Shell": 199496, "Objective-C": 47117, "TypeScript": 38627, "HTML": 28384, "Swift": 21386, "Svelte": 20307, "ANTLR": 19860, "C": 15043, "CMake": 14435, "JavaScript": 6457, "GLSL": 3842, "CSS": 1760, "Batchfile": 295} | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.text
import androidx.compose.foundation.ContextMenuArea
import androidx.compose.foundation.ContextMenuItem
import androidx.compose.foundation.ContextMenuState
import androidx.compose.foundation.DesktopPlatform
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.JPopupContextMenuRepresentation
import androidx.compose.foundation.LocalContextMenuRepresentation
import androidx.compose.foundation.text.TextContextMenu.TextManager
import androidx.compose.foundation.text.input.internal.selection.TextFieldSelectionState
import androidx.compose.foundation.text.selection.SelectionManager
import androidx.compose.foundation.text.selection.TextFieldSelectionManager
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.ProvidableCompositionLocal
import androidx.compose.runtime.remember
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.awt.ComposePanel
import androidx.compose.ui.awt.ComposeWindow
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.platform.LocalLocalization
import androidx.compose.ui.text.AnnotatedString
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.getSelectedText
import java.awt.Component
import javax.swing.JPopupMenu
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal actual fun ContextMenuArea(
manager: TextFieldSelectionManager,
content: @Composable () -> Unit
) {
val state = remember { ContextMenuState() }
if (DesktopPlatform.Current == DesktopPlatform.MacOS) {
OpenMenuAdjuster(state) { manager.contextMenuOpenAdjustment(it) }
}
LocalTextContextMenu.current.Area(manager.textManager, state, content)
}
@Composable
internal actual fun ContextMenuArea(
selectionState: TextFieldSelectionState,
enabled: Boolean,
content: @Composable () -> Unit
) {
// TODO: Implement merged from Compose 1.7.0 overload
content()
}
@OptIn(ExperimentalFoundationApi::class)
@Composable
internal actual fun ContextMenuArea(
manager: SelectionManager,
content: @Composable () -> Unit
) {
val state = remember { ContextMenuState() }
if (DesktopPlatform.Current == DesktopPlatform.MacOS) {
OpenMenuAdjuster(state) { manager.contextMenuOpenAdjustment(it) }
}
LocalTextContextMenu.current.Area(manager.textManager, state, content)
}
@Composable
internal fun OpenMenuAdjuster(state: ContextMenuState, adjustAction: (Offset) -> Unit) {
LaunchedEffect(state) {
snapshotFlow { state.status }.collect { status ->
if (status is ContextMenuState.Status.Open) {
adjustAction(status.rect.center)
}
}
}
}
@OptIn(ExperimentalFoundationApi::class)
private val TextFieldSelectionManager.textManager get() = object : TextManager {
override val selectedText get() = value.getSelectedText()
val isPassword get() = visualTransformation is PasswordVisualTransformation
override val cut: (() -> Unit)? get() =
if (!value.selection.collapsed && editable && !isPassword) {
{
cut()
focusRequester?.requestFocus()
}
} else {
null
}
override val copy: (() -> Unit)? get() =
if (!value.selection.collapsed && !isPassword) {
{
copy(false)
focusRequester?.requestFocus()
}
} else {
null
}
override val paste: (() -> Unit)? get() =
if (editable && clipboardManager?.getText() != null) {
{
paste()
focusRequester?.requestFocus()
}
} else {
null
}
override val selectAll: (() -> Unit)? get() =
if (value.selection.length != value.text.length) {
{
selectAll()
focusRequester?.requestFocus()
}
} else {
null
}
}
@OptIn(ExperimentalFoundationApi::class)
private val SelectionManager.textManager get() = object : TextManager {
override val selectedText get() = getSelectedText() ?: AnnotatedString("")
override val cut = null
override val copy = { copy() }
override val paste = null
override val selectAll = null
}
/**
* Composition local that keeps [TextContextMenu].
*/
@ExperimentalFoundationApi
val LocalTextContextMenu:
ProvidableCompositionLocal<TextContextMenu> = staticCompositionLocalOf { TextContextMenu.Default }
/**
* Describes how to show the text context menu for selectable texts and text fields.
*/
@ExperimentalFoundationApi
interface TextContextMenu {
/**
* Defines an area, that describes how to open and show text context menus.
* Usually it uses [ContextMenuArea] as the implementation.
*
* @param textManager Provides useful methods and information for text for which we show the text context menu.
* @param state [ContextMenuState] of menu controlled by this area.
* @param content The content of the [ContextMenuArea].
*/
@Composable
fun Area(textManager: TextManager, state: ContextMenuState, content: @Composable () -> Unit)
/**
* Provides useful methods and information for text for which we show the text context menu.
*/
@ExperimentalFoundationApi
interface TextManager {
/**
* The current selected text.
*/
val selectedText: AnnotatedString
/**
* Action for cutting the selected text to the clipboard. Null if there is no text to cut.
*/
val cut: (() -> Unit)?
/**
* Action for copy the selected text to the clipboard. Null if there is no text to copy.
*/
val copy: (() -> Unit)?
/**
* Action for pasting text from the clipboard. Null if there is no text in the clipboard.
*/
val paste: (() -> Unit)?
/**
* Action for selecting the whole text. Null if the text is already selected.
*/
val selectAll: (() -> Unit)?
}
companion object {
/**
* [TextContextMenu] that is used by default in Compose.
*/
@ExperimentalFoundationApi
val Default = object : TextContextMenu {
@Composable
override fun Area(textManager: TextManager, state: ContextMenuState, content: @Composable () -> Unit) {
val localization = LocalLocalization.current
val items = {
listOfNotNull(
textManager.cut?.let {
ContextMenuItem(localization.cut, it)
},
textManager.copy?.let {
ContextMenuItem(localization.copy, it)
},
textManager.paste?.let {
ContextMenuItem(localization.paste, it)
},
textManager.selectAll?.let {
ContextMenuItem(localization.selectAll, it)
},
)
}
ContextMenuArea(items, state, content = content)
}
}
}
}
/**
* [TextContextMenu] that uses [JPopupMenu] to show the text context menu.
*
* You can use it by overriding [TextContextMenu] on the top level of your application.
*
* @param owner The root component that owns a context menu. Usually it is [ComposeWindow] or [ComposePanel].
* @param createMenu Describes how to create [JPopupMenu] from [TextManager] and from list of custom [ContextMenuItem]
* defined by [CompositionLocalProvider].
*/
@ExperimentalFoundationApi
class JPopupTextMenu(
private val owner: Component,
private val createMenu: (TextManager, List<ContextMenuItem>) -> JPopupMenu,
) : TextContextMenu {
@Composable
override fun Area(textManager: TextManager, state: ContextMenuState, content: @Composable () -> Unit) {
CompositionLocalProvider(
LocalContextMenuRepresentation provides JPopupContextMenuRepresentation(owner) {
createMenu(textManager, it)
}
) {
// We pass emptyList, but it will be merged with the other custom items defined via ContextMenuDataProvider, and passed to createMenu
ContextMenuArea({ emptyList() }, state, content = content)
}
}
}
| 0 | Kotlin | 0 | 2 | 9730aa39ce1cafe408f28962a59b95b82c68587f | 9,302 | compose | Apache License 2.0 |
jacodb-core/src/main/kotlin/org/utbot/jacodb/impl/types/JcTypedMethodImpl.kt | UnitTestBot | 491,176,077 | false | null | /*
* Copyright 2022 UnitTestBot contributors (utbot.org)
* <p>
* 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
* <p>
* http://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.utbot.jacodb.impl.types
import org.objectweb.asm.Type
import org.objectweb.asm.tree.LocalVariableNode
import org.utbot.jacodb.api.JcClassOrInterface
import org.utbot.jacodb.api.JcMethod
import org.utbot.jacodb.api.JcRefType
import org.utbot.jacodb.api.JcType
import org.utbot.jacodb.api.JcTypeVariableDeclaration
import org.utbot.jacodb.api.JcTypedMethod
import org.utbot.jacodb.api.JcTypedMethodParameter
import org.utbot.jacodb.api.MethodResolution
import org.utbot.jacodb.api.ext.findClass
import org.utbot.jacodb.api.ext.isNullable
import org.utbot.jacodb.api.ext.isStatic
import org.utbot.jacodb.api.throwClassNotFound
import org.utbot.jacodb.impl.types.signature.FieldResolutionImpl
import org.utbot.jacodb.impl.types.signature.FieldSignature
import org.utbot.jacodb.impl.types.signature.MethodResolutionImpl
import org.utbot.jacodb.impl.types.signature.MethodSignature
import org.utbot.jacodb.impl.types.substition.JcSubstitutor
class JcTypedMethodImpl(
override val enclosingType: JcRefType,
override val method: JcMethod,
private val parentSubstitutor: JcSubstitutor
) : JcTypedMethod {
private class TypedMethodInfo(
val substitutor: JcSubstitutor,
private val resolution: MethodResolution
) {
val impl: MethodResolutionImpl? get() = resolution as? MethodResolutionImpl
}
private val classpath = method.enclosingClass.classpath
private val info by lazy(LazyThreadSafetyMode.NONE) {
val signature = MethodSignature.withDeclarations(method)
val impl = signature as? MethodResolutionImpl
val substitutor = if (!method.isStatic) {
parentSubstitutor.newScope(impl?.typeVariables.orEmpty())
} else {
JcSubstitutor.empty.newScope(impl?.typeVariables.orEmpty())
}
TypedMethodInfo(
substitutor = substitutor,
resolution = MethodSignature.withDeclarations(method)
)
}
override val name: String
get() = method.name
override val typeParameters: List<JcTypeVariableDeclaration>
get() {
val impl = info.impl ?: return emptyList()
return impl.typeVariables.map { it.asJcDeclaration(method) }
}
override val exceptions: List<JcClassOrInterface>
get() {
val impl = info.impl ?: return emptyList()
return impl.exceptionTypes.map {
classpath.findClass(it.name)
}
}
override val typeArguments: List<JcRefType>
get() {
return emptyList()
}
override val parameters: List<JcTypedMethodParameter>
get() {
val methodInfo = info
return method.parameters.mapIndexed { index, jcParameter ->
JcTypedMethodParameterImpl(
enclosingMethod = this,
substitutor = methodInfo.substitutor,
parameter = jcParameter,
jvmType = methodInfo.impl?.parameterTypes?.get(index)
)
}
}
override val returnType: JcType by lazy(LazyThreadSafetyMode.NONE) {
val typeName = method.returnType.typeName
val info = info
val impl = info.impl
val type = if (impl == null) {
classpath.findTypeOrNull(typeName)
?: throw IllegalStateException("Can't resolve type by name $typeName")
} else {
classpath.typeOf(info.substitutor.substitute(impl.returnType))
}
method.isNullable?.let {
(type as? JcRefType)?.copyWithNullability(it)
} ?: type
}
override fun typeOf(inst: LocalVariableNode): JcType {
val variableSignature =
FieldSignature.of(inst.signature, method.allVisibleTypeParameters(), null) as? FieldResolutionImpl
if (variableSignature == null) {
val type = Type.getType(inst.desc)
return classpath.findTypeOrNull(type.className) ?: type.className.throwClassNotFound()
}
val info = info
return classpath.typeOf(info.substitutor.substitute(variableSignature.fieldType))
}
} | 12 | Kotlin | 3 | 7 | 25bbd79ec4e001c0d5e642afabb01f4c2d5a3b16 | 4,792 | jacodb | Apache License 2.0 |
UserService/src/main/kotlin/com/phonetool/service/user/exception/AccessDeniedException.kt | VividKnife | 291,526,784 | false | null | package com.phonetool.service.user.exception
import org.springframework.http.HttpStatus
import org.springframework.web.bind.annotation.ResponseStatus
import java.lang.RuntimeException
@ResponseStatus(code = HttpStatus.FORBIDDEN, reason = "ForbiddenException")
class ForbiddenException: RuntimeException()
| 0 | Kotlin | 0 | 0 | 21ec19dc915d1660a0af731c946212eaaecf8c79 | 307 | PhoneTool | MIT License |
app/src/main/java/com/example/berberappointment/berber/Shaved.kt | BerkayKaramehmetoglu | 733,084,694 | false | {"Kotlin": 11845} | package com.example.berberappointment.berber
import com.google.firebase.database.IgnoreExtraProperties
@IgnoreExtraProperties
data class Shaved(
var shavedType: String,
var shavedPrice: Int,
) {
} | 0 | Kotlin | 0 | 0 | 1062d163b65995038db04801432e30c3dffbc7dd | 206 | BerberAppointment | MIT License |
2023/day04-25/src/main/kotlin/Day20.kt | CakeOrRiot | 317,423,901 | false | {"Kotlin": 62169, "Python": 56994, "C#": 20675, "Rust": 10417} | import java.io.File
import java.util.LinkedList
import java.util.Queue
class Day20 {
fun solve1() {
val modules = emptyMap<String, Module>().toMutableMap()
val moduleOutputs = emptyMap<String, List<String>>().toMutableMap()
val conjunctionModules = emptyList<String>().toMutableList()
File("inputs/20.txt").inputStream().bufferedReader().lineSequence().toList().forEach { line ->
val split = line.split(" -> ").filter { it.isNotBlank() }
val type = split[0][0]
val name = if (type == 'b') split[0] else split[0].drop(1)
val outputs = split[1].split("[, ]".toRegex()).filter { it.isNotBlank() }
val module = when (type) {
'%' -> FlipFlop(name)
'&' -> {
conjunctionModules.add(name)
Conjunction(name)
}
else -> Broadcaster(name)
}
modules[name] = module
moduleOutputs[name] = outputs
}
val undefinedModules = emptyList<String>().toMutableList()
for ((module, outputList) in moduleOutputs) {
for (output in outputList) {
if (!modules.containsKey(output)) undefinedModules.add(output)
if (conjunctionModules.contains(output)) {
(modules[output] as Conjunction).memory[modules.getValue(module)] = Pulse.LOW
}
}
}
undefinedModules.forEach {
modules[it] = Undefined(it)
moduleOutputs[it] = emptyList()
}
for ((moduleName, module) in modules) {
val outputs = emptyList<Module>().toMutableList()
for (output in moduleOutputs.getValue(moduleName)) {
outputs.add(modules.getValue(output))
}
module.outputs = outputs
}
var lowPulses = 0L
var highPulses = 0L
for (i in 0..<1000) {
val q: Queue<QueueItem> = LinkedList()
val broadcaster = modules.getValue("broadcaster")
broadcaster.outputs.forEach { output -> q.add(QueueItem(broadcaster, output, Pulse.LOW)) }
lowPulses += 1
while (!q.isEmpty()) {
val next = q.poll()
if (next.pulse == Pulse.LOW) lowPulses += 1
else highPulses += 1
q.addAll(next.to.apply(next.from, next.pulse))
}
}
println(lowPulses * highPulses)
}
fun solve2() {
val modules = emptyMap<String, Module>().toMutableMap()
val moduleOutputs = emptyMap<String, List<String>>().toMutableMap()
val conjunctionModules = emptyList<String>().toMutableList()
File("inputs/20.txt").inputStream().bufferedReader().lineSequence().toList().forEach { line ->
val split = line.split(" -> ").filter { it.isNotBlank() }
val type = split[0][0]
val name = if (type == 'b') split[0] else split[0].drop(1)
val outputs = split[1].split("[, ]".toRegex()).filter { it.isNotBlank() }
val module = when (type) {
'%' -> FlipFlop(name)
'&' -> {
conjunctionModules.add(name)
Conjunction(name)
}
else -> Broadcaster(name)
}
modules[name] = module
moduleOutputs[name] = outputs
}
val undefinedModules = emptyList<String>().toMutableList()
for ((module, outputList) in moduleOutputs) {
for (output in outputList) {
if (!modules.containsKey(output)) undefinedModules.add(output)
if (conjunctionModules.contains(output)) {
(modules[output] as Conjunction).memory[modules.getValue(module)] = Pulse.LOW
}
}
}
undefinedModules.forEach {
modules[it] = Undefined(it)
moduleOutputs[it] = emptyList()
}
for ((moduleName, module) in modules) {
val outputs = emptyList<Module>().toMutableList()
for (output in moduleOutputs.getValue(moduleName)) {
outputs.add(modules.getValue(output))
}
module.outputs = outputs
}
var i = 0L
var res = -1L
val states = emptyMap<String, MutableList<Pulse>>().toMutableMap()
modules.forEach { states[it.key] = emptyList<Pulse>().toMutableList() }
while (i < 40000) {
i += 1
val seen = emptySet<String>().toMutableSet()
val queue: Queue<QueueItem> = LinkedList()
val broadcaster = modules.getValue("broadcaster")
broadcaster.outputs.forEach { output -> queue.add(QueueItem(broadcaster, output, Pulse.LOW)) }
while (!queue.isEmpty()) {
val next = queue.poll()
if (!seen.contains(next.from.name))
states[next.from.name]?.add(next.pulse)
seen.add(next.from.name)
if (next.pulse == Pulse.LOW && next.to.name == "rx") {
res = i
break
}
queue.addAll(next.to.apply(next.from, next.pulse))
}
if (res != -1L) break
}
for (node in listOf("bb", "mr", "gl", "kk")) {
println(node)
val cycles = states[node]?.mapIndexedNotNull { index, elem -> index.takeIf { elem == Pulse.HIGH } } ?: break
println(cycles[0])
println(cycles.windowed(2, 1).map { window -> window[1] - window[0] })
}
//ответ - LCM длин
}
enum class Pulse {
LOW, HIGH
}
interface Module {
var outputs: List<Module>
val name: String
fun apply(source: Module, pulse: Pulse): Queue<QueueItem>
}
data class QueueItem(val from: Module, val to: Module, val pulse: Pulse)
data class Broadcaster(override val name: String) : Module {
override var outputs: List<Module> = emptyList()
override fun apply(source: Module, pulse: Pulse): Queue<QueueItem> {
val q: Queue<QueueItem> = LinkedList()
outputs.forEach { output -> q.add(QueueItem(this, output, pulse)) }
return q
}
}
data class Undefined(override val name: String) : Module {
override var outputs: List<Module> = emptyList()
override fun apply(source: Module, pulse: Pulse): Queue<QueueItem> {
val q: Queue<QueueItem> = LinkedList()
return q
}
}
data class FlipFlop(override val name: String) : Module {
private var isOn = false
override var outputs: List<Module> = emptyList()
override fun apply(source: Module, pulse: Pulse): Queue<QueueItem> {
val q: Queue<QueueItem> = LinkedList()
if (pulse == Pulse.HIGH) return q
outputs.forEach { output -> q.add(QueueItem(this, output, if (isOn) Pulse.LOW else Pulse.HIGH)) }
isOn = !isOn
return q
}
}
data class Conjunction(override val name: String) : Module {
val memory = emptyMap<Module, Pulse>().toMutableMap()
override var outputs: List<Module> = emptyList()
override fun apply(source: Module, pulse: Pulse): Queue<QueueItem> {
val q: Queue<QueueItem> = LinkedList()
memory[source] = pulse
var pulseToSend = Pulse.HIGH
if (memory.all { (_, p) -> p == Pulse.HIGH }) {
pulseToSend = Pulse.LOW
}
outputs.forEach { output -> q.add(QueueItem(this, output, pulseToSend)) }
return q
}
}
} | 0 | Kotlin | 0 | 0 | 8fda713192b6278b69816cd413de062bb2d0e400 | 7,783 | AdventOfCode | MIT License |
src/main/kotlin/no/nav/syfo/sykmelding/PubliserNySykmeldingStatusService.kt | navikt | 218,005,192 | false | null | package no.nav.syfo.sykmelding
import no.nav.syfo.db.DatabasePostgres
import no.nav.syfo.log
import no.nav.syfo.model.sykmeldingstatus.KafkaMetadataDTO
import no.nav.syfo.model.sykmeldingstatus.STATUS_APEN
import no.nav.syfo.model.sykmeldingstatus.SykmeldingStatusKafkaEventDTO
import no.nav.syfo.persistering.db.postgres.getEnkelSykmeldingUtenStatus
import no.nav.syfo.sykmelding.aivenmigrering.SykmeldingV2KafkaMessage
import no.nav.syfo.sykmelding.aivenmigrering.SykmeldingV2KafkaProducer
import no.nav.syfo.sykmelding.kafka.model.toArbeidsgiverSykmelding
import no.nav.syfo.sykmelding.model.EnkelSykmeldingDbModel
import java.time.OffsetDateTime
import java.time.ZoneOffset
class PubliserNySykmeldingStatusService(
private val sykmeldingStatusKafkaProducer: SykmeldingStatusKafkaProducer,
private val mottattSykmeldingProudcer: SykmeldingV2KafkaProducer,
private val databasePostgres: DatabasePostgres,
private val mottattSykmeldingTopic: String
) {
val sykmeldingId = ""
fun start() {
val sykmelding = databasePostgres.connection.getEnkelSykmeldingUtenStatus(sykmeldingId)
if (sykmelding != null) {
log.info("oppdaterer status for sykmeldingid {}", sykmeldingId)
val sykmeldingStatusKafkaEventDTO = SykmeldingStatusKafkaEventDTO(
sykmeldingId = sykmeldingId,
timestamp = OffsetDateTime.now(ZoneOffset.UTC),
statusEvent = STATUS_APEN,
arbeidsgiver = null,
sporsmals = null
)
sykmeldingStatusKafkaProducer.send(
sykmeldingStatusKafkaEventDTO,
"macgyver",
sykmelding.fnr
)
log.info("Sendt statusendring")
mottattSykmeldingProudcer.sendSykmelding(
sykmeldingKafkaMessage = mapTilMottattSykmelding(sykmelding),
sykmeldingId = sykmeldingId,
topic = mottattSykmeldingTopic
)
log.info("Sendt til mottatt-topic")
} else {
log.info("fant ikke sykmelding med id {}", sykmeldingId)
}
}
private fun mapTilMottattSykmelding(enkelSykmeldingDbModel: EnkelSykmeldingDbModel): SykmeldingV2KafkaMessage {
return SykmeldingV2KafkaMessage(
sykmelding = enkelSykmeldingDbModel.toArbeidsgiverSykmelding(),
kafkaMetadata = KafkaMetadataDTO(
sykmeldingId = enkelSykmeldingDbModel.id,
timestamp = enkelSykmeldingDbModel.mottattTidspunkt.atOffset(ZoneOffset.UTC),
fnr = enkelSykmeldingDbModel.fnr,
source = "macgyver"
),
event = null
)
}
}
| 0 | Kotlin | 1 | 0 | 2baff402e14cf8f46339f0b8d171b6fc80888ce5 | 2,714 | syfoservice-data-syfosmregister | MIT License |
questDomain/src/main/java/ru/nekit/android/qls/domain/model/StatisticsAndHistory.kt | ru-nekit-android | 126,668,350 | false | null | package ru.nekit.android.qls.domain.model
import ru.nekit.android.qls.shared.model.QuestType
import ru.nekit.android.qls.shared.model.QuestionType
data class QuestStatisticsReport(val questAndQuestionType: QuestAndQuestionType,
var rightAnswerCount: Int = 0,
var rightAnswerSeriesCount: Int = 0,
var rightAnswerSeriesCounter: Int = 0,
var wrongAnswerCount: Int = 0,
var wrongAnswerSeriesCounter: Int = 0,
var bestAnswerTime: Long = 0,
var worseAnswerTime: Long = 0,
var rightAnswerSummandTime: Long = 0
)
data class QuestHistory(
val questAndQuestionType: QuestAndQuestionType,
val score: Int,
val lockScreenStartType: LockScreenStartType,
val answerType: AnswerType,
val sessionTime: Long,
var rewards: List<Reward>,
val recordTypes: Int,
val levelUp: Boolean,
val timeStamp: Long
)
data class QuestHistoryCriteria(
val limitByLastItem: Boolean = false,
val timestampGreaterThan: Boolean? = null,
val questType: QuestType? = null,
val questionType: QuestionType? = null,
val score: Int? = null,
val lockScreenStartType: LockScreenStartType? = null,
val answerType: AnswerType? = null,
val sessionTime: Long? = null,
var rewards: List<Reward>? = null,
val recordTypes: Int? = null,
val levelUp: Boolean? = null,
val timestamp: Long? = null
)
data class PupilStatistics(var score: Int)
data class Statistics(
val periodNumber: Int,
val statisticsPeriodType: StatisticsPeriodType,
val periodInterval: Pair<Long, Long>,
val answerCount: Int = 0,
val rightAnswerCount: Int = 0,
val history: List<QuestHistory> = ArrayList(),
val statisticsByQuestAndQuestionType: Map<QuestAndQuestionType, StatisticsByQuestAndQuestionType> = HashMap(),
var averageAnswerTime: Long = 0,
val rewardList: Map<Reward, Int> = HashMap(),
val isCurrentPeriod: Boolean = false,
val isReachedPeriod: Boolean = false)
data class StatisticsByQuestAndQuestionType(var history: MutableList<QuestHistory>) {
var answerCount: Int = 0
var rightAnswerCount: Int = -1
var bestAnswerTime: Long = -1
var averageAnswerTime: Long = -1
var worseAnswerTime: Long = -1
}
enum class StatisticsPeriodType {
HOURLY,
DAILY,
WEEKLY,
MONTHLY;
} | 0 | Kotlin | 0 | 1 | 37a2037be2ecdbe19607b5fbb9e5f7852320a5a0 | 2,658 | QuestLockScreen | Apache License 2.0 |
app/src/commonMain/kotlin/com/example/kmp/di/component/ViewModelComponent.kt | hadion82 | 797,506,685 | false | {"Kotlin": 108361, "Swift": 1033} | package com.example.kmp.di.component
import com.example.kmp.ui.main.MainActionDispatcher
import com.example.kmp.ui.main.MainActionDispatcherImpl
import com.example.kmp.ui.main.MainActionReducer
import com.example.kmp.ui.main.MainActionReducerImpl
import com.example.kmp.ui.main.MainIntentProcessor
import com.example.kmp.ui.main.MainProcessor
import com.example.kmp.ui.main.MainViewModelDelegate
import com.example.kmp.ui.main.MainViewModelDelegateImpl
import me.tatarka.inject.annotations.Provides
interface ViewModelComponent {
@Provides
fun MainViewModelDelegateImpl.bind(): MainViewModelDelegate = this
@Provides
fun MainActionDispatcherImpl.bind(): MainActionDispatcher = this
@Provides
fun MainIntentProcessor.bind(): MainProcessor = this
@Provides
fun MainActionReducerImpl.bind(): MainActionReducer = this
} | 1 | Kotlin | 0 | 0 | 57f36ceffcf386462c338edb3f98d3233321ad09 | 853 | compose-multiplatform-architecture | Apache License 2.0 |
common/base/src/main/java/com/bytebitx/base/event/ScrollEvent.kt | bytebitx | 371,705,786 | false | {"Kotlin": 368798, "Java": 130630} | package com.bytebitx.base.event
data class ScrollEvent(val index: Int)
| 3 | Kotlin | 13 | 51 | bd66b15a5f990067be7148fabcd22e3fb560bac7 | 72 | WanAndroid | Apache License 2.0 |
app/src/main/java/com/example/chefai/Views/MainActivity.kt | abenezermario | 480,656,546 | false | {"Kotlin": 32036} | package com.example.chefai.Views
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP
import android.os.Bundle
import android.text.TextUtils
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.chefai.R
import com.google.android.material.color.DynamicColors
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.auth.FirebaseUser
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private lateinit var mAuth: FirebaseAuth
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
DynamicColors.applyIfAvailable(this)
mAuth = FirebaseAuth.getInstance()
loginBtn.setOnClickListener {
loginUser()
}
resetPassword.setOnClickListener {
val intent = Intent(this@MainActivity, ResetPassword::class.java)
startActivity(intent)
}
register.setOnClickListener {
val intent = Intent(this@MainActivity, RegisterActivity::class.java)
startActivity(intent)
}
}
private fun loginUser() {
when {
TextUtils.isEmpty(email.text.toString().trim { it <= ' ' }) -> {
Toast.makeText(this@MainActivity, "Invalid email address", Toast.LENGTH_SHORT)
.show()
}
TextUtils.isEmpty(password.text.toString().trim { it <= ' ' }) -> {
Toast.makeText(this@MainActivity, "Invalid Password", Toast.LENGTH_SHORT)
.show()
}
else -> {
val email = email.text.toString().trim { it <= ' ' }
val password = password.text.toString().trim { it <= ' ' }
mAuth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener {
if (it.isSuccessful) {
// progress_circular.visibility = android.view.View.VISIBLE
Toast.makeText(
this@MainActivity,
"Login sucess",
Toast.LENGTH_SHORT
)
.show()
val user = mAuth.currentUser
updateUI(user!!)
} else {
Toast.makeText(
this@MainActivity,
it.exception?.message,
Toast.LENGTH_SHORT
)
.show()
updateUI(null!!)
}
}
}
}
}
override fun onStart() {
super.onStart()
var currentUser = mAuth.currentUser
if (currentUser != null) {
updateUI(currentUser)
}
}
private fun updateUI(currentUser: FirebaseUser) {
val intent = Intent(this@MainActivity, HomeActivity::class.java)
intent.addFlags(FLAG_ACTIVITY_CLEAR_TOP)
startActivity(intent)
}
} | 0 | Kotlin | 1 | 0 | f47f460d0268be3bebc3901b943c3ed802c8dbfd | 3,286 | Chefai | MIT License |
platform/android/goldengate/remoteapi/src/test/kotlin/com/fitbit/remoteapi/StartPairingRpcHandlerTest.kt | Fitbit | 252,750,226 | false | {"C": 2519513, "Kotlin": 897890, "Swift": 806092, "C++": 805305, "CMake": 121256, "Python": 115131, "Objective-C": 88567, "JavaScript": 20929, "HTML": 13841, "Shell": 2041, "Dockerfile": 1379, "Ruby": 252} | // Copyright 2017-2020 Fitbit, Inc
// SPDX-License-Identifier: Apache-2.0
package com.fitbit.remoteapi
import co.nstant.`in`.cbor.CborBuilder
import co.nstant.`in`.cbor.model.Map
import co.nstant.`in`.cbor.model.SimpleValue
import co.nstant.`in`.cbor.model.UnicodeString
import co.nstant.`in`.cbor.model.UnsignedInteger
import com.fitbit.remoteapi.handlers.StartPairingRpc
import org.junit.Test
import kotlin.test.assertEquals
const val MAC_ADDRESS = "AA:BB:CC:DD:EE:FF"
class StartPairingRpcHandlerTest {
private val peerIdParam = "peer"
private val idParam = "id"
private val typeParam = "type"
@Test
fun testCommandParsing() {
// { "peer_id" : {id: "AA:BB:CC:DD:EE:FF", type: "macAddress"} }
val dataItems = CborBuilder().addMap().putMap("peer").put(idParam, MAC_ADDRESS)
.put(typeParam, "macAddress").end().end().build()
val expectedPeerId = PeerId(MAC_ADDRESS, PeerIdType.MAC_ADDRESS)
assertEquals(expectedPeerId, StartPairingRpc.Parser().parse(dataItems))
}
@Test(expected = IllegalArgumentException::class)
fun testThrowsOnInvalidParamKeyAndValueType() {
// { "invalid" : 2 }
val dataItems = CborBuilder().addMap().put("invalid", 2).end().build()
StartPairingRpc.Parser().parse(dataItems)
}
@Test(expected = IllegalArgumentException::class)
fun testThrowsOnNullValueForPeerId() {
// { "peer_id" : null }
val dataItems = listOf(Map().put(UnicodeString(peerIdParam), SimpleValue.NULL))
StartPairingRpc.Parser().parse(dataItems)
}
@Test(expected = IllegalArgumentException::class)
fun testThrowsOnNullValueForIdField() {
// { "peer_id" : {id: null, type: "macAddress"} }
val peerIdItem = Map().put(UnicodeString(idParam), SimpleValue.NULL).put(UnicodeString(typeParam), UnicodeString(PeerIdType.MAC_ADDRESS.value))
val dataItems = listOf(Map().put(UnicodeString(peerIdParam), peerIdItem))
StartPairingRpc.Parser().parse(dataItems)
}
@Test(expected = IllegalArgumentException::class)
fun testThrowsOnInvalidPeerType() {
// { "peer_id" : {id: "AA:BB:CC:DD:EE:FF", type: "banana"} }
val peerIdItem = Map().put(UnicodeString(idParam), UnicodeString(MAC_ADDRESS))
.put(UnicodeString(typeParam), UnicodeString("banana"))
val dataItems = listOf(Map().put(UnicodeString(peerIdParam), peerIdItem))
StartPairingRpc.Parser().parse(dataItems)
}
@Test(expected = IllegalArgumentException::class)
fun testThrowsOnInvalidPeerTypeType() {
// { "peer_id" : {id: "AA:BB:CC:DD:EE:FF", type: 9} }
val peerIdItem = Map().put(UnicodeString(idParam), UnicodeString(MAC_ADDRESS))
.put(UnicodeString(typeParam), UnsignedInteger(9))
val dataItems = listOf(Map().put(UnicodeString(peerIdParam), peerIdItem))
StartPairingRpc.Parser().parse(dataItems)
}
@Test(expected = IllegalArgumentException::class)
fun testThrowsOnInvalidPeerIdType() {
// { "peer_id" : {id: 5, type: "macAddress"} }
val peerIdItem = Map().put(UnicodeString(idParam), UnsignedInteger(5))
.put(UnicodeString(typeParam), UnicodeString(PeerIdType.MAC_ADDRESS.value))
val dataItems = listOf(Map().put(UnicodeString(peerIdParam), peerIdItem))
StartPairingRpc.Parser().parse(dataItems)
}
}
| 14 | C | 32 | 290 | 417aad0080bdc8b20c27cf8fff2455c20e6f3adb | 3,396 | golden-gate | Apache License 2.0 |
core/src/commonMain/kotlin/com/paligot/kighlighter/core/Language.kt | GerardPaligot | 402,898,581 | false | null | package com.paligot.kighlighter.core
interface Language<T : ColorScheme> {
val colorScheme: T
fun patterns(): List<LanguagePattern<T>>
} | 0 | Kotlin | 1 | 23 | 4001f7f7bbb9996ecfc3d9d34dde6d2523c143df | 145 | kighlighter | Apache License 2.0 |
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/broken/Wifisquare.kt | Tlaster | 560,394,734 | false | {"Kotlin": 25133302} | package moe.tlaster.icons.vuesax.vuesaxicons.broken
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Round
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import moe.tlaster.icons.vuesax.vuesaxicons.BrokenGroup
public val BrokenGroup.Wifisquare: ImageVector
get() {
if (_wifisquare != null) {
return _wifisquare!!
}
_wifisquare = Builder(name = "Wifisquare", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(6.0f, 9.96f)
curveTo(9.63f, 7.15f, 14.37f, 7.15f, 18.0f, 9.96f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(7.5996f, 13.0501f)
curveTo(10.2696f, 10.9901f, 13.7396f, 10.9901f, 16.4096f, 13.0501f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(9.8008f, 16.1399f)
curveTo(11.1308f, 15.1099f, 12.8708f, 15.1099f, 14.2008f, 16.1399f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF292D32)),
strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin =
StrokeJoin.Companion.Round, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(2.0f, 13.05f)
verticalLineTo(15.0f)
curveTo(2.0f, 20.0f, 4.0f, 22.0f, 9.0f, 22.0f)
horizontalLineTo(15.0f)
curveTo(20.0f, 22.0f, 22.0f, 20.0f, 22.0f, 15.0f)
verticalLineTo(9.0f)
curveTo(22.0f, 4.0f, 20.0f, 2.0f, 15.0f, 2.0f)
horizontalLineTo(9.0f)
curveTo(4.0f, 2.0f, 2.0f, 4.0f, 2.0f, 9.0f)
}
}
.build()
return _wifisquare!!
}
private var _wifisquare: ImageVector? = null
| 0 | Kotlin | 0 | 2 | b8a8231e6637c2008f675ae76a3423b82ee53950 | 3,049 | VuesaxIcons | MIT License |
kdroidext/src/main/java/com/nowfal/kdroidext/kex/DialogExtensions.kt | nowfalsalahudeen | 167,347,983 | false | null | /*
* Copyright 2019 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.nowfal.kdroidext.kex
import android.app.Dialog
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import androidx.annotation.*
import androidx.fragment.app.DialogFragment
fun Dialog.color(@ColorRes clr: Int): Int {
return context.color(clr)
}
fun Dialog.string(@StringRes str: Int): String {
return context.string(str)
}
fun Dialog.drawable(@DrawableRes drw: Int): Drawable? {
return context.drawable(drw)
}
fun Dialog.dimen(@DimenRes dmn: Int): Float {
return context.dimen(dmn)
}
fun Dialog.dimenInt(@DimenRes dmn: Int): Int {
return context.dimenInt(dmn)
}
fun Dialog.int(@IntegerRes int: Int): Int {
return context.int(int)
}
fun Dialog.font(@FontRes font: Int): Typeface? {
return context.font(font)
}
fun Dialog.stringArray(array: Int): Array<String> {
return context.stringArray(array)
}
fun Dialog.intArray(array: Int): IntArray {
return context.intArray(array)
}
fun DialogFragment.color(@ColorRes clr: Int): Int {
return context!!.color(clr)
}
fun DialogFragment.string(@StringRes str: Int): String {
return context!!.string(str)
}
fun DialogFragment.drawable(@DrawableRes drw: Int): Drawable? {
return context!!.drawable(drw)
}
fun DialogFragment.dimen(@DimenRes dmn: Int): Float {
return context!!.dimen(dmn)
}
fun DialogFragment.dimenInt(@DimenRes dmn: Int): Int {
return context!!.dimenInt(dmn)
}
fun DialogFragment.int(@IntegerRes int: Int): Int {
return context!!.int(int)
}
fun DialogFragment.font(@FontRes font: Int): Typeface? {
return context!!.font(font)
}
fun DialogFragment.stringArray(array: Int): Array<String> {
return context!!.stringArray(array)
}
fun DialogFragment.intArray(array: Int): IntArray {
return context!!.intArray(array)
} | 1 | null | 1 | 29 | fb91a3febf73a3bb5f3582de2694c6f829cf3c58 | 2,375 | KdroidExt | Apache License 2.0 |
app/src/main/java/serat/maemaeen/mahdavistories/base/BaseFragment.kt | AliMansoorzare | 578,880,407 | false | null | package serat.maemaeen.mahdavistories.base
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.LiveData
import androidx.lifecycle.Observer
import androidx.viewbinding.ViewBinding
import serat.maemaeen.mahdavistories.di.DaggerInjector
abstract class BaseFragment<VB : ViewBinding, VM : BaseViewModel> : Fragment() {
private val daggerInjector: DaggerInjector by lazy { requireActivity().application as DaggerInjector }
protected val viewModel: VM by lazy { createViewModel() }
protected val binding: VB by lazy { inflateViewBinding(layoutInflater) }
protected abstract fun createViewModel(): VM
protected abstract fun inflateViewBinding(inflater: LayoutInflater): VB
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
daggerInjector.inject(this)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View = binding.root
protected fun <T> LiveData<T>.observe(observer: Observer<in T>) =
observe(this@BaseFragment,observer)
} | 0 | Kotlin | 0 | 0 | b5675394c5fa7af231d2b918fb77dfb2fcf078c8 | 1,238 | Android-Clean-Architecture | MIT License |
core/src/main/kotlin/io/customer/sdk/data/store/GlobalPreferenceStore.kt | customerio | 355,691,391 | false | null | package io.customer.sdk.data.store
import android.content.Context
import androidx.core.content.edit
/**
* Store for global preferences that are not tied to a specific api key, user
* or any other entity.
*/
interface GlobalPreferenceStore {
fun saveDeviceToken(token: String)
fun getDeviceToken(): String?
fun removeDeviceToken()
fun clear(key: String)
fun clearAll()
}
internal class GlobalPreferenceStoreImpl(
context: Context
) : PreferenceStore(context), GlobalPreferenceStore {
override val prefsName: String by lazy {
"io.customer.sdk.${context.packageName}"
}
override fun saveDeviceToken(token: String) = prefs.edit {
putString(KEY_DEVICE_TOKEN, token)
}
override fun getDeviceToken(): String? = prefs.read {
getString(KEY_DEVICE_TOKEN, null)
}
override fun removeDeviceToken() = clear(KEY_DEVICE_TOKEN)
companion object {
private const val KEY_DEVICE_TOKEN = "device_token"
}
}
| 9 | null | 9 | 13 | 7ee9714bff991675042e7929ae269272f69a4706 | 990 | customerio-android | MIT License |
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/ToggleOnSolid.kt | DevSrSouza | 311,134,756 | false | null | package compose.icons.lineawesomeicons
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 compose.icons.LineAwesomeIcons
public val LineAwesomeIcons.ToggleOnSolid: ImageVector
get() {
if (_toggleOnSolid != null) {
return _toggleOnSolid!!
}
_toggleOnSolid = Builder(name = "ToggleOnSolid", defaultWidth = 32.0.dp, defaultHeight =
32.0.dp, viewportWidth = 32.0f, viewportHeight = 32.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(9.0f, 7.0f)
curveTo(4.039f, 7.0f, 0.0f, 11.035f, 0.0f, 16.0f)
curveTo(0.0f, 20.965f, 4.039f, 25.0f, 9.0f, 25.0f)
lineTo(23.0f, 25.0f)
curveTo(27.957f, 25.0f, 32.0f, 20.957f, 32.0f, 16.0f)
curveTo(32.0f, 11.043f, 27.957f, 7.0f, 23.0f, 7.0f)
close()
moveTo(23.0f, 9.0f)
curveTo(26.879f, 9.0f, 30.0f, 12.121f, 30.0f, 16.0f)
curveTo(30.0f, 19.879f, 26.879f, 23.0f, 23.0f, 23.0f)
curveTo(19.121f, 23.0f, 16.0f, 19.879f, 16.0f, 16.0f)
curveTo(16.0f, 12.121f, 19.121f, 9.0f, 23.0f, 9.0f)
close()
}
}
.build()
return _toggleOnSolid!!
}
private var _toggleOnSolid: ImageVector? = null
| 17 | null | 25 | 571 | a660e5f3033e3222e3553f5a6e888b7054aed8cd | 1,950 | compose-icons | MIT License |
sdk/src/main/kotlin/io/rover/sdk/ui/blocks/poll/text/TextPollBlockView.kt | RoverPlatform | 55,724,334 | false | null | package io.rover.sdk.ui.blocks.poll.text
import android.content.Context
import android.graphics.Canvas
import android.widget.LinearLayout
import io.rover.sdk.ui.blocks.concerns.ViewComposition
import io.rover.sdk.ui.blocks.concerns.background.ViewBackground
import io.rover.sdk.ui.blocks.concerns.border.ViewBorder
import io.rover.sdk.ui.blocks.concerns.layout.LayoutableView
import io.rover.sdk.ui.blocks.concerns.layout.ViewBlock
import io.rover.sdk.ui.concerns.MeasuredBindableView
import io.rover.sdk.ui.concerns.ViewModelBinding
internal class TextPollBlockView(context: Context?) : LinearLayout(context),
LayoutableView<TextPollBlockViewModel> {
// mixins
private val viewComposition = ViewComposition()
private val viewBackground = ViewBackground(this)
private val viewBorder = ViewBorder(this, viewComposition)
private val viewBlock = ViewBlock(this)
private val viewTextPoll = ViewTextPoll(this)
init {
orientation = VERTICAL
}
override var viewModelBinding: MeasuredBindableView.Binding<TextPollBlockViewModel>? by ViewModelBinding { binding, _ ->
viewBorder.viewModelBinding = binding
viewBlock.viewModelBinding = binding
viewBackground.viewModelBinding = binding
viewTextPoll.viewModelBinding = binding
}
override fun draw(canvas: Canvas) {
viewComposition.beforeDraw(canvas)
super.draw(canvas)
viewComposition.afterDraw(canvas)
}
}
| 16 | null | 13 | 6 | 1b6e627a1e4b3651d0cc9f6e78f995ed9e4a821a | 1,467 | rover-android | Apache License 2.0 |
tools-manage/invocationlab-admin-21/src/main/kotlin/org/javamaster/invocationlab/admin/service/registry/impl/EurekaRegisterFactory.kt | jufeng98 | 191,107,543 | false | null | package org.javamaster.invocationlab.admin.service.registry.impl
import org.javamaster.invocationlab.admin.service.registry.Register
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Component
import org.springframework.web.client.RestTemplate
/**
* @author yudong
*/
@Component
class EurekaRegisterFactory : AbstractRegisterFactory() {
@Autowired
private lateinit var restTemplate: RestTemplate
override fun create(cluster: String): Register {
return EurekaRegister(cluster, restTemplate)
}
}
| 32 | null | 66 | 129 | 0ea2a5644bd08c1b8b2226a8490ab7c37a25a36f | 573 | java-master | Apache License 2.0 |
j2k/src/org/jetbrains/jet/j2k/ast/Enum.kt | hhariri | 21,116,939 | true | {"Markdown": 19, "XML": 443, "Ant Build System": 23, "Ignore List": 7, "Protocol Buffer": 2, "Java": 3757, "Kotlin": 11162, "Roff": 59, "JAR Manifest": 1, "INI": 7, "Text": 916, "Java Properties": 10, "HTML": 102, "Roff Manpage": 8, "Groovy": 7, "Gradle": 61, "Maven POM": 34, "CSS": 10, "JavaScript": 42, "JFlex": 3, "Batchfile": 7, "Shell": 7} | /*
* Copyright 2010-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.jet.j2k.ast
import org.jetbrains.jet.j2k.Converter
class Enum(
converter: Converter,
name: Identifier,
comments: MemberComments,
modifiers: Set<Modifier>,
typeParameterList: TypeParameterList,
extendsTypes: List<Type>,
baseClassParams: List<Expression>,
implementsTypes: List<Type>,
bodyElements: List<Element>
) : Class(converter, name, comments, modifiers, typeParameterList,
extendsTypes, baseClassParams, implementsTypes, bodyElements) {
override fun primaryConstructorSignatureToKotlin(): String
= classMembers.primaryConstructor?.signatureToKotlin() ?: ""
override fun toKotlin(): String {
return modifiersToKotlin() +
"enum class " + name.toKotlin() +
primaryConstructorSignatureToKotlin() +
typeParameterList.toKotlin() +
implementTypesToKotlin() +
" {" +
classMembers.allMembers.toKotlin() +
primaryConstructorBodyToKotlin() +
"}"
}
} | 0 | Java | 0 | 0 | d150bfbce0e2e47d687f39e2fd233ea55b2ccd26 | 1,709 | kotlin | Apache License 2.0 |
EvoMaster/core/src/main/kotlin/org/evomaster/core/output/ObjectGenerator.kt | mitchellolsthoorn | 364,836,402 | false | null | package org.evomaster.core.output
import io.swagger.v3.oas.models.OpenAPI
import org.evomaster.core.problem.rest.RestActionBuilderV3
import org.evomaster.core.problem.rest.RestCallAction
import org.evomaster.core.problem.rest.RestIndividual
import org.evomaster.core.search.gene.DisruptiveGene
import org.evomaster.core.search.gene.Gene
import org.evomaster.core.search.gene.ObjectGene
import org.evomaster.core.search.gene.OptionalGene
class ObjectGenerator {
private lateinit var swagger: OpenAPI
private val modelCluster: MutableMap<String, ObjectGene> = mutableMapOf()
fun initialize() {
if (swagger != null) {
modelCluster.clear()
RestActionBuilderV3.getModelsFromSwagger(swagger, modelCluster)
}
}
fun setSwagger(sw: OpenAPI){
swagger = sw
if (swagger != null) {
modelCluster.clear()
RestActionBuilderV3.getModelsFromSwagger(swagger, modelCluster)
}
}
fun getSwagger(): OpenAPI{
return swagger
}
fun longestCommonSubsequence(a: String, b: String): String {
if (a.length > b.length) return longestCommonSubsequence(b, a)
var res = ""
for (ai in 0 until a.length) {
for (len in a.length - ai downTo 1) {
for (bi in 0 until b.length - len + 1) {
if (a.regionMatches(ai, b, bi,len) && len > res.length) {
res = a.substring(ai, ai + len)
}
}
}
}
return res
}
fun <T> likelyhoodsExtended(parameter: String, candidates: MutableMap<String, T>): MutableMap<Pair<String, String>, Float>{
//TODO BMR: account for empty candidate sets.
val result = mutableMapOf<Pair<String, String>, Float>()
var sum : Float = 0.toFloat()
if (candidates.isEmpty()) return result
candidates.forEach { k, v ->
for (field in (v as ObjectGene).fields) {
val fieldName = field.name
val extendedName = "$k${fieldName}"
// even if there are not characters in common, a matching field should still have
// a probability of being chosen (albeit a small one).
val temp = (1.toLong() + longestCommonSubsequence(parameter.toLowerCase(), extendedName.toLowerCase())
.length.toFloat())/ (1.toLong() + Integer.max(parameter.length, extendedName.length).toFloat())
result[Pair(k, fieldName)] = temp
sum += temp
}
}
result.forEach { k, u ->
result[k] = u/sum
}
return result
}
private fun findSelectedGene(selectedGene: Pair<String, String>): Gene {
val foundGene = (modelCluster[selectedGene.first]!!).fields.filter{ field ->
field.name == selectedGene.second
}.first()
when (foundGene::class) {
OptionalGene::class -> return (foundGene as OptionalGene).gene
DisruptiveGene::class -> return (foundGene as DisruptiveGene<*>).gene
else -> return foundGene
}
}
fun addResponseObjects(action: RestCallAction, individual: RestIndividual){
val refs = action.responseRefs.values
refs.forEach{
val respObject = swagger.components.schemas.get(it)
}
}
fun getNamedReference(name: String): ObjectGene{
return modelCluster.getValue(name)
}
} | 1 | null | 1 | 1 | 50e9fb327fe918cc64c6b5e30d0daa2d9d5d923f | 3,505 | ASE-Technical-2021-api-linkage-replication | MIT License |
Leetcode-Solution-Kotlin/solvingQuestionsWIthBrainpower.kt | harshraj9988 | 491,534,142 | false | null | private fun recursion(questions: Array<IntArray>, i: Int): Long {
if (i >= questions.size) {
return 0L
}
val solve = questions[i][0].toLong() + recursion(questions, i + questions[i][1] + 1)
val notSolve = recursion(questions, i + 1)
return solve.coerceAtLeast(notSolve)
}
private fun memoization(questions: Array<IntArray>, i: Int, dp: LongArray): Long {
if (i >= questions.size) {
return 0L
}
if (dp[i] != -1L) {
return dp[i]
}
val solve = questions[i][0].toLong() + memoization(questions, i + questions[i][1] + 1, dp)
val notSolve = memoization(questions, i + 1, dp)
dp[i] = solve.coerceAtLeast(notSolve)
return dp[i]
}
private fun tabulation(questions: Array<IntArray>): Long {
val dp = LongArray(questions.size)
for (i in questions.lastIndex downTo 0) {
val solve =
questions[i][0].toLong() + (if (i + questions[i][1] + 1 < questions.size) dp[i + questions[i][1] + 1] else 0)
val notSolve = (if (i + 1 < questions.size) dp[i + 1] else 0)
dp[i] = solve.coerceAtLeast(notSolve)
}
return dp[0]
}
fun mostPoints(questions: Array<IntArray>): Long {
// return recursion(questions, 0)
// val dp = LongArray(questions.size) { -1L }
// return memoization(questions, 0, dp)
return tabulation(questions)
} | 1 | null | 1 | 1 | 3fc29ceffe3eaf92d9e6e79bfb097ba0db1c40ad | 1,488 | LeetCode-solutions | Apache License 2.0 |
src/test/kotlin/org/intellij/plugin/tracker/services/LinkUpdaterServiceTest.kt | JetBrains-Research | 277,519,535 | false | null | package org.intellij.plugin.tracker.services
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiElement
import com.intellij.psi.search.FilenameIndex
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.PsiTreeUtil
import com.intellij.psi.util.elementType
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import org.intellij.markdown.MarkdownElementTypes.INLINE_LINK
import org.intellij.plugin.tracker.data.diff.Line
import org.intellij.plugin.tracker.data.changes.Change
import org.intellij.plugin.tracker.data.changes.CustomChange
import org.intellij.plugin.tracker.data.changes.CustomChangeType
import org.intellij.plugin.tracker.data.changes.LineChange
import org.intellij.plugin.tracker.data.changes.LineChangeType
import org.intellij.plugin.tracker.data.links.Link
import org.intellij.plugin.tracker.data.links.LinkInfo
import org.intellij.plugin.tracker.data.links.RelativeLinkToDirectory
import org.intellij.plugin.tracker.data.links.RelativeLinkToFile
import org.intellij.plugin.tracker.data.links.RelativeLinkToLine
import org.intellij.plugin.tracker.core.update.LinkElementImpl
import org.intellij.plugins.markdown.lang.MarkdownElementType
/**
* This class is a template for testing updating links.
* In order to create tests with a new project instance per test
* it is necessary to create a different instance of this class for each test case.
* WARNING: All filenames of test files should be unique project-wide,
* and all link texts should be unique file-wide.
*/
abstract class TestUpdateLinks : BasePlatformTestCase() {
protected lateinit var myLinkUpdateService: LinkUpdaterService
private val myFiles = arrayOf(
"testUpdateLinks.md",
"testUpdateRelativeLinks.md",
"main/file.txt",
"main/directory/file1.txt",
"main/directory/file2.txt"
)
override fun getTestDataPath(): String {
return "src/test/kotlin/org/intellij/plugin/tracker/services/testdata"
}
override fun setUp() {
super.setUp()
myFixture.configureByFiles(*myFiles)
myLinkUpdateService = LinkUpdaterService.getInstance(project)
}
protected fun refresh(dir: VirtualFile = project.baseDir) {
VfsUtil.markDirtyAndRefresh(false, true, false, dir)
}
/**
* Finds the Psi link destination element in the given file with the given link text.
* Assumes that the filename is unique in the project's file tree and that the element's text
* is unique in its file.
*/
protected fun findElement(fileName: String, text: String): PsiElement {
val files = FilenameIndex.getFilesByName(
project, fileName,
GlobalSearchScope.projectScope(project)
)
assert(files.size == 1)
val file = files[0]
val matches = PsiTreeUtil
.findChildrenOfType(file, ASTWrapperPsiElement::class.java)
.toList()
.filter { it.elementType == MarkdownElementType.platformType(INLINE_LINK) }
.filter { it.children[0].text == "[$text]" }
assert(matches.size == 1)
return matches[0].children[1]
}
}
/**
* This class tests updating a single link.
* Simulates the effect of moving test file "file.txt"
* from the root directory to a new directory "main".
*/
class TestRelativeLinkToFile : TestUpdateLinks() {
fun testUpdateRelativeLinkToFile() {
val linkText = "relative link to file"
val fileName = "testUpdateLinks.md"
val linkElement =
LinkElementImpl(findElement(fileName, linkText))
val linkInfo = LinkInfo(
linkText = linkText,
linkPath = "file.txt",
proveniencePath = fileName,
foundAtLineNumber = 1,
fileName = fileName,
project = project,
linkElement = linkElement
)
val link = RelativeLinkToFile(
linkInfo = linkInfo
)
val change = CustomChange(
customChangeType = CustomChangeType.MOVED,
afterPathString = "main/file.txt"
)
val list = mutableListOf<Pair<Link, Change>>(
Pair(link, change)
)
WriteCommandAction.runWriteCommandAction(project) {
myLinkUpdateService.batchUpdateLinks(list, null)
}
myFixture.configureByFile("expected/expectedTestUpdateRelativeLinkToFile.md")
ApplicationManager.getApplication().runReadAction {
val fileExpected = myFixture.findFileInTempDir("expected/expectedTestUpdateRelativeLinkToFile.md")
val fileActual = myFixture.findFileInTempDir("testUpdateLinks.md")
PlatformTestUtil.assertFilesEqual(fileExpected, fileActual)
}
}
}
/**
* This class tests updating a single link.
* Simulates the effect of moving test file "file.txt"
* from the root directory to a new directory "main".
*/
class TestRelativeLinkToLine : TestUpdateLinks() {
fun testUpdateRelativeLinkToLine() {
val linkText = "relative link to line"
val fileName = "testUpdateLinks.md"
val linkElement =
LinkElementImpl(findElement(fileName, linkText))
val linkInfo = LinkInfo(
linkText = linkText,
linkPath = "file.txt#L1",
proveniencePath = fileName,
foundAtLineNumber = 2,
fileName = fileName,
project = project,
linkElement = linkElement
)
val link = RelativeLinkToFile(
linkInfo = linkInfo
)
val change = CustomChange(
customChangeType = CustomChangeType.MOVED,
afterPathString = "main/file.txt#L1"
)
val list = mutableListOf<Pair<Link, Change>>(
Pair(link, change)
)
WriteCommandAction.runWriteCommandAction(project) {
myLinkUpdateService.batchUpdateLinks(list, null)
}
myFixture.configureByFile("expected/expectedTestUpdateRelativeLinkToLine.md")
ApplicationManager.getApplication().runReadAction {
val fileExpected = myFixture.findFileInTempDir("expected/expectedTestUpdateRelativeLinkToLine.md")
val fileActual = myFixture.findFileInTempDir("testUpdateLinks.md")
PlatformTestUtil.assertFilesEqual(fileExpected, fileActual)
}
}
}
/**
* This class tests updating multiple relative links within a single file.
* Simulates the effect of moving test file "file.txt" from the root directory
* to a new directory "main", and moving files "file1.txt" and "file2.txt"
* from the root directory to a new directory "main/directory".
*/
class TestRelativeLinks : TestUpdateLinks() {
fun testUpdateRelativeLinks() {
val fileName = "testUpdateRelativeLinks.md"
val linkText1 = "relative link 1"
val linkElement1 =
LinkElementImpl(findElement(fileName, linkText1))
val linkInfo1 = LinkInfo(
linkText = linkText1,
linkPath = "file.txt",
proveniencePath = fileName,
foundAtLineNumber = 1,
fileName = fileName,
project = project,
linkElement = linkElement1
)
val linkText2 = "relative link 2"
val linkElement2 =
LinkElementImpl(findElement(fileName, linkText2))
val linkInfo2 = LinkInfo(
linkText = linkText2,
linkPath = "file1.txt",
proveniencePath = fileName,
foundAtLineNumber = 2,
fileName = fileName,
project = project,
linkElement = linkElement2
)
val linkText3 = "relative link 3"
val linkElement3 =
LinkElementImpl(findElement(fileName, linkText3))
val linkInfo3 = LinkInfo(
linkText = linkText3,
linkPath = "file2.txt",
proveniencePath = fileName,
foundAtLineNumber = 3,
fileName = fileName,
project = project,
linkElement = linkElement3
)
val link1 = RelativeLinkToFile(
linkInfo = linkInfo1
)
val link2 = RelativeLinkToFile(
linkInfo = linkInfo2
)
val link3 = RelativeLinkToFile(
linkInfo = linkInfo3
)
val change1 = CustomChange(
customChangeType = CustomChangeType.MOVED,
afterPathString = "main/file.txt"
)
val change2 = CustomChange(
customChangeType = CustomChangeType.MOVED,
afterPathString = "main/directory/file1.txt"
)
val change3 = CustomChange(
customChangeType = CustomChangeType.MOVED,
afterPathString = "main/directory/file2.txt"
)
val list = mutableListOf<Pair<Link, Change>>(
Pair(link1, change1),
Pair(link2, change2),
Pair(link3, change3)
)
WriteCommandAction.runWriteCommandAction(project) {
myLinkUpdateService.batchUpdateLinks(list, null)
}
myFixture.configureByFile("expected/expectedTestUpdateRelativeLinks.md")
ApplicationManager.getApplication().runReadAction {
val fileExpected = myFixture.findFileInTempDir("expected/expectedTestUpdateRelativeLinks.md")
val fileActual = myFixture.findFileInTempDir("testUpdateRelativeLinks.md")
PlatformTestUtil.assertFilesEqual(fileExpected, fileActual)
}
}
}
/**
* This class tests updating multiple links of different types within a single file.
* Simulates the effect of moving test file "file.txt"
* from the root directory to a new directory "main".
*/
class TestMultipleLinks : TestUpdateLinks() {
// This test case is disabled because one of the tested features
// (updating links to directories) is not yet ready.
// Do not remove the test.
fun testUpdateVariousLinks() {
val fileName = "testUpdateLinks.md"
val linkText1 = "relative link to file"
val linkElement1 =
LinkElementImpl(findElement(fileName, linkText1))
val linkInfoToFile = LinkInfo(
linkText = linkText1,
linkPath = "file.txt",
proveniencePath = fileName,
foundAtLineNumber = 1,
fileName = fileName,
project = project,
linkElement = linkElement1
)
val linkText2 = "relative link to line"
val linkElement2 =
LinkElementImpl(findElement(fileName, linkText2))
val linkInfoToLine = LinkInfo(
linkText = linkText2,
linkPath = "file.txt#L1",
proveniencePath = fileName,
foundAtLineNumber = 2,
fileName = fileName,
project = project,
linkElement = linkElement2
)
val linkText3 = "relative link to directory"
val linkElement3 =
LinkElementImpl(findElement(fileName, linkText3))
val linkInfoToDir = LinkInfo(
linkText = linkText3,
linkPath = ".",
proveniencePath = fileName,
foundAtLineNumber = 3,
fileName = fileName,
project = project,
linkElement = linkElement3
)
val linkToFile = RelativeLinkToFile(
linkInfo = linkInfoToFile
)
val linkToLine = RelativeLinkToLine(
linkInfo = linkInfoToLine
)
val linkToDir = RelativeLinkToDirectory(
linkInfo = linkInfoToDir
)
val linkChangeToFile = CustomChange(
customChangeType = CustomChangeType.MOVED,
afterPathString = "main/file.txt"
)
val linkChangeToLine = LineChange(
fileChange = CustomChange(CustomChangeType.MOVED, afterPathString = "main/file.txt"),
lineChangeType = LineChangeType.MOVED,
newLine = Line(
lineNumber = 1,
content = "dummy line"
)
)
val linkChangeToDir = CustomChange(
customChangeType = CustomChangeType.MOVED,
afterPathString = "main"
)
val list = mutableListOf<Pair<Link, Change>>(
Pair(linkToFile, linkChangeToFile),
Pair(linkToLine, linkChangeToLine),
Pair(linkToDir, linkChangeToDir)
)
WriteCommandAction.runWriteCommandAction(project) {
myLinkUpdateService.batchUpdateLinks(list, null)
}
myFixture.configureByFile("expected/expectedTestUpdateMultipleLinks.md")
ApplicationManager.getApplication().runReadAction {
val fileExpected = myFixture.findFileInTempDir("expected/expectedTestUpdateMultipleLinks.md")
val fileActual = myFixture.findFileInTempDir("testUpdateLinks.md")
PlatformTestUtil.assertFilesEqual(fileExpected, fileActual)
}
}
}
| 5 | Kotlin | 1 | 2 | 831e3eaa7ead78ffe277cb415b6f993139fb4de3 | 13,214 | linktracker | Apache License 2.0 |
app/src/debug/java/com/oheuropa/android/ui/test/TestKotlinActivity.kt | ElroidLtd | 123,912,674 | false | {"Gradle": 3, "Markdown": 2, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "JSON": 2, "Kotlin": 78, "XML": 38, "Java": 1, "Text": 12} | package com.oheuropa.android.ui.test
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.widget.Button
import com.github.ajalt.timberkt.d
import com.github.ajalt.timberkt.i
import com.oheuropa.android.R
import com.oheuropa.android.domain.AudioComponent
import com.oheuropa.android.domain.AudioComponent.State.*
import com.oheuropa.android.ui.base.BaseActivity
import dagger.android.AndroidInjection
import javax.inject.Inject
/**
* Class: com.oheuropa.android.ui.test.TestActivity
* Project: OhEuropa-Android
* Created Date: 07/03/2018 16:48
*
* @author [Elliot Long](mailto:[email protected])
* Copyright (c) 2018 Elroid Ltd. All rights reserved.
*/
class TestKotlinActivity : BaseActivity() {
companion object {
fun createIntent(ctx: Context): Intent {
return Intent(ctx, TestKotlinActivity::class.java)
}
}
@Inject lateinit var audioPlayer: AudioComponent
override fun onCreate(savedInstanceState: Bundle?) {
AndroidInjection.inject(this)
super.onCreate(savedInstanceState)
setContentView(R.layout.kotlin_test)
findViewById<Button>(R.id.but1).setOnClickListener({
i { "Playing static" }
audioPlayer.setState(STATIC)
})
findViewById<Button>(R.id.but2).setOnClickListener({
i { "Playing static + stream" }
audioPlayer.setState(STATIC_MIX)
})
findViewById<Button>(R.id.but3).setOnClickListener({
i { "Playing stream" }
audioPlayer.setState(SIGNAL)
})
findViewById<Button>(R.id.but4).setOnClickListener({
i { "Playing silence" }
audioPlayer.setState(QUIET)
})
}
override fun onResume() {
super.onResume()
audioPlayer.activate()
d { "done with activate()" }
}
override fun onPause() {
audioPlayer.deactivate()
super.onPause()
}
}
| 0 | Kotlin | 0 | 0 | cc7b3f634b4edd1a20176383decf173f493db130 | 1,760 | OhEuropa-Android | BSD 2-Clause with views sentence |
app/src/main/java/com/me/impression/base/BaseApiRemoteSource.kt | caiji200 | 347,794,891 | false | {"Gradle": 4, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 67, "XML": 99, "JSON": 6, "Java": 9} | package com.me.impression.base
import android.text.TextUtils
import com.google.gson.Gson
import com.me.impression.exception.ExceptionEngine
import com.me.impression.utils.L
import io.reactivex.Observable
import io.reactivex.ObservableSource
import io.reactivex.functions.Function
import okhttp3.MediaType
import okhttp3.RequestBody
import org.json.JSONObject
open class BaseApiRemoteSource
{
/**
* @description: public params
* @param:
* @return:
*/
fun publicParams(): Map<String, String> {
val params:MutableMap<String,String> = HashMap()
return params
}
fun checkParams(params: Map<String, Any>?): Boolean {
if (params == null) {
return false
}
L.d("http params:\n")
L.d("==================================================\n")
val keySet = params.keys
val keys = ArrayList(keySet)
keys.sort()
val urlParams = StringBuilder()
for (key in keys) {
if (!TextUtils.isEmpty(params[key].toString())) {
urlParams.append(key)
.append("=")
.append(params[key])
urlParams.append("&")
L.d("║ \"" + key + "\":\"" + params[key] + "\"")
}
}
var paramStr = ""
if(!TextUtils.isEmpty(urlParams)){
paramStr = urlParams.subSequence(0, urlParams.length - 1).toString()
} else {
L.d("║ \"")
L.d("║ \"")
L.d("║ \"")
}
L.d( "==================================================\n")
L.d("commit params str : $paramStr")
return true
}
fun checkParams(params: JSONObject):Boolean
{
if (params == null) {
return false
}
L.d("http params:\n")
L.d("==================================================\n")
val keyIter = params.keys()
val keys = ArrayList<String>()
while(keyIter.hasNext()){
keys.add(keyIter.next())
}
keys.sort()
val urlParams = StringBuilder()
for (key in keys) {
if (!TextUtils.isEmpty(params[key].toString())) {
urlParams.append(key)
.append("=")
.append(params[key])
urlParams.append("&")
L.d("║ \"" + key + "\":\"" + params[key] + "\"")
}
}
var paramStr = ""
if(!TextUtils.isEmpty(urlParams)){
paramStr = urlParams.subSequence(0, urlParams.length - 1).toString()
} else {
L.d("║ \"")
L.d("║ \"")
L.d("║ \"")
}
L.d("==================================================\n")
return true
}
fun convertToRequestBody(params:Map<String,Any>):RequestBody{
var body = Gson().toJson(params)
return RequestBody.create(MediaType.parse("application/json;charset=UTF-8"), body)
}
inner class HttpResponseErrorInterceptor<T> : Function<Throwable, ObservableSource<T>> {
@Throws(Exception::class)
override fun apply(throwable: Throwable): ObservableSource<T> {
L.d( "exception===>" + throwable.message)
val stack = Throwable().stackTrace
for (element in stack) {
L.d(" |----$element")
}
return Observable.error(ExceptionEngine.handleException(throwable))
}
}
}
| 0 | Kotlin | 0 | 0 | 98b0469ca540fc6249518d448152d3ec6b57590b | 3,486 | impression | MIT License |
plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/impl/arguments.kt | dansanduleac | 232,394,039 | false | null | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.groovy.lang.resolve.impl
import com.intellij.psi.PsiClassType
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMethod
import com.intellij.psi.PsiSubstitutor
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrSpreadArgument
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.GrMapType
import org.jetbrains.plugins.groovy.lang.psi.impl.GrTupleType
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
import org.jetbrains.plugins.groovy.lang.psi.util.isEffectivelyVarArgs
import org.jetbrains.plugins.groovy.lang.psi.util.isOptional
import org.jetbrains.plugins.groovy.lang.resolve.api.*
import java.util.*
fun GrCall.getArguments(): Arguments? {
val argumentList = argumentList ?: return null
return getArguments(argumentList.namedArguments, argumentList.expressionArguments, closureArguments, this)
}
private fun getArguments(namedArguments: Array<out GrNamedArgument>,
expressionArguments: Array<out GrExpression>,
closureArguments: Array<out GrClosableBlock>,
context: PsiElement): Arguments? {
val result = ArrayList<Argument>()
if (namedArguments.isNotEmpty()) {
result += LazyTypeArgument {
GrMapType.createFromNamedArgs(context, namedArguments)
}
}
if (!getExpressionArguments(expressionArguments, result)) {
return null
}
closureArguments.mapTo(result) {
ExpressionArgument(it)
}
return result
}
private fun getExpressionArguments(expressionArguments: Array<out GrExpression>, result: MutableList<Argument>): Boolean {
for (expression in expressionArguments) {
if (expression is GrSpreadArgument) {
val type = expression.argument.type as? GrTupleType ?: return false
type.componentTypes.mapTo(result) {
JustTypeArgument(it)
}
}
else {
result += ExpressionArgument(expression)
}
}
return true
}
fun getExpressionArguments(expressionArguments: Array<out GrExpression>): Arguments? {
val result = ArrayList<Argument>()
if (getExpressionArguments(expressionArguments, result)) {
return result
}
else {
return null
}
}
fun argumentMapping(method: PsiMethod, substitutor: PsiSubstitutor, arguments: Arguments, context: PsiElement): ArgumentMapping = when {
method.isEffectivelyVarArgs -> {
val invokedAsIs = run(fun(): Boolean {
// call foo(X[]) as is, i.e. with argument of type X[] (or subtype)
val parameters = method.parameterList.parameters
if (arguments.size != parameters.size) return false
val parameterType = parameterType(parameters.last().type, substitutor, true)
val lastArgApplicability = argumentApplicability(parameterType, arguments.last().runtimeType, context)
return lastArgApplicability == Applicability.applicable
})
if (invokedAsIs) {
PositionalArgumentMapping(method, arguments, context)
}
else {
VarargArgumentMapping(method, arguments, context)
}
}
arguments.isEmpty() -> {
val parameters = method.parameterList.parameters
val parameter = parameters.singleOrNull()
if (parameter != null && !parameter.isOptional && parameter.type is PsiClassType && !PsiUtil.isCompileStatic(context)) {
NullArgumentMapping(parameter)
}
else {
PositionalArgumentMapping(method, arguments, context)
}
}
else -> PositionalArgumentMapping(method, arguments, context)
}
| 1 | null | 1 | 1 | 9d972139413a00942fd4a0c58998ac8a2d80a493 | 3,931 | intellij-community | Apache License 2.0 |
intellij-plugin/Edu-Python/testSrc/com/jetbrains/edu/python/learning/checkio/PyCheckiOSettingsTest.kt | JetBrains | 43,696,115 | false | {"Kotlin": 5077727, "HTML": 3429210, "Java": 42994, "Python": 19649, "CSS": 12266, "JavaScript": 302, "Shell": 71} | package com.jetbrains.edu.python.learning.checkio
import com.jetbrains.edu.learning.EduSettingsServiceTestBase
import org.junit.Test
class PyCheckiOSettingsTest : EduSettingsServiceTestBase() {
@Test
fun `test serialization`() {
val settings = PyCheckiOSettings()
settings.loadStateAndCheck("""
<PyCheckiOSettings>
<CheckiOAccount>
<option name="tokenExpiresIn" value="1698710755" />
<option name="guest" value="false" />
<option name="uid" value="12345678" />
<option name="username" value="abcd" />
</CheckiOAccount>
</PyCheckiOSettings>
""")
}
}
| 7 | Kotlin | 47 | 144 | bfd82908fe7cee12b2ebd57076f9180a9b022694 | 638 | educational-plugin | Apache License 2.0 |
nav/editor/src/com/android/tools/idea/naveditor/property/ui/ArgumentCellRenderer.kt | JetBrains | 60,701,247 | false | null | /*
* Copyright (C) 2019 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.naveditor.property.ui
import com.android.tools.idea.common.model.NlComponent
import com.android.tools.idea.naveditor.model.argumentName
import com.android.tools.idea.naveditor.model.defaultValue
import com.android.tools.idea.naveditor.model.nullable
import com.android.tools.idea.naveditor.model.typeAttr
import icons.StudioIcons.NavEditor.Properties.ARGUMENT
import javax.swing.JList
class ArgumentCellRenderer : NavListCellRenderer(ARGUMENT) {
override fun customizeCellRenderer(list: JList<out NlComponent>, value: NlComponent?, index: Int, selected: Boolean, hasFocus: Boolean) {
super.customizeCellRenderer(list, value, index, selected, hasFocus)
val name = value?.argumentName ?: "<missing name>"
val type = value?.typeAttr ?: "<inferred type>"
val nullable = value?.nullable ?: false
val default = value?.defaultValue?.let { "(${it})" }
val title = "${name}: ${type}${if (nullable) "?" else ""} ${default ?: ""}"
append(title)
}
} | 5 | null | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 1,623 | android | Apache License 2.0 |
src/main/kotlin/com/github/vatbub/finance/manager/view/ImportView.kt | vatbub | 396,977,213 | false | null | /*-
* #%L
* Smart Charge
* %%
* Copyright (C) 2016 - 2020 <NAME>
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package com.github.vatbub.finance.manager.view
import com.github.vatbub.finance.manager.BackgroundScheduler
import com.github.vatbub.finance.manager.RunnableWithProgressUpdates
import com.github.vatbub.finance.manager.database.MemoryDataHolder
import com.github.vatbub.finance.manager.model.Account
import com.github.vatbub.finance.manager.model.BankTransaction
import com.github.vatbub.finance.manager.util.parallelForEach
import javafx.application.Platform
import javafx.beans.property.SimpleBooleanProperty
import javafx.collections.FXCollections
import javafx.fxml.FXML
import javafx.fxml.FXMLLoader
import javafx.scene.Parent
import javafx.scene.Scene
import javafx.scene.control.Button
import javafx.scene.control.ComboBox
import javafx.scene.control.Label
import javafx.scene.layout.GridPane
import javafx.scene.layout.Priority
import javafx.scene.layout.VBox
import javafx.stage.Stage
import javafx.util.StringConverter
import java.net.URL
import java.util.*
import kotlin.properties.Delegates
class ImportView {
companion object {
fun show(bankTransactions: List<BankTransaction>): ImportView {
val stage = Stage()
val fxmlLoader = FXMLLoader(ImportView::class.java.getResource("ImportView.fxml"), null)
val root = fxmlLoader.load<Parent>()
val importView = fxmlLoader.getController<ImportView>().apply {
transactionsToBeImported = bankTransactions
initTransactionTableView()
}
importView.stage = stage
val scene = Scene(root)
stage.title = "Finance manager: Import"
// val iconName = "icon.png"
// primaryStage.icons.add(Image(javaClass.getResourceAsStream(iconName)))
stage.minWidth = root.minWidth(0.0) + 70
stage.minHeight = root.minHeight(0.0) + 70
stage.scene = scene
stage.show()
return importView
}
}
@FXML
private lateinit var resources: ResourceBundle
@FXML
private lateinit var location: URL
@FXML
private lateinit var rootPane: GridPane
@FXML
private lateinit var vboxWithTransactionTable: VBox
@FXML
private lateinit var comboBoxDestinationAccount: ComboBox<Account>
@FXML
private lateinit var buttonImport: Button
@FXML
private lateinit var labelWaitForBackgroundTasks: Label
private var transactionsToBeImported: List<BankTransaction> by Delegates.observable(listOf()) { _, _, newValue ->
deselectDuplicatesAndIncompleteTransactions(newValue)
}
private val transactionTableView by lazy {
BankTransactionTableView(FXCollections.observableArrayList(transactionsToBeImported)).also {
it.isEditable = true
}
}
private val duplicateDetectionInProgress = SimpleBooleanProperty(false)
private lateinit var stage: Stage
@FXML
fun initialize() {
MemoryDataHolder.currentInstance.addListener { _, _, newHolder ->
memoryDataHolderChanged(newHolder)
}
buttonImport.disableProperty().bind(duplicateDetectionInProgress)
labelWaitForBackgroundTasks.visibleProperty().bind(duplicateDetectionInProgress)
comboBoxDestinationAccount.converter = object : StringConverter<Account>() {
override fun toString(`object`: Account?): String = `object`?.name?.value ?: "<null>"
override fun fromString(string: String?): Account {
throw NotImplementedError()
}
}
memoryDataHolderChanged()
}
private fun initTransactionTableView() {
vboxWithTransactionTable.children.add(transactionTableView)
VBox.setVgrow(transactionTableView, Priority.ALWAYS)
}
@FXML
fun buttonEditAccountsOnAction() {
AccountEditView.show()
}
@FXML
fun buttonImportOnAction() {
val selectedAccount = comboBoxDestinationAccount.selectionModel.selectedItem
?: throw IllegalStateException("Please select an account to import to")
BackgroundScheduler.singleThreaded.enqueue(message = "Importing data...") {
selectedAccount.import(transactionsToBeImported)
}
stage.hide()
}
private fun memoryDataHolderChanged(memoryDataHolder: MemoryDataHolder = MemoryDataHolder.currentInstance.value) {
val currentIndex = comboBoxDestinationAccount.selectionModel.selectedIndex.let {
if (it < 0) 0 else it
}
comboBoxDestinationAccount.items = memoryDataHolder.accountList
comboBoxDestinationAccount.selectionModel.select(currentIndex)
}
private fun deselectDuplicatesAndIncompleteTransactions(transactionsToImport: List<BankTransaction>) {
val allTransactions = MemoryDataHolder.currentInstance.value
.accountList
.map { it.transactions }
.flatten()
BackgroundScheduler.multiThreaded.enqueue(
RunnableWithProgressUpdates<Unit>(
taskMessage = "Finding duplicates...",
totalSteps = allTransactions.size.toLong()
) {
duplicateDetectionInProgress.value = true
transactionsToImport.parallelForEach() { transactionToEvaluate ->
if (transactionToEvaluate.isIncomplete()) {
Platform.runLater { transactionToEvaluate.selected.value = false }
return@parallelForEach
}
if (allTransactions.isEmpty()) return@parallelForEach
val maxSimilarity = allTransactions
.filter { transactionToEvaluate.bookingDate.value == it.bookingDate.value }
.filter { transactionToEvaluate.valutaDate.value == it.valutaDate.value }
.maxOf { it similarityTo transactionToEvaluate }
stepDone()
if (maxSimilarity < 0.999) return@parallelForEach
Platform.runLater { transactionToEvaluate.selected.value = false }
}
duplicateDetectionInProgress.value = false
})
}
private fun BankTransaction.isIncomplete(): Boolean {
return bookingDate.value == null ||
valutaDate.value == null
}
}
| 0 | Kotlin | 0 | 0 | 653f687fab36b710ceee87c9299f1be55839e6d2 | 7,005 | finance-manager | Apache License 2.0 |
nugu-interface/src/main/java/com/skt/nugu/sdk/core/interfaces/message/MessageObserver.kt | junheelee070712 | 243,897,227 | true | {"Gradle": 9, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 8, "Batchfile": 1, "Markdown": 1, "Kotlin": 249, "Proguard": 5, "Java": 5, "XML": 57, "JSON": 11, "Protocol Buffer": 3} | /**
* Copyright (c) 2019 SK Telecom Co., Ltd. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.skt.nugu.sdk.core.interfaces.message
/**
* The observer to be called when receive an message
*/
interface MessageObserver {
/** Called when receive an message
* @param message the received message
*/
fun receive(message: String)
} | 0 | null | 10 | 0 | 770180239d10fe0f147f86514fe4431b065c4bb5 | 892 | nugu-android | Apache License 2.0 |
jobcan-client/src/main/java/x7c1/cyan/jobcan/actions/recorder/Group.kt | x7c1 | 142,662,621 | false | null | package x7c1.cyan.jobcan.actions.recorder
data class Group(
val id: GroupId,
val label: String
)
| 1 | Kotlin | 0 | 0 | e979497c58428be1bfdf0f534ef8198b3308cda7 | 106 | Cyan | MIT License |
src/test/kotlin/de/flapdoodle/swing/playground/PlaygroundApp.kt | flapdoodle-oss | 749,867,865 | false | {"Batchfile": 1, "Shell": 4, "Maven POM": 1, "Text": 2, "Ignore List": 1, "Groovy": 1, "Markdown": 1, "INI": 1, "Java": 162, "Kotlin": 23} | package de.flapdoodle.swing.playground
import de.flapdoodle.swing.ComponentTreeModel
import de.flapdoodle.swing.events.MouseListenerAdapter
import de.flapdoodle.swing.events.MouseMotionListenerAdapter
import java.awt.*
import java.awt.event.MouseEvent
import java.awt.geom.AffineTransform
import java.util.concurrent.atomic.AtomicReference
import javax.swing.*
import javax.swing.plaf.LayerUI
object PlaygroundApp {
@JvmStatic
fun main(vararg args: String) {
if (false) {
val e: EventQueue = EventQueue()
Toolkit.getDefaultToolkit().addAWTEventListener({ event ->
// println("event --> $event")
if (event is MouseEvent) {
// event.consume()
// println("--> "+event.source)
if (event.source is JButton) {
event.consume()
}
}
}, AWTEvent.MOUSE_EVENT_MASK)
}
val frame = JFrame("Playground")
frame.defaultCloseOperation = JFrame.EXIT_ON_CLOSE
frame.setSize(800, 600)
frame.contentPane = playground()
if (false) frame.pack()
frame.isVisible = true
}
private fun playground(): JComponent {
val ret = JPanel()
ret.layout = BoxLayout(ret, BoxLayout.Y_AXIS)
val button = JButton("show tree")
val nodeEditor = nodeEditor()
button.addActionListener { action ->
ComponentTreeModel.showTree(nodeEditor)
}
ret.add(button)
ret.add(nodeEditor)
return ret
}
private fun nodeEditor(): JComponent {
val subwindow = subWindow().also { win ->
win.preferredSize = Dimension(100, 100)
win.setBounds(350, 130, 100, 100)
}
val content = JPanel().also {
it.layout = null
//it.layout = DragLayout()
// it.layout = AbsoluteLayout()
it.addMouseListener(MouseListenerAdapter(
pressed = { event ->
println("pressed in panel")
// event.consume()
}
))
// it.bounds = Rectangle(0,0,200,200)
it.preferredSize = Dimension(800, 600)
it.add(subwindow)
it.add(JButton("A").also { button ->
//button.minimumSize = Dimension(300, 200)
button.preferredSize = Dimension(300, 200)
button.setBounds(90, 10, 200, 300)
button.addMouseListener(MouseListenerAdapter(
pressed = { event ->
println("pressed")
// event.consume()
}
))
button.addActionListener { println("button pressed") }
})
it.add(JButton("B").also { button ->
//button.minimumSize = Dimension(300, 200)
button.preferredSize = Dimension(300, 200)
button.setBounds(-50, 30, 100, 100)
})
}
val ui=object : LayerUI<JPanel>() {
override fun installUI(c: JComponent?) {
super.installUI(c)
// enable mouse motion events for the layer's subcomponents
(c as JLayer<*>).layerEventMask = AWTEvent.MOUSE_EVENT_MASK or AWTEvent.MOUSE_MOTION_EVENT_MASK
}
override fun uninstallUI(c: JComponent?) {
(c as JLayer<*>).layerEventMask = 0
super.uninstallUI(c)
}
override fun eventDispatched(e: AWTEvent, l: JLayer<out JPanel>) {
if (e.source == subwindow && e is MouseEvent) {
println("subwindow --> "+e)
// e.consume()
}
super.eventDispatched(e, l)
}
}
val layer = JLayer<JPanel>(content, ui);
// val glassPane =
val ret = JScrollPane(layer)
return ret
}
private fun subWindow(): JComponent {
val ret = object : JPanel() {
override fun paintComponent(g: Graphics?) {
if (g is Graphics2D) {
// g.scale(0.9, 0.9)
val at = AffineTransform()
at.scale(0.9, 0.9)
g.transform(at)
}
super.paintComponent(g)
}
override fun update(g: Graphics?) {
if (g is Graphics2D) {
// g.scale(0.9, 0.9)
val at = AffineTransform()
at.scale(0.9, 0.9)
g.transform(at)
}
super.update(g)
}
}
ret.insets.set(10, 10, 10, 10)
ret.background = Color.RED
ret.isOpaque = true
ret.add(JButton("move me").also {
it.insets.set(10, 10, 10, 10)
})
val lock = AtomicReference<StartDrag>()
ret.addMouseListener(MouseListenerAdapter(
pressed = { event ->
println("start "+event.point)
lock.set(StartDrag(ret.location, event.locationOnScreen))
},
released = { event ->
println("released "+event.point)
lock.getAndSet(null)
}
))
ret.addMouseMotionListener(MouseMotionListenerAdapter(
moved = { event ->
// if (lock.get() != null) {
//// println("moved " + (event.point - lock.get()))
// }
},
dragged = { event ->
val oldPosition = lock.get()
if (oldPosition != null) {
// println("dragged " + (event.point - lock.get()))
val delta = event.locationOnScreen - oldPosition.mouse
val newLocation = oldPosition.pos + delta
ret.setLocation(newLocation.x, newLocation.y)
}
}
))
return ret
}
}
data class StartDrag(val pos: Point, val mouse: Point)
private operator fun Point.plus(delta: Dimension): Point {
return Point(x + delta.width, y + delta.height)
}
private operator fun Point.minus(other: Point): Dimension {
return Dimension(this.x - other.x, this.y - other.y)
}
| 0 | Java | 0 | 0 | 3c128843335213d1a896db6a23683ad57341ab96 | 5,396 | de.flapdoodle.swing | Apache License 2.0 |
common/src/main/java/com/ruzhan/lion/glide/ImageLoader.kt | ckrgithub | 150,102,569 | false | null | package com.ruzhan.lion.glide
/**
* Created by ruzhan123 on 2018/7/4.
*/
class ImageLoader {
companion object {
private var INSTANCE: IImageLoader? = null
@JvmStatic
fun get(): IImageLoader {
if (INSTANCE == null) {
synchronized(ImageLoader::class.java) {
if (INSTANCE == null) {
INSTANCE = GlideImpl()
}
}
}
return this.INSTANCE!!
}
}
} | 1 | null | 1 | 1 | e73bcaf999e3de04905e781004f02ede6d85eaea | 516 | Lion | Apache License 2.0 |
src/main/kotlin/currentLegislatorsCmds.kt | sam-hoodie | 534,831,633 | false | null | import kotlin.collections.HashMap
fun interpretCurrentCommands(command: String, data: List<Person>) {
val cmdParts = command.split(' ')[1].split('.')
val stateToFind = stateToAbbreviation(cmdParts[3].lowercase())
var legislators = getLegislators(data, stateToFind, command)
if (legislators.isNotEmpty()) {
legislators = legislators.toSet().toList() as ArrayList<List<String>>
if (cmdParts[0] != "house") {
for (i in legislators.indices) {
when (cmdParts[0]) {
"senate" -> println(" " + legislators[i][0])
"congress" -> println(" " + legislators[i][0] + " (" + legislators[i][1] + ")")
}
}
return
} else if (cmdParts[0] == "house") {
val sorted = sortByDistrict(legislators)
for (i in sorted.indices) {
val district = sorted[i][1]
println(" " + sorted[i][0] + " (District " + district + ")")
}
return
}
}
printAutocorrect(command)
}
fun getLegislators(data: List<Person>, stateToFind: String, command: String): List<List<String>> {
val cmdParts = command.split(' ')[1].split('.')
val legislators = arrayListOf<List<String>>()
for (i in data.indices) {
val terms = data[i].terms
if (terms[terms.size - 1].state == stateToFind) {
if (cmdParts[0] == "congress") {
if (terms[terms.size - 1].type == "rep") {
val partToAdd = listOf((data[i].name.first + " " + data[i].name.last), "House")
legislators.add(partToAdd)
} else {
val partToAdd = listOf((data[i].name.first + " " + data[i].name.last), "Senate")
legislators.add(partToAdd)
}
}
if (cmdParts[0] == "senate") {
if (terms[terms.size - 1].type == "sen") {
val partToAdd = listOf((data[i].name.first + " " + data[i].name.last))
legislators.add(partToAdd)
}
}
if (cmdParts[0] == "house") {
if (terms[terms.size - 1].type == "rep") {
val partToAdd = listOf(
(data[i].name.first + " " + data[i].name.last),
terms[terms.size - 1].district.toString()
)
legislators.add(partToAdd)
}
}
}
}
return legislators
}
fun sortByDistrict(input: List<List<String>>): List<List<String>> {
var district = 1
val result = arrayListOf<List<String>>()
while (result.size != input.size) {
for (i in input.indices) {
if (input[i][1].toInt() == district) {
result.add(input[i])
}
}
district++
}
return result
}
fun stateToAbbreviation(state: String): String {
val states = HashMap<String, String>()
states["alabama"] = "AL"
states["alaska"] = "AK"
states["alberta"] = "AB"
states["american_samoa"] = "AS"
states["arizona"] = "AZ"
states["arkansas"] = "AR"
states["british_columbia"] = "BC"
states["california"] = "CA"
states["colorado"] = "CO"
states["connecticut"] = "CT"
states["delaware"] = "DE"
states["district_of_columbia"] = "DC"
states["florida"] = "FL"
states["georgia"] = "GA"
states["guam"] = "GU"
states["hawaii"] = "HI"
states["idaho"] = "ID"
states["illinois"] = "IL"
states["indiana"] = "IN"
states["iowa"] = "IA"
states["kansas"] = "KS"
states["kentucky"] = "KY"
states["louisiana"] = "LA"
states["maine"] = "ME"
states["manitoba"] = "MB"
states["maryland"] = "MD"
states["massachusetts"] = "MA"
states["michigan"] = "MI"
states["minnesota"] = "MN"
states["mississippi"] = "MS"
states["missouri"] = "MO"
states["montana"] = "MT"
states["nebraska"] = "NE"
states["nevada"] = "NV"
states["new_brunswick"] = "NB"
states["new_hampshire"] = "NH"
states["new_jersey"] = "NJ"
states["new_mexico"] = "NM"
states["new_york"] = "NY"
states["newfoundland"] = "NF"
states["north_carolina"] = "NC"
states["north_dakota"] = "ND"
states["northwest_territories"] = "NT"
states["nova_scotia"] = "NS"
states["nunavut"] = "NU"
states["ohio"] = "OH"
states["oklahoma"] = "OK"
states["ontario"] = "ON"
states["oregon"] = "OR"
states["pennsylvania"] = "PA"
states["puerto_rico"] = "PR"
states["quebec"] = "QC"
states["rhode_island"] = "RI"
states["saskatchewan"] = "SK"
states["south_carolina"] = "SC"
states["south_dakota"] = "SD"
states["tennessee"] = "TN"
states["texas"] = "TX"
states["utah"] = "UT"
states["vermont"] = "VT"
states["virgin_islands"] = "VI"
states["virginia"] = "VA"
states["washington"] = "WA"
states["west_virginia"] = "WV"
states["wisconsin"] = "WI"
states["wyoming"] = "WY"
states["yukon_territory"] = "YT"
return states[state].toString()
} | 0 | Kotlin | 0 | 0 | 9efea9f9eec55c1e61ac1cb11d3e3460f825994b | 5,148 | congress-challenge | Apache License 2.0 |
linkt/src/androidTest/java/org/linkt/DeepLinkLoaderTest.kt | jeziellago | 335,140,648 | false | null | /* MIT License
*
* Copyright (c) 2021 Jeziel Lago
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package org.linkt
import android.content.Intent
import android.net.Uri
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class DeepLinkLoaderTest {
@Test
fun shouldMatchesUris() {
val expectedUri = Uri.parse("test://test/{id}/b/{name}/c")
deepLinkOf("test://tester/{id}/b/{name}/c") { _, _ -> Intent() }
deepLinkOf("test://test/{id}/b/{name}/c") { _, _ -> Intent() }
deepLinkOf("test://test/{id}/b/c") { _, _ -> Intent() }
val result = DeepLinkLoader.matches(
Uri.parse("test://test/123/b/jeziel/c?value=myValue")
)
assertEquals(expectedUri, result)
}
@Test
fun shouldNotMatchWithDifferentAuthority() {
deepLinkOf("test://tester/{id}/b/{name}/c") { _, _ -> Intent() }
val result = DeepLinkLoader.matches(Uri.parse("test://test/123/b/jeziel/c"))
assertNull(result)
}
@Test
fun shouldMatchesWithoutParams() {
val expected = Uri.parse("test://test/a/b/c")
deepLinkOf("test://tester/a/b/c") { _, _ -> Intent() }
deepLinkOf("test://test/a/b/c") { _, _ -> Intent() }
deepLinkOf("test://test/b/c") { _, _ -> Intent() }
val result = DeepLinkLoader.matches(Uri.parse("test://test/a/b/c"))
assertEquals(expected, result)
}
@Test
fun shouldParseParamsWhenReceivedUriContainsData() {
val r = DeepLinkLoader.getParamsFrom(
Uri.parse("test://test/{id}/b/{name}/c"),
Uri.parse("test://test/123/b/jeziel/c?value1=myValue1&value2=MyValue2")
)
val params = mutableMapOf(
"id" to "123",
"name" to "jeziel",
"value1" to "myValue1",
"value2" to "MyValue2",
)
assertEquals(params, r)
}
@Test
fun shouldParseParamsWithUriWithoutQuery() {
val r = DeepLinkLoader.getParamsFrom(
Uri.parse("test://test/{id}/b/{name}/c"),
Uri.parse("test://test/123/b/jeziel/c")
)
val params = mutableMapOf(
"id" to "123",
"name" to "jeziel"
)
assertEquals(params, r)
}
@After
fun tearDown() {
DeepLinkLoader.clear()
}
} | 0 | Kotlin | 2 | 99 | 9b18cded5de5630183ef059fa7f67977592dd301 | 3,511 | Linkt | MIT License |
lib_base/src/main/java/com/example/lib_base/utils/time/GetLastWeekDateUtils.kt | TReturn | 399,864,608 | false | null | package com.example.lib_base.utils.time
import android.annotation.SuppressLint
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.ArrayList
/**
* @CreateDate: 2022/7/1 15:16
* @Author: 青柠
* @Description: 获取过去一周日期
*/
object GetLastWeekDateUtils {
fun getWeek(dateTime: String): String {
var week = ""
val sdf = SimpleDateFormat("yyyy-MM-dd")
try {
val date: Date = sdf.parse(dateTime)
val dateFm = SimpleDateFormat("EEEE")
week = dateFm.format(date)
week = week.replace("星期".toRegex(), "周")
} catch (e: ParseException) {
e.printStackTrace()
}
return week
}
/**
* 获取过去7天内的日期数组
* @param intervals intervals天内
* @return 日期数组
*/
fun getDays(intervals: Int): ArrayList<String> {
val pastDaysList: ArrayList<String> = ArrayList()
for (i in intervals - 1 downTo 0) {
pastDaysList.add(getPastDate(i))
}
return pastDaysList
}
/**
* 获取过去第几天的日期
* @param past
* @return
*/
@SuppressLint("SimpleDateFormat")
private fun getPastDate(past: Int): String {
val calendar: Calendar = Calendar.getInstance()
calendar.set(Calendar.DAY_OF_YEAR, calendar.get(Calendar.DAY_OF_YEAR) - past)
val today: Date = calendar.time
val format = SimpleDateFormat("MM/dd")
return format.format(today)
}
} | 0 | Kotlin | 1 | 1 | 41099aa4de890edb7afdd0327080a576e5386862 | 1,522 | BaseApp | Apache License 2.0 |
aTalk/src/main/java/net/java/sip/communicator/service/resources/SkinPack.kt | cmeng-git | 704,328,019 | false | {"Kotlin": 14462775, "Java": 2824517, "C": 275021, "Shell": 49203, "Makefile": 28273, "C++": 13642, "HTML": 7793, "CSS": 3127, "JavaScript": 2758, "AIDL": 375} | /*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* 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 net.java.sip.communicator.service.resources
/**
* Default Skin Pack interface.
*
* @author Adam Netocny
*/
interface SkinPack : ResourcePack {
/**
* Returns a `Map`, containing all [key, value] pairs for image
* resource pack.
*
* @return a `Map`, containing all [key, value] pairs for image
* resource pack.
*/
fun getImageResources(): Map<String?, String?>?
/**
* Returns a `Map`, containing all [key, value] pairs for style
* resource pack.
*
* @return a `Map`, containing all [key, value] pairs for style
* resource pack.
*/
fun getStyleResources(): Map<String?, String?>?
/**
* Returns a `Map`, containing all [key, value] pairs for color
* resource pack.
*
* @return a `Map`, containing all [key, value] pairs for color
* resource pack.
*/
fun getColorResources(): Map<String?, String?>?
/**
* Returns a `Map`, containing all [key, value] pairs for settings
* resource pack.
*
* @return a `Map`, containing all [key, value] pairs for settings
* resource pack.
*/
fun getSettingsResources(): Map<String?, String?>?
companion object {
/**
* Default resource name.
*/
const val RESOURCE_NAME_DEFAULT_VALUE = "SkinPack"
}
} | 0 | Kotlin | 0 | 0 | 393d94a8b14913b718800238838801ce6cdf5a1f | 1,966 | atalk-hmos_kotlin | Apache License 2.0 |
app/src/main/java/hosseinzafari/github/codequestion/ui/main/fragment/FactoryFragment.kt | HosseinZafari | 282,155,541 | false | null | package hosseinzafari.github.codequestion.ui.ui.main.fragment
import hosseinzafari.github.codequestion.ui.main.fragment.*
import hosseinzafari.github.framework.core.ui.fragment.GFragment
/*
@created in 26/06/2020 - 10:09 AM
@project Code Question
@author <NAME>
@email <EMAIL>
*/
object FactoryFragment {
const val CART_FRAGMENT: Byte = 1
const val HOME_FRAGMENT: Byte = 2
const val PROFILE_FRAGMENT: Byte = 3
const val CODE_FRAGMENT: Byte = 4
const val QUESTION_FRAGMENT: Byte = 5
const val LOGIN_FRAGMENT: Byte = 6
const val SIGNUP_FRAGMENT: Byte = 7
const val RULES_FRAGMENT: Byte = 8
const val ASK_FRAGMENT: Byte = 9
const val ANSWER_FRAGMENT: Byte = 10
const val DETAIL_CODE_FRAGMENT: Byte = 11
const val ADD_CODE_FRAGMENT: Byte = 12
const val ABOUT_FRAGMENT: Byte = 13
const val ACCOUNT_FRAGMENT: Byte = 14
const val DETAIL_COURSE_FRAGMENT: Byte = 15
const val BOOKMARK_FRAGMENT: Byte = 16
const val ALL_COURSE_FRAGMNET: Byte = 17
const val ADMIN_ANSWER_FRAGMENT: Byte = 18
const val PENDING_FRAGMENT: Byte = 19
const val PENDING_LIST_FRAGMENT: Byte = 20
fun getFragment(type: Byte): GFragment =
when (type) {
CART_FRAGMENT -> CartFragment()
HOME_FRAGMENT -> HomeFragment()
PROFILE_FRAGMENT -> ProfileFragment()
CODE_FRAGMENT -> CodeFragment()
QUESTION_FRAGMENT -> QuestionFragment()
LOGIN_FRAGMENT -> LoginFragment()
SIGNUP_FRAGMENT -> SignupFragment()
RULES_FRAGMENT -> RulesFragment()
ASK_FRAGMENT -> AskFragment()
ANSWER_FRAGMENT -> AnswerFragment()
DETAIL_CODE_FRAGMENT -> DetailCodeFragment()
ADD_CODE_FRAGMENT -> AddCodeFragment()
ABOUT_FRAGMENT -> AboutFragment()
ACCOUNT_FRAGMENT -> AccountFragment()
DETAIL_COURSE_FRAGMENT-> DetailCourseFragment()
BOOKMARK_FRAGMENT -> BookmarkFragment()
ALL_COURSE_FRAGMNET -> AllCourseFragment()
ADMIN_ANSWER_FRAGMENT -> AdminAnswerFragment()
PENDING_FRAGMENT -> PendingFragment()
PENDING_LIST_FRAGMENT -> PendingCodeFragment()
else -> throw IllegalArgumentException("Not Found Type Fragment For You")
}
} | 0 | null | 0 | 1 | 7eddd28c2cd2ce0fd5b3b257097fdc3b86c251c1 | 2,320 | CodeQuestion | Apache License 2.0 |
luak/src/jvmMain/kotlin/org/luaj/vm2/script/LuaScriptEngineFactory.kt | korlibs | 595,720,892 | false | null | /*******************************************************************************
* Copyright (c) 2008 LuaJ. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.luaj.vm2.script
import javax.script.ScriptEngine
import javax.script.ScriptEngineFactory
/**
* Jsr 223 scripting engine factory.
*
* Exposes metadata to support the lua language, and constructs
* instances of LuaScriptEngine to handl lua scripts.
*/
class LuaScriptEngineFactory : ScriptEngineFactory {
override fun getEngineName(): String = scriptEngine.get(ScriptEngine.ENGINE).toString()
override fun getEngineVersion(): String = scriptEngine.get(ScriptEngine.ENGINE_VERSION).toString()
override fun getExtensions(): List<String> = EXTENSIONS
override fun getMimeTypes(): List<String> = MIMETYPES
override fun getNames(): List<String> = NAMES
override fun getLanguageName(): String = scriptEngine.get(ScriptEngine.LANGUAGE).toString()
override fun getLanguageVersion(): String = scriptEngine.get(ScriptEngine.LANGUAGE_VERSION).toString()
override fun getParameter(key: String): Any = scriptEngine.get(key).toString()
override fun getMethodCallSyntax(obj: String, m: String, vararg args: String): String {
val sb = StringBuffer()
sb.append("$obj:$m(")
val len = args.size
for (i in 0 until len) {
if (i > 0) {
sb.append(',')
}
sb.append(args[i])
}
sb.append(")")
return sb.toString()
}
override fun getOutputStatement(toDisplay: String): String = "print($toDisplay)"
override fun getProgram(vararg statements: String): String {
val sb = StringBuffer()
val len = statements.size
for (i in 0 until len) {
if (i > 0) {
sb.append('\n')
}
sb.append(statements[i])
}
return sb.toString()
}
override fun getScriptEngine(): ScriptEngine = LuaScriptEngine()
companion object {
private val EXTENSIONS = listOf("lua", ".lua")
private val MIMETYPES = listOf("text/lua", "application/lua")
private val NAMES = listOf("lua", "luaj")
}
}
| 2 | Kotlin | 5 | 9 | c3257906b473bb1cd2b2aa12e0c045b4df68851a | 3,246 | korge-luak | MIT License |
luak/src/jvmMain/kotlin/org/luaj/vm2/script/LuaScriptEngineFactory.kt | korlibs | 595,720,892 | false | null | /*******************************************************************************
* Copyright (c) 2008 LuaJ. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.luaj.vm2.script
import javax.script.ScriptEngine
import javax.script.ScriptEngineFactory
/**
* Jsr 223 scripting engine factory.
*
* Exposes metadata to support the lua language, and constructs
* instances of LuaScriptEngine to handl lua scripts.
*/
class LuaScriptEngineFactory : ScriptEngineFactory {
override fun getEngineName(): String = scriptEngine.get(ScriptEngine.ENGINE).toString()
override fun getEngineVersion(): String = scriptEngine.get(ScriptEngine.ENGINE_VERSION).toString()
override fun getExtensions(): List<String> = EXTENSIONS
override fun getMimeTypes(): List<String> = MIMETYPES
override fun getNames(): List<String> = NAMES
override fun getLanguageName(): String = scriptEngine.get(ScriptEngine.LANGUAGE).toString()
override fun getLanguageVersion(): String = scriptEngine.get(ScriptEngine.LANGUAGE_VERSION).toString()
override fun getParameter(key: String): Any = scriptEngine.get(key).toString()
override fun getMethodCallSyntax(obj: String, m: String, vararg args: String): String {
val sb = StringBuffer()
sb.append("$obj:$m(")
val len = args.size
for (i in 0 until len) {
if (i > 0) {
sb.append(',')
}
sb.append(args[i])
}
sb.append(")")
return sb.toString()
}
override fun getOutputStatement(toDisplay: String): String = "print($toDisplay)"
override fun getProgram(vararg statements: String): String {
val sb = StringBuffer()
val len = statements.size
for (i in 0 until len) {
if (i > 0) {
sb.append('\n')
}
sb.append(statements[i])
}
return sb.toString()
}
override fun getScriptEngine(): ScriptEngine = LuaScriptEngine()
companion object {
private val EXTENSIONS = listOf("lua", ".lua")
private val MIMETYPES = listOf("text/lua", "application/lua")
private val NAMES = listOf("lua", "luaj")
}
}
| 2 | Kotlin | 5 | 9 | c3257906b473bb1cd2b2aa12e0c045b4df68851a | 3,246 | korge-luak | MIT License |
android-solitaire/app/src/main/java/in/thekev/solitaire/MenuActivity.kt | TheKevJames | 108,588,864 | false | {"Kotlin": 105574, "Erlang": 65774, "C": 64660, "Ruby": 61667, "Python": 48980, "Makefile": 9153, "Dockerfile": 7614, "Rust": 4387, "HCL": 4304, "Shell": 4123, "Nim": 1763, "Java": 885, "C++": 623, "Haskell": 335, "Racket": 299, "Go": 215, "HTML": 172} | package `in`.thekev.solitaire
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import com.google.accompanist.appcompattheme.AppCompatTheme
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class MenuActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
AppCompatTheme {
NavGraph()
}
}
}
}
| 0 | Kotlin | 3 | 6 | efb8ef2a04dde7acb0686fd436ae4ee614565013 | 521 | experiments | MIT License |
solar/src/main/java/com/chiksmedina/solar/bold/facesemotionsstickers/StickerSmileSquare.kt | CMFerrer | 689,442,321 | false | {"Kotlin": 36591890} | package com.chiksmedina.solar.bold.facesemotionsstickers
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd
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 com.chiksmedina.solar.bold.FacesEmotionsStickersGroup
val FacesEmotionsStickersGroup.StickerSmileSquare: ImageVector
get() {
if (_stickerSmileSquare != null) {
return _stickerSmileSquare!!
}
_stickerSmileSquare = Builder(
name = "StickerSmileSquare", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f
).apply {
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(16.5f, 21.8389f)
curveTo(16.4873f, 21.8417f, 16.4745f, 21.8444f, 16.4617f, 21.8472f)
lineTo(16.4582f, 21.8479f)
curveTo(16.4424f, 21.8512f, 16.4266f, 21.8545f, 16.4107f, 21.8578f)
lineTo(16.4092f, 21.8581f)
curveTo(16.4256f, 21.8548f, 16.4419f, 21.8514f, 16.4582f, 21.8479f)
curveTo(16.4722f, 21.8449f, 16.4861f, 21.8419f, 16.5f, 21.8389f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero
) {
moveTo(22.0f, 15.0f)
curveTo(21.4162f, 15.0f, 20.9239f, 15.0f, 20.5f, 15.0076f)
curveTo(19.5724f, 15.0241f, 18.9718f, 15.0768f, 18.4549f, 15.2447f)
curveTo(16.9327f, 15.7393f, 15.7393f, 16.9327f, 15.2447f, 18.4549f)
curveTo(15.0768f, 18.9718f, 15.0241f, 19.5724f, 15.0076f, 20.5f)
curveTo(15.0f, 20.9239f, 15.0f, 21.4162f, 15.0f, 22.0f)
curveTo(15.4827f, 22.0f, 15.954f, 21.9511f, 16.4092f, 21.8581f)
lineTo(16.4107f, 21.8578f)
lineTo(16.4582f, 21.8479f)
lineTo(16.4617f, 21.8472f)
lineTo(16.5f, 21.8389f)
curveTo(19.162f, 21.2577f, 21.2577f, 19.162f, 21.8389f, 16.5f)
curveTo(21.9444f, 16.0168f, 22.0f, 15.5149f, 22.0f, 15.0f)
close()
}
path(
fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = EvenOdd
) {
moveTo(2.0f, 12.0f)
curveTo(2.0f, 16.714f, 2.0f, 19.0711f, 3.4645f, 20.5355f)
curveTo(4.9289f, 22.0f, 7.286f, 22.0f, 12.0f, 22.0f)
horizontalLineTo(13.5f)
lineTo(13.4999f, 21.7409f)
curveTo(13.499f, 20.1325f, 13.4984f, 18.9754f, 13.8181f, 17.9914f)
curveTo(13.8873f, 17.7786f, 13.9669f, 17.5708f, 14.0565f, 17.3684f)
curveTo(13.4157f, 17.615f, 12.723f, 17.75f, 12.0f, 17.75f)
curveTo(10.7151f, 17.75f, 9.5259f, 17.3234f, 8.5534f, 16.6026f)
curveTo(8.2207f, 16.3559f, 8.1509f, 15.8862f, 8.3975f, 15.5534f)
curveTo(8.6442f, 15.2207f, 9.1139f, 15.1509f, 9.4467f, 15.3975f)
curveTo(10.175f, 15.9374f, 11.0541f, 16.25f, 12.0f, 16.25f)
curveTo(12.9459f, 16.25f, 13.8251f, 15.9374f, 14.5534f, 15.3975f)
curveTo(14.8179f, 15.2015f, 15.1688f, 15.2053f, 15.4255f, 15.3822f)
curveTo(16.1372f, 14.6772f, 17.012f, 14.1364f, 17.9914f, 13.8181f)
curveTo(18.9754f, 13.4984f, 20.1325f, 13.499f, 21.7409f, 13.4999f)
lineTo(22.0f, 13.5f)
verticalLineTo(12.0f)
curveTo(22.0f, 7.286f, 22.0f, 4.9289f, 20.5355f, 3.4645f)
curveTo(19.0711f, 2.0f, 16.714f, 2.0f, 12.0f, 2.0f)
curveTo(7.286f, 2.0f, 4.9289f, 2.0f, 3.4645f, 3.4645f)
curveTo(2.0f, 4.9289f, 2.0f, 7.286f, 2.0f, 12.0f)
close()
moveTo(15.0f, 12.0f)
curveTo(15.5523f, 12.0f, 16.0f, 11.3284f, 16.0f, 10.5f)
curveTo(16.0f, 9.6716f, 15.5523f, 9.0f, 15.0f, 9.0f)
curveTo(14.4477f, 9.0f, 14.0f, 9.6716f, 14.0f, 10.5f)
curveTo(14.0f, 11.3284f, 14.4477f, 12.0f, 15.0f, 12.0f)
close()
moveTo(9.0f, 12.0f)
curveTo(9.5523f, 12.0f, 10.0f, 11.3284f, 10.0f, 10.5f)
curveTo(10.0f, 9.6716f, 9.5523f, 9.0f, 9.0f, 9.0f)
curveTo(8.4477f, 9.0f, 8.0f, 9.6716f, 8.0f, 10.5f)
curveTo(8.0f, 11.3284f, 8.4477f, 12.0f, 9.0f, 12.0f)
close()
}
}
.build()
return _stickerSmileSquare!!
}
private var _stickerSmileSquare: ImageVector? = null
| 0 | Kotlin | 0 | 0 | 3414a20650d644afac2581ad87a8525971222678 | 5,521 | SolarIconSetAndroid | MIT License |
shared/src/commonMain/kotlin/composables/screens/history/HistoryScreen.kt | SergStas | 697,631,567 | false | {"Kotlin": 55889, "Swift": 592, "Shell": 228} | package composables.screens.history
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import cafe.adriel.voyager.core.screen.Screen
import composables.screens.history.model.HistoryViewModel
import util.static.getVm
class HistoryScreen: Screen {
@Composable
override fun Content() {
val viewModel = getVm(::HistoryViewModel)
viewModel.loadContent()
val debts by viewModel.debtList.collectAsState()
Column(Modifier.fillMaxSize()) {
debts.forEach {
DebtHistoryCard(it)
}
}
}
} | 0 | Kotlin | 0 | 0 | 955b263d2669fdfda8b57b8a584c99dc6a905c40 | 787 | DebtsTrackerCompose | Apache License 2.0 |
sample/src/main/java/com/aaaamirabbas/sample/SampleData.kt | aaaamirabbas | 137,922,881 | false | null | package com.aaaamirabbas.sample
import com.aaaamirabbas.reactor.helper.ReactorContract
data class SampleData(
val id: Int = 24,
val name: String = "abbas"
) : ReactorContract | 2 | Kotlin | 1 | 39 | 677d0f8a582f6f733a3a0a69b6bed7cbbb08b20c | 184 | reactor | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.