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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PurposefulCommunity/app/src/main/java/com/bounswe/purposefulcommunity/Fragments/Instances/ShowTemplatesActivity.kt
|
yilmazvolkan
| 215,142,781
| false
| null |
package com.bounswe.purposefulcommunity.Fragments.Instances
import android.content.Context
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bounswe.mercatus.API.ApiInterface
import com.bounswe.mercatus.API.RetrofitInstance
import com.bounswe.purposefulcommunity.Adapters.TemplatesAdapter
import com.bounswe.purposefulcommunity.Models.GetTempBody
import com.bounswe.purposefulcommunity.Models.ShowTempBody
import com.bounswe.purposefulcommunity.R
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import java.net.ConnectException
class ShowTemplatesActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_show_templates)
val actionBar = supportActionBar
actionBar!!.title = getString(R.string.templates)
actionBar.setDisplayHomeAsUpEnabled(true)
val communityID = intent.getStringExtra("comm_temp_id")
getTemplates(communityID!!)
}
private fun getTemplates(communityID: String){
val res = getSharedPreferences("TOKEN_INFO", Context.MODE_PRIVATE)
val tokenV = res.getString("token", "Data Not Found!")
val purApp = RetrofitInstance.getRetrofitInstance().create(ApiInterface::class.java)
val communityName = intent.getStringExtra("comm_temp_name")
purApp.getTemplates(communityID, tokenV!!).enqueue(object : Callback<List<GetTempBody>> {
override fun onFailure(call: Call<List<GetTempBody>>, t: Throwable) {
if(t.cause is ConnectException){
Toast.makeText(
this@ShowTemplatesActivity,
"Check your connection!",
Toast.LENGTH_SHORT
).show()
}
else{
Toast.makeText(
this@ShowTemplatesActivity,
"Something bad happened!",
Toast.LENGTH_SHORT
).show()
}
}
override fun onResponse(call: Call<List<GetTempBody>>, response: Response<List<GetTempBody>>) {
if (response.code() == 200) {
val rv = findViewById<RecyclerView>(R.id.recyclerViewTemplates)
rv.layoutManager = LinearLayoutManager(this@ShowTemplatesActivity, RecyclerView.VERTICAL, false)
val users = ArrayList<ShowTempBody>()
var adapter = TemplatesAdapter(this@ShowTemplatesActivity, users)
rv.adapter = adapter
val res: List<GetTempBody>? = response.body()
for(i in res.orEmpty()){
users.add(ShowTempBody(i.id, i.createdDate, i.name, communityID, communityName!!))
}
if(users.isEmpty()){
Toast.makeText(this@ShowTemplatesActivity, "No template is found!", Toast.LENGTH_SHORT).show()
}
adapter.notifyDataSetChanged()
} else {
Toast.makeText(this@ShowTemplatesActivity, "Templates cannot retrieve!", Toast.LENGTH_SHORT).show()
}
}
})
}
override fun onSupportNavigateUp(): Boolean {
finish()
onBackPressed()
return true
}
override fun finish() {
super.finish()
overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right)
}
}
| 1
| null |
1
| 3
|
cce8b454712517799e9823bc75dc396495cf38a7
| 3,748
|
purposefulCommunityPlatform
|
MIT License
|
app/src/debug/java/hu/mrolcsi/muzik/theme/ThemeTestViewModel.kt
|
mrolcsi
| 169,584,173
| false
| null |
package hu.mrolcsi.muzik.theme
import androidx.databinding.Observable
import androidx.lifecycle.LiveData
import hu.mrolcsi.muzik.data.model.theme.Theme
interface ThemeTestViewModel : Observable {
val theme: LiveData<Theme>
}
| 3
|
Kotlin
|
0
| 0
|
23da4e22ebc1b6d44ee7ff3c3bfa21e9bd4e30d5
| 230
|
Muzik
|
Apache License 2.0
|
src/main/kotlin/com/slack/moshi/interop/gson/AdapterMethodsClassChecker.kt
|
slackhq
| 297,518,185
| false
|
{"Kotlin": 43523}
|
/*
* Copyright (C) 2020 Slack Technologies, LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.slack.moshi.interop.gson
import com.slack.moshi.interop.gson.Serializer.MOSHI
import com.squareup.moshi.FromJson
import com.squareup.moshi.ToJson
/**
* Checks if a class has any [FromJson] or [ToJson] annotated methods and should be used with Moshi.
*/
public object AdapterMethodsClassChecker : ClassChecker {
override fun serializerFor(rawType: Class<*>): Serializer? {
var clazz: Class<*>? = rawType
while (clazz != Any::class.java && clazz != null) {
for (method in clazz.declaredMethods) {
if (
method.isAnnotationPresent(ToJson::class.java) ||
method.isAnnotationPresent(FromJson::class.java)
) {
return MOSHI
}
}
clazz = clazz.superclass
}
return null
}
override fun toString(): String {
return "AdapterMethodsClassChecker"
}
}
| 6
|
Kotlin
|
7
| 43
|
6efc8086f641a77667de0fa61748739f7cec60ea
| 1,465
|
moshi-gson-interop
|
Apache License 2.0
|
platform/lang-impl/src/com/intellij/ide/navbar/ui/StaticNavBarPanel.kt
|
xGreat
| 182,651,778
| false
|
{"Text": 7190, "INI": 570, "YAML": 416, "Ant Build System": 10, "Batchfile": 28, "Shell": 616, "Markdown": 680, "Ignore List": 125, "Git Revision List": 1, "Git Attributes": 10, "EditorConfig": 244, "XML": 7188, "SVG": 3739, "Kotlin": 48905, "Java": 80666, "HTML": 3312, "Java Properties": 214, "Gradle": 419, "Maven POM": 82, "JavaScript": 212, "CSS": 69, "JFlex": 32, "JSON": 1374, "Groovy": 3308, "XSLT": 113, "desktop": 1, "Python": 15070, "JAR Manifest": 18, "PHP": 47, "Gradle Kotlin DSL": 477, "Protocol Buffer": 3, "Microsoft Visual Studio Solution": 2, "C#": 33, "Smalltalk": 17, "Diff": 135, "Erlang": 1, "Perl": 9, "Jupyter Notebook": 1, "Rich Text Format": 2, "AspectJ": 2, "HLSL": 2, "Objective-C": 27, "CoffeeScript": 2, "HTTP": 2, "JSON with Comments": 67, "GraphQL": 60, "OpenStep Property List": 47, "Tcl": 1, "Dockerfile": 5, "fish": 1, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 5, "XML Property List": 81, "Starlark": 2, "E-mail": 18, "Roff": 38, "Roff Manpage": 2, "Swift": 3, "C": 84, "TOML": 153, "Proguard": 2, "PlantUML": 6, "Checksums": 72, "Java Server Pages": 8, "reStructuredText": 68, "SQL": 1, "Vim Snippet": 8, "AMPL": 4, "Linux Kernel Module": 1, "CMake": 17, "C++": 32, "Handlebars": 1, "Rust": 9, "Makefile": 1, "Go": 34, "Go Checksums": 1, "Go Module": 1, "VBScript": 1, "NSIS": 5, "Thrift": 3, "Cython": 12, "Regular Expression": 3, "JSON5": 4}
|
// 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.ide.navbar.ui
import com.intellij.ide.navbar.vm.StaticNavBarVm
import com.intellij.openapi.application.EDT
import com.intellij.openapi.project.Project
import com.intellij.util.ui.EDT
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import java.awt.BorderLayout
import javax.swing.JPanel
internal class StaticNavBarPanel(
cs: CoroutineScope,
staticVm: StaticNavBarVm,
project: Project,
) : JPanel(BorderLayout()) {
init {
EDT.assertIsEdt()
cs.launch(Dispatchers.EDT) {
staticVm.vm.collectLatest { vm ->
if (vm == null) {
removeAll()
}
else {
coroutineScope {
add(NewNavBarPanel(this@coroutineScope, vm, project, isFloating = false))
}
}
}
}
}
}
| 1
| null |
1
| 1
|
fb5f23167ce9cc53bfa3ee054b445cf4d8f1ce98
| 1,046
|
intellij-community
|
Apache License 2.0
|
net/craftventure/core/metadata/EquippedItemsMeta.kt
|
Craftventure
| 770,049,457
| false
|
{"Kotlin": 3656616, "Java": 684034}
|
package net.craftventure.core.metadata
import com.comphenix.packetwrapper.WrapperPlayServerEntityMetadata
import com.comphenix.protocol.wrappers.WrappedDataValue
import kotlinx.coroutines.Job
import net.craftventure.bukkit.ktx.entitymeta.getMetadata
import net.craftventure.bukkit.ktx.entitymeta.getOrCreateMetadata
import net.craftventure.bukkit.ktx.extension.isConnected
import net.craftventure.bukkit.ktx.extension.packAllReflection
import net.craftventure.bukkit.ktx.extension.sendPacket
import net.craftventure.bukkit.ktx.manager.FeatureManager
import net.craftventure.core.database.metadata.OwnableItemMetadata
import net.craftventure.core.extension.getMatrix
import net.craftventure.core.extension.getSafeEyeMatrix
import net.craftventure.core.manager.EquipmentManager
import net.craftventure.core.npc.EntityMetadata
import net.craftventure.core.npc.NpcEntity
import net.craftventure.database.type.EquippedItemSlot
import net.kyori.adventure.text.Component
import net.minecraft.nbt.CompoundTag
import net.minecraft.network.protocol.game.ClientboundSetEntityDataPacket
import org.bukkit.entity.Player
class EquippedItemsMeta(
val player: Player
) : TickingBaseMetadata() {
var equippedItems: Map<EquippedItemSlot, EquipmentManager.EquippedItemData> = emptyMap()
var appliedEquippedItems: EquipmentManager.AppliedEquippedItems? = null
set(value) {
field = value
updateEffects()
}
private var costumeEffect: EffectData? = null
private var helmetEffect: EffectData? = null
private var chestplateEffect: EffectData? = null
private var leggingsEffect: EffectData? = null
private var bootsEffect: EffectData? = null
private var job: Job? = null
override fun debugComponent() =
Component.text("job=${job != null}/${job?.isActive} equippedItems=${equippedItems.entries.joinToString { "${it.key}=${it.value.id}" }}")
fun replaceUpdateJob(job: Job) {
this.job?.cancel()
this.job = job
}
override fun isValid(target: Any): Boolean = super.isValid(target) || player.isConnected()
private fun updateEffects() {
val costume = appliedEquippedItems?.costumeItem
if (costume != null) {
setCostumeEffect(appliedEquippedItems?.costumeItem)
} else {
setHelmetEffect(appliedEquippedItems?.helmetItem)
setChestplateEffect(appliedEquippedItems?.chestplateItem)
setLeggingsEffect(appliedEquippedItems?.leggingsItem)
setBootsEffect(appliedEquippedItems?.bootsItem)
}
}
override fun update() {
if (player.isDead) return
if (FeatureManager.isFeatureEnabled(FeatureManager.Feature.CLOTHING_PARTICLES)) {
if (costumeEffect != null || helmetEffect != null || chestplateEffect != null || leggingsEffect != null || bootsEffect != null) {
val playerMatrix = player.getMatrix()
val headMatrix = player.getSafeEyeMatrix() ?: return
costumeEffect?.let { applyEffects(it, playerMatrix, headMatrix, player) }
helmetEffect?.let { applyEffects(it, playerMatrix, headMatrix, player) }
chestplateEffect?.let { applyEffects(it, playerMatrix, headMatrix, player) }
leggingsEffect?.let { applyEffects(it, playerMatrix, headMatrix, player) }
bootsEffect?.let { applyEffects(it, playerMatrix, headMatrix, player) }
}
}
}
private fun applyEffects(data: EffectData, playerMatrix: Matrix4x4, headMatrix: Matrix4x4, player: Player) {
data.effects?.let { wearMeta ->
wearMeta.effects.forEach { it.apply(player, playerMatrix, headMatrix, data.equippedItemData, this) }
}
}
private fun clearEffects() {
costumeEffect = null
helmetEffect = null
chestplateEffect = null
leggingsEffect = null
bootsEffect = null
}
private fun setCostumeEffect(effect: EquipmentManager.EquippedItemData?) {
costumeEffect = effect?.let(::EffectData)
helmetEffect = null
chestplateEffect = null
leggingsEffect = null
bootsEffect = null
}
private fun setHelmetEffect(effect: EquipmentManager.EquippedItemData?) {
helmetEffect = effect?.let(::EffectData)
costumeEffect = null
}
private fun setChestplateEffect(effect: EquipmentManager.EquippedItemData?) {
chestplateEffect = effect?.let(::EffectData)
costumeEffect = null
}
private fun setLeggingsEffect(effect: EquipmentManager.EquippedItemData?) {
leggingsEffect = effect?.let(::EffectData)
costumeEffect = null
}
private fun setBootsEffect(effect: EquipmentManager.EquippedItemData?) {
bootsEffect = effect?.let(::EffectData)
costumeEffect = null
}
// private fun getEffect(name: String?): PlayerEffect? {
// return when (name) {
// "costume_5yearcv" -> Costume5YearCvEffect(name)
// "magicarp" -> MagicarpEffect(name)
// "hat_addict_5" -> HatAddict5Effect(name)
// "well_wisher" -> WellWisherEffect(name)
// else -> null
// }
// }
fun applySpawnPacketsTo(vararg other: Player) {
val entityData = NpcEntity.generateSynchedEntityData(player.location)
// entityData.setMetadata()
val packet = ClientboundSetEntityDataPacket(player.entityId, entityData.packAllReflection())
other.forEach { it.sendPacket(packet) }
val wrapperPlayServerEntityMetadata = WrapperPlayServerEntityMetadata()
wrapperPlayServerEntityMetadata.entityID = player.entityId
wrapperPlayServerEntityMetadata.metadata = listOf(
WrappedDataValue(
EntityMetadata.Player.shoulderLeft.absoluteIndex!!,
EntityMetadata.Player.shoulderLeft.wrappedSerializer,
appliedEquippedItems?.shoulderPetLeft?.ownableItemMeta?.parsedCompoundTag ?: CompoundTag()
),
WrappedDataValue(
EntityMetadata.Player.shoulderRight.absoluteIndex!!,
EntityMetadata.Player.shoulderRight.wrappedSerializer,
appliedEquippedItems?.shoulderPetRight?.ownableItemMeta?.parsedCompoundTag ?: CompoundTag()
)
)
other.forEach { wrapperPlayServerEntityMetadata.sendPacket(it) }
}
private data class EffectData(
val equippedItemData: EquipmentManager.EquippedItemData,
val effects: OwnableItemMetadata.ItemWearMeta? = equippedItemData.ownableItemMeta?.itemWear,
)
companion object {
fun getOrCreate(player: Player) = player.getOrCreateMetadata { EquippedItemsMeta(player) }
fun get(player: Player) = player.getMetadata<EquippedItemsMeta>()
fun Player.equippedItemsMeta() = get(this)
fun Player.requireEquippedItemsMeta() = getOrCreate(this)
}
}
| 0
|
Kotlin
|
1
| 21
|
015687ff6687160835deacda57121480f542531b
| 6,942
|
open-plugin-parts
|
MIT License
|
compose/src/main/kotlin/statemachine/WeilerStateMachine.kt
|
85vmh
| 543,628,296
| false
| null |
package statemachine
import ru.nsk.kstatemachine.*
class WeilerStateMachine {
val machine = createStateMachine {
addInitialState(States.MachineStarted) {
onEntry {
println("Entered $this")
}
transition<Events.EStopPressed> {
targetState = States.SpindleRunning
onTriggered {
println("Transition to yellow state")
}
}
onExit {
println("Exit $this")
}
}
}
}
object States {
object MachineStarted : DefaultState("Green")
object MachineInEStop : DefaultState("Green")
object MachineNotOn : DefaultState("Green")
object MachineNotHomed : DefaultState("Green")
object MachineHoming : DefaultState("Green")
object MachineReady : DefaultState("Green")
object SpindleRunning : DefaultState("Yellow")
object AxisFeeding : DefaultState("Axis Feeding")
object AxisJogging : DefaultState("Axis Jogging")
}
sealed class Events {
object EStopPressed : Event
object MachineOn : Event
object MachineOff : Event
object MachineHome : Event
object StartSpindle : Event
object StopSpindle : Event
}
| 1
|
Kotlin
|
1
| 2
|
89a7092538447e34df90637b6b721c73a0ed739a
| 1,238
|
mindovercnclathe
|
Apache License 2.0
|
all-alarms/src/main/java/com/eventful/all/alarms/AllAlarmsViewModel.kt
|
tosoba
| 542,691,274
| false
|
{"Kotlin": 428063, "Java": 1125}
|
package com.eventful.all.alarms
import androidx.lifecycle.SavedStateHandle
import com.eventful.alarms.AlarmsFlowProcessor
import com.eventful.alarms.AlarmsViewModel
import com.eventful.core.android.di.viewmodel.AssistedSavedStateViewModelFactory
import com.squareup.inject.assisted.Assisted
import com.squareup.inject.assisted.AssistedInject
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.FlowPreview
@ExperimentalCoroutinesApi
@FlowPreview
class AllAlarmsViewModel
@AssistedInject
constructor(
@AllAlarmsViewModelProcessor processor: AlarmsFlowProcessor,
@Assisted savedStateHandle: SavedStateHandle
) : AlarmsViewModel(processor = processor, savedStateHandle = savedStateHandle) {
@AssistedInject.Factory
interface Factory : AssistedSavedStateViewModelFactory<AllAlarmsViewModel> {
override fun create(savedStateHandle: SavedStateHandle): AllAlarmsViewModel
}
}
| 0
|
Kotlin
|
0
| 0
|
0ba84b32680768acd172dfd54d57f513ed2d1baa
| 925
|
Eventful
|
MIT License
|
src/test/kotlin/no/nav/klage/oppgave/clients/PdlClientTest.kt
|
navikt
| 297,650,936
| false
| null |
package no.nav.klage.oppgave.clients
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.junit5.MockKExtension
import no.nav.klage.oppgave.clients.pdl.graphql.HentPersonResponse
import no.nav.klage.oppgave.clients.pdl.graphql.PdlClient
import no.nav.klage.oppgave.util.TokenUtil
import org.assertj.core.api.Assertions.assertThat
import org.intellij.lang.annotations.Language
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
@ExtendWith(MockKExtension::class)
internal class PdlClientTest {
@MockK
lateinit var tokenUtilMock: TokenUtil
@BeforeEach
fun before() {
every { tokenUtilMock.getAppAccessTokenWithPdlScope() } returns "abc"
every { tokenUtilMock.getSaksbehandlerAccessTokenWithPdlScope() } returns "abc"
}
@Test
fun `pdl response kan mappes selv med tomme arrays`() {
val hentPersonResponse = getHentPersonResponse(pdlResponse())
assertThat(hentPersonResponse.data).isNotNull
assertThat(hentPersonResponse.data!!.hentPerson!!.navn.first().fornavn).isEqualTo("AREMARK")
}
private fun getHentPersonResponse(jsonResponse: String): HentPersonResponse {
val pdlClient = PdlClient(
createShortCircuitWebClient(jsonResponse),
tokenUtilMock
)
return pdlClient.getPersonInfo("fnr")
}
@Language("json")
fun pdlResponse() = """
{
"data": {
"hentPerson": {
"navn": [
{
"fornavn": "AREMARK",
"mellomnavn": null,
"etternavn": "TESTFAMILIEN"
}
],
"kjoenn": [
{
"kjoenn": "MANN"
}
],
"adressebeskyttelse": [],
"sivilstand": [],
"vergemaalEllerFremtidsfullmakt": [],
"doedsfall": [],
"fullmakt": []
}
}
}
"""
}
| 4
| null |
3
| 2
|
168c8c4b9ed5192ac6870f88b6e82a665b29a4b9
| 2,072
|
kabal-api
|
MIT License
|
ui/src/main/java/com/wb/ui/screens/contacts/list/ContactListLoadingScreen.kt
|
waynils
| 747,230,996
| false
|
{"Kotlin": 82427}
|
package com.wb.ui.screens.contacts.detail
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import com.wb.ui.theme.MyAppTheme
import com.wb.ui.utils.LightDarkModeOneDevicePreviews
@Composable
internal fun ContactLoadingScreen(modifier: Modifier = Modifier) {
Box(modifier = modifier) {
CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center)
)
}
}
@LightDarkModeOneDevicePreviews
@Composable
private fun ContactsLoadingScreenPreview() {
MyAppTheme {
Surface(modifier = Modifier.fillMaxSize()) {
ContactLoadingScreen(modifier = Modifier.fillMaxSize())
}
}
}
| 0
|
Kotlin
|
0
| 0
|
1c0064b1a63d37d4cc3987b321a954c3f25ea95d
| 912
|
contactApp
|
Apache License 2.0
|
src/main/kotlin/no/nav/familie/ba/sak/kjerne/autovedtak/satsendring/AutovedtakSatsendringScheduler.kt
|
navikt
| 224,639,942
| false
|
{"Kotlin": 6319849, "Gherkin": 731897, "PLpgSQL": 4478, "Shell": 1628, "Dockerfile": 196}
|
package no.nav.familie.ba.sak.kjerne.autovedtak.satsendring
import no.nav.familie.ba.sak.config.FeatureToggleConfig
import no.nav.familie.leader.LeaderClient
import no.nav.familie.unleash.UnleashService
import org.slf4j.LoggerFactory
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Service
@Service
class AutovedtakSatsendringScheduler(
private val startSatsendring: StartSatsendring,
private val unleashService: UnleashService,
) {
@Scheduled(cron = CRON_HVERT_10_MIN_UKEDAG)
fun triggSatsendring() {
if (unleashService.isEnabled(FeatureToggleConfig.SATSENDRING_HØYT_VOLUM, false)) {
startSatsendring(1200)
} else {
startSatsendring(100)
}
}
@Scheduled(cron = CRON_HVERT_5_MIN_UKEDAG_UTENFOR_ARBEIDSTID)
fun triggSatsendringUtenforArbeidstid() {
if (unleashService.isEnabled(FeatureToggleConfig.SATSENDRING_KVELD, false)) {
startSatsendring(1000)
}
}
@Scheduled(cron = CRON_HVERT_5_MIN_LØRDAG)
fun triggSatsendringLørdag() {
if (unleashService.isEnabled(FeatureToggleConfig.SATSENDRING_LØRDAG, false)) {
startSatsendring(1000)
}
}
private fun startSatsendring(antallFagsaker: Int) {
if (LeaderClient.isLeader() == true) {
logger.info("Starter schedulert jobb for satsendring 2024-01. antallFagsaker=$antallFagsaker")
startSatsendring.startSatsendring(
antallFagsaker = antallFagsaker,
)
}
}
companion object {
val logger = LoggerFactory.getLogger(AutovedtakSatsendringScheduler::class.java)
const val CRON_HVERT_10_MIN_UKEDAG = "0 */10 7-18 * * MON-FRI"
const val CRON_HVERT_5_MIN_UKEDAG_UTENFOR_ARBEIDSTID = "0 */5 16-20 * * MON-FRI"
const val CRON_HVERT_5_MIN_LØRDAG = "0 */5 7-17 * * SAT"
}
}
| 4
|
Kotlin
|
1
| 9
|
e531227fb85cd4d7ef8f85fea7e3d285605a5527
| 1,916
|
familie-ba-sak
|
MIT License
|
app/src/main/java/com/example/todo/adapters/TodoAdapter.kt
|
it-21360978
| 625,595,540
| false
|
{"Kotlin": 7982}
|
package com.example.todo.adapters
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.ImageView
import android.widget.Toast
import androidx.recyclerview.widget.RecyclerView
import com.example.todo.R
import com.example.todo.database.ToDoDatabase
import com.example.todo.database.entities.ToDo
import com.example.todo.database.repositories.TodoRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class TodoAdapter(): RecyclerView.Adapter<TodoAdapter.ViewHolder>() {
lateinit var context: Context
lateinit var data: List<ToDo>
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val cbTodos: CheckBox
val ivDelete: ImageView
init {
cbTodos = view.findViewById(R.id.cbitem)
ivDelete = view.findViewById(R.id.delete)
}
}
fun setData(data: List<ToDo>, context: Context) {
this.data = data
this.context = context
notifyDataSetChanged()
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context)
.inflate(R.layout.todo_list, parent, false)
return ViewHolder(view)
}
override fun getItemCount(): Int {
return data.size
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.cbTodos.text = data[position].item
holder.ivDelete.setOnClickListener {
if(holder.cbTodos.isChecked){
val repository = TodoRepository(ToDoDatabase.getInstance(context))
CoroutineScope(Dispatchers.IO).launch {
repository.delete(data[position])
val data = repository.getAllTodos()
withContext(Dispatchers.Main) {
setData(data, context)
}
}
}else{
Toast.makeText(context,"Cannot delete unmarked Todo items",Toast.LENGTH_LONG)
.show()
}
}
}
}
| 0
|
Kotlin
|
0
| 0
|
c4ce08bcafcab4a9a8323195b3530133ee82a448
| 2,268
|
ToDo-Application
|
MIT License
|
src/main/kotlin/dev/shtanko/algorithms/leetcode/NumberOfSteps.kt
|
ashtanko
| 203,993,092
| false
| null |
/*
* Copyright 2020 Oleksii Shtanko
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shtanko.algorithms.leetcode
fun interface NumberOfStepsStrategy {
operator fun invoke(n: Int): Int
}
class NumberOfStepsStraightForward : NumberOfStepsStrategy {
override operator fun invoke(n: Int): Int {
return n.numberOfSteps()
}
private fun Int.numberOfSteps(): Int {
if (this == 0) return 0
var result = 0
var a = this
var mod: Int
while (a != 0) {
mod = a % 2
if (mod == 0) {
a /= 2
} else {
a -= 1
}
result++
}
return result
}
}
class NumberOfStepsBinary : NumberOfStepsStrategy {
override operator fun invoke(n: Int): Int {
if (n == 0) return 0
var result = 0
var a = n
while (a != 0) {
result += if (a and 1 == 0) 1 else 2
a = a shr 1
}
return result - 1
}
}
| 4
|
Kotlin
|
0
| 18
|
ffacb9bfbdfa68628386e7f2585e3edd4508d9e8
| 1,541
|
kotlab
|
Apache License 2.0
|
library/src/main/java/io/github/boguszpawlowski/composecalendar/header/WeekState.kt
|
boguszpawlowski
| 355,182,891
| false
|
{"Kotlin": 88782}
|
package io.github.boguszpawlowski.composecalendar.header
import androidx.compose.runtime.Stable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.saveable.Saver
import androidx.compose.runtime.setValue
import io.github.boguszpawlowski.composecalendar.week.Week
import java.time.LocalDate
@Suppress("FunctionName") // Factory function
public fun WeekState(initialWeek: Week): WeekState = WeekStateImpl(initialWeek)
@Stable
public interface WeekState {
public var currentWeek: Week
public companion object {
@Suppress("FunctionName") // Factory function
public fun Saver(): Saver<WeekState, String> = Saver(
save = { it.currentWeek.start.toString() },
restore = { WeekState(initialWeek = Week(firstDay = LocalDate.parse(it))) }
)
}
}
@Stable
private class WeekStateImpl(
initialWeek: Week,
) : WeekState {
private var _currentWeek by mutableStateOf<Week>(initialWeek)
override var currentWeek: Week
get() = _currentWeek
set(value) {
_currentWeek = value
}
}
| 5
|
Kotlin
|
37
| 285
|
1cdea2bbf0741f0230c680fd30b53b7472b4bea5
| 1,087
|
ComposeCalendar
|
Apache License 2.0
|
app/src/main/java/com/aposiamp/smartliving/domain/utils/Result.kt
|
ApostolisSiampanis
| 783,913,411
| false
|
{"Kotlin": 490999}
|
package com.aposiamp.smartliving.domain.utils
sealed class Result<out T> {
data class Success<out T>(val result: T) : Result<T>()
data class Error(val exception: Exception) : Result<Nothing>()
data object Loading : Result<Nothing>()
}
| 0
|
Kotlin
|
0
| 3
|
8184e402e0121dba16a08675395184bd5413f20f
| 247
|
Smart_Living
|
MIT License
|
backend/src/main/kotlin/com/denchic45/studiversity/database/table/Attachments.kt
|
denchic45
| 435,895,363
| false
|
{"Kotlin": 2103689, "Vue": 15083, "JavaScript": 2830, "CSS": 1496, "HTML": 867}
|
package com.denchic45.studiversity.database.table
import com.denchic45.stuiversity.api.course.element.model.AttachmentType
import org.jetbrains.exposed.dao.UUIDEntity
import org.jetbrains.exposed.dao.UUIDEntityClass
import org.jetbrains.exposed.dao.id.EntityID
import org.jetbrains.exposed.dao.id.UUIDTable
import java.util.*
object Attachments : UUIDTable("attachment", "attachment_id") {
val name = text("attachment_name")
val url = text("url").nullable()
val thumbnailUrl = text("thumbnail_url").nullable()
val type = enumerationByName<AttachmentType>("type", 8)
// val path = text("path").nullable()
val ownerId = uuid("owner_id")
// val ownerType = enumerationByName<AttachmentOwner>("owner_type", 22)
}
class AttachmentDao(id: EntityID<UUID>) : UUIDEntity(id) {
companion object : UUIDEntityClass<AttachmentDao>(Attachments)
var name by Attachments.name
var url by Attachments.url
var thumbnailUrl by Attachments.thumbnailUrl
var type by Attachments.type
// var path by Attachments.path
var ownerId by Attachments.ownerId
// var ownerType by Attachments.ownerType
}
| 0
|
Kotlin
|
0
| 7
|
9d1744ffd9e1652e93af711951e924b739e96dcc
| 1,143
|
Studiversity
|
Apache License 2.0
|
src/main/kotlin/org/eightsines/kotlinperfopt/A5.kt
|
restorer
| 217,991,803
| false
|
{"Java": 16759, "Kotlin": 7977}
|
package org.eightsines.kotlinperfopt
class A5 {
class Item(@JvmField val x: Int, @JvmField var y: Int)
private fun foo(item: Item) {
item.y = 2
println("${item.x}, ${item.y}")
}
}
| 1
| null |
1
| 1
|
00f3010d5c21810e2b3068283323ac933b2c9a22
| 210
|
grocon-19-kotlin-perf-opt
|
MIT License
|
kotlintest-tests/src/test/kotlin/com/sksamuel/kotlintest/tests/specs/BehaviourSpecLambdaTest.kt
|
martinlau
| 127,972,633
| false
| null |
package io.kotlintest.specs
import io.kotlintest.shouldBe
import org.junit.jupiter.api.extension.ExtendWith
@ExtendWith()
class BehaviourSpecLambdaTest : AbstractBehaviorSpec() {
data class User(var email: String? = "")
var user: User? = null
init {
given("user") {
user = User(null)
`when`("set valid email") {
user!!.email = "<EMAIL>"
then("should get correct email") {
user!!.email shouldBe "<EMAIL>"
}
}
`when`("set null email") {
user!!.email = null
then("should get null email") {
user!!.email shouldBe null
}
}
}
given("null") {
user = null
`when`("setting user to not null") {
user = User("<EMAIL>")
then("should get correct email") {
user!!.email shouldBe "<EMAIL>"
}
}
}
}
}
| 1
| null |
1
| 1
|
963fdbe4221e50b4344fbe408bbc0a24a44ba142
| 871
|
kotlintest
|
Apache License 2.0
|
comsumerapp/src/main/java/com/noranekoit/comsumerapp/MappingHelper.kt
|
NoraNekoIT
| 398,503,232
| false
| null |
package com.noranekoit.comsumerapp
import android.database.Cursor
import com.noranekoit.comsumerapp.model.UserGithub
object MappingHelper {
fun mapCursorToArrayList(cursor: Cursor?): ArrayList<UserGithub>{
val list = ArrayList<UserGithub>()
if (cursor != null){
while (cursor.moveToNext()){
val id = cursor.getInt(cursor.getColumnIndexOrThrow(DatabaseContract.FavoriteUserColumns.ID))
val username = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.FavoriteUserColumns.USERNAME))
val avatarUrl = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.FavoriteUserColumns.AVATAR_URL))
val type = cursor.getString(cursor.getColumnIndexOrThrow(DatabaseContract.FavoriteUserColumns.TYPE))
list.add(
UserGithub(
username,id,avatarUrl,type
)
)
}
}
return list
}
}
| 0
|
Kotlin
|
0
| 0
|
45514d5cc640ebe4c2729afaf6986f30eec64030
| 1,005
|
Learn-Fundamentals-Android-Apps
|
MIT License
|
parent/src/main/java/sk/backbone/parent/repositories/server/client/exceptions/NotFoundException.kt
|
backbonesk
| 273,036,191
| false
| null |
package sk.backbone.parent.repositories.server.client.exceptions
import com.android.volley.VolleyError
class ForbiddenException @JvmOverloads constructor(volleyError: VolleyError? = null) : ParentHttpException(volleyError)
| 0
|
Kotlin
|
1
| 2
|
efb701901aaf4b91e9273dbdcc16730d92ef7c41
| 224
|
parent
|
MIT License
|
compiler/testData/codegen/box/specialBuiltins/enumAsOrdinaled.kt
|
JakeWharton
| 99,388,807
| false
| null |
// IGNORE_BACKEND: JS_IR
interface Ordinaled {
val ordinal: Int
}
enum class A : Ordinaled {
X
}
fun box(): String {
val result = (A.X as Ordinaled).ordinal
if (result != 0) return "fail 1: $result"
return "OK"
}
| 181
| null |
8
| 83
|
4383335168338df9bbbe2a63cb213a68d0858104
| 237
|
kotlin
|
Apache License 2.0
|
services/csm.cloud.project.activity/src/main/kotlin/com/bosch/pt/csm/cloud/projectmanagement/project/workarea/facade/listener/strategies/state/UpdateStateFromWorkAreaListEvent.kt
|
boschglobal
| 805,348,245
| false
|
{"Kotlin": 13156190, "HTML": 274761, "Go": 184388, "HCL": 158560, "Shell": 117666, "Java": 52634, "Python": 51306, "Dockerfile": 10348, "Vim Snippet": 3969, "CSS": 344}
|
/*
* ************************************************************************
*
* Copyright: <NAME> Power Tools GmbH, 2018 - 2021
*
* ************************************************************************
*/
package com.bosch.pt.csm.cloud.projectmanagement.project.workarea.facade.listener.strategies.state
import com.bosch.pt.csm.cloud.common.model.key.EventMessageKey
import com.bosch.pt.csm.cloud.projectmanagement.common.facade.listener.strategies.state.AbstractStateStrategy
import com.bosch.pt.csm.cloud.projectmanagement.common.facade.listener.strategies.state.UpdateStateStrategy
import com.bosch.pt.csm.cloud.projectmanagement.project.workarea.facade.listener.message.toEntity
import com.bosch.pt.csm.cloud.projectmanagement.project.workarea.service.WorkAreaListService
import com.bosch.pt.csm.cloud.projectmanagement.workarea.messages.WorkAreaListEventAvro
import datadog.trace.api.Trace
import org.apache.avro.specific.SpecificRecordBase
import org.springframework.stereotype.Component
@Component
class UpdateStateFromWorkAreaListEvent(private val workAreaListService: WorkAreaListService) :
AbstractStateStrategy<WorkAreaListEventAvro>(), UpdateStateStrategy {
override fun handles(key: EventMessageKey, value: SpecificRecordBase?): Boolean =
value is WorkAreaListEventAvro
@Trace
override fun updateState(key: EventMessageKey, event: WorkAreaListEventAvro): Unit =
event.getAggregate().run { workAreaListService.save(toEntity()) }
}
| 0
|
Kotlin
|
3
| 9
|
9f3e7c4b53821bdfc876531727e21961d2a4513d
| 1,488
|
bosch-pt-refinemysite-backend
|
Apache License 2.0
|
core/designsystem/src/main/java/com/melih/android/pokeapp/core/designsystem/compose/DevicePreviews.kt
|
melomg
| 458,631,034
| false
|
{"Kotlin": 95088}
|
package com.melih.android.pokeapp.core.designsystem.compose
import android.content.res.Configuration
import androidx.compose.ui.tooling.preview.Preview
@Preview(
showBackground = true,
name = "phone",
device = "spec:shape=Normal,width=360,height=640,unit=dp,dpi=480",
uiMode = Configuration.UI_MODE_NIGHT_NO,
)
@Preview(
showBackground = true,
name = "phone dark mode",
device = "spec:shape=Normal,width=360,height=640,unit=dp,dpi=480",
uiMode = Configuration.UI_MODE_NIGHT_YES,
)
@Preview(
showBackground = true,
name = "landscape",
device = "spec:shape=Normal,width=640,height=360,unit=dp,dpi=480",
uiMode = Configuration.UI_MODE_NIGHT_NO,
)
@Preview(
showBackground = true,
name = "foldable",
device = "spec:shape=Normal,width=673,height=841,unit=dp,dpi=480",
uiMode = Configuration.UI_MODE_NIGHT_NO,
)
@Preview(
showBackground = true,
name = "tablet",
device = "spec:shape=Normal,width=1280,height=800,unit=dp,dpi=480",
uiMode = Configuration.UI_MODE_NIGHT_NO,
)
annotation class DevicePreviews
| 3
|
Kotlin
|
0
| 0
|
00fbfe60e75d26eeda2e9e1ce87250a6604d2fd1
| 1,081
|
pokeapp-android
|
Apache License 2.0
|
HingeAngle/src/main/java/com/microsoft/device/display/samples/hingeangle/fragments/SingleScreenFragment.kt
|
microsoft
| 239,923,437
| false
| null |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License.
*
*/
package com.microsoft.device.display.samples.hingeangle.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.TextView
import androidx.core.content.ContextCompat.getColor
import androidx.core.view.drawToBitmap
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.microsoft.device.display.samples.hingeangle.R
import com.microsoft.device.display.samples.hingeangle.databinding.HingeAngleFragmentSingleScreenBinding
import com.microsoft.device.display.samples.hingeangle.model.DEFAULT_HINGE_ANGLE
import com.microsoft.device.display.samples.hingeangle.model.HingeAngleLiveData
import com.microsoft.device.display.samples.hingeangle.model.HingeAngleViewModel
import com.microsoft.device.display.samples.hingeangle.model.PaintColors
import com.microsoft.device.display.samples.hingeangle.model.UNAVAILABLE_HINGE
import com.microsoft.device.display.samples.hingeangle.model.color
import com.microsoft.device.display.samples.hingeangle.views.PenDrawingView
/**
* Fragment containing the drawing surface and the color selector component.
*/
class SingleScreenFragment : Fragment() {
private lateinit var binding: HingeAngleFragmentSingleScreenBinding
private lateinit var viewModel: HingeAngleViewModel
private lateinit var drawingView: PenDrawingView
private lateinit var hingeAngleValueView: TextView
private var currentAngle: Int = 0
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
binding = HingeAngleFragmentSingleScreenBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
setupViewModel()
bindUI(view)
restoreDrawingSurfaceState()
observeHingeAngle()
}
/**
* Setup for [HingeAngleViewModel]
*/
private fun setupViewModel() {
viewModel = ViewModelProvider(requireActivity()).get(HingeAngleViewModel::class.java)
}
/**
* Binds all UI components.
*/
private fun bindUI(view: View) {
hingeAngleValueView = view.findViewById(R.id.hinge_angle)
drawingView = view.findViewById(R.id.drawing_view)
val clearButton = view.findViewById<Button>(R.id.button_clear)
clearButton.setOnClickListener { clearDrawingSurface() }
binding.colorsSelector.penGroup.setOnCheckedChangeListener { group, optionId ->
when (optionId) {
R.id.button_red -> chooseColor(PaintColors.Red)
R.id.button_blue -> chooseColor(PaintColors.Blue)
R.id.button_green -> chooseColor(PaintColors.Green)
R.id.button_yellow -> chooseColor(PaintColors.Yellow)
R.id.button_purple -> chooseColor(PaintColors.Purple)
}
}
}
/**
* Changes the color for the drawing surface.
*/
private fun chooseColor(paintColors: PaintColors) {
drawingView.paintColor = getColor(requireContext(), paintColors.color)
}
/**
* Clears the drawing surface.
*/
private fun clearDrawingSurface() {
drawingView.clearDrawingSurface()
viewModel.setImage(null)
viewModel.pathList = emptyList()
}
/**
* Restores the drawing surface with the latest known drawing elements
* (for example, after screen rotation)
*/
private fun restoreDrawingSurfaceState() {
drawingView.drawingPathList = viewModel.pathList
drawingView.paintRadius = viewModel.penRadius
drawingView.paints = viewModel.paints
viewModel.selectedPen
.takeIf { it != 0 }
?.let {
binding.colorsSelector.penGroup.check(it)
}
}
private fun observeHingeAngle() {
HingeAngleLiveData.get(requireContext()).observe(
viewLifecycleOwner
) { angle ->
if (angle != UNAVAILABLE_HINGE) {
hingeAngleValueView.text = getString(R.string.hinge_angle_value, angle)
drawingView.paintRadius = angle
currentAngle = angle
} else {
hingeAngleValueView.text = getString(R.string.hinge_angle_unavailable)
drawingView.paintRadius = DEFAULT_HINGE_ANGLE
currentAngle = DEFAULT_HINGE_ANGLE
}
}
}
override fun onResume() {
super.onResume()
drawingView.attachOnDrawListener {
saveDrawingState()
}
}
override fun onPause() {
super.onPause()
drawingView.detachOnDrawListener()
}
/**
* Save the last known drawing elements
*/
private fun saveDrawingState() {
if (isAdded) {
viewModel.setImage(drawingView.drawToBitmap())
viewModel.pathList = drawingView.drawingPathList
viewModel.penRadius = currentAngle
viewModel.paints = drawingView.paints
viewModel.selectedPen = binding.colorsSelector.penGroup.checkedRadioButtonId
}
}
}
| 4
| null |
16
| 38
|
34170fbae5fcee097e9c852d14888d8c4118689e
| 5,402
|
surface-duo-sdk-samples-kotlin
|
MIT License
|
src/main/kotlin/uk/gov/justice/digital/hmpps/oauth2server/resource/MfaControllerAccountDetails.kt
|
ministryofjustice
| 118,512,431
| false
|
{"Kotlin": 2268341, "HTML": 207227, "Shell": 16327, "CSS": 11834, "Dockerfile": 1459, "JavaScript": 439, "Procfile": 74}
|
@file:Suppress("SpringJavaInjectionPointsAutowiringInspection", "SpringMVCViewInspection")
package uk.gov.justice.digital.hmpps.oauth2server.resource
import com.microsoft.applicationinsights.TelemetryClient
import org.springframework.beans.factory.annotation.Value
import org.springframework.security.core.Authentication
import org.springframework.stereotype.Controller
import org.springframework.validation.annotation.Validated
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.servlet.ModelAndView
import uk.gov.justice.digital.hmpps.oauth2server.auth.model.User.MfaPreferenceType
import uk.gov.justice.digital.hmpps.oauth2server.auth.model.UserToken.TokenType
import uk.gov.justice.digital.hmpps.oauth2server.service.MfaService
import uk.gov.justice.digital.hmpps.oauth2server.verify.TokenService
import java.io.IOException
import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
@Controller
@Validated
class MfaControllerAccountDetails(
private val tokenService: TokenService,
telemetryClient: TelemetryClient,
mfaService: MfaService,
@Value("\${application.smoketest.enabled}") private val smokeTestEnabled: Boolean,
) : AbstractMfaController(
tokenService,
telemetryClient,
mfaService,
smokeTestEnabled,
"AccountDetails",
"/account-details",
"/account/mfa-challenge",
) {
@GetMapping("/account/mfa-send-challenge")
fun mfaSendChallengeAccountDetail(
authentication: Authentication,
@RequestParam contactType: String,
@RequestParam passToken: String?,
): ModelAndView {
passTokenInvalidForEmail(contactType, passToken)?.let {
return ModelAndView(
"redirect:/account-details",
"error",
it
)
}
return mfaSendChallenge(authentication, extraModel(contactType, passToken))
}
private fun passTokenInvalidForEmail(contactType: String, passToken: String?): String? {
if (contactType != "email") return null
if (passToken.isNullOrEmpty()) return "tokeninvalid"
val optionalErrorForToken = tokenService.checkToken(TokenType.CHANGE, passToken)
return optionalErrorForToken.map { "token$it" }.orElse(null)
}
@GetMapping("/account/mfa-challenge")
fun mfaChallengeRequestAccountDetail(
@RequestParam contactType: String,
@RequestParam error: String?,
@RequestParam token: String?,
@RequestParam passToken: String?,
@RequestParam mfaPreference: MfaPreferenceType?,
): ModelAndView {
passTokenInvalidForEmail(contactType, passToken)?.let {
return ModelAndView(
"redirect:/account-details",
"error",
it
)
}
return mfaChallengeRequest(error, token, mfaPreference, extraModel(contactType, passToken))
}
@PostMapping("/account/mfa-challenge")
@Throws(IOException::class, ServletException::class)
fun mfaChallengeAccountDetail(
@RequestParam token: String,
@RequestParam passToken: String,
@RequestParam mfaPreference: MfaPreferenceType,
@RequestParam code: String,
@RequestParam contactType: String,
request: HttpServletRequest,
response: HttpServletResponse,
): ModelAndView? = mfaChallenge(token, mfaPreference, code, extraModel(contactType, passToken)) {
continueToChangeAccountDetails(it, contactType)
}
private fun continueToChangeAccountDetails(username: String, contactType: String): ModelAndView {
// successfully passed 2fa, so generate change password token
val token = tokenService.createToken(TokenType.ACCOUNT, username)
return ModelAndView("redirect:/new-$contactType", "token", token)
}
@GetMapping("/account/mfa-resend")
fun mfaResendRequest(
@RequestParam contactType: String,
@RequestParam token: String,
@RequestParam passToken: String,
@RequestParam mfaPreference: MfaPreferenceType
): ModelAndView = createMfaResendRequest(token, mfaPreference, extraModel(contactType, passToken))
@PostMapping("/account/mfa-resend")
fun mfaResend(
@RequestParam contactType: String,
@RequestParam token: String,
@RequestParam passToken: String,
@RequestParam mfaResendPreference: MfaPreferenceType,
): ModelAndView = createMfaResend(token, mfaResendPreference, extraModel(contactType, passToken))
private fun extraModel(contactType: String, passToken: String?) =
mapOf("contactType" to contactType, "passToken" to passToken)
}
| 5
|
Kotlin
|
4
| 8
|
f2c661d8e7237e8c500682366ad87e0a0b0b6359
| 4,554
|
hmpps-auth
|
MIT License
|
feature/detail/src/main/kotlin/team/duckie/app/android/feature/detail/viewmodel/sideeffect/DetailSideEffect.kt
|
duckie-team
| 503,869,663
| false
| null |
/*
* Designed and developed by Duckie Team, 2022
*
* Licensed under the MIT.
* Please see full license: https://github.com/duckie-team/duckie-android/blob/develop/LICENSE
*/
package team.duckie.app.android.feature.detail.viewmodel.sideeffect
import team.duckie.app.android.feature.detail.viewmodel.DetailViewModel
/** [DetailViewModel] 에서 사용되는 SideEffect 모음 */
sealed class DetailSideEffect {
class SendToast(val message: String) : DetailSideEffect()
/**
* [DetailViewModel] 의 비즈니스 로직 처리 중에 발생한 예외를 [exception] 으로 받고
* 해당 exception 을 [FirebaseCrashlytics] 에 제보합니다.
*
* @param exception 발생한 예외
*/
class ReportError(val exception: Throwable) : DetailSideEffect()
class StartExam(
val examId: Int,
val certifyingStatement: String,
val isQuiz: Boolean,
) : DetailSideEffect()
class StartQuiz(
val examId: Int,
val requirementQuestion: String,
val requirementPlaceholder: String,
val timer: Int,
val isQuiz: Boolean,
) : DetailSideEffect()
/**
* [SearchActivity] 로 이동하는 SideEffect 입니다.
*/
class NavigateToSearch(val searchTag: String?) : DetailSideEffect()
class NavigateToMyPage(val userId: Int) : DetailSideEffect()
class NavigateToExamResult(val examId: Int) : DetailSideEffect()
class NavigateToCreateProblem(val examId: Int) : DetailSideEffect()
data class CopyExamIdDynamicLink(val examId: Int) : DetailSideEffect()
}
| 32
| null |
2
| 8
|
5dbd5b7a42c621931d05a96e66431f67a3a50762
| 1,486
|
duckie-android
|
MIT License
|
src/main/kotlin/yandex/cloud/toolkit/ui/dialog/CLIAuthConfigDialog.kt
|
yandex-cloud
| 386,235,739
| false
|
{"Kotlin": 506192, "HTML": 1351}
|
package yandex.cloud.toolkit.ui.dialog
import com.intellij.icons.AllIcons
import com.intellij.ide.util.BrowseFilesListener
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.TextFieldWithBrowseButton
import com.intellij.openapi.ui.ValidationInfo
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.SimpleTextAttributes
import com.intellij.ui.TextFieldWithHistory
import com.intellij.ui.components.JBLabel
import com.intellij.util.containers.addIfNotNull
import com.intellij.util.ui.UIUtil
import icons.CloudIcons
import yandex.cloud.toolkit.api.auth.impl.cli.CLICloudAuthMethod
import yandex.cloud.toolkit.util.*
import java.time.Duration
import javax.swing.JButton
import javax.swing.JComponent
import javax.swing.JList
import javax.swing.SwingConstants
import kotlin.concurrent.thread
class CLIAuthConfigDialog(
lastConfig: CLICloudAuthMethod.Config?
) : DialogWrapper(true) {
private val cliLocationField = TextFieldWithBrowseButton()
private val profileField = TextFieldWithHistory()
private val cliCheckButton = JButton("Test CLI")
private val loadProfilesButton = JButton("Load Profiles")
private val cliStatus = JBLabel("", SwingConstants.LEFT)
@Volatile
private var cliProcess: Process? = null
var cliLocation: String = ""
private set
var profile: String? = null
private set
init {
cliLocationField.text = lastConfig?.cliLocation ?: ""
profileField.renderer = ProfilesListRenderer()
val profiles = mutableListOf("")
profiles.addIfNotNull(lastConfig?.profile)
setProfilesHistory(profiles)
cliLocationField.addBrowseFolderListener(
"Select CLI Yandex.Cloud executable", "", null,
BrowseFilesListener.SINGLE_FILE_DESCRIPTOR
)
cliStatus.font = UIUtil.getLabelFont(UIUtil.FontSize.SMALL)
updateToolStatus()
updateProcessButtons()
cliLocationField.textField.addCaretListener {
updateToolStatus()
updateProcessButtons()
}
cliCheckButton.addActionListener { runCLICheckProcess() }
loadProfilesButton.addActionListener { runLoadProfilesProcess() }
title = "CLI Yandex.Cloud Authentication"
init()
}
private fun updateToolStatus() {
if (cliLocationField.text.isEmpty()) {
cliStatus.icon = null
cliStatus.text = null
}
}
private fun updateProcessButtons() {
val canStartProcess = cliLocationField.text.isNotEmpty() && cliProcess == null
cliCheckButton.isEnabled = canStartProcess
loadProfilesButton.isEnabled = canStartProcess
}
private fun runCLICheckProcess() {
val cliLocation = cliLocationField.text
if (cliProcess != null || cliLocation.isEmpty()) return
val process = try {
Runtime.getRuntime().exec(
arrayOf(cliLocation, "version")
)
} catch (e: Exception) {
updateStatus(null)
null
}
cliProcess = process ?: return
updateProcessButtons()
val timeoutTask = process.setupTimeout(Duration.ofSeconds(3))
thread(name = "yc-cli-check", isDaemon = true) {
val ycToolVersion: String? = try {
process.inputStream.bufferedReader().use { it.readText() }
} catch (e: Exception) {
null
}
cliProcess = null
timeoutTask.cancel()
invokeLaterAt(this.contentPanel) {
updateStatus(ycToolVersion)
updateProcessButtons()
}
}
}
private fun runLoadProfilesProcess() {
val cliLocation = cliLocationField.text
if (cliProcess != null || cliLocation.isEmpty()) return
val process = try {
Runtime.getRuntime().exec(
arrayOf(cliLocation, "config", "profile", "list")
)
} catch (e: Exception) {
null
}
cliProcess = process ?: return
updateProcessButtons()
profileField.history = emptyList()
val timeoutTask = process.setupTimeout(Duration.ofSeconds(3))
thread(name = "yc-profiles-load", isDaemon = true) {
val rawProfilesList: List<String>? = try {
process.inputStream.bufferedReader().use { it.readLines() }
} catch (e: Exception) {
null
}
cliProcess = null
timeoutTask.cancel()
invokeLaterAt(this.contentPanel) {
updateProcessButtons()
if (!rawProfilesList.isNullOrEmpty()) {
val profiles = mutableListOf("")
rawProfilesList.mapNotNullTo(profiles) { it.split(" ").firstOrNull() }
setProfilesHistory(profiles)
}
}
}
}
private fun setProfilesHistory(profiles: List<String>) {
profileField.history = profiles
if (profiles.size > 1) {
profileField.selectedIndex = 1
}
}
private fun updateStatus(ycToolVersion: String?) = invokeLaterAt(this.contentPanel) {
if (ycToolVersion != null && ycToolVersion.startsWith("Yandex.Cloud")) {
cliStatus.text = ycToolVersion
cliStatus.icon = CloudIcons.Status.Success
} else {
cliStatus.text = "Invalid CLI Yandex.Cloud selected"
cliStatus.icon = AllIcons.General.Error
}
}
override fun doValidate(): ValidationInfo? {
return when {
cliLocationField.text.isEmpty() -> ValidationInfo("Please select CLI Yandex.Cloud location")
else -> null
}
}
override fun doOKAction() {
if (!myOKAction.isEnabled) return
cliLocation = cliLocationField.text
val rawProfile = profileField.text
profile = if (rawProfile.isNullOrEmpty()) null else rawProfile
super.doOKAction()
}
override fun createCenterPanel(): JComponent = YCUI.gridPanel {
YCUI.gridBag(horizontal = true) {
withPreferredSize(650, 70)
JBLabel("CLI Location:") addAs nextln(0.0)
cliLocationField addAs next(1.0)
cliCheckButton addAs next(0.0)
JBLabel("Profile:") addAs nextln(0.0)
profileField addAs next(1.0)
loadProfilesButton addAs next(0.0)
cliStatus addAs fullLine()
}
}
private class ProfilesListRenderer : ColoredListCellRenderer<String>() {
override fun customizeCellRenderer(
list: JList<out String>,
value: String,
index: Int,
selected: Boolean,
hasFocus: Boolean
) {
if (value.isEmpty()) {
append("(No profile)", SimpleTextAttributes.GRAYED_ATTRIBUTES)
} else {
append(value, SimpleTextAttributes.REGULAR_ATTRIBUTES)
}
}
}
}
| 9
|
Kotlin
|
4
| 65
|
2f8eaa54aad978e5ab452e5d05ba573f68b72943
| 7,066
|
ide-plugin-jetbrains
|
MIT License
|
data/RF00793/rnartist.kts
|
fjossinet
| 449,239,232
| false
|
{"Kotlin": 8214424}
|
import io.github.fjossinet.rnartist.core.*
rnartist {
ss {
rfam {
id = "RF00793"
name = "consensus"
use alignment numbering
}
}
theme {
details {
value = 3
}
color {
location {
12 to 14
80 to 82
}
value = "#24411f"
}
color {
location {
15 to 18
69 to 72
}
value = "#f93261"
}
color {
location {
20 to 23
64 to 67
}
value = "#b4bf71"
}
color {
location {
25 to 33
54 to 62
}
value = "#215c3e"
}
color {
location {
35 to 37
50 to 52
}
value = "#551557"
}
color {
location {
38 to 39
46 to 47
}
value = "#c50f10"
}
color {
location {
15 to 14
73 to 79
}
value = "#d7e377"
}
color {
location {
19 to 19
68 to 68
}
value = "#252b1d"
}
color {
location {
24 to 24
63 to 63
}
value = "#b8c7cf"
}
color {
location {
34 to 34
53 to 53
}
value = "#2af603"
}
color {
location {
38 to 37
48 to 49
}
value = "#075cd9"
}
color {
location {
40 to 45
}
value = "#63e958"
}
color {
location {
1 to 11
}
value = "#3630a7"
}
color {
location {
83 to 85
}
value = "#e5fcc7"
}
}
}
| 0
|
Kotlin
|
0
| 0
|
3016050675602d506a0e308f07d071abf1524b67
| 2,233
|
Rfam-for-RNArtist
|
MIT License
|
features/search/src/test/java/com/chesire/nekome/app/search/results/ResultsViewModelTests.kt
|
rmwthorne
| 330,431,997
| true
|
{"Kotlin": 497025, "Ruby": 7928, "JavaScript": 64}
|
package com.chesire.nekome.app.search.results
import com.chesire.nekome.core.AuthCaster
import com.chesire.nekome.core.Resource
import com.chesire.nekome.core.flags.SeriesType
import com.chesire.nekome.core.flags.UserSeriesStatus
import com.chesire.nekome.core.settings.ApplicationSettings
import com.chesire.nekome.library.SeriesRepository
import com.chesire.nekome.testing.CoroutinesMainDispatcherRule
import io.mockk.Runs
import io.mockk.coEvery
import io.mockk.coVerify
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.verify
import org.junit.Rule
import org.junit.Test
class ResultsViewModelTests {
@get:Rule
val coroutineRule = CoroutinesMainDispatcherRule()
@Test
fun `trackNewSeries on anime type calls addAnime on the repo`() {
val mockRepo = mockk<SeriesRepository> {
coEvery {
addAnime(any(), any())
} coAnswers {
Resource.Success(mockk())
}
every { getSeries() } returns mockk()
}
val mockCaster = mockk<AuthCaster>()
val mockSettings = mockk<ApplicationSettings> {
every { defaultSeriesState } returns UserSeriesStatus.Current
}
val testObject = ResultsViewModel(mockRepo, mockCaster, mockSettings)
testObject.trackNewSeries(ResultsData(0, SeriesType.Anime)) {}
coVerify { mockRepo.addAnime(any(), any()) }
}
@Test
fun `trackNewSeries on manga type calls addManga on the repo`() {
val mockRepo = mockk<SeriesRepository> {
coEvery {
addManga(any(), any())
} coAnswers {
Resource.Success(mockk())
}
every { getSeries() } returns mockk()
}
val mockCaster = mockk<AuthCaster>()
val mockSettings = mockk<ApplicationSettings> {
every { defaultSeriesState } returns UserSeriesStatus.Current
}
val testObject = ResultsViewModel(mockRepo, mockCaster, mockSettings)
testObject.trackNewSeries(ResultsData(0, SeriesType.Manga)) {}
coVerify { mockRepo.addManga(any(), any()) }
}
@Test
fun `trackNewSeries on failure to add and could not refresh fires authCaster`() {
val mockRepo = mockk<SeriesRepository> {
coEvery {
addManga(any(), any())
} coAnswers {
Resource.Error("", Resource.Error.CouldNotRefresh)
}
every { getSeries() } returns mockk()
}
val mockCaster = mockk<AuthCaster> {
every { issueRefreshingToken() } just Runs
}
val mockSettings = mockk<ApplicationSettings> {
every { defaultSeriesState } returns UserSeriesStatus.Current
}
val testObject = ResultsViewModel(mockRepo, mockCaster, mockSettings)
testObject.trackNewSeries(ResultsData(0, SeriesType.Manga)) {}
verify { mockCaster.issueRefreshingToken() }
}
@Test
fun `trackNewSeries on success executes callback`() {
val mockRepo = mockk<SeriesRepository> {
coEvery {
addAnime(any(), any())
} coAnswers {
Resource.Success(mockk())
}
every { getSeries() } returns mockk()
}
val mockCaster = mockk<AuthCaster>()
val mockCallback = mockk<(Boolean) -> Unit>(relaxed = true)
val mockSettings = mockk<ApplicationSettings> {
every { defaultSeriesState } returns UserSeriesStatus.Current
}
val testObject = ResultsViewModel(mockRepo, mockCaster, mockSettings)
testObject.trackNewSeries(ResultsData(0, SeriesType.Anime), mockCallback)
verify { mockCallback.invoke(any()) }
}
}
| 0
| null |
0
| 0
|
88a808b7ad4131f298cffbd9de21e2c9aa085093
| 3,787
|
Nekome
|
Apache License 2.0
|
Kotlin-Samples/src/main/kotlin/chapter2/Recipe3.kt
|
PacktPublishing
| 126,314,798
| false
| null |
package chapter2
/**
* Chapter: Expressive functions and adjustable interfaces
* Recipe: Extending functionalities of classes
*/
fun main(vararg args: String) {
val array: Array<String> = arrayOf("a", "b", "c", "d")
array.swap("c", "b")
print(array.joinToString())
}
fun <T> Array<T>.swap(a: T, b: T) {
val positionA = indexOf(a)
val positionB = indexOf(b)
if (positionA < 0 || positionB < 0) {
throw IllegalArgumentException("Given param doesn't belong to the array")
}
val tmp = this[positionA]
this[positionA] = this[positionB]
this[positionB] = tmp
}
| 0
|
Kotlin
|
24
| 26
|
a9118396250ded6f4466c20fd0dc62ea6a598ed1
| 609
|
Kotlin-Standard-Library-Cookbook
|
MIT License
|
pop-miners/altchain-pop-miner/src/main/kotlin/org/veriblock/miners/pop/api/controller/MiningController.kt
|
VeriBlock
| 179,742,374
| false
| null |
// VeriBlock NodeCore
// Copyright 2017-2021 <NAME>
// All rights reserved.
// https://www.veriblock.org
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
package org.veriblock.miners.pop.api.controller
import com.papsign.ktor.openapigen.annotations.Path
import com.papsign.ktor.openapigen.annotations.parameters.PathParam
import com.papsign.ktor.openapigen.annotations.parameters.QueryParam
import com.papsign.ktor.openapigen.route.info
import com.papsign.ktor.openapigen.route.path.auth.OpenAPIAuthenticatedRoute
import com.papsign.ktor.openapigen.route.path.auth.get
import com.papsign.ktor.openapigen.route.path.auth.post
import com.papsign.ktor.openapigen.route.response.respond
import com.papsign.ktor.openapigen.route.route
import io.ktor.auth.UserIdPrincipal
import org.apache.logging.log4j.Level
import org.veriblock.core.MineException
import org.veriblock.miners.pop.api.dto.AltChainReadyStatusResponse
import org.veriblock.miners.pop.api.dto.ConfiguredAltchain
import org.veriblock.miners.pop.api.dto.ConfiguredAltchainList
import org.veriblock.miners.pop.api.dto.MineRequest
import org.veriblock.miners.pop.api.dto.MinerInfoResponse
import org.veriblock.miners.pop.api.dto.MinerStatusResponse
import org.veriblock.miners.pop.api.dto.OperationDetailResponse
import org.veriblock.miners.pop.api.dto.OperationSummaryListResponse
import org.veriblock.miners.pop.api.dto.OperationSummaryResponse
import org.veriblock.miners.pop.api.dto.OperationWorkflow
import org.veriblock.miners.pop.api.dto.toAltChainSyncStatusResponse
import org.veriblock.miners.pop.api.dto.toDetailedResponse
import org.veriblock.miners.pop.api.dto.toExplorerBaseUrlsResponse
import org.veriblock.miners.pop.api.dto.toSummaryResponse
import org.veriblock.miners.pop.core.MiningOperationStatus
import org.veriblock.miners.pop.service.AltchainPopMinerService
import org.veriblock.miners.pop.service.ApmOperationExplainer
import org.veriblock.miners.pop.util.CheckResult
import org.veriblock.sdk.alt.plugin.PluginService
import java.util.*
class MiningController(
private val miner: AltchainPopMinerService,
private val operationExplainer: ApmOperationExplainer,
private val pluginService: PluginService
) : ApiController {
@Path("mine")
class MineActionPath
@Path("operations")
class MinerOperationsPath(
@QueryParam("Operation altchain key (optional)") val altchainKey: String?,
@QueryParam("Operation status (optional)") val status: String?,
@QueryParam("Pagination limit (optional)") val limit: Int?,
@QueryParam("Pagination offset (optional)") val offset: Int?
)
@Path("operations/{id}")
class MinerOperationPath(
@PathParam("Operation ID") val id: String
)
@Path("operations/{id}/cancel")
class CancelOperationPath(
@PathParam("Operation ID") val id: String
)
@Path("operations/{id}/workflow")
class MinerOperationWorkflowPath(
@PathParam("Operation ID") val id: String
)
@Path("operations/{id}/logs")
class MinerOperationLogsPath(
@PathParam("Operation ID") val id: String,
@QueryParam("Log level (optional, INFO by default)") val level: String?
)
@Path("configured-altchains")
class MinerConfiguredAltchainsPath
override fun OpenAPIAuthenticatedRoute<UserIdPrincipal>.registerApi() = route("miner") {
get<Unit, MinerInfoResponse, UserIdPrincipal>(
info("Get miner data")
) {
val ready = miner.checkReadyConditions()
val responseModel = MinerInfoResponse(
vbkAddress = miner.getAddress(),
vbkBalance = miner.getBalance().confirmedBalance.atomicUnits,
status = MinerStatusResponse(
ready is CheckResult.Success,
(ready as? CheckResult.Failure)?.error?.message
)
)
respond(responseModel)
}
post<MineActionPath, OperationSummaryResponse, MineRequest, UserIdPrincipal>(
info("Start mining operation")
) { _, mineRequest ->
val operation = try {
miner.mine(mineRequest.chainSymbol, mineRequest.height)
} catch(exception: MineException) {
throw BadRequestException("Failed to start operation: ${exception.message}")
}
respond(operation.toSummaryResponse())
}
get<MinerOperationsPath, OperationSummaryListResponse, UserIdPrincipal>(
info("Get operations list")
) { location ->
// Get the given status filter
val status = location.status?.let { stateString ->
MiningOperationStatus.values().find { it.name == stateString.uppercase(Locale.getDefault()) }
?: throw BadRequestException("'$stateString' is not valid. Available options: 'active', 'failed', 'completed', 'all'")
} ?: MiningOperationStatus.ACTIVE
// Get the given limit filter
val limit = location.limit ?: 50
// Get the given offset filter
val offset = location.offset ?: 0
// Get the operations
val operations = miner.getOperations(location.altchainKey, status, limit, offset)
val count = miner.getOperationsCount(location.altchainKey, status)
// Paginate and map operations
val result = operations.map {
it.toSummaryResponse()
}.toList()
respond(OperationSummaryListResponse(result, count))
}
get<MinerOperationPath, OperationDetailResponse, UserIdPrincipal>(
info("Get operation details")
) { location ->
val id = location.id
val operationState = miner.getOperation(id)
?: throw NotFoundException("Operation $id not found")
val responseModel = operationState.toDetailedResponse()
respond(responseModel)
}
post<CancelOperationPath, Unit, Unit, UserIdPrincipal>(
info("Cancel an operation")
) { location, _ ->
val result = miner.cancelOperation(location.id)
respond(result)
}
get<MinerOperationLogsPath, List<String>, UserIdPrincipal>(
info("Get the operation logs")
) { location ->
val level: Level = Level.toLevel(location.level, Level.INFO)
val operation = miner.getOperation(location.id)
?: throw NotFoundException("Operation ${location.id} not found")
val responseModel = operation.getLogs(level).map { it.toString() }
respond(responseModel)
}
get<MinerOperationWorkflowPath, OperationWorkflow, UserIdPrincipal>(
info("Get operation workflow")
) { location ->
val id = location.id
val operation = miner.getOperation(id)
?: throw NotFoundException("Operation $id not found")
val workflow = operationExplainer.explainOperation(operation)
respond(workflow)
}
get<MinerConfiguredAltchainsPath, ConfiguredAltchainList, UserIdPrincipal>(
info("Get configured altchains")
) {
val altchains = pluginService.getPlugins().values.map {
val altChainReadyResult = miner.checkAltChainReadyConditions(it.key)
val stateInfo = miner.getStateInfo(it.key)
val isAltChainReady = altChainReadyResult !is CheckResult.Failure
val readyStatusResponse = AltChainReadyStatusResponse(
isAltChainReady,
if (!isAltChainReady) {
(altChainReadyResult as CheckResult.Failure).error.message
} else {
null
}
)
ConfiguredAltchain(
it.id,
it.key,
it.name,
it.getPayoutDelay(),
stateInfo.toAltChainSyncStatusResponse(),
readyStatusResponse,
it.config.explorerBaseUrls.toExplorerBaseUrlsResponse()
)
}.sortedBy {
it.key
}
respond(ConfiguredAltchainList(altchains))
}
}
}
| 72
| null |
16
| 12
|
ef06c51c1410ba59da13403b65e367b21dcfed21
| 8,451
|
nodecore
|
MIT License
|
mobile_app1/module41/src/main/java/module41packageKt0/Foo100.kt
|
uber-common
| 294,831,672
| false
| null |
package module41packageKt0;
annotation class Foo100Fancy
@Foo100Fancy
class Foo100 {
fun foo0(){
module41packageKt0.Foo99().foo6()
}
fun foo1(){
foo0()
}
fun foo2(){
foo1()
}
fun foo3(){
foo2()
}
fun foo4(){
foo3()
}
fun foo5(){
foo4()
}
fun foo6(){
foo5()
}
}
| 6
|
Java
|
6
| 72
|
9cc83148c1ca37d0f2b2fcb08c71ac04b3749e5e
| 324
|
android-build-eval
|
Apache License 2.0
|
kt.kt
|
cucerdariancatalin
| 598,115,774
| false
| null |
fun boyerMoore(text: String, pattern: String): Int {
val n = text.length
val m = pattern.length
val right = IntArray(256) { -1 }
for (i in 0 until m) {
right[pattern[i].toInt()] = i
}
var skip: Int
for (i in 0 <= n - m) {
skip = 0
for (j in m - 1 downTo 0) {
if (pattern[j] != text[i + j]) {
skip = Math.max(1, j - right[text[i + j].toInt()])
break
}
}
if (skip == 0) return i
}
return -1
}
| 0
|
Kotlin
|
0
| 0
|
b9b2bc51b275212943511a7222198a4fd00c972c
| 525
|
boyer-moore-algorithm
|
MIT License
|
src/main/kotlin/org/mechdancer/algebra/function/matrix/Check.kt
|
MechDancer
| 128,765,281
| false
| null |
package org.mechdancer.algebra.function.matrix
import org.mechdancer.algebra.core.Matrix
import org.mechdancer.algebra.doubleEquals
import org.mechdancer.algebra.implement.matrix.builder.I
import org.mechdancer.algebra.implement.matrix.special.*
fun Matrix.isSquare() = row == column
fun Matrix.isNotSquare() = row != column
fun Matrix.isFullRank() = row == column && row == rank
fun Matrix.isNotFullRank() = row != column || row != rank
fun ZeroMatrix.isSymmetric() = row == column
fun NumberMatrix.isSymmetric() = true
fun DiagonalMatrix.isSymmetric() = true
fun SymmetricMatrix.isSymmetric() = true
fun HilbertMatrix.isSymmetric() = row == column
fun Matrix.isSymmetric() =
row == column && (1 until row).all { r -> (0 until r).all { c -> doubleEquals(get(r, c), get(c, r)) } }
fun Matrix.isNotSymmetric() = !isSymmetric()
fun Matrix.isOrthogonal() =
row == column && transpose() * this == I[dim]
fun Matrix.isNotOrthogonal() = !isOrthogonal()
| 1
|
Kotlin
|
1
| 6
|
2cbc7e60b3cd32f46a599878387857f738abda46
| 962
|
linearalgebra
|
Do What The F*ck You Want To Public License
|
contentchef-jvm-common/src/main/java/io/contentchef/common/exception/InvalidResponseException.kt
|
ContentChef
| 237,468,762
| false
| null |
package io.contentchef.common.exception
/**
* Exception thrown in case the server response is not a valid JSON object
* [responseContent] server's response
*/
data class InvalidResponseException(val responseContent: String) : Throwable()
| 1
| null |
1
| 1
|
5b10f4e2f32a4bcb81296a15dfbf27e81bece856
| 241
|
contentchef-jvm
|
Apache License 2.0
|
core/database/src/main/java/com/merxury/blocker/core/database/cmpdetail/ComponentDetailDao.kt
|
lihenggui
| 115,417,337
| false
| null |
/*
* Copyright 2023 Blocker
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.merxury.blocker.core.database.cmpdetail
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
@Dao
interface ComponentDetailDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertComponentDetail(entity: ComponentDetailEntity)
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertComponentDetails(entities: List<ComponentDetailEntity>)
@Delete
suspend fun delete(entity: ComponentDetailEntity)
@Update
suspend fun update(entity: ComponentDetailEntity)
@Query("SELECT * FROM component_detail WHERE full_name = :fullName")
suspend fun getComponentDetail(fullName: String): List<ComponentDetailEntity>
}
| 20
|
Kotlin
|
39
| 418
|
a038beb2ada9a2d4cf9558f72ec338fcd58f3e04
| 1,405
|
blocker
|
Apache License 2.0
|
back/src/test/kotlin/org/kontza/musicalumbrellaback/MusicalUmbrellaBackApplicationTests.kt
|
kontza
| 471,445,928
| false
| null |
package org.kontza.musicalumbrellaback
import org.junit.jupiter.api.Test
import org.springframework.boot.test.context.SpringBootTest
@SpringBootTest
class MusicalUmbrellaBackApplicationTests {
@Test
fun contextLoads() {
}
}
| 0
|
Kotlin
|
0
| 0
|
8baa46a2dfbe764b1f307a587844eeec4f3f0e79
| 231
|
musical-umbrella
|
MIT License
|
app/src/main/java/com/example/kavach/Onboarding/Splash_Screen.kt
|
ShivangeeRajput
| 739,837,492
| false
|
{"Kotlin": 31907, "Java": 2073}
|
package com.Onboarding
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import com.example.kavach.R
class Splash_Screen : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_splash_screen)
supportActionBar?.hide()
Handler().postDelayed({
val intent=Intent(this@Splash_Screen, Welcome_Screen::class.java)
startActivity(intent)
finish()
},3000)
}
}
| 0
|
Kotlin
|
0
| 2
|
b2268df4dfdb6ae34878116452ccf97a81525c63
| 605
|
Kavach
|
Apache License 2.0
|
kirc-core/src/main/kotlin/de/cmdjulian/kirc/spec/manifest/OciManifestV1.kt
|
cmdjulian
| 524,628,199
| false
|
{"Kotlin": 99363}
|
package de.cmdjulian.kirc.spec.manifest
import io.goodforgod.graalvm.hint.annotation.ReflectionHint
// https://github.com/opencontainers/image-spec/blob/main/manifest.md
@ReflectionHint
data class OciManifestV1(
override val schemaVersion: Byte,
override val mediaType: String?,
override val config: LayerReference,
override val layers: List<LayerReference>,
val subject: LayerReference?,
val annotations: Map<String, String>,
) : ManifestSingle {
@ReflectionHint
@Suppress("ktlint:standard:property-naming")
companion object {
const val MediaType = "application/vnd.oci.image.manifest.v1+json"
}
}
| 3
|
Kotlin
|
0
| 10
|
d91d4899dfb5dbaa268a113942288db87b27eebd
| 649
|
kirc
|
MIT License
|
components/flow/flow-service/src/test/kotlin/net/corda/flow/maintenance/TimeoutEventCleanupProcessorTest.kt
|
corda
| 346,070,752
| false
|
{"Kotlin": 20585393, "Java": 308202, "Smarty": 115357, "Shell": 54409, "Groovy": 30246, "PowerShell": 6470, "TypeScript": 5826, "Solidity": 2024, "Batchfile": 244}
|
package net.corda.flow.maintenance
import net.corda.avro.serialization.CordaAvroDeserializer
import net.corda.data.flow.FlowTimeout
import net.corda.data.flow.state.checkpoint.Checkpoint
import net.corda.data.messaging.mediator.MediatorState
import net.corda.flow.pipeline.exceptions.FlowFatalException
import net.corda.flow.state.impl.FlowCheckpointFactory
import net.corda.libs.configuration.SmartConfig
import net.corda.libs.statemanager.api.State
import net.corda.libs.statemanager.api.StateManager
import net.corda.messaging.api.records.Record
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.mockito.Mockito.mock
import org.mockito.kotlin.any
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import java.nio.ByteBuffer
import java.time.Instant
class TimeoutEventCleanupProcessorTest {
private val config = mock<SmartConfig>()
private val stateManager = mock<StateManager>()
private val flowCheckpointFactory = mock<FlowCheckpointFactory>()
private val checkpointCleanupHandler = mock<CheckpointCleanupHandler>()
private val checkpointCordaAvroDeserializer = mock<CordaAvroDeserializer<Checkpoint>>()
private val mediatorDeserializer = mock<CordaAvroDeserializer<MediatorState>>()
private val exceptionCaptor = argumentCaptor<FlowFatalException>()
private val processor = TimeoutEventCleanupProcessor(
checkpointCleanupHandler,
stateManager,
mediatorDeserializer,
checkpointCordaAvroDeserializer,
flowCheckpointFactory,
config
)
private val inputRecords = listOf(
buildRecord("key1", "TestReason1"),
buildRecord("key2", "TestReason2")
)
@BeforeEach
fun setup() {
val checkpointBytes = mock<ByteBuffer>().apply {
whenever(array()).thenReturn("bytes".toByteArray())
}
val checkpoint = mock<Checkpoint>().apply {
whenever(flowId).thenReturn("flowID")
}
val mediatorState = mock<MediatorState>().apply {
whenever(state).thenReturn(checkpointBytes)
}
whenever(checkpointCordaAvroDeserializer.deserialize(any())).thenReturn(checkpoint)
whenever(mediatorDeserializer.deserialize(any())).thenReturn(mediatorState)
whenever(flowCheckpointFactory.create(any(), any(), any())).thenReturn(mock())
whenever(checkpointCleanupHandler.cleanupCheckpoint(any(), any(), any())).thenReturn(listOf(mock()))
}
@Test
fun `records with null values are not processed and no output records are generated`() {
val output = processor.onNext(listOf(Record("timeout", "key", null)))
assertThat(output.size).isEqualTo(0)
}
@Test
fun `when timeout processor receives events with states output records are generated`() {
whenever(stateManager.get(any())).thenReturn(inputRecords.associate { it.key to buildState(it.key) })
whenever(stateManager.delete(any())).thenReturn(mapOf())
val output = processor.onNext(inputRecords)
assertThat(output.size).isEqualTo(2)
verify(checkpointCleanupHandler, times(2)).cleanupCheckpoint(any(), any(), exceptionCaptor.capture())
assertThat(exceptionCaptor.firstValue.message).isEqualTo("TestReason1")
assertThat(exceptionCaptor.secondValue.message).isEqualTo("TestReason2")
}
@Test
fun `when timeout processor fails to delete a state no records are output`() {
whenever(stateManager.get(any())).thenReturn(inputRecords.associate { it.key to buildState(it.key) })
whenever(stateManager.delete(any())).thenReturn(inputRecords.associate { it.key to buildState(it.key) })
val output = processor.onNext(inputRecords)
assertThat(output).isEmpty()
}
@Test
fun `when state manager does not have states available no records are output`() {
whenever(stateManager.get(any())).thenReturn(mapOf())
whenever(stateManager.delete(any())).thenReturn(mapOf())
val output = processor.onNext(inputRecords)
assertThat(output).isEmpty()
}
@Test
fun `when avro deserializer fails to deserialize no records are output`() {
whenever(stateManager.get(any())).thenReturn(inputRecords.associate { it.key to buildState(it.key) })
whenever(checkpointCordaAvroDeserializer.deserialize(any())).thenReturn(null)
whenever(stateManager.delete(any())).thenReturn(mapOf())
val output = processor.onNext(inputRecords)
assertThat(output).isEmpty()
}
private fun buildRecord(key: String, timeOutReason: String? = ""): Record<String, FlowTimeout> {
return Record("timeout", key, FlowTimeout(key, timeOutReason, Instant.now()))
}
private fun buildState(key: String): State {
return State(key, byteArrayOf())
}
}
| 86
|
Kotlin
|
27
| 69
|
0766222eb6284c01ba321633e12b70f1a93ca04e
| 4,974
|
corda-runtime-os
|
Apache License 2.0
|
app/src/main/java/com/vr/app/sh/ui/books/viewmodel/AddBookViewModel.kt
|
Vadim-Rudak
| 510,027,925
| false
|
{"Kotlin": 260458}
|
package com.vr.app.sh.ui.books.viewmodel
import android.content.res.Resources
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.vr.app.sh.R
import com.vr.app.sh.domain.UseCase.GetAllBookListInternet
import com.vr.app.sh.domain.UseCase.SaveBookListInBD
import com.vr.app.sh.domain.UseCase.SendBook
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
class AddBookViewModel(
private val resources: Resources,
val getAllBookListInternet: GetAllBookListInternet,
val saveBookListInBD: SaveBookListInBD,
private val internetConnection:Boolean,
private val sendBook: SendBook
): ViewModel() {
var pathFile: String? = null
lateinit var file: File
val visibleProgressBar = MutableLiveData<Boolean>()
val send = MutableLiveData<Boolean>()
val errorMessage = MutableLiveData<String>()
fun sendFile(nameBook:String,numClass:Int){
if(internetConnection){
visibleProgressBar.value = true
CoroutineScope(Dispatchers.IO).launch {
sendBook.execute(numClass,nameBook,file)
getAllBookListInternet.execute().also {
if (it.success){
it.list?.let { it1 -> saveBookListInBD.execute(it1) }
withContext(Dispatchers.Main){
visibleProgressBar.value = false
send.value = true
}
}
}
}
}else{
visibleProgressBar.value = false
errorMessage.value = resources.getString(R.string.alrNotInternetConnection)
}
}
}
| 0
|
Kotlin
|
0
| 0
|
740f626a79c53adc4deda25ce2ec3a85b984c981
| 1,787
|
SH
|
Apache License 2.0
|
SceytChatUiKit/src/main/java/com/sceyt/chatuikit/data/channeleventobserver/ChannelMembersEventData.kt
|
sceyt
| 549,073,085
| false
|
{"Kotlin": 2361738, "Java": 107894}
|
package com.sceyt.chatuikit.data.channeleventobserver
import com.sceyt.chatuikit.data.models.channels.SceytChannel
import com.sceyt.chatuikit.data.models.channels.SceytMember
data class ChannelMembersEventData(
val channel: SceytChannel,
val members: List<SceytMember>,
val eventType: ChannelMembersEventEnum
)
| 0
|
Kotlin
|
1
| 2
|
aa03d3d9f046243cd1bbb98bd5e9d5abcfeae822
| 336
|
sceyt-chat-android-uikit
|
MIT License
|
interfaces/src/main/kotlin/com/noxcrew/interfaces/view/PlayerInterfaceView.kt
|
Noxcrew
| 764,059,799
| false
|
{"Kotlin": 111397}
|
package com.noxcrew.interfaces.view
import com.noxcrew.interfaces.InterfacesListeners
import com.noxcrew.interfaces.interfaces.PlayerInterface
import com.noxcrew.interfaces.inventory.PlayerInterfacesInventory
import com.noxcrew.interfaces.pane.PlayerPane
import com.noxcrew.interfaces.utilities.runSync
import net.kyori.adventure.text.Component
import org.bukkit.entity.Player
import org.bukkit.event.inventory.InventoryType
import kotlin.time.Duration
/** Implements a player interface view. */
public class PlayerInterfaceView internal constructor(
player: Player,
backing: PlayerInterface
) : AbstractInterfaceView<PlayerInterfacesInventory, PlayerPane>(
player,
backing,
null
) {
override fun title(value: Component) {
error("PlayerInventoryView's cannot have a title")
}
override fun runChatQuery(timeout: Duration, onCancel: () -> Unit, onComplete: (Component) -> Unit) {
error("PlayerInventoryView does not support chat queries")
}
override fun createInventory(): PlayerInterfacesInventory = PlayerInterfacesInventory(player)
override fun openInventory() {
// Close whatever inventory the player has open so they can look at their normal inventory!
// This will only continue if the menu hasn't been closed yet.
if (!isOpen()) {
// First we close then we set the interface so we don't double open!
InterfacesListeners.INSTANCE.setOpenInterface(player.uniqueId, null)
player.closeInventory()
InterfacesListeners.INSTANCE.setOpenInterface(player.uniqueId, this)
}
// Double-check that this inventory is open now!
if (isOpen()) {
if (!backing.properties.inheritExistingItems) {
// Clear the player's inventory!
player.inventory.clear()
if (player.openInventory.topInventory.type == InventoryType.CRAFTING ||
player.openInventory.topInventory.type == InventoryType.CREATIVE
) {
player.openInventory.topInventory.clear()
}
player.openInventory.cursor = null
}
// Trigger onOpen manually because there is no real inventory being opened,
// this will also re-draw the player inventory parts!
onOpen()
}
}
override suspend fun close() {
markClosed()
// Ensure we update the interface state in the main thread!
// Even if the menu is not currently on the screen.
runSync {
InterfacesListeners.INSTANCE.setOpenInterface(player.uniqueId, null)
}
}
override fun isOpen(): Boolean =
(
player.openInventory.type == InventoryType.CRAFTING ||
player.openInventory.type == InventoryType.CREATIVE
) &&
InterfacesListeners.INSTANCE.getOpenInterface(player.uniqueId) == this
}
| 1
|
Kotlin
|
4
| 22
|
66363479038df90195c6c2a187a9fc83d992b075
| 2,963
|
interfaces-kotlin
|
MIT License
|
app-desktop/src/jvmMain/kotlin/io/stardewvalleydesigner/screens/mainmenu/rightside/topmenu/LayoutsGrid.kt
|
AzimMuradov
| 377,785,069
| false
|
{"Kotlin": 641349, "HTML": 864, "JavaScript": 461}
|
/*
* Copyright 2021-2024 <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 io.stardewvalleydesigner.screens.mainmenu.rightside.topmenu
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.*
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawWithContent
import androidx.compose.ui.unit.dp
import io.stardewvalleydesigner.component.mainmenu.Wrapper
import io.stardewvalleydesigner.engine.EditorEngineData
import io.stardewvalleydesigner.engine.layout.LayoutsProvider.layoutOf
import io.stardewvalleydesigner.screens.mainmenu.rightside.LayoutPreview
import io.stardewvalleydesigner.ui.component.settings.GlobalSettings
@Composable
fun LayoutsGrid(
layouts: List<Wrapper<EditorEngineData>>,
chosenLayout: Wrapper<EditorEngineData>?,
onChoose: (Wrapper<EditorEngineData>) -> Unit,
) {
val wordList = GlobalSettings.strings
LazyVerticalGrid(
columns = GridCells.Fixed(count = 3),
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(8.dp),
horizontalArrangement = Arrangement.spacedBy(8.dp),
) {
items(items = layouts) { engine ->
val chosenColor = MaterialTheme.colors.primary.copy(alpha = 0.3f)
Column(
modifier = Modifier
.clip(MaterialTheme.shapes.medium)
.drawWithContent {
drawContent()
if (chosenLayout == engine) {
drawRect(chosenColor)
}
}
.clickable(onClick = { onChoose(engine) })
.padding(8.dp),
verticalArrangement = Arrangement.spacedBy(4.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
val (layoutType, layeredEntitiesData, wallpaper, flooring) = engine.value
Box {
LayoutPreview(
layout = layoutOf(layoutType),
entities = layeredEntitiesData,
wallpaper = wallpaper,
flooring = flooring,
)
}
Text(
text = wordList.layout(layoutType),
style = MaterialTheme.typography.subtitle2
)
}
}
}
}
| 17
|
Kotlin
|
0
| 3
|
fb2ce5dc14eaad43c9003b84979be998346de2d1
| 3,199
|
stardew-valley-designer
|
Apache License 2.0
|
core/src/commonMain/kotlin/io/data2viz/math/ticks.kt
|
data2viz
| 89,368,762
| false
| null |
/*
* Copyright (c) 2018-2019. data2viz sàrl.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package io.data2viz.math
import kotlin.math.*
val e10: Double by lazy { sqrt(50.0) }
val e5: Double by lazy { sqrt(10.0) }
val e2: Double by lazy { sqrt(2.0) }
val ln10: Double by lazy { ln(10.0) }
fun ticks(start: Double, stop: Double, count: Int): List<Double> {
if (count <= 0) return listOf()
if (start.isNaN() || stop.isNaN()) return listOf()
if (start == stop) return listOf(start)
var from = start
var to = stop
val reverse = to < from
if (reverse) {
val temp = from
from = to
to = temp
}
var step = tickIncrement(from, to, count)
if (step == .0) return listOf()
lateinit var ticks: List<Double>
val range = if (start <= stop) (start..stop) else (stop..start)
if (step > 0) {
from = ceil(from / step)
to = floor(to / step)
val numTicks = ceil(to - from + 1).toInt()
ticks = (0 until numTicks).map { (from + it) * step }.filter { range.contains(it) }
} else {
step = -step
from = floor(from * step)
to = ceil(to * step)
val numTicks = ceil(to - from + 1).toInt()
ticks = (0 until numTicks).map { (from + it) / step }.filter { range.contains(it) }
}
return if (reverse) ticks.reversed() else ticks
}
fun tickIncrement(start: Double, stop: Double, count: Int): Double {
val step = (stop - start) / count
val power = floor(ln(step) / ln10)
val error = step / 10.0.pow(power)
return if (power >= 0) {
getValueForError(error) * 10.0.pow(power)
} else {
-(10.0.pow(-power)) / getValueForError(error)
}
}
fun tickStep(start: Double, stop: Double, count: Int): Double {
val step0 = abs(stop - start) / count
var step1 = 10.0.pow(floor(ln(step0) / ln10))
val error = step0 / step1
step1 *= getValueForError(error)
return if (stop < start) -step1 else step1
}
fun range(start: Double, stop: Double, step: Double = 1.0): List<Double> {
val n = if (step == .0) 0 else maxOf(0, ceil((stop - start) / step).toInt())
return (0 until n).map { start + it * step }
}
private fun getValueForError(error: Double): Int {
return if (error >= e10) 10 else if (error >= e5) 5 else if (error >= e2) 2 else 1
}
| 80
| null |
29
| 400
|
bc4ed872c526264727f868f5127e48462301dbf8
| 2,848
|
data2viz
|
Apache License 2.0
|
browser-kotlin/src/jsMain/kotlin/web/cssom/CSSMathMax.kt
|
karakum-team
| 393,199,102
| false
| null |
// Automatically generated - do not modify!
package web.cssom
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathMax)
*/
external class CSSMathMax(
vararg values: CSSNumberish,
) : CSSMathValue {
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/CSSMathMax/values)
*/
val values: CSSNumericArray
}
| 0
| null |
8
| 36
|
95b065622a9445caf058ad2581f4c91f9e2b0d91
| 360
|
types-kotlin
|
Apache License 2.0
|
data-onecall/src/main/java/de/niklasbednarczyk/nbweather/data/onecall/models/common/WeatherModelData.kt
|
NiklasBednarczyk
| 529,683,941
| false
|
{"Kotlin": 1005119}
|
package de.niklasbednarczyk.nbweather.data.onecall.models.common
import de.niklasbednarczyk.nbweather.core.common.nullsafe.nbNullSafe
import de.niklasbednarczyk.nbweather.data.onecall.local.models.common.WeatherModelLocal
import de.niklasbednarczyk.nbweather.data.onecall.remote.models.common.WeatherModelRemote
import de.niklasbednarczyk.nbweather.data.onecall.types.weather.WeatherConditionType
import de.niklasbednarczyk.nbweather.data.onecall.types.weather.WeatherIconType
data class WeatherModelData(
val icon: WeatherIconType?,
val condition: WeatherConditionType?
) {
internal companion object {
fun localToData(
local: WeatherModelLocal?
): WeatherModelData? {
return nbNullSafe(local) { l ->
WeatherModelData(
icon = WeatherIconType.from(l.icon),
condition = WeatherConditionType.from(l.id)
)
}
}
fun remoteToLocal(
remote: WeatherModelRemote?,
): WeatherModelLocal? {
return nbNullSafe(remote) { r ->
WeatherModelLocal(
id = r.id,
main = r.main,
description = r.description,
icon = r.icon
)
}
}
}
}
| 18
|
Kotlin
|
0
| 1
|
e10dbb86dc6e37eda9dba29dd1ee51aa19c4477d
| 1,335
|
NBWeather
|
MIT License
|
app/src/main/java/com/hoc/comicapp/ui/downloaded_comics/DownloadedComicsFragment.kt
|
ironelder
| 259,572,670
| true
|
{"Kotlin": 416967}
|
package com.hoc.comicapp.ui.downloaded_comics
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import com.chauthai.swipereveallayout.ViewBinderHelper
import com.hoc.comicapp.GlideApp
import com.hoc.comicapp.R
import com.hoc.comicapp.domain.models.getMessage
import com.hoc.comicapp.ui.detail.ComicArg
import com.hoc.comicapp.ui.downloaded_comics.DownloadedComicsContract.SingleEvent
import com.hoc.comicapp.ui.downloaded_comics.DownloadedComicsContract.SortOrder
import com.hoc.comicapp.ui.downloaded_comics.DownloadedComicsContract.ViewIntent
import com.hoc.comicapp.ui.downloaded_comics.DownloadedComicsContract.ViewState.ComicItem
import com.hoc.comicapp.utils.exhaustMap
import com.hoc.comicapp.utils.itemSelections
import com.hoc.comicapp.utils.observe
import com.hoc.comicapp.utils.observeEvent
import com.hoc.comicapp.utils.showAlertDialogAsObservable
import com.hoc.comicapp.utils.snack
import io.reactivex.Observable
import io.reactivex.disposables.CompositeDisposable
import io.reactivex.rxkotlin.addTo
import io.reactivex.rxkotlin.subscribeBy
import kotlinx.android.synthetic.main.fragment_downloaded_comics.*
import org.koin.androidx.viewmodel.ext.android.viewModel
import timber.log.Timber
import com.hoc.comicapp.ui.downloaded_comics.DownloadedComicsFragmentDirections.Companion.actionDownloadedComicsFragmentToComicDetailFragment as toComicDetailFragment
class DownloadedComicsFragment : Fragment() {
private val viewModel by viewModel<DownloadedComicsViewModel>()
private val compositeDisposable = CompositeDisposable()
private val viewBinderHelper = ViewBinderHelper()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return inflater.inflate(R.layout.fragment_downloaded_comics, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val adapter = DownloadedComicsAdapter(
GlideApp.with(this),
viewBinderHelper,
compositeDisposable
)
initView(adapter)
bind(adapter)
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewBinderHelper.restoreStates(savedInstanceState)
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
viewBinderHelper.saveStates(outState)
}
private fun initView(downloadedComicsAdapter: DownloadedComicsAdapter) {
recycler_comics.run {
setHasFixedSize(true)
layoutManager = LinearLayoutManager(context)
adapter = downloadedComicsAdapter
}
spinner_sort.setItems(SortOrder.values().toList())
spinner_sort.selectedIndex = viewModel.state.safeValue?.sortOrder?.let { SortOrder.values().indexOf(it) } ?: 0
downloadedComicsAdapter.clickItem.subscribeBy {
findNavController().navigate(
toComicDetailFragment(
comic = ComicArg(
title = it.title,
thumbnail = it.thumbnail.toRelativeString(requireContext().filesDir),
link = it.comicLink,
view = it.view,
remoteThumbnail = it.remoteThumbnail
),
title = it.title,
isDownloaded = true
)
)
}.addTo(compositeDisposable)
}
private fun bind(adapter: DownloadedComicsAdapter) {
viewModel.state.observe(owner = viewLifecycleOwner) { (isLoading, errorMessage, comics) ->
if (isLoading) {
progress_bar.visibility = View.VISIBLE
} else {
progress_bar.visibility = View.INVISIBLE
}
if (errorMessage == null) {
group_error.visibility = View.GONE
} else {
group_error.visibility = View.VISIBLE
text_error_message.text = errorMessage
}
adapter.submitList(comics)
empty_layout.isVisible = !isLoading && errorMessage === null && comics.isEmpty()
}
viewModel.singleEvent.observeEvent(owner = viewLifecycleOwner) {
when (it) {
is SingleEvent.Message -> {
view?.snack(it.message)
}
is SingleEvent.DeletedComic -> {
view?.snack("Deleted ${it.comic.title}")
}
is SingleEvent.DeleteComicError -> {
view?.snack("Error when deleting ${it.comic.title}, error: ${it.error.getMessage()}")
}
}
}
viewModel.processIntents(
Observable.mergeArray(
Observable.just(ViewIntent.Initial),
spinner_sort
.itemSelections<SortOrder>()
.map { ViewIntent.ChangeSortOrder(it) }
.doOnNext { Timber.d("Sort $it") },
adapter
.clickDelete
.doOnNext { Timber.d("Delete[1] $it") }
.exhaustMap(::showDeleteComicDialog)
.doOnNext { Timber.d("Delete[2] $it") }
.map { ViewIntent.DeleteComic(it) }
)
).addTo(compositeDisposable)
}
override fun onDestroyView() {
super.onDestroyView()
compositeDisposable.clear()
}
private fun showDeleteComicDialog(comic: ComicItem): Observable<ComicItem> {
return requireActivity()
.showAlertDialogAsObservable {
title("Delete comic")
message("All chapter in this comic won't be available to read offline")
cancelable(true)
iconId(R.drawable.ic_delete_white_24dp)
}
.map { comic }
}
}
| 0
| null |
0
| 0
|
aabdac73a86487a89350c8b13ce62c956a70825f
| 5,597
|
ComicReaderApp_MVI_Coroutine_RxKotlin_Jetpack
|
MIT License
|
page/src/main/kotlin/dev/entao/web/page/ext/TagEvents.kt
|
yangentao
| 532,703,720
| false
| null |
package dev.entao.web.page.ext
import dev.entao.web.tag.tag.AnchorTag
import dev.entao.web.tag.tag.ButtonTag
import dev.entao.web.tag.tag.FormTag
import dev.entao.web.tag.tag.script
fun FormTag.needsValidation() {
classAdd("needs-validation")
val formId = this.idx
script {
"""
pagescript.formOnSubmitById('$formId');
""".trimIndent()
}
}
var ButtonTag.dataScript: String
get() = getAttr(PageData.script)
set(value) {
PageData.script attr value
onclick = "pagescript.evalElementAttr('${this.idx}')"
}
var AnchorTag.dataScript: String
get() = getAttr(PageData.script)
set(value) {
PageData.script attr value
onclick = "pagescript.evalElementAttr('${this.idx}');return false;"
}
| 0
|
Kotlin
|
0
| 0
|
f6431e275c77539efb27bde89b0292e0f783413b
| 782
|
WebSweet
|
Apache License 2.0
|
app/src/main/java/com/aqib/chatty/ui/ChattyApp.kt
|
aqib-m31
| 733,899,799
| false
|
{"Kotlin": 99636, "Shell": 1285}
|
package com.aqib.chatty.ui
import android.content.Context
import android.content.Intent
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import com.aqib.chatty.R
import com.aqib.chatty.ui.screens.ChatScreen
import com.aqib.chatty.ui.screens.CreateRoomScreen
import com.aqib.chatty.ui.screens.HomeScreen
import com.aqib.chatty.ui.screens.JoinRoomScreen
import com.aqib.chatty.ui.screens.LoginScreen
import com.aqib.chatty.ui.screens.RegisterScreen
/**
* Enum class representing the different screens in the ChattyApp.
*/
enum class ChattyAppScreen {
Register,
Login,
Home,
CreateRoom,
JoinRoom,
Chat
}
/**
* The main Composable function for the ChattyApp. It sets up the navigation and the top bar.
* It also collects the state from the ViewModel and passes it to the different screens.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChattyApp() {
val viewModel: ChattyAppViewModel = viewModel(factory = ChattyAppViewModel.Factory)
val userState = viewModel.userState.collectAsState()
val chatState = viewModel.chatState.collectAsState()
val chatUiState = viewModel.chatUiState.collectAsState()
val navController = rememberNavController()
Scaffold(
topBar = {
TopAppBar(
title = {
Row(
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically
) {
Image(
painter = painterResource(id = R.drawable.chatty),
contentDescription = null,
modifier = Modifier.size(35.dp)
)
Text(
text = stringResource(id = R.string.app_name),
fontWeight = FontWeight.Bold
)
Spacer(modifier = Modifier.weight(1f))
if (userState.value.authenticated && !userState.value.joinedRoom) {
TextButton(onClick = {
viewModel.logout()
}) {
Text(text = "Logout")
}
}
}
}
)
}
) { innerPadding ->
// Navigation setup
NavHost(
navController = navController,
startDestination = if (userState.value.authenticated) ChattyAppScreen.Home.name else ChattyAppScreen.Login.name
) {
composable(route = ChattyAppScreen.Register.name) {
RegisterScreen(
navigateLoginScreen = { navController.navigate(ChattyAppScreen.Login.name) },
authenticate = viewModel::authenticate,
modifier = Modifier.padding(innerPadding)
)
}
composable(route = ChattyAppScreen.Login.name) {
LoginScreen(
navigateRegisterScreen = { navController.navigate(ChattyAppScreen.Register.name) },
authenticate = viewModel::authenticate,
modifier = Modifier.padding(innerPadding)
)
}
composable(route = ChattyAppScreen.Home.name) {
val context = LocalContext.current
HomeScreen(
username = userState.value.username,
navigateToJoinRoomScreen = {
navController.navigate(
route = ChattyAppScreen.JoinRoom.name
)
},
navigateToCreateRoomScreen = {
navController.navigate(
route = ChattyAppScreen.CreateRoom.name
)
},
contentPadding = innerPadding,
rooms = userState.value.joinedRooms,
onJoinRoom = viewModel::joinRoom,
onDeleteRoom = viewModel::deleteRoom,
isJoined = viewModel::isJoined,
onShare = { subject: String, roomId: String ->
shareRoomId(context = context, subject = subject, roomId = roomId)
},
message = userState.value.homeScreenMessage
)
}
composable(route = ChattyAppScreen.CreateRoom.name) {
CreateRoomScreen(
roomName = userState.value.newRoomName,
onRoomNameChange = viewModel::updateNewRoomName,
onCreateRoom = viewModel::createRoom,
message = userState.value.message,
)
}
composable(route = ChattyAppScreen.JoinRoom.name) {
JoinRoomScreen(
roomId = userState.value.joinedRoomId,
onRoomIdChange = viewModel::updateJoinedRoomId,
onJoinRoom = viewModel::joinRoom,
message = userState.value.message
)
}
composable(route = ChattyAppScreen.Chat.name) {
BackHandler(true) {
navController.navigate(route = ChattyAppScreen.Home.name)
viewModel.setJoinedToFalse()
}
ChatScreen(
roomName = userState.value.joinedRoomName,
messages = chatState.value.currentRoomMessages,
currentMessage = chatUiState.value.currentMessage,
onMessageChange = viewModel::updateCurrentMessage,
onSend = viewModel::sendMessage,
contentPadding = innerPadding,
onLeave = {
viewModel.leaveRoom()
navController.navigate(route = ChattyAppScreen.Home.name)
},
navigateToHomeScreen = {
navController.navigate(route = ChattyAppScreen.Home.name)
viewModel.setJoinedToFalse()
}
)
}
}
if (userState.value.joinedRoom) {
navController.navigate(route = ChattyAppScreen.Chat.name)
}
}
}
/**
* Function for sharing the room ID. It creates an intent for sharing text and starts the activity.
*
* @param context The context to use for starting the activity.
* @param subject The subject of the sharing intent.
* @param roomId The room ID to share.
*/
private fun shareRoomId(context: Context, subject: String, roomId: String) {
val intent = Intent(Intent.ACTION_SEND).apply {
type = "text/plain"
putExtra(Intent.EXTRA_SUBJECT, subject)
putExtra(Intent.EXTRA_TEXT, roomId)
}
context.startActivity(Intent.createChooser(intent, "Room Invitation"))
}
| 0
|
Kotlin
|
0
| 6
|
79ae7c4331eed9c434c2fe390a2bc28234112dfc
| 8,134
|
Chatty
|
MIT License
|
app/src/main/java/com/example/androiddevchallenge/models/Pet.kt
|
Varsha-Kulkarni
| 342,268,961
| false
| null |
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.models
import androidx.annotation.DrawableRes
import androidx.compose.runtime.Immutable
@Immutable
data class Pet(
val petId: Int,
val name: String,
val sex: String,
val age: String,
val characteristics: List<String>,
@DrawableRes val imageResource: Int,
val publisher: String,
val breed: String,
val breedDetails: String
)
| 0
|
Kotlin
|
0
| 1
|
d2de368010ecf69b0b859fa90664294d3a40c856
| 1,018
|
AdoptMe
|
Apache License 2.0
|
app/src/main/java/com/borabor/movieapp/domain/usecase/GetSearchResults.kt
|
bbor98
| 510,432,451
| false
|
{"Kotlin": 205881}
|
package com.borabor.movieapp.domain.usecase
import com.borabor.movieapp.domain.repository.MovieRepository
import com.borabor.movieapp.domain.repository.PersonRepository
import com.borabor.movieapp.domain.repository.TvRepository
import com.borabor.movieapp.util.Constants
import com.borabor.movieapp.util.Detail
import com.borabor.movieapp.util.Resource
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import javax.inject.Inject
class GetSearchResults @Inject constructor(
private val movieRepository: MovieRepository,
private val tvRepository: TvRepository,
private val personRepository: PersonRepository
) {
operator fun invoke(
detailType: Detail,
query: String,
page: Int
): Flow<Resource<Any>> = flow {
emit(
when (detailType) {
Detail.MOVIE -> movieRepository.getMovieSearchResults(query, page)
Detail.TV -> tvRepository.getTvSearchResults(query, page)
Detail.PERSON -> personRepository.getPersonSearchResults(query, page)
else -> throw IllegalArgumentException(Constants.ILLEGAL_ARGUMENT_DETAIL_TYPE)
}
)
}
}
| 0
|
Kotlin
|
4
| 15
|
369393ac387ed6c1c30939831b60c78b51f6f56a
| 1,192
|
movieapp-mvvm-clean-architecture
|
MIT License
|
app/src/main/java/org/tuerantuer/launcher/ui/components/SettingsSwitch.kt
|
digitalfabrik
| 522,865,990
| false
| null |
package org.tuerantuer.launcher.ui.components
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.selection.toggleable
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.semantics.Role
import androidx.compose.ui.unit.dp
/**
* A switch with a [title] and an optional [description].
*/
@Composable
fun SettingSwitchItem(
modifier: Modifier = Modifier,
checked: Boolean,
onCheckedChange: (Boolean) -> Unit,
title: String,
description: String? = null,
enabled: Boolean = true,
) {
Row(
modifier = modifier
.fillMaxWidth()
.toggleable(
value = checked,
enabled = enabled,
role = Role.Switch,
onValueChange = onCheckedChange,
),
verticalAlignment = Alignment.CenterVertically,
) {
Column(
modifier = Modifier
.weight(1.0f)
.padding(horizontal = 16.dp, vertical = 16.dp),
verticalArrangement = Arrangement.spacedBy(8.dp),
) {
val contentAlpha = if (enabled) 1.0f else 0.38f
Text(
text = title,
style = MaterialTheme.typography.bodyLarge,
)
if (description != null) {
Text(
text = description,
style = MaterialTheme.typography.bodyMedium,
modifier = Modifier.alpha(contentAlpha),
)
}
}
Switch(
modifier = Modifier.padding(end = 16.dp),
checked = checked,
onCheckedChange = null,
enabled = enabled,
)
}
}
| 6
| null |
0
| 8
|
ef7ed60e78e2326ef93c7fddabcbc538d57e35ac
| 2,174
|
accessibility-launcher
|
Apache License 2.0
|
hello-grpc-kotlin/stub/src/main/kotlin/org/feuyeux/grpc/conn/Connection.kt
|
feuyeux
| 406,614,264
| false
|
{"JavaScript": 72419, "Shell": 69280, "Swift": 54396, "Dart": 49900, "Java": 41928, "Go": 35972, "C++": 22657, "Rust": 21675, "Python": 19876, "Kotlin": 19251, "C#": 19091, "Dockerfile": 14975, "TypeScript": 10902, "PHP": 9842, "CMake": 7066, "Batchfile": 266}
|
package org.feuyeux.grpc.conn
import io.grpc.ClientInterceptor
import io.grpc.ManagedChannel
import io.grpc.ManagedChannelBuilder
import io.grpc.netty.GrpcSslContexts
import io.grpc.netty.NegotiationType
import io.grpc.netty.NettyChannelBuilder
import io.netty.handler.ssl.SslContext
import io.netty.handler.ssl.SslContextBuilder
import org.apache.logging.log4j.kotlin.logger
import java.io.File
import javax.net.ssl.SSLException
object Connection {
private val log = logger()
//https://myssl.com/create_test_cert.html
private const val cert = "/var/hello_grpc/client_certs/cert.pem"
private const val certKey = "/var/hello_grpc/client_certs/private.pkcs8.key"
private const val certChain = "/var/hello_grpc/client_certs/full_chain.pem"
private const val rootCert = "/var/hello_grpc/client_certs/myssl_root.cer"
private const val serverName = "hello.grpc.io"
val port = System.getenv("GRPC_SERVER_PORT")?.toInt() ?: 9996
@Throws(SSLException::class)
private fun buildSslContext(): SslContext {
val builder: SslContextBuilder = GrpcSslContexts.forClient()
builder.trustManager(File(rootCert))
builder.keyManager(File(certChain), File(certKey))
return builder.build()
}
fun getChannel(clientInterceptor: ClientInterceptor): ManagedChannel {
val backend = System.getenv("GRPC_HELLO_BACKEND")
val grcServer = System.getenv("GRPC_SERVER") ?: "localhost"
val host = backend ?: grcServer
val secure = System.getenv("GRPC_HELLO_SECURE")
val serverPort = getServerPort()
return if (secure == null || secure != "Y") {
log.info("Connect With InSecure(:$serverPort)")
ManagedChannelBuilder.forAddress(host, serverPort)
.usePlaintext()
.intercept(clientInterceptor)
.build()
} else {
log.info("Connect With TLS(:$serverPort)")
NettyChannelBuilder.forAddress(host, serverPort)
.overrideAuthority(serverName) /* Only for using provided test certs. */
.sslContext(buildSslContext())
.negotiationType(NegotiationType.TLS)
.intercept(clientInterceptor)
.build()
}
}
fun getServerPort() = (System.getenv("GRPC_HELLO_BACKEND_PORT")?.toInt()
?: System.getenv("GRPC_SERVER_PORT")?.toInt() ?: port)
}
| 0
|
JavaScript
|
0
| 9
|
c985bd5a8a7e119ba152fa7a4aad7d3a9e17efaf
| 2,456
|
hello-grpc
|
Apache License 2.0
|
core/src/main/java/tachiyomi/core/util/lang/BooleanExtensions.kt
|
aniyomiorg
| 358,887,741
| false
|
{"Kotlin": 4787748}
|
package tachiyomi.core.util.lang
fun Boolean.toLong() = if (this) 1L else 0L
| 232
|
Kotlin
|
270
| 4,425
|
e1087abfb68988d21cd3d80253ee955b2d58cd05
| 78
|
aniyomi
|
Apache License 2.0
|
core/src/main/java/threads4j/model/ThreadsUser.kt
|
takke
| 817,329,095
| false
|
{"Kotlin": 21978}
|
package threads4j.model
import com.google.gson.annotations.SerializedName
data class ThreadsUser(
@SerializedName("id")
val id: String,
@SerializedName("username")
val username: String? = null,
@SerializedName("threads_profile_picture_url")
val threadsProfilePictureUrl: String? = null,
@SerializedName("threads_biography")
val threadsBiography: String? = null
)
| 0
|
Kotlin
|
0
| 2
|
dace2b203387378643c4107b132a0947cb9176f9
| 397
|
threads4j
|
MIT License
|
build-logic/convention/src/main/kotlin/com/autonomousapps/convention/ConventionPlugin.kt
|
autonomousapps
| 217,134,508
| false
| null |
package com.autonomousapps.convention
import nexus.Credentials
import nexus.NexusPublishTask
import org.gradle.api.Action
import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.artifacts.VersionCatalogsExtension
import org.gradle.api.plugins.JavaPluginExtension
import org.gradle.api.provider.Provider
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPom
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.tasks.testing.Test
import org.gradle.jvm.toolchain.JavaLanguageVersion
import org.gradle.plugin.devel.GradlePluginDevelopmentExtension
import org.gradle.plugins.signing.Sign
import org.gradle.plugins.signing.SigningExtension
import java.util.Locale
@Suppress("unused")
class ConventionPlugin : Plugin<Project> {
override fun apply(target: Project): Unit = target.run {
pluginManager.apply("org.jetbrains.kotlin.jvm")
pluginManager.apply("org.gradle.maven-publish")
pluginManager.apply("org.gradle.signing")
group = "com.autonomousapps"
val convention = ConventionExtension.of(this)
val isSnapshot = convention.isSnapshot
val publishedVersion = convention.publishedVersion
val versionCatalog = extensions.getByType(VersionCatalogsExtension::class.java).named("libs")
val signing = extensions.getByType(SigningExtension::class.java)
val publishing = extensions.getByType(PublishingExtension::class.java)
val publishToMavenCentral = tasks.register("publishToMavenCentral")
extensions.configure(JavaPluginExtension::class.java) { j ->
j.withJavadocJar()
j.withSourcesJar()
j.toolchain {
it.languageVersion.set(
JavaLanguageVersion.of(versionCatalog.findVersion("java").orElseThrow().requiredVersion)
)
}
}
// We only use the Jupiter platform (JUnit 5)
configurations.all {
it.exclude(mapOf("group" to "junit", "module" to "junit"))
it.exclude(mapOf("group" to "org.junit.vintage", "module" to "junit-vintage-engine"))
}
tasks.withType(Test::class.java).configureEach {
it.useJUnitPlatform()
}
afterEvaluate {
val isPluginProject = pluginManager.hasPlugin("java-gradle-plugin")
if (isPluginProject) {
// For plugin projects, the task name is different because one gets added automatically with a publication named
// "pluginMaven".
publishToMavenCentral.configure {
it.dependsOn("publishPluginMavenPublicationTo$SONATYPE_REPO_SUFFIX")
}
} else {
// Not a plugin project. We don't need this publication for the plugin itself, because it already exists.
publishing.publications.create(MAVEN_PUB_NAME, MavenPublication::class.java) { p ->
p.from(project.components.getAt("java"))
}
publishToMavenCentral.configure {
it.dependsOn("publish${MAVEN_PUB_NAME.capitalizeSafely()}PublicationTo$SONATYPE_REPO_SUFFIX")
}
}
publishing.publications.all { pub ->
signing.sign(pub)
// Some weird behavior with the `com.gradle.plugin-publish` plugin.
// I need to do this in afterEvaluate or it breaks.
convention.pomConfiguration?.let { configure ->
if (pub is MavenPublication) {
setupPom(pub.pom, configure)
}
}
}
}
val promoteTask = tasks.register("promote", NexusPublishTask::class.java) {
it.onlyIf { !isSnapshot.get() }
it.configureWith(Credentials(project))
}
publishToMavenCentral.configure { t ->
with(t) {
inputs.property("is-snapshot", isSnapshot)
finalizedBy(promoteTask)
group = "publishing"
doLast {
if (isSnapshot.get()) {
logger.quiet("Browse files at https://oss.sonatype.org/content/repositories/snapshots/com/autonomousapps/")
} else {
logger.quiet(
"After publishing to Sonatype, visit https://oss.sonatype.org to close and release from staging"
)
}
}
}
}
// Used to set the description dynamically
convention.setPublishToMavenCentral(publishToMavenCentral)
//pluginManager.withPlugin("com.gradle.plugin-publish")
pluginManager.withPlugin("java-gradle-plugin") {
extensions.getByType(GradlePluginDevelopmentExtension::class.java).plugins.all { pluginConfig ->
publishToMavenCentral.configure { t ->
// e.g. publishDependencyAnalysisPluginPluginMarkerMavenPublicationToSonatypeRepository
t.dependsOn(
"publish${pluginConfig.name.capitalizeSafely()}PluginMarkerMavenPublicationTo$SONATYPE_REPO_SUFFIX"
)
}
}
}
val isRunningTests = objects.property(Boolean::class.java).convention(false)
gradle.taskGraph.whenReady { g ->
g.allTasks.any { t ->
t.name.contains("functionalTest")
}.also {
isRunningTests.set(it)
}
}
val isCi: Provider<Boolean> = providers
.environmentVariable("CI")
.orElse("false")
.map { it.toBoolean() }
tasks.withType(Sign::class.java).configureEach { t ->
with(t) {
inputs.property("version", publishedVersion)
inputs.property("is-ci", isCi)
inputs.property("is-running-tests", isRunningTests)
// Don't sign snapshots
onlyIf("Not a snapshot") { !isSnapshot.get() }
// We currently don't support publishing from CI
onlyIf("release environment") { !isCi.get() }
// Don't sign tests
onlyIf("not running tests") { !isRunningTests.get() }
doFirst {
logger.quiet("Signing v${publishedVersion.get()}")
}
}
}
// TODO do this?
//publishing {
// publications {
// create<MavenPublication>("truth") {
// from(components["java"])
// configurePom(pom)
// signing.sign(this)
//
// versionMapping {
// usage("java-api") {
// fromResolutionOf("runtimeClasspath")
// }
// usage("java-runtime") {
// fromResolutionResult()
// }
// }
// }
// }
//}
}
private fun setupPom(pom: MavenPom, configure: Action<MavenPom>) {
pom.run {
url.set("https://github.com/autonomousapps/dependency-analysis-android-gradle-plugin")
inceptionYear.set("2022")
licenses {
it.license { l ->
l.name.set("The Apache License, Version 2.0")
l.url.set("https://www.apache.org/licenses/LICENSE-2.0.txt")
}
}
developers {
it.developer { d ->
d.id.set("autonomousapps")
d.name.set("Tony Robalik")
}
}
scm {
it.connection.set("scm:git:git://github.com/autonomousapps/dependency-analysis-android-gradle-plugin.git")
it.developerConnection.set(
"scm:git:ssh://github.com/autonomousapps/dependency-analysis-android-gradle-plugin.git"
)
it.url.set("https://github.com/autonomousapps/dependency-analysis-android-gradle-plugin")
}
}
configure.execute(pom)
}
internal companion object {
const val MAVEN_PUB_NAME = "maven"
const val SONATYPE_REPO_NAME = "sonatype"
val SONATYPE_REPO_SUFFIX = "${SONATYPE_REPO_NAME.capitalizeSafely()}Repository"
}
}
// copied from StringsJVM.kt
private fun String.capitalizeSafely(locale: Locale = Locale.ROOT): String {
if (isNotEmpty()) {
val firstChar = this[0]
if (firstChar.isLowerCase()) {
return buildString {
val titleChar = firstChar.titlecaseChar()
if (titleChar != firstChar.uppercaseChar()) {
append(titleChar)
} else {
append(this@capitalizeSafely.substring(0, 1).uppercase(locale))
}
append(this@capitalizeSafely.substring(1))
}
}
}
return this
}
| 93
| null |
99
| 910
|
da02a56a0b7a00a26876cdaa29321f8376bf7099
| 7,916
|
dependency-analysis-android-gradle-plugin
|
Apache License 2.0
|
identity-sample/src/main/java/io/falu/identity/VerificationViewModel.kt
|
faluapp
| 345,511,436
| false
| null |
package io.falu.identity
import android.app.Application
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.liveData
import io.falu.identity.models.IdentityVerification
import io.falu.identity.models.IdentityVerificationCreationRequest
import io.falu.identity.models.IdentityVerificationOptions
import io.falu.identity.models.IdentityVerificationOptionsForDocument
import io.falu.identity.models.IdentityVerificationOptionsForIdNumber
import io.falu.identity.models.IdentityVerificationOptionsForSelfie
import io.falu.identity.sample.BuildConfig
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.logging.HttpLoggingInterceptor
import software.tingle.api.AbstractHttpApiClient
import software.tingle.api.ResourceResponse
import software.tingle.api.authentication.EmptyAuthenticationProvider
import java.util.concurrent.TimeUnit
class VerificationViewModel(application: Application) : AndroidViewModel(application) {
private val apiClient = ApiClient()
fun requestIdentityVerification(
allowDrivingLicense: Boolean,
allowPassport: Boolean,
allowIdentityCard: Boolean,
allowUploads: Boolean,
allowDocumentSelfie: Boolean,
allowIdNumberVerification: Boolean
) = liveData {
val request = IdentityVerificationCreationRequest(
options = IdentityVerificationOptions(
allowUploads = allowUploads,
document = if (allowDrivingLicense || allowPassport || allowIdentityCard)
generateDocumentOptions(
allowDrivingLicense,
allowPassport,
allowIdentityCard
) else null,
selfie = if (allowDocumentSelfie) IdentityVerificationOptionsForSelfie() else null,
idNumber = if (allowIdNumberVerification) IdentityVerificationOptionsForIdNumber() else null
),
type = getVerificationType(allowDocumentSelfie, allowIdNumberVerification)
)
val response = apiClient.createIdentityVerification(request)
emit(response)
}
private fun generateDocumentOptions(
allowDrivingLicense: Boolean,
allowPassport: Boolean,
allowIdentityCard: Boolean
): IdentityVerificationOptionsForDocument {
return IdentityVerificationOptionsForDocument(
allowed = mutableListOf<String>().also {
if (allowDrivingLicense) it.add(ALLOWED_TYPE_DRIVING_LICENSE)
if (allowPassport) it.add(ALLOWED_TYPE_PASSPORT)
if (allowIdentityCard) it.add(ALLOWED_TYPE_ID_CARD)
}
)
}
private fun getVerificationType(
requireMatchingSelfie: Boolean,
allowIdNumberVerification: Boolean
): String {
return if (requireMatchingSelfie && !allowIdNumberVerification) {
VERIFICATION_TYPE_DOCUMENT_AND_SELFIE
} else if (allowIdNumberVerification) {
VERIFICATION_TYPE_ID_NUMBER
} else {
VERIFICATION_TYPE_DOCUMENT
}
}
companion object {
const val ALLOWED_TYPE_DRIVING_LICENSE = "driving_license"
const val ALLOWED_TYPE_PASSPORT = "passport"
const val ALLOWED_TYPE_ID_CARD = "id_card"
const val VERIFICATION_TYPE_DOCUMENT = "document"
const val VERIFICATION_TYPE_DOCUMENT_AND_SELFIE = "document_and_selfie"
const val VERIFICATION_TYPE_ID_NUMBER = "id_number"
}
}
class ApiClient : AbstractHttpApiClient(EmptyAuthenticationProvider()) {
suspend fun createIdentityVerification(request: IdentityVerificationCreationRequest): ResourceResponse<IdentityVerification> {
val builder = Request.Builder()
.url("https://identity-verification.hst-smpls.falu.io/identity/create-verification/")
.post(makeJson(request).toRequestBody(MEDIA_TYPE_JSON))
return executeAsync(builder, IdentityVerification::class.java)
}
override fun buildBackChannel(builder: OkHttpClient.Builder): OkHttpClient {
builder
.followRedirects(false)
.connectTimeout(30, TimeUnit.SECONDS) // default is 30 seconds
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
if (BuildConfig.DEBUG) {
builder.addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
}
return super.buildBackChannel(builder)
}
}
| 4
| null |
0
| 1
|
7e029bde160f676bc2d4dfe86c355aa23af8ce7d
| 4,549
|
falu-android
|
MIT License
|
Library/base/src/main/kotlin/com/existing/boilerx/core/base/view/SystemUISpaceView.kt
|
THE-EXISTING
| 176,088,785
| false
| null |
package com.existing.boilerx.core.base.view
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Rect
import android.os.Build
import android.util.AttributeSet
import android.view.View
import android.view.WindowInsets
import androidx.annotation.RequiresApi
import com.existing.boilerx.core.R
/**
* Created by <NAME> on 21 Apr 2018 :)
*/
class SystemUISpaceView : View {
companion object {
const val TOP = 0
const val LEFT = 1
const val RIGHT = 2
const val BOTTOM = 3
}
var topSystemUI: Int = 0
var bottomSystemUI: Int = 0
var leftSystemUI: Int = 0
var rightSystemUI: Int = 0
var isConsumedInsets: Boolean = false
var systemUI: Int = TOP
@JvmOverloads
constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0)
: super(context, attrs, defStyleAttr) {
setupStyleables(attrs, defStyleAttr, 0)
}
@SuppressLint("NewApi")
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int)
: super(context, attrs, defStyleAttr, defStyleRes) {
setupStyleables(attrs, defStyleAttr, defStyleRes)
}
@Suppress("UNUSED_PARAMETER")
protected fun setupStyleables(attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) {
attrs?.let {
val attrArray = context.obtainStyledAttributes(attrs, R.styleable.SystemUISpaceView, defStyleRes, 0)
isConsumedInsets = attrArray.getBoolean(R.styleable.SystemUISpaceView_isConsumeInsets, false)
systemUI = attrArray.getInt(R.styleable.SystemUISpaceView_systemUI, TOP)
attrArray.recycle()
}
}
@Suppress("OverridingDeprecatedMember")
override
fun fitSystemWindows(insets: Rect): Boolean {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT_WATCH) {
topSystemUI = insets.top
leftSystemUI = insets.left
rightSystemUI = insets.right
bottomSystemUI = insets.bottom
}
return isConsumedInsets
}
@SuppressLint("NewApi")
@RequiresApi(Build.VERSION_CODES.KITKAT_WATCH)
override
fun onApplyWindowInsets(insets: WindowInsets?): WindowInsets {
topSystemUI = insets?.systemWindowInsetTop ?: 0
leftSystemUI = insets?.systemWindowInsetLeft ?: 0
rightSystemUI = insets?.systemWindowInsetRight ?: 0
bottomSystemUI = insets?.systemWindowInsetBottom ?: 0
return if (isConsumedInsets) {
super.onApplyWindowInsets(insets?.consumeSystemWindowInsets())
} else {
super.onApplyWindowInsets(insets)
}
}
override
fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
var newHeightMeasureSpec = 0
var newWidthMeasureSpec = 0
var width = 0
var height = 0
when (systemUI) {
TOP -> {
width = View.MeasureSpec.getSize(widthMeasureSpec)
height = topSystemUI
newWidthMeasureSpec = widthMeasureSpec
newHeightMeasureSpec = View.MeasureSpec.makeMeasureSpec(
topSystemUI,
View.MeasureSpec.EXACTLY
)
}
LEFT -> {
width = leftSystemUI
height = View.MeasureSpec.getSize(heightMeasureSpec)
newWidthMeasureSpec = View.MeasureSpec.makeMeasureSpec(
leftSystemUI,
View.MeasureSpec.EXACTLY
)
newHeightMeasureSpec = heightMeasureSpec
}
RIGHT -> {
width = rightSystemUI
height = View.MeasureSpec.getSize(heightMeasureSpec)
newWidthMeasureSpec = View.MeasureSpec.makeMeasureSpec(
rightSystemUI,
View.MeasureSpec.EXACTLY
)
newHeightMeasureSpec = heightMeasureSpec
}
BOTTOM -> {
width = View.MeasureSpec.getSize(widthMeasureSpec)
height = bottomSystemUI
newWidthMeasureSpec = widthMeasureSpec
newHeightMeasureSpec = View.MeasureSpec.makeMeasureSpec(
bottomSystemUI,
View.MeasureSpec.EXACTLY
)
}
}
super.onMeasure(newWidthMeasureSpec, newHeightMeasureSpec)
setMeasuredDimension(width, height)
}
}
| 1
| null |
36
| 2
|
6483e245ea45db0c8642b30366d6a81e86d8b48d
| 4,573
|
boilerx-android-architecture
|
Apache License 2.0
|
app/src/main/java/com/example/beering/feature/auth/join/domain/JoinRepository.kt
|
Beering-KUIT
| 659,221,278
| false
|
{"Kotlin": 234542, "HTML": 25307}
|
package com.example.beering.feature.auth.join.domain
import com.example.beering.data.ApiResult
import com.example.beering.data.auth.dto.CheckIdResult
import com.example.beering.data.auth.dto.CheckNameResult
import com.example.beering.data.auth.dto.JoinAgreements
import com.example.beering.data.auth.dto.JoinRequest
import com.example.beering.data.auth.dto.JoinResponse
import com.example.beering.util.base.BaseResponse
interface UserRepository {
suspend fun checkId(id : String) : ApiResult<BaseResponse<CheckIdResult>>
suspend fun checkNickName(name : String) : ApiResult<BaseResponse<CheckNameResult>>
suspend fun requestJoin(joinRequest: JoinRequest) : ApiResult<BaseResponse<JoinResponse>>
}
| 5
|
Kotlin
|
5
| 0
|
e521263ec1c001e4369ee1f94227d8610b54b5dd
| 710
|
Beering-Android
|
MIT License
|
app/src/main/kotlin/com/duongkhai/snakegame/data/repository/IRepository.kt
|
duongkhaineverdie
| 784,021,262
| false
|
{"Kotlin": 60320}
|
package com.duongkhai.snakegame.data.repository
import com.duongkhai.snakegame.data.model.IPLocation
import com.duongkhai.snakegame.data.model.RemoteConfigs
import com.duongkhai.snakegame.data.model.SecretKey
import kotlinx.coroutines.flow.Flow
interface IRepository {
suspend fun getDetailIPLocation(secretKey: SecretKey): IPLocation
fun initConfigs()
fun getConfigs(): Flow<RemoteConfigs>
}
| 0
|
Kotlin
|
0
| 0
|
25aad736e4ddd449be826a93bda8d5997dc1b77b
| 407
|
SnakeWebview
|
MIT License
|
compiler/ir/backend.wasm/src/org/jetbrains/kotlin/backend/wasm/lower/WasmInlineFunctionResolver.kt
|
JetBrains
| 3,432,266
| false
| null |
/*
* Copyright 2010-2023 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.backend.wasm.lower
import org.jetbrains.kotlin.backend.common.lower.inline.InlineFunctionResolverReplacingCoroutineIntrinsics
import org.jetbrains.kotlin.backend.wasm.WasmBackendContext
import org.jetbrains.kotlin.ir.symbols.IrFunctionSymbol
class WasmInlineFunctionResolver(context: WasmBackendContext) : InlineFunctionResolverReplacingCoroutineIntrinsics(context) {
private val enumEntriesIntrinsic = context.wasmSymbols.enumEntriesIntrinsic
override fun shouldExcludeFunctionFromInlining(symbol: IrFunctionSymbol): Boolean {
// TODO: After the expect fun enumEntriesIntrinsic become non-inline function, the code will be removed
return symbol == enumEntriesIntrinsic || super.shouldExcludeFunctionFromInlining(symbol)
}
}
| 184
| null |
5771
| 49,172
|
33eb9cef3d146062c103f9853d772f0a1da0450e
| 994
|
kotlin
|
Apache License 2.0
|
incubator.clients.kroviz/src/test/kotlin/org/apache/isis/client/kroviz/snapshots/demo2_0_0/DEMO_FILE_NODE.kt
|
joerg-rade
| 163,651,410
| false
| null |
package org.apache.isis.client.kroviz.snapshots.demo2_0_0
import org.apache.isis.client.kroviz.snapshots.Response
object DEMO_FILE_NODE : Response() {
override val url = "http://localhost:8080/restful/domain-types/demo.FileNode"
override val str = """
{
"links": [
{
"rel": "self",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\""
},
{
"rel": "urn:org.apache.isis.restfulobjects:rels/layout",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/layout",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/layout-bs3\""
}
],
"canonicalName": "demoapp.dom.tree.FileNode",
"members": [
{
"rel": "urn:org.restfulobjects:rels/property",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/properties/parent",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\""
},
{
"rel": "urn:org.restfulobjects:rels/property",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/properties/path",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\""
},
{
"rel": "urn:org.restfulobjects:rels/property",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/properties/type",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\""
},
{
"rel": "urn:org.restfulobjects:rels/action",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/actions/rebuildMetamodel",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\""
},
{
"rel": "urn:org.restfulobjects:rels/action",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/actions/openRestApi",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\""
},
{
"rel": "urn:org.restfulobjects:rels/action",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/actions/downloadMetaModelXml",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\""
},
{
"rel": "urn:org.restfulobjects:rels/action",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/actions/downloadLayoutXml",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\""
},
{
"rel": "urn:org.restfulobjects:rels/action",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/actions/clearHints",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\""
}
],
"typeActions": [
{
"rel": "urn:org.restfulobjects:rels/invoke;typeaction=\"isSubtypeOf\"",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/type-actions/isSubtypeOf/invoke",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/type-action-result\"",
"arguments": {
"supertype": {
"href": null
}
}
},
{
"rel": "urn:org.restfulobjects:rels/invoke;typeaction=\"isSupertypeOf\"",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/type-actions/isSupertypeOf/invoke",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/type-action-result\"",
"arguments": {
"subtype": {
"href": null
}
}
}
],
"extensions": {
"friendlyName": "File Node",
"pluralName": "File Nodes",
"isService": false
}
}
"""
}
| 20
| null |
1
| 10
|
07e7ed9aa6dabc7e8a9a0100451d89ae18e46950
| 4,534
|
kroviz
|
Apache License 2.0
|
incubator.clients.kroviz/src/test/kotlin/org/apache/isis/client/kroviz/snapshots/demo2_0_0/DEMO_FILE_NODE.kt
|
joerg-rade
| 163,651,410
| false
| null |
package org.apache.isis.client.kroviz.snapshots.demo2_0_0
import org.apache.isis.client.kroviz.snapshots.Response
object DEMO_FILE_NODE : Response() {
override val url = "http://localhost:8080/restful/domain-types/demo.FileNode"
override val str = """
{
"links": [
{
"rel": "self",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/domain-type\""
},
{
"rel": "urn:org.apache.isis.restfulobjects:rels/layout",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/layout",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/layout-bs3\""
}
],
"canonicalName": "demoapp.dom.tree.FileNode",
"members": [
{
"rel": "urn:org.restfulobjects:rels/property",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/properties/parent",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\""
},
{
"rel": "urn:org.restfulobjects:rels/property",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/properties/path",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\""
},
{
"rel": "urn:org.restfulobjects:rels/property",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/properties/type",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/property-description\""
},
{
"rel": "urn:org.restfulobjects:rels/action",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/actions/rebuildMetamodel",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\""
},
{
"rel": "urn:org.restfulobjects:rels/action",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/actions/openRestApi",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\""
},
{
"rel": "urn:org.restfulobjects:rels/action",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/actions/downloadMetaModelXml",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\""
},
{
"rel": "urn:org.restfulobjects:rels/action",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/actions/downloadLayoutXml",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\""
},
{
"rel": "urn:org.restfulobjects:rels/action",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/actions/clearHints",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/action-description\""
}
],
"typeActions": [
{
"rel": "urn:org.restfulobjects:rels/invoke;typeaction=\"isSubtypeOf\"",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/type-actions/isSubtypeOf/invoke",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/type-action-result\"",
"arguments": {
"supertype": {
"href": null
}
}
},
{
"rel": "urn:org.restfulobjects:rels/invoke;typeaction=\"isSupertypeOf\"",
"href": "http://localhost:8080/restful/domain-types/demo.FileNode/type-actions/isSupertypeOf/invoke",
"method": "GET",
"type": "application/json;profile=\"urn:org.restfulobjects:repr-types/type-action-result\"",
"arguments": {
"subtype": {
"href": null
}
}
}
],
"extensions": {
"friendlyName": "File Node",
"pluralName": "File Nodes",
"isService": false
}
}
"""
}
| 20
| null |
1
| 10
|
07e7ed9aa6dabc7e8a9a0100451d89ae18e46950
| 4,534
|
kroviz
|
Apache License 2.0
|
app/src/main/java/volovyk/thenullpointer/ui/MainScreen.kt
|
oleksandrvolovyk
| 706,337,016
| false
|
{"Kotlin": 45835}
|
package volovyk.thenullpointer.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import volovyk.thenullpointer.data.entity.UploadedFile
import volovyk.thenullpointer.data.remote.entity.FileUploadState
import volovyk.thenullpointer.ui.filelist.FileList
import volovyk.thenullpointer.ui.fileuploadstatelist.FileUploadStateList
import volovyk.thenullpointer.ui.theme.AppTheme
import java.util.Date
@Composable
fun MainScreen(
uiState: MainUiState,
onFileClick: (UploadedFile) -> Unit,
onShareButtonClick: (UploadedFile) -> Unit,
onOpenButtonClick: (UploadedFile) -> Unit,
onDeleteButtonClick: (UploadedFile) -> Unit,
onUploadFileFabClick: () -> Unit,
onFileUploadStateClick: (FileUploadState) -> Unit
) {
Column(verticalArrangement = Arrangement.SpaceBetween) {
Column(horizontalAlignment = Alignment.End, modifier = Modifier.weight(1f).fillMaxWidth()) {
// Display files
Box(modifier = Modifier.weight(1f)) {
FileList(
files = uiState.files,
onItemClick = onFileClick,
onItemShareButtonClick = onShareButtonClick,
onItemOpenButtonClick = onOpenButtonClick,
onItemDeleteButtonClick = onDeleteButtonClick
)
}
// Display "Upload file" FAB
UploadFileFab(
onClick = onUploadFileFabClick
)
}
// Display file upload states
FileUploadStateList(
fileUploadStates = uiState.fileUploadState,
onItemClick = onFileUploadStateClick
)
}
}
@Preview(showBackground = true)
@Composable
fun MainScreenPreview() {
AppTheme {
MainScreen(
MainUiState(
files = listOf(
UploadedFile("File1.pdf", null, "link", Date(), Date()),
UploadedFile("File2.docx", null, "link", Date(), Date()),
UploadedFile("File3.jpg", null, "link", Date(), Date()),
UploadedFile("File4.avi", null, "link", Date(), Date())
), fileUploadState = listOf(
FileUploadState.Success("file5.mp4", "", "", Date()),
FileUploadState.InProgress("file6.mp3", 67),
FileUploadState.Failure("file7.png", "Something went wrong!", null)
)
), {}, {}, {}, {}, {}, {}
)
}
}
| 0
|
Kotlin
|
0
| 0
|
5c58b2928564e9e2667f1c6ad31f0dedd9f34505
| 2,786
|
the-null-pointer-android-client
|
MIT License
|
project-generator/src/main/kotlin/io/github/cdsap/projectgenerator/files/android/ValuesStringsSmall.kt
|
cdsap
| 688,226,196
| false
|
{"Kotlin": 268624}
|
package io.github.cdsap.projectgenerator.files.android
class ValuesStringsSmall {
fun getLib(module: String) = """
<resources>
<string name="${module}_string">$module - My lib</string>
<!-- Recent Tabs -->
<!-- Header text for jumping back into the recent tab in the home screen -->
<string name="${module}_recent_tabs_header">Jump back in</string>
<!-- Button text for showing all the tabs in the tabs tray -->
<string name="${module}_recent_tabs_show_all">Show all</string>
<!-- Content description for the button which navigates the user to show all recent tabs in the tabs tray. -->
<string name="${module}_recent_tabs_show_all_content_description_2">Show all recent tabs button</string>
<!-- Text for button in synced tab card that opens synced tabs tray -->
<string name="${module}_recent_tabs_see_all_synced_tabs_button_text">See all synced tabs</string>
<!-- Accessibility description for device icon used for recent synced tab -->
<string name="${module}_recent_tabs_synced_device_icon_content_description">Synced device</string>
<!-- Text for the dropdown menu to remove a recent synced tab from the homescreen -->
<string name="${module}_recent_synced_tab_menu_item_remove">Remove</string>
<!-- Text for the menu button to remove a grouped highlight from the user's browsing history
in the Recently visited section -->
<string name="${module}_recent_tab_menu_item_remove">Remove</string>
</resources>
""".trimIndent()
}
| 5
|
Kotlin
|
1
| 65
|
59df5e5a5929454f3591795b5ee4b56c8d75f7e9
| 1,733
|
ProjectGenerator
|
MIT License
|
app/src/main/java/com/skydoves/pokedexar/ui/login/LoginActivity.kt
|
fosemfhtm
| 447,322,435
| false
| null |
package com.skydoves.pokedexar.ui.login
import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Window
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import com.amn.easysharedpreferences.EasySharedPreference
import com.amn.easysharedpreferences.EasySharedPreferenceConfig
import com.skydoves.pokedexar.R
import com.skydoves.pokedexar.ui.main.MainActivity
import retrofit2.*
import retrofit2.converter.gson.GsonConverterFactory
import java.lang.Exception
class LoginActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_login)
EasySharedPreferenceConfig.initDefault(EasySharedPreferenceConfig.Builder().inputFileName("easy_preference").inputMode(Context.MODE_PRIVATE).build())
if(EasySharedPreference.Companion.getString("token", "") != "") {
intent = Intent(this@LoginActivity, MainActivity::class.java)
startActivity(intent)
finish()
}
val retrofit = Retrofit.Builder().baseUrl("http://192.249.18.193:80")
.addConverterFactory(GsonConverterFactory.create()).build()
val service = retrofit.create(LoginService::class.java)
val service2 = retrofit.create(SignupService::class.java)
findViewById<Button>(R.id.login_button).setOnClickListener {
val dialog = Dialog(this)
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setContentView(R.layout.dialog_login)
val idEditText = dialog.findViewById<EditText>(R.id.idEditText)
val passwordEditText = dialog.findViewById<EditText>(R.id.passwordEditText)
val loginErrorMessage = dialog.findViewById<TextView>(R.id.login_error_message)
dialog.findViewById<Button>(R.id.real_login_button).setOnClickListener{
val loading = Dialog(this@LoginActivity)
loading.setContentView(R.layout.loading_dialog)
loading.setCancelable(false);
loading.show()
service.requestLogin(idEditText.text.toString(), passwordEditText.text.toString()).enqueue(object : Callback<Login> {
override fun onFailure(call: Call<Login>, t: Throwable) {
loginErrorMessage.text = "서버 연결에 문제가 발생했습니다."
loading.dismiss()
}
override fun onResponse(call: Call<Login>, response: Response<Login>) {
try {
println(response.body().toString())
println(response.body()!!.token)
val token = response.body()!!.token
dialog.dismiss()
EasySharedPreference.Companion.putString("token", token)
intent = Intent(this@LoginActivity, MainActivity::class.java)
startActivity(intent)
loading.dismiss()
finish()
} catch (e: Exception){
loginErrorMessage.text = "아이디와 비밀번호가 일치하지 않습니다."
loading.dismiss()
}
}
})
}
dialog.show()
}
findViewById<Button>(R.id.signup_button).setOnClickListener {
val dialog = Dialog(this)
dialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
dialog.setContentView(R.layout.dialog_signup)
val idEditText = dialog.findViewById<EditText>(R.id.idEditText)
val nameEditText = dialog.findViewById<EditText>(R.id.nameEditText)
val emailEditText = dialog.findViewById<EditText>(R.id.emailEditText)
// TO DO 이메일
val passwordEditText = dialog.findViewById<EditText>(R.id.passwordEditText)
val passwordEditTextR = dialog.findViewById<EditText>(R.id.passwordEditText_repeat)
val signupErrorMessage = dialog.findViewById<TextView>(R.id.signup_error_message)
dialog.findViewById<Button>(R.id.real_signup_button).setOnClickListener{
if(passwordEditText.text.toString() != passwordEditTextR.text.toString()){
signupErrorMessage.text = "비밀번호가 일치하지 않습니다."
} else {
val loading = Dialog(this@LoginActivity)
loading.setContentView(R.layout.loading_dialog)
loading.setCancelable(false);
loading.show()
service2.requestSignup(
idEditText.text.toString(),
nameEditText.text.toString(),
emailEditText.text.toString(),
passwordEditText.text.toString()
).enqueue(object : Callback<Signup> {
override fun onFailure(call: Call<Signup>, t: Throwable) {
signupErrorMessage.text = "서버 연결에 문제가 발생했습니다."
loading.dismiss()
}
override fun onResponse(call: Call<Signup>, response: Response<Signup>) {
try {
//println(response.body().toString())
//println(response.body()!!.token)
val success = response.body()!!.success
val message = response.body()!!.message
if (success == 1) {
Toast.makeText(
this@LoginActivity,
"회원가입에 성공하였습니다.",
Toast.LENGTH_SHORT
).show()
dialog.dismiss()
} else {
signupErrorMessage.text = message
}
//EasySharedPreference.Companion.putString("token", token)
loading.dismiss()
//finish()
} catch (e: Exception) {
signupErrorMessage.text = "서버 연결에 문제가 발생했습니다."
loading.dismiss()
}
}
})
}
}
dialog.show()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
e0e6120209c87a5ece1bc5dd816ca7607a55dc3d
| 7,089
|
Pokemon_RealGo
|
Apache License 2.0
|
src/main/kotlin/com/robotutor/iot/accounts/services/RoleInitializer.kt
|
IOT-echo-system
| 768,195,181
| false
|
{"Kotlin": 190037, "HTML": 428, "Shell": 151, "Dockerfile": 130}
|
package com.robotutor.iot.accounts.services
import com.robotutor.iot.accounts.models.IdType
import com.robotutor.iot.accounts.models.Role
import org.springframework.boot.ApplicationArguments
import org.springframework.boot.ApplicationRunner
import org.springframework.stereotype.Component
import reactor.kotlin.core.publisher.switchIfEmpty
@Component
class RoleInitializer(private val roleService: RoleService, private val policyInitializer: PolicyInitializer) :
ApplicationRunner {
override fun run(args: ApplicationArguments?) {
val roles = listOf(
Role(roleId = "1".padStart(IdType.ROLE_ID.length, '0'),
name = "Owner",
createdBy = "System",
policies = listOf(
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"17",
"20",
"21",
"22",
"23",
"24",
"26",
"27",
"28",
"29",
"30",
"31",
"32",
"33",
"34"
).map { policyInitializer.getPolicyId(it) }),
Role(roleId = "2".padStart(IdType.ROLE_ID.length, '0'),
name = "Admin",
createdBy = "System",
policies = listOf(
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12",
"13",
"14",
"15",
"16",
"20",
"21",
"22",
"23",
"24"
).map { policyInitializer.getPolicyId(it) }),
Role(roleId = "3".padStart(IdType.ROLE_ID.length, '0'),
name = "User",
createdBy = "System",
policies = listOf(
"1", "5", "9", "13", "20", "21"
).map { policyInitializer.getPolicyId(it) }),
Role(roleId = "4".padStart(IdType.ROLE_ID.length, '0'),
name = "Board",
createdBy = "System",
policies = listOf(
"18", "19", "25", "35"
).map { policyInitializer.getPolicyId(it) }),
)
roles.forEach { role ->
roleService.getRoleByRoleId(role.roleId).switchIfEmpty {
roleService.addRole(name = role.name, createdBy = role.createdBy, policies = role.policies)
}.block()
}
}
}
| 0
|
Kotlin
|
0
| 0
|
f8f314ba33164725e5f3586dcf7566ae16eaae37
| 3,195
|
cloud-backend-service
|
MIT License
|
owncloudComLibrary/src/main/java/com/owncloud/android/lib/resources/shares/GetRemoteShareOperation.kt
|
jesmrec
| 464,454,115
| true
|
{"INI": 2, "Gradle": 4, "Shell": 1, "EditorConfig": 1, "Markdown": 2, "Batchfile": 1, "Ignore List": 1, "XML": 11, "YAML": 2, "Text": 1, "Java": 46, "Kotlin": 74, "JSON": 2}
|
/* ownCloud Android Library is available under MIT license
* @author <NAME>
* Copyright (C) 2021 ownCloud GmbH
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.owncloud.android.lib.resources.shares
import android.net.Uri
import com.owncloud.android.lib.common.OwnCloudClient
import com.owncloud.android.lib.common.http.HttpConstants
import com.owncloud.android.lib.common.http.HttpConstants.PARAM_FORMAT
import com.owncloud.android.lib.common.http.HttpConstants.VALUE_FORMAT
import com.owncloud.android.lib.common.http.methods.nonwebdav.GetMethod
import com.owncloud.android.lib.common.operations.RemoteOperation
import com.owncloud.android.lib.common.operations.RemoteOperationResult
import com.owncloud.android.lib.resources.CommonOcsResponse
import com.owncloud.android.lib.resources.shares.responses.ShareItem
import com.squareup.moshi.JsonAdapter
import com.squareup.moshi.Moshi
import com.squareup.moshi.Types
import timber.log.Timber
import java.lang.reflect.Type
import java.net.URL
class GetRemoteShareOperation(private val remoteId: String) : RemoteOperation<ShareResponse>() {
private fun buildRequestUri(baseUri: Uri) =
baseUri.buildUpon()
.appendEncodedPath(OCS_ROUTE)
.appendEncodedPath(remoteId)
.appendQueryParameter(PARAM_FORMAT, VALUE_FORMAT)
.build()
private fun parseResponse(response: String): ShareResponse? {
val moshi = Moshi.Builder().build()
val listOfShareItemType: Type = Types.newParameterizedType(List::class.java, ShareItem::class.java)
val commonOcsType: Type = Types.newParameterizedType(CommonOcsResponse::class.java, listOfShareItemType)
val adapter: JsonAdapter<CommonOcsResponse<List<ShareItem>>> = moshi.adapter(commonOcsType)
return adapter.fromJson(response)?.ocs?.data?.let { listOfShareItems ->
ShareResponse(listOfShareItems.map { shareItem ->
shareItem.toRemoteShare()
})
}
}
private fun onResultUnsuccessful(
method: GetMethod,
response: String?,
status: Int
): RemoteOperationResult<ShareResponse> {
Timber.e("Failed response while while getting remote shares ")
if (response != null) {
Timber.e("*** status code: $status; response message: $response")
} else {
Timber.e("*** status code: $status")
}
return RemoteOperationResult(method)
}
private fun onRequestSuccessful(response: String?): RemoteOperationResult<ShareResponse> {
val result = RemoteOperationResult<ShareResponse>(RemoteOperationResult.ResultCode.OK)
Timber.d("Successful response: $response")
result.data = parseResponse(response!!)
Timber.d("*** Get Users or groups completed ")
return result
}
override fun run(client: OwnCloudClient): RemoteOperationResult<ShareResponse> {
val requestUri = buildRequestUri(client.baseUri)
val getMethod = GetMethod(URL(requestUri.toString())).apply {
addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE)
}
return try {
val status = client.executeHttpMethod(getMethod)
val response = getMethod.getResponseBodyAsString()
if (!isSuccess(status)) {
onResultUnsuccessful(getMethod, response, status)
} else {
onRequestSuccessful(response)
}
} catch (e: Exception) {
Timber.e(e, "Exception while getting remote shares")
RemoteOperationResult(e)
}
}
private fun isSuccess(status: Int) = status == HttpConstants.HTTP_OK
companion object {
//OCS Route
private const val OCS_ROUTE = "ocs/v2.php/apps/files_sharing/api/v1/shares"
}
}
| 0
| null |
0
| 0
|
fb7bfb23e0aeabdcdfaadc48ecbe7c6bca4889b4
| 4,891
|
android-library
|
MIT License
|
src/test/kotlin/com/freenow/apis/phraseapi/client/PhraseApiClientTranslationTest.kt
|
freenowtech
| 145,117,901
| false
| null |
package com.mytaxi.apis.phraseapi.client
import com.google.common.net.HttpHeaders
import com.google.common.net.MediaType
import com.google.gson.Gson
import com.mytaxi.apis.phraseapi.client.model.CreateTranslation
import com.mytaxi.apis.phraseapi.client.model.PhraseLocale
import com.mytaxi.apis.phraseapi.client.model.Translation
import com.mytaxi.apis.phraseapi.client.model.TranslationKey
import feign.Response
import org.apache.commons.httpclient.HttpStatus
import org.junit.Test
import org.mockito.Mockito.`when` as on
import org.mockito.Mockito.mock
import org.mockito.Mockito.withSettings
import java.nio.charset.StandardCharsets
import java.util.Locale
import java.util.UUID
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
class PhraseApiClientTranslationTest {
private var client: PhraseApi = mock(PhraseApi::class.java, withSettings().extraInterfaces(CacheApi::class.java))
private var phraseApiClient: PhraseApiClient
init {
phraseApiClient = PhraseApiClientImpl(client)
}
@Test
fun `Should create translation with optional parameters`() {
//GIVEN
val projectId = UUID.randomUUID().toString()
val localeId = UUID.randomUUID().toString()
val keyId = UUID.randomUUID().toString()
val keyName = "key.name"
val translationContent = "translation"
val headers = mapOf(
HttpHeaders.CONTENT_TYPE to listOf(MediaType.JSON_UTF_8.toString())
)
val createTranslation = CreateTranslation(
localeId = localeId,
keyId = keyId,
content = translationContent,
unverified = true,
excluded = false
)
val translationJSON = Gson().toJson(createTranslation)
val response = Response.create(
HttpStatus.SC_CREATED,
"OK",
headers,
translationJSON,
StandardCharsets.UTF_8
)
on(client.createTranslation(
projectId = projectId,
localeId = localeId,
keyId = keyId,
content = translationContent
)).thenReturn(response)
val expectedTranslation = Translation(
id = UUID.randomUUID().toString(),
key = TranslationKey(
id = keyId,
name = keyName
),
locale = PhraseLocale(
id = localeId,
code = Locale.US.toLanguageTag(),
name = UUID.randomUUID().toString()
),
content = translationContent
)
//WHEN
val actualResponse = phraseApiClient.createTranslation(projectId, createTranslation)
//THEN
assertNotNull(actualResponse)
assertEquals(actualResponse!!.content, expectedTranslation.content)
}
@Test
fun `Should create translation with only the required parameters`() {
//GIVEN
val projectId = UUID.randomUUID().toString()
val localeId = UUID.randomUUID().toString()
val keyId = UUID.randomUUID().toString()
val keyName = "key.name"
val translationContent = "translation"
val headers = mapOf(
HttpHeaders.CONTENT_TYPE to listOf(MediaType.JSON_UTF_8.toString())
)
val createTranslation = CreateTranslation(
localeId = localeId,
keyId = keyId,
content = translationContent
)
val translationJSON = Gson().toJson(createTranslation)
val response = Response.create(
HttpStatus.SC_CREATED,
"OK",
headers,
translationJSON,
StandardCharsets.UTF_8
)
on(client.createTranslation(
projectId = projectId,
localeId = localeId,
keyId = keyId,
content = translationContent
)).thenReturn(response)
val expectedTranslation = Translation(
id = UUID.randomUUID().toString(),
key = TranslationKey(
id = keyId,
name = keyName
),
locale = PhraseLocale(
id = localeId,
code = Locale.US.toLanguageTag(),
name = UUID.randomUUID().toString()
),
content = translationContent
)
//WHEN
val actualResponse = phraseApiClient.createTranslation(projectId, localeId, keyId, translationContent)
//THEN
assertNotNull(actualResponse)
assertEquals(actualResponse!!.content, expectedTranslation.content)
}
}
| 3
|
Kotlin
|
6
| 2
|
86c74c39804d6a0dae050907e72df663bffcf568
| 4,642
|
phrase-kotlin-client
|
Apache License 2.0
|
laser-native-editor/src/main/java/com/github/irshulx/components/input/spans/custom/SpecialSpansBase.kt
|
AlShevelev
| 207,271,222
| true
|
{"Kotlin": 101147, "Java": 309}
|
package com.github.irshulx.components.input.spans.custom
import android.text.TextPaint
import android.text.style.UnderlineSpan
import androidx.annotation.ColorInt
abstract class SpecialSpansBase<T>(
val value: T,
@ColorInt private val textColor: Int
) : UnderlineSpan() {
abstract override fun getSpanTypeId(): Int
override fun describeContents(): Int = 0
override fun updateDrawState(ds: TextPaint) {
super.updateDrawState(ds)
ds.color = textColor
}
}
| 0
|
Kotlin
|
0
| 0
|
c1bb3976d29eeb336243777f289ef6e431cbe6ef
| 497
|
Android-WYSIWYG-Editor
|
Apache License 2.0
|
app/src/main/java/com/example/cookrecipe/view_model/LoginViewModel.kt
|
eristich
| 574,412,169
| false
| null |
package com.example.cookrecipe.view_model
import android.app.Application
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.cookrecipe.R
import com.example.cookrecipe.model.repo.FirebaseAuth
class LoginViewModel(application: Application) : AndroidViewModel(application) {
private var firebaseAuth: FirebaseAuth = FirebaseAuth
private val _msgToast = MutableLiveData<String>()
val msgToast: LiveData<String> get() = _msgToast
var activityListener: ActivityListener? = null
var email: String = ""
var password: String = ""
/**
* Get data is valid for logged user
* @return boolean true or false if bad data send
*/
private fun dataValidator(): Boolean {
return if (email.isEmpty()) {
_msgToast.value =
getApplication<Application>().getString(R.string.error_no_username)
false
} else if (password.isEmpty()) {
_msgToast.value =
getApplication<Application>().getString(R.string.error_no_password)
false
} else if (password.length < 6) {
_msgToast.value =
getApplication<Application>().getString(R.string.error_length_password)
false
} else {
true
}
}
/**
* Log user white firebase
* @return Void
*/
fun loginUser() {
// Check data input
if (this.dataValidator()) {
val taskResult = firebaseAuth.loginUser(email, password)
taskResult.addOnCompleteListener { tasks ->
Log.d(TAG, "LoginUser: " + tasks.isSuccessful)
if (tasks.isSuccessful) {
_msgToast.value =
getApplication<Application>().getString(R.string.success_sign_in)
activityClose()
} else {
_msgToast.value =
getApplication<Application>().getString(R.string.error_sign_in)
}
}
}
}
/**
* Set event for closing activity
*/
interface ActivityListener {
fun onClose()
}
/**
* Close the current activity
*/
private fun activityClose() {
activityListener?.onClose()
}
companion object {
// define TAG of console
const val TAG: String = "Main-ModelView"
}
}
| 0
|
Kotlin
|
1
| 0
|
f613cfa4c391be509f54d660426379103eafcfd2
| 2,493
|
cook-recipe
|
MIT License
|
design-catalog/src/main/java/little/goose/design/catalog/ui/ChartCatalogScreen.kt
|
MReP1
| 525,822,587
| false
| null |
package little.goose.design.catalog.ui
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import little.goose.chart.ChartLabel
import little.goose.chart.bar.BarChart
import little.goose.chart.bar.BarChartProperties
import little.goose.chart.bar.BarData
import little.goose.chart.pie.PieChart
import little.goose.chart.pie.PieChartWithContent
import little.goose.chart.pie.PieData
@Composable
internal fun ChartCatalogScreen(
modifier: Modifier
) {
Surface(modifier = modifier) {
Column(modifier = Modifier.fillMaxSize()) {
BarChartCatalog(modifier = Modifier.fillMaxWidth())
PieChartCatalog(modifier = Modifier.fillMaxWidth())
}
}
}
@Preview(showBackground = true)
@Composable
fun BarChartCatalog(
modifier: Modifier = Modifier
) {
val dataList = remember {
buildList {
repeat(4) {
add(BarData("${it + 1}", (it + 1).toFloat()))
}
}
}
val (selectedData, onSelectedDataChange) = remember {
mutableStateOf<BarData?>(null)
}
BarChart(
modifier = modifier
.fillMaxWidth()
.size(200.dp),
dataList = dataList,
selectedData = selectedData,
onSelectedDataChange = onSelectedDataChange,
properties = remember { BarChartProperties(showXText = true) }
)
selectedData?.let {
TextButton(onClick = {
}) {
Text(text = selectedData.xText)
}
}
}
@OptIn(ExperimentalLayoutApi::class)
@Preview(showBackground = true)
@Composable
private fun PieChartCatalog(
modifier: Modifier = Modifier
) {
val dataList = remember {
listOf(
PieData("123", 15F, Color.Red),
PieData("123", 16F, Color.Black),
PieData("Sample", 50F, Color.Gray),
PieData("Sample2", 32F, Color.Green),
PieData("Sample3", 24F, Color.Magenta)
)
}
Column(modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally) {
Row {
Spacer(modifier = Modifier.weight(1F))
var selectedData1: PieData? by rememberSaveable(stateSaver = PieData.saver) {
mutableStateOf(
null
)
}
Box(modifier = Modifier.size(200.dp), contentAlignment = Alignment.Center) {
PieChart(
modifier = Modifier
.height(200.dp)
.aspectRatio(1F),
dataList = dataList,
selectedData = selectedData1,
onSelectedData = { selectedData1 = it }
)
selectedData1?.let { data ->
Text(
text = data.content,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurface
)
}
}
Column(modifier = Modifier.weight(1F)) {
Spacer(modifier = Modifier.height(16.dp))
dataList.forEach { data ->
ChartLabel(
modifier = Modifier,
color = data.color,
text = data.content
)
}
}
}
Column(
modifier = Modifier.width(200.dp),
horizontalAlignment = Alignment.CenterHorizontally
) {
PieChartWithContent(
modifier = Modifier
.height(200.dp)
.aspectRatio(1F),
dataList = dataList
)
FlowRow(
modifier = Modifier.width(172.dp),
verticalArrangement = Arrangement.spacedBy(
space = 2.dp,
alignment = Alignment.Bottom
),
horizontalArrangement = Arrangement.Center
) {
for (index in dataList.indices) {
val data = dataList[index]
ChartLabel(color = data.color, text = data.content)
if (index < dataList.lastIndex) {
Spacer(modifier = Modifier.width(6.dp))
}
}
}
}
}
}
| 1
| null |
29
| 99
|
a6ee70d1b3dcf4b9b24ca00bbed725e8374e105a
| 5,619
|
LittleGooseOffice
|
MIT License
|
app/src/main/java/com/coolweather/coolweatherjetpack/ui/area/ChooseAreaViewModel.kt
|
Orion-wubo
| 175,758,870
| true
|
{"Kotlin": 35306}
|
package com.coolweather.coolweatherjetpack.ui.area
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.coolweather.coolweatherjetpack.data.PlaceRepository
import com.coolweather.coolweatherjetpack.data.model.place.City
import com.coolweather.coolweatherjetpack.data.model.place.County
import com.coolweather.coolweatherjetpack.data.model.place.Province
import kotlinx.coroutines.launch
import java.util.*
class ChooseAreaViewModel(private val repository: PlaceRepository) : ViewModel() {
var currentLevel = MutableLiveData<Int>()
var selectedProvince: Province? = null
var selectedCity: City? = null
var provinces = MutableLiveData<Result<MutableList<Province>>>()
var cities = MutableLiveData<Result<MutableList<City>>>()
var counties = MutableLiveData<Result<MutableList<County>>>()
var dataList = ArrayList<String>()
fun getProvinces() = launch({
provinces.value = Result.success(repository.getProvinceList())
}, {
provinces.value = Result.failure(it)
})
fun getCities(provinceId: Int) = launch({
cities.value = Result.success(repository.getCityList(provinceId))
}, {
cities.value = Result.failure(it)
})
fun getCounties(provinceId: Int, cityId: Int) = launch({
counties.value = Result.success(repository.getCountyList(provinceId, cityId))
}, {
counties.value = Result.failure(it)
})
private fun launch(block: suspend () -> Unit, error: suspend (Throwable) -> Unit) = viewModelScope.launch {
try {
block()
} catch (t: Throwable) {
error(t)
}
}
}
| 0
|
Kotlin
|
0
| 1
|
64ae7953145800b2b7d3a31327e34a669a379581
| 1,708
|
coolweatherjetpack
|
Apache License 2.0
|
web/src/test/kotlin/no/nav/su/se/bakover/web/routes/søknadsbehandling/GrunnlagBosituasjonFullførRoutesTest.kt
|
navikt
| 227,366,088
| false
| null |
package no.nav.su.se.bakover.web.routes.søknadsbehandling
import arrow.core.left
import arrow.core.right
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldContain
import io.ktor.http.HttpMethod
import io.ktor.http.HttpStatusCode
import io.ktor.server.testing.setBody
import io.ktor.server.testing.withTestApplication
import no.nav.su.se.bakover.common.Tidspunkt
import no.nav.su.se.bakover.domain.Brukerrolle
import no.nav.su.se.bakover.domain.Fnr
import no.nav.su.se.bakover.domain.Saksnummer
import no.nav.su.se.bakover.domain.behandling.Attesteringshistorikk
import no.nav.su.se.bakover.domain.behandling.Behandlingsinformasjon
import no.nav.su.se.bakover.domain.grunnlag.Grunnlagsdata
import no.nav.su.se.bakover.domain.oppgave.OppgaveId
import no.nav.su.se.bakover.domain.søknadsbehandling.Søknadsbehandling
import no.nav.su.se.bakover.domain.vilkår.Vilkårsvurderinger
import no.nav.su.se.bakover.service.søknadsbehandling.SøknadsbehandlingService
import no.nav.su.se.bakover.service.vilkår.BosituasjonValg
import no.nav.su.se.bakover.service.vilkår.FullførBosituasjonRequest
import no.nav.su.se.bakover.test.generer
import no.nav.su.se.bakover.web.TestServicesBuilder
import no.nav.su.se.bakover.web.argThat
import no.nav.su.se.bakover.web.defaultRequest
import no.nav.su.se.bakover.web.routes.sak.sakPath
import no.nav.su.se.bakover.web.routes.søknadsbehandling.BehandlingTestUtils.journalførtSøknadMedOppgave
import no.nav.su.se.bakover.web.routes.søknadsbehandling.BehandlingTestUtils.stønadsperiode
import no.nav.su.se.bakover.web.testSusebakover
import org.junit.jupiter.api.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.verifyNoMoreInteractions
import java.util.UUID
class GrunnlagBosituasjonFullførRoutesTest {
private val services = TestServicesBuilder.services()
private val søknadsbehandling: Søknadsbehandling.Vilkårsvurdert.Uavklart = Søknadsbehandling.Vilkårsvurdert.Uavklart(
id = UUID.randomUUID(),
opprettet = Tidspunkt.EPOCH,
sakId = UUID.randomUUID(),
saksnummer = Saksnummer(2021),
søknad = journalførtSøknadMedOppgave,
oppgaveId = OppgaveId("oppgaveId"),
behandlingsinformasjon = Behandlingsinformasjon.lagTomBehandlingsinformasjon(),
fnr = Fnr.generer(),
fritekstTilBrev = "",
stønadsperiode = stønadsperiode,
grunnlagsdata = Grunnlagsdata.IkkeVurdert,
vilkårsvurderinger = Vilkårsvurderinger.Søknadsbehandling.IkkeVurdert,
attesteringer = Attesteringshistorikk.empty(),
)
@Test
fun `andre roller enn saksbehandler skal ikke ha tilgang til bosituasjon`() {
Brukerrolle.values().filterNot { it == Brukerrolle.Saksbehandler }.forEach { rolle ->
withTestApplication(
{
testSusebakover()
},
) {
defaultRequest(
HttpMethod.Post,
"$sakPath/${søknadsbehandling.sakId}/behandlinger/${søknadsbehandling.id}/grunnlag/bosituasjon/fullfør",
listOf(rolle),
) {
setBody("""{ "epsFnr": null}""".trimIndent())
}.apply {
response.status() shouldBe HttpStatusCode.Forbidden
}
}
}
}
@Test
fun `happy case deler bolig med voksne`() {
val søknadsbehandlingServiceMock = mock<SøknadsbehandlingService> {
on { fullførBosituasjongrunnlag(any()) } doReturn søknadsbehandling.right()
}
withTestApplication(
{
testSusebakover(services = services.copy(søknadsbehandling = søknadsbehandlingServiceMock))
},
) {
defaultRequest(
HttpMethod.Post,
"$sakPath/${søknadsbehandling.sakId}/behandlinger/${søknadsbehandling.id}/grunnlag/bosituasjon/fullfør",
listOf(Brukerrolle.Saksbehandler),
) {
setBody("""{ "bosituasjon": "DELER_BOLIG_MED_VOKSNE", "begrunnelse": null}""".trimIndent())
}.apply {
response.status() shouldBe HttpStatusCode.Created
verify(søknadsbehandlingServiceMock).fullførBosituasjongrunnlag(
argThat {
it shouldBe FullførBosituasjonRequest(
behandlingId = søknadsbehandling.id,
bosituasjon = BosituasjonValg.DELER_BOLIG_MED_VOKSNE,
begrunnelse = null,
)
}
)
verifyNoMoreInteractions(søknadsbehandlingServiceMock)
}
}
}
@Test
fun `happy case bor alene`() {
val søknadsbehandlingServiceMock = mock<SøknadsbehandlingService> {
on { fullførBosituasjongrunnlag(any()) } doReturn søknadsbehandling.right()
}
withTestApplication(
{
testSusebakover(services = services.copy(søknadsbehandling = søknadsbehandlingServiceMock))
},
) {
defaultRequest(
HttpMethod.Post,
"$sakPath/${søknadsbehandling.sakId}/behandlinger/${søknadsbehandling.id}/grunnlag/bosituasjon/fullfør",
listOf(Brukerrolle.Saksbehandler),
) {
setBody("""{ "bosituasjon": "BOR_ALENE", "begrunnelse": null}""".trimIndent())
}.apply {
response.status() shouldBe HttpStatusCode.Created
verify(søknadsbehandlingServiceMock).fullførBosituasjongrunnlag(
argThat {
it shouldBe FullførBosituasjonRequest(
behandlingId = søknadsbehandling.id,
bosituasjon = BosituasjonValg.BOR_ALENE,
begrunnelse = null,
)
}
)
verifyNoMoreInteractions(søknadsbehandlingServiceMock)
}
}
}
@Test
fun `happy case eps ufør flykning`() {
val søknadsbehandlingServiceMock = mock<SøknadsbehandlingService> {
on { fullførBosituasjongrunnlag(any()) } doReturn søknadsbehandling.right()
}
withTestApplication(
{
testSusebakover(services = services.copy(søknadsbehandling = søknadsbehandlingServiceMock))
},
) {
defaultRequest(
HttpMethod.Post,
"$sakPath/${søknadsbehandling.sakId}/behandlinger/${søknadsbehandling.id}/grunnlag/bosituasjon/fullfør",
listOf(Brukerrolle.Saksbehandler),
) {
setBody("""{ "bosituasjon": "EPS_UFØR_FLYKTNING", "begrunnelse": null}""".trimIndent())
}.apply {
response.status() shouldBe HttpStatusCode.Created
verify(søknadsbehandlingServiceMock).fullførBosituasjongrunnlag(
argThat {
it shouldBe FullførBosituasjonRequest(
behandlingId = søknadsbehandling.id,
bosituasjon = BosituasjonValg.EPS_UFØR_FLYKTNING,
begrunnelse = null,
)
}
)
verifyNoMoreInteractions(søknadsbehandlingServiceMock)
}
}
}
@Test
fun `happy case eps ikke ufør flykning`() {
val søknadsbehandlingServiceMock = mock<SøknadsbehandlingService> {
on { fullførBosituasjongrunnlag(any()) } doReturn søknadsbehandling.right()
}
withTestApplication(
{
testSusebakover(services = services.copy(søknadsbehandling = søknadsbehandlingServiceMock))
},
) {
defaultRequest(
HttpMethod.Post,
"$sakPath/${søknadsbehandling.sakId}/behandlinger/${søknadsbehandling.id}/grunnlag/bosituasjon/fullfør",
listOf(Brukerrolle.Saksbehandler),
) {
setBody("""{ "bosituasjon": "EPS_IKKE_UFØR_FLYKTNING", "begrunnelse": null}""".trimIndent())
}.apply {
response.status() shouldBe HttpStatusCode.Created
verify(søknadsbehandlingServiceMock).fullførBosituasjongrunnlag(
argThat {
it shouldBe FullførBosituasjonRequest(
behandlingId = søknadsbehandling.id,
bosituasjon = BosituasjonValg.EPS_IKKE_UFØR_FLYKTNING,
begrunnelse = null,
)
}
)
verifyNoMoreInteractions(søknadsbehandlingServiceMock)
}
}
}
@Test
fun `happy case eps 67 eller over`() {
val søknadsbehandlingServiceMock = mock<SøknadsbehandlingService> {
on { fullførBosituasjongrunnlag(any()) } doReturn søknadsbehandling.right()
}
withTestApplication(
{
testSusebakover(services = services.copy(søknadsbehandling = søknadsbehandlingServiceMock))
},
) {
defaultRequest(
HttpMethod.Post,
"$sakPath/${søknadsbehandling.sakId}/behandlinger/${søknadsbehandling.id}/grunnlag/bosituasjon/fullfør",
listOf(Brukerrolle.Saksbehandler),
) {
setBody("""{ "bosituasjon": "EPS_67_ELLER_OVER", "begrunnelse": null}""".trimIndent())
}.apply {
response.status() shouldBe HttpStatusCode.Created
verify(søknadsbehandlingServiceMock).fullførBosituasjongrunnlag(
argThat {
it shouldBe FullførBosituasjonRequest(
behandlingId = søknadsbehandling.id,
bosituasjon = BosituasjonValg.EPS_67_ELLER_OVER,
begrunnelse = null,
)
}
)
verifyNoMoreInteractions(søknadsbehandlingServiceMock)
}
}
}
@Test
fun `happy case begrunnelse`() {
val søknadsbehandlingServiceMock = mock<SøknadsbehandlingService> {
on { fullførBosituasjongrunnlag(any()) } doReturn søknadsbehandling.right()
}
withTestApplication(
{
testSusebakover(services = services.copy(søknadsbehandling = søknadsbehandlingServiceMock))
},
) {
defaultRequest(
HttpMethod.Post,
"$sakPath/${søknadsbehandling.sakId}/behandlinger/${søknadsbehandling.id}/grunnlag/bosituasjon/fullfør",
listOf(Brukerrolle.Saksbehandler),
) {
setBody("""{ "bosituasjon": "EPS_67_ELLER_OVER", "begrunnelse": "Begrunnelse"}""".trimIndent())
}.apply {
response.status() shouldBe HttpStatusCode.Created
verify(søknadsbehandlingServiceMock).fullførBosituasjongrunnlag(
argThat {
it shouldBe FullførBosituasjonRequest(
behandlingId = søknadsbehandling.id,
bosituasjon = BosituasjonValg.EPS_67_ELLER_OVER,
begrunnelse = "Begrunnelse",
)
}
)
verifyNoMoreInteractions(søknadsbehandlingServiceMock)
}
}
}
@Test
fun `service finner ikke behandling`() {
val søknadsbehandlingServiceMock = mock<SøknadsbehandlingService> {
on { fullførBosituasjongrunnlag(any()) } doReturn SøknadsbehandlingService.KunneIkkeFullføreBosituasjonGrunnlag.FantIkkeBehandling.left()
}
withTestApplication(
{
testSusebakover(services = services.copy(søknadsbehandling = søknadsbehandlingServiceMock))
},
) {
defaultRequest(
HttpMethod.Post,
"$sakPath/${søknadsbehandling.sakId}/behandlinger/${søknadsbehandling.id}/grunnlag/bosituasjon/fullfør",
listOf(Brukerrolle.Saksbehandler),
) {
setBody("""{ "bosituasjon": "DELER_BOLIG_MED_VOKSNE", "begrunnelse": null}""".trimIndent())
}.apply {
response.status() shouldBe HttpStatusCode.NotFound
response.content shouldContain ("fant_ikke_behandling")
}
}
}
@Test
fun `service klarer ikke å lagre bosituasjon`() {
val søknadsbehandlingServiceMock = mock<SøknadsbehandlingService> {
on { fullførBosituasjongrunnlag(any()) } doReturn SøknadsbehandlingService.KunneIkkeFullføreBosituasjonGrunnlag.KlarteIkkeLagreBosituasjon.left()
}
withTestApplication(
{
testSusebakover(services = services.copy(søknadsbehandling = søknadsbehandlingServiceMock))
},
) {
defaultRequest(
HttpMethod.Post,
"$sakPath/${søknadsbehandling.sakId}/behandlinger/${søknadsbehandling.id}/grunnlag/bosituasjon/fullfør",
listOf(Brukerrolle.Saksbehandler),
) {
setBody("""{ "bosituasjon": "EPS_UFØR_FLYKTNING", "begrunnelse": null}""".trimIndent())
}.apply {
response.status() shouldBe HttpStatusCode.BadRequest
response.content shouldContain ("kunne_ikke_legge_til_bosituasjonsgrunnlag")
// For å treffe denne må man prøve å fullføre en ufullstendig bosituasjon som burde ha fnr, men som ikke har det
}
}
}
}
| 6
|
Kotlin
|
0
| 0
|
b0864f973c8986f58af07c4bc7f601caa602dbfc
| 13,924
|
su-se-bakover
|
MIT License
|
src/main/kotlin/com/github/guangzhengli/dotnetmigrationideaplugin/services/MyProjectService.kt
|
guangzhengli
| 526,061,411
| false
| null |
package com.github.guangzhengli.dotnetmigrationideaplugin.services
import com.intellij.openapi.project.Project
import com.github.guangzhengli.dotnetmigrationideaplugin.MyBundle
class MyProjectService(project: Project) {
init {
println(MyBundle.message("projectService", project.name))
}
}
| 0
|
Kotlin
|
0
| 0
|
6a968734853e3f0ee727e0a12a65412098493523
| 309
|
dotnet-migration-idea-plugin
|
Apache License 2.0
|
src/main/kotlin/no/nav/helseidnavtest/HelseIdNavTestApplication.kt
|
navikt
| 754,033,318
| false
|
{"Kotlin": 75874}
|
package no.nav.helseidnavtest
import no.nav.boot.conditionals.Cluster.Companion.profiler
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.context.properties.ConfigurationPropertiesScan
import org.springframework.boot.runApplication
import org.springframework.retry.annotation.EnableRetry
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
@SpringBootApplication
@EnableWebSecurity
@EnableMethodSecurity(prePostEnabled = true)
@ConfigurationPropertiesScan
@EnableRetry
class HelseIdNavTestApplication
fun main(args: Array<String>) {
runApplication<no.nav.helseidnavtest.HelseIdNavTestApplication>(*args) {
setAdditionalProfiles(*profiler())
}
}
| 0
|
Kotlin
|
0
| 0
|
82e2081c072e2ae38463c06bbcd14d90fe40bfa6
| 847
|
helseid-nav-test
|
MIT License
|
android/app/src/main/java/com/algorand/android/modules/perawebview/ui/BasePeraWebViewViewModel.kt
|
perawallet
| 364,359,642
| false
|
{"Swift": 8753304, "Kotlin": 7709389, "Objective-C": 88978, "Shell": 7715, "Ruby": 4727, "C": 596}
|
/*
* Copyright 2022 Pera Wallet, LDA
* 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.algorand.android.modules.perawebview.ui
import androidx.lifecycle.viewModelScope
import com.algorand.android.discover.common.ui.model.WebViewError
import com.algorand.android.modules.basewebview.ui.BaseWebViewViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
abstract class BasePeraWebViewViewModel : BaseWebViewViewModel() {
private val _lastErrorFlow: MutableStateFlow<WebViewError?> = MutableStateFlow(null)
open fun onPageRequestedShouldOverrideUrlLoading(url: String): Boolean { return false }
open fun onPageStarted() {}
open fun onPageFinished(title: String? = null, url: String? = null) {}
open fun onError() {}
open fun onHttpError() {}
open fun onPageUrlChanged() {}
fun saveLastError(error: WebViewError?) {
viewModelScope.launch {
_lastErrorFlow
.emit(error)
}
}
fun getLastError(): WebViewError? {
return _lastErrorFlow.value
}
fun clearLastError() {
viewModelScope.launch {
_lastErrorFlow.emit(null)
}
}
}
| 22
|
Swift
|
62
| 181
|
92fc77f73fa4105de82d5e87b03c1e67600a57c0
| 1,696
|
pera-wallet
|
Apache License 2.0
|
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/HandFist.kt
|
localhostov
| 808,861,591
| false
|
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
|
package me.localx.icons.straight.outline
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Outline.HandFist: ImageVector
get() {
if (_handFist != null) {
return _handFist!!
}
_handFist = Builder(name = "HandFist", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp,
viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveToRelative(20.943f, 1.714f)
curveToRelative(-0.671f, -0.572f, -1.56f, -0.817f, -2.439f, -0.674f)
curveToRelative(-0.349f, 0.057f, -0.677f, 0.179f, -0.973f, 0.352f)
curveToRelative(-0.533f, -0.836f, -1.468f, -1.392f, -2.531f, -1.392f)
curveToRelative(-0.768f, 0.0f, -1.469f, 0.29f, -2.0f, 0.766f)
curveToRelative(-0.531f, -0.476f, -1.232f, -0.766f, -2.0f, -0.766f)
curveToRelative(-1.061f, 0.0f, -1.994f, 0.554f, -2.528f, 1.388f)
curveToRelative(-0.435f, -0.246f, -0.937f, -0.388f, -1.472f, -0.388f)
curveToRelative(-1.654f, 0.0f, -3.0f, 1.346f, -3.0f, 3.0f)
verticalLineToRelative(3.521f)
lineToRelative(-2.121f, 2.115f)
curveToRelative(-0.567f, 0.567f, -0.879f, 1.32f, -0.879f, 2.122f)
reflectiveCurveToRelative(0.312f, 1.555f, 0.884f, 2.127f)
lineToRelative(5.116f, 5.034f)
verticalLineToRelative(5.081f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(-5.919f)
lineToRelative(-5.707f, -5.616f)
curveToRelative(-0.189f, -0.189f, -0.293f, -0.44f, -0.293f, -0.708f)
reflectiveCurveToRelative(0.104f, -0.518f, 0.292f, -0.706f)
lineToRelative(2.996f, -2.987f)
curveToRelative(0.389f, -0.39f, 1.024f, -0.39f, 1.415f, 0.0f)
curveToRelative(0.39f, 0.39f, 0.39f, 1.024f, 0.0f, 1.414f)
lineToRelative(-2.256f, 2.251f)
lineToRelative(1.413f, 1.416f)
lineToRelative(2.256f, -2.251f)
curveToRelative(0.846f, -0.846f, 1.08f, -2.076f, 0.702f, -3.135f)
curveToRelative(0.363f, 0.156f, 0.762f, 0.243f, 1.182f, 0.243f)
curveToRelative(0.768f, 0.0f, 1.469f, -0.29f, 2.0f, -0.766f)
curveToRelative(0.531f, 0.476f, 1.232f, 0.766f, 2.0f, 0.766f)
reflectiveCurveToRelative(1.469f, -0.29f, 2.0f, -0.766f)
curveToRelative(0.531f, 0.476f, 1.232f, 0.766f, 2.0f, 0.766f)
curveToRelative(0.351f, 0.0f, 0.687f, -0.061f, 1.0f, -0.171f)
verticalLineToRelative(5.156f)
curveToRelative(0.0f, 1.146f, -0.3f, 2.275f, -0.868f, 3.27f)
lineToRelative(-1.132f, 1.98f)
verticalLineToRelative(5.766f)
horizontalLineToRelative(2.0f)
verticalLineToRelative(-5.234f)
lineToRelative(0.868f, -1.52f)
curveToRelative(0.74f, -1.295f, 1.132f, -2.77f, 1.132f, -4.262f)
lineTo(22.0f, 4.0f)
curveToRelative(0.0f, -0.881f, -0.385f, -1.714f, -1.057f, -2.286f)
close()
moveTo(8.0f, 5.944f)
curveToRelative(-0.646f, -0.228f, -1.354f, -0.229f, -2.0f, -0.004f)
verticalLineToRelative(-1.941f)
curveToRelative(0.0f, -0.551f, 0.449f, -1.0f, 1.0f, -1.0f)
reflectiveCurveToRelative(1.0f, 0.449f, 1.0f, 1.0f)
verticalLineToRelative(1.945f)
close()
moveTo(12.0f, 4.999f)
curveToRelative(0.0f, 0.551f, -0.449f, 1.0f, -1.0f, 1.0f)
reflectiveCurveToRelative(-1.0f, -0.449f, -1.0f, -1.0f)
verticalLineToRelative(-2.0f)
curveToRelative(0.0f, -0.551f, 0.449f, -1.0f, 1.0f, -1.0f)
reflectiveCurveToRelative(1.0f, 0.449f, 1.0f, 1.0f)
verticalLineToRelative(2.0f)
close()
moveTo(16.0f, 4.999f)
curveToRelative(0.0f, 0.551f, -0.449f, 1.0f, -1.0f, 1.0f)
reflectiveCurveToRelative(-1.0f, -0.449f, -1.0f, -1.0f)
verticalLineToRelative(-2.0f)
curveToRelative(0.0f, -0.551f, 0.449f, -1.0f, 1.0f, -1.0f)
reflectiveCurveToRelative(1.0f, 0.449f, 1.0f, 1.0f)
verticalLineToRelative(2.0f)
close()
moveTo(20.0f, 4.999f)
curveToRelative(0.0f, 0.551f, -0.449f, 1.0f, -1.0f, 1.0f)
reflectiveCurveToRelative(-1.0f, -0.449f, -1.0f, -1.0f)
lineToRelative(0.01f, -1.019f)
curveToRelative(0.005f, -0.548f, 0.452f, -0.988f, 1.0f, -0.986f)
curveToRelative(0.548f, 0.003f, 0.99f, 0.447f, 0.99f, 0.995f)
verticalLineToRelative(1.01f)
close()
}
}
.build()
return _handFist!!
}
private var _handFist: ImageVector? = null
| 1
|
Kotlin
|
0
| 5
|
cbd8b510fca0e5e40e95498834f23ec73cc8f245
| 5,767
|
icons
|
MIT License
|
src/main/kotlin/insyncwithfoo/ryecharm/ruff/actions/ShowLinters.kt
|
InSyncWithFoo
| 849,672,176
| false
|
{"Kotlin": 264146, "Python": 3171, "HTML": 624}
|
package insyncwithfoo.ryecharm.ruff.actions
import com.intellij.execution.process.ProcessOutput
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.DialogWrapper
import com.intellij.openapi.ui.VerticalFlowLayout
import com.intellij.ui.ScrollPaneFactory
import com.intellij.ui.scale.JBUIScale.scale
import com.intellij.ui.table.TableView
import com.intellij.util.ui.ColumnInfo
import com.intellij.util.ui.ListTableModel
import insyncwithfoo.ryecharm.Command
import insyncwithfoo.ryecharm.defaultProject
import insyncwithfoo.ryecharm.message
import insyncwithfoo.ryecharm.notifyIfProcessIsUnsuccessfulOr
import insyncwithfoo.ryecharm.ruff.commands.Ruff
import insyncwithfoo.ryecharm.ruff.commands.ruff
import insyncwithfoo.ryecharm.runInBackground
import insyncwithfoo.ryecharm.unableToRunCommand
import insyncwithfoo.ryecharm.unknownError
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import java.awt.BorderLayout
import javax.swing.JComponent
import javax.swing.JPanel
@Serializable
private data class Category(
val prefix: String,
val name: String
)
@Serializable
private data class Linter(
val prefix: String,
val name: String,
val categories: List<Category>? = null
)
private val Linter.categoriesOrSynthesized: List<Category>
get() = categories ?: listOf(Category(prefix = "", name = ""))
private data class LinterTableRow(
val name: String,
val prefix: String,
val linterName: String,
val linterPrefix: String
)
private fun LinterTableRow(linter: Linter, category: Category) = LinterTableRow(
name = category.name,
prefix = category.prefix,
linterName = linter.name,
linterPrefix = linter.prefix
)
private fun column(header: String, getText: (LinterTableRow) -> String) =
object : ColumnInfo<LinterTableRow, String>(header) {
override fun valueOf(item: LinterTableRow) = getText(item)
}
/**
* @see com.intellij.ide.actions.AboutDialog.showOssInfo
*/
private class LintersDialog(private val linters: List<Linter>, project: Project) : DialogWrapper(project) {
private var okButtonText: String
@Deprecated("The getter must not be used.", level = DeprecationLevel.ERROR)
get() = throw RuntimeException()
set(value) = setOKButtonText(value)
private var widthAndHeight: Pair<Int, Int>
@Deprecated("The getter must not be used.", level = DeprecationLevel.ERROR)
get() = throw RuntimeException()
set(value) {
val (width, height) = value
setSize(width, height)
}
private val columns = arrayOf<ColumnInfo<LinterTableRow, String>>(
column(message("dialogs.ruffLinters.linterName")) { it.linterName },
column(message("dialogs.ruffLinters.linterPrefix")) { it.linterPrefix },
column(message("dialogs.ruffLinters.categoryName")) { it.name },
column(message("dialogs.ruffLinters.categoryPrefix")) { it.prefix }
)
init {
init()
@Suppress("DialogTitleCapitalization")
title = message("dialogs.ruffLinters.title")
isAutoAdjustable = true
okButtonText = message("dialogs.actions.close")
widthAndHeight = scale(750) to scale(650)
}
override fun createActions() = arrayOf(okAction)
override fun createCenterPanel(): JComponent {
val selectedColumn = 0
val rows = linters.flatMap { linter ->
linter.categoriesOrSynthesized.map { category ->
LinterTableRow(linter, category)
}
}
val table = TableView(ListTableModel(columns, rows, selectedColumn))
val controlsPanel = JPanel(VerticalFlowLayout())
return JPanel(BorderLayout()).apply {
add(controlsPanel, BorderLayout.NORTH)
add(ScrollPaneFactory.createScrollPane(table), BorderLayout.CENTER)
}
}
}
internal class ShowLinters : AnAction(), DumbAware {
override fun actionPerformed(event: AnActionEvent) {
val project = event.project ?: defaultProject
val ruff = project.ruff ?: return project.unableToRunCommand()
project.runRuffLinterAndShowTable(ruff)
}
private fun Project.runRuffLinterAndShowTable(ruff: Ruff) = runAction {
val command = ruff.linter()
runInBackground(command) { output ->
notifyIfProcessIsUnsuccessfulOr(command, output) {
parseOutputAndShowLinters(command, output)
}
}
}
private fun Project.parseOutputAndShowLinters(command: Command, output: ProcessOutput) {
val linters = parseRuffLinterOutput(output.stdout)
?: return unknownError(command, output)
LintersDialog(linters, this).show()
}
private fun parseRuffLinterOutput(raw: String): List<Linter>? {
val json = Json { ignoreUnknownKeys = true }
return try {
json.decodeFromString<List<Linter>>(raw)
} catch (_: SerializationException) {
null
}
}
}
| 2
|
Kotlin
|
1
| 7
|
c1a04b622fbfb02a2fb155d8c9aa069520eda23e
| 5,363
|
ryecharm
|
MIT License
|
lib-kotlinmvvm/src/main/java/com/mtjsoft/www/kotlinmvputils/utils/AndDialogUtils.kt
|
mtjsoft
| 291,952,943
| false
| null |
package com.mtjsoft.www.kotlinmvputils.utils
import android.app.Dialog
import android.content.Context
import android.text.Html
import android.view.View
import android.widget.TextView
import com.mtjsoft.www.kotlinmvputils.R
import com.mtjsoft.www.kotlinmvputils.imp.AndDialogClickListener
/**
* 对话框操作的工具类
*
* @author mtj
*/
class AndDialogUtils : Builder() {
override fun buildCancelText(cancelText: String): Builder {
cancelTextView!!.text = cancelText
return hhDialogUtils!!
}
override fun buildSureText(sureText: String): Builder {
sureTextView!!.text = sureText
return hhDialogUtils!!
}
override fun buildHideAll(hideAll: Boolean): Builder {
if (hideAll) {
cancelTextView!!.visibility = View.GONE
sureTextView!!.visibility = View.GONE
lineView!!.visibility = View.GONE
lineHView!!.visibility = View.GONE
}
return hhDialogUtils!!
}
override fun buildTitle(title: String): Builder {
titleTextView!!.text = title
return hhDialogUtils!!
}
override fun buildMsg(msg: String): Builder {
msgTextView!!.text = msg
return hhDialogUtils!!
}
override fun buildCancelClickListener(cancelClickListener: AndDialogClickListener?): Builder {
cancelTextView!!.setOnClickListener { v ->
dialog!!.dismiss()
if (cancelClickListener != null) {
cancelClickListener!!.onClick(dialog!!, v)
}
}
return hhDialogUtils!!
}
override fun buildSureClickListener(sureClickListener: AndDialogClickListener?): Builder {
sureTextView!!.setOnClickListener { v ->
if (sureClickListener != null) {
sureClickListener!!.onClick(dialog!!, v)
}
}
return hhDialogUtils!!
}
override fun buildSureTextColor(colorId: Int): Builder {
sureTextView!!.setTextColor(sureTextView!!.context.resources.getColor(colorId))
// cancelTextView!!.setTextColor(thisContext!!.resources.getColor(colorId))
return hhDialogUtils!!
}
override fun buildCanCancel(canCancel: Boolean): Builder {
dialog!!.setCancelable(canCancel)
return hhDialogUtils!!
}
override fun buildShowAll(showAll: Boolean): Builder {
if (!showAll) {
lineView!!.visibility = View.GONE
cancelTextView!!.visibility = View.GONE
}
return hhDialogUtils!!
}
override fun showDialog() {
dialog!!.show()
}
companion object {
private var hhDialogUtils: AndDialogUtils? = null
private var dialog: Dialog? = null
private var titleTextView: TextView? = null
private var msgTextView: TextView? = null
private var cancelTextView: TextView? = null
private var sureTextView: TextView? = null
private var lineView: View? = null
private var lineHView: View? = null
fun builder(context: Context): AndDialogUtils {
dialog = Dialog(context, R.style.huahan_dialog)
val view = View.inflate(context, R.layout.and_dialog_capture_tip, null)
titleTextView = view.findViewById(R.id.tv_dialog_title) as TextView?
msgTextView = view.findViewById(R.id.tv_dialog_msg) as TextView?
cancelTextView = view.findViewById(R.id.tv_dialog_cancel) as TextView?
sureTextView = view.findViewById(R.id.tv_dialog_sure) as TextView?
lineView = view.findViewById(R.id.view)
lineHView = view.findViewById(R.id.line_h)
dialog!!.setContentView(view)
val attributes = dialog!!.window!!
.attributes
attributes.width = AndScreenUtils.getScreenWidth(context) - AndDensityUtils.dip2px(context, 30)
dialog!!.window!!.attributes = attributes
if (hhDialogUtils == null) {
hhDialogUtils = com.mtjsoft.www.kotlinmvputils.utils.AndDialogUtils()
}
dialog!!.setOnDismissListener {
dialog = null
titleTextView = null
msgTextView = null
cancelTextView = null
sureTextView = null
lineView = null
lineHView = null
}
return hhDialogUtils as AndDialogUtils
}
}
}
| 1
|
Kotlin
|
1
| 4
|
9d0e8e70bbcad1f506fb848e3faf684ebe8b0a19
| 4,420
|
LibKM
|
Apache License 2.0
|
lib/src/test/java/com/jintin/bundle/key/ParcelableArrayListKeyTest.kt
|
Jintin
| 684,450,428
| false
|
{"Kotlin": 60382, "Shell": 55}
|
package com.jintin.bundle.key
import io.mockk.every
import io.mockk.verify
import org.junit.Before
import org.junit.Test
class ParcelableArrayListKeyTest : BaseKeyTest() {
private val key = ParcelableArrayListKey<FakeParcelable>("Test")
private val expect = ArrayList<FakeParcelable>()
@Before
fun setup() {
every { bundle.getParcelableArrayList<FakeParcelable>(any()) } returns expect
every { intent.getParcelableArrayListExtra<FakeParcelable>(any()) } returns expect
}
@Test
fun putTest() {
key.put(bundle, expect)
verify(exactly = 1) { bundle.putParcelableArrayList(key.key, expect) }
}
@Test
fun putIntentTest() {
key.put(intent, expect)
verify(exactly = 1) { intent.putExtra(key.key, expect) }
}
@Test
fun getTest() {
val result = key.get(bundle)
verify(exactly = 1) { bundle.getParcelableArrayList<FakeParcelable>(key.key) }
assert(result == expect)
}
@Test
fun getIntentTest() {
val result = key.get(intent)
verify(exactly = 1) { intent.getParcelableArrayListExtra<FakeParcelable>(key.key) }
assert(result == expect)
}
}
| 0
|
Kotlin
|
2
| 18
|
bcb69f1b6505eb23c355ccf3be1039f6a4d2493b
| 1,198
|
TypedBundle
|
Apache License 2.0
|
navigationlistview/src/main/java/com/dvinfosys/adapter/NavigationListAdapter.kt
|
ktmoe
| 301,278,541
| false
|
{"Java Properties": 2, "Gradle": 4, "Shell": 1, "Markdown": 1, "Git Attributes": 1, "Batchfile": 1, "Text": 1, "Ignore List": 3, "XML": 35, "Proguard": 2, "Java": 5, "Kotlin": 5, "INI": 1}
|
package com.dvinfosys.adapter
import android.content.Context
import android.graphics.Typeface
import android.os.Build
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseExpandableListAdapter
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import com.dvinfosys.R
import com.dvinfosys.model.ChildModel
import com.dvinfosys.model.HeaderModel
/**
* Created by ktmmoe on 05, October, 2020
**/
class NavigationListAdapter(
private val context: Context,
private val listHeader: List<HeaderModel>,
private val groupLayoutTap: (Int)->Unit
) :
BaseExpandableListAdapter() {
private val mmTypeFace = Typeface.createFromAsset(context.assets, "fonts/myanmarpixel.ttf")
private val enTypeFace = Typeface.createFromAsset(context.assets, "fonts/dinpro.otf")
override fun getChild(groupPosition: Int, childPosititon: Int): Any {
return listHeader[groupPosition].childModelList[childPosititon]
}
override fun getChildId(groupPosition: Int, childPosition: Int): Long {
return childPosition.toLong()
}
@RequiresApi(Build.VERSION_CODES.N)
override fun getChildView(
groupPosition: Int, childPosition: Int,
isLastChild: Boolean, convertView: View?, parent: ViewGroup?
): View? {
var view: View? = convertView
val childText: ChildModel = getChild(groupPosition, childPosition) as ChildModel
if (view == null) {
val inflater: LayoutInflater = context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
view = inflater.inflate(R.layout.list_item, null)
}
val txtListChild: TextView = view!!.findViewById(R.id.lblListItem)
txtListChild.typeface = if (context.resources.configuration.locales[0].toLanguageTag() == "en") enTypeFace else mmTypeFace
txtListChild.setTextColor(ContextCompat.getColor(context, R.color.colorAccent))
txtListChild.text = childText.menuName
return view
}
override fun getChildrenCount(groupPosition: Int): Int {
return listHeader[groupPosition].childModelList.count()
}
override fun getGroup(groupPosition: Int): Any {
return listHeader[groupPosition]
}
override fun getGroupCount(): Int {
return listHeader.size
}
override fun getGroupId(groupPosition: Int): Long {
return groupPosition.toLong()
}
@RequiresApi(Build.VERSION_CODES.N)
override fun getGroupView(
groupPosition: Int, isExpanded: Boolean,
convertView: View?, parent: ViewGroup?
): View? {
var view: View? = convertView
val header: HeaderModel = getGroup(groupPosition) as HeaderModel
if (view == null) {
val inflater: LayoutInflater = context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
view = inflater.inflate(R.layout.list_group, null)
}
val lblListHeader: TextView? = view?.findViewById(R.id.lblListHeader)
val ivGroupIndicator: ImageView? = view?.findViewById(R.id.ivGroupIndicator)
val iconMenu: ImageView? = view?.findViewById(R.id.icon_menu)
lblListHeader?.typeface = if (context.resources.configuration.locales[0].toLanguageTag() == "en") enTypeFace else mmTypeFace
lblListHeader?.text = header.menuName
lblListHeader?.setTextColor(ContextCompat.getColor(context, R.color.colorAccent))
iconMenu?.setBackgroundResource(header.menuIcon)
iconMenu?.visibility = View.VISIBLE
if (header.hasChild) {
ivGroupIndicator?.visibility = View.VISIBLE
} else {
ivGroupIndicator?.visibility = View.GONE
}
lblListHeader?.setOnClickListener { groupLayoutTap.invoke(groupPosition) }
if (isExpanded) {
ivGroupIndicator?.setImageResource(R.drawable.ic_remove)
} else {
ivGroupIndicator?.setImageResource(R.drawable.ic_add)
}
return view
}
override fun hasStableIds(): Boolean {
return false
}
override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean {
return true
}
}
fun Context.fonts(view: TextView, resource: Int) {
if (Build.VERSION.SDK_INT < 23) {
view.setTextAppearance(this, resource)
} else {
view.setTextAppearance(resource)
}
}
| 1
| null |
1
| 1
|
e72f97cf97e868776076d7723c74fbc554226792
| 4,582
|
Navigation-ListView
|
Apache License 2.0
|
extensions-compose-jetpack/src/main/java/com/arkivanov/decompose/extensions/compose/jetpack/animation/child/Typealias.kt
|
badoo
| 287,788,515
| false
| null |
@file:OptIn(ExperimentalDecomposeApi::class)
package com.arkivanov.decompose.extensions.compose.jetbrains.animation.child
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import com.arkivanov.decompose.Child
import com.arkivanov.decompose.ExperimentalDecomposeApi
import com.arkivanov.decompose.extensions.compose.jetbrains.ChildContent
import com.arkivanov.decompose.router.RouterState
typealias ChildAnimation<C, T> = @Composable (RouterState<C, T>, Modifier, ChildContent<C, T>) -> Unit
/**
* Called for every animation frame, displays the current frame using the provided `content` callback.
*
* Arguments:
*
* - `child` - a child being animated
* - `factor` - the progress of the child animation.
* From 0 to 1 for [ChildAnimationDirection.ENTER], from 1 to 0 for [ChildAnimationDirection.EXIT].
* - `placement` - a relative position of the child being animated, see [ChildPlacement] for details
* - `direction` - a direction of the child animation, see [ChildAnimationDirection] for details
* - `content` - a `@Composable` content block to display the child
*/
// @ExperimentalDecomposeApi (can not be applied to typealias)
typealias ChildAnimator<C, T> =
@Composable (
child: Child.Created<C, T>,
factor: Float,
placement: ChildPlacement,
direction: ChildAnimationDirection,
content: @Composable () -> Unit
) -> Unit
| 7
|
Kotlin
|
44
| 806
|
acc4374212839bfaaffeab89bbcceebdb63cbe13
| 1,418
|
Decompose
|
Apache License 2.0
|
exercises/src/test/kotlin/de/iteratec/kotlin/basic/solutions/T17DelegationTask.kt
|
iteratec
| 190,216,048
| false
|
{"Kotlin": 119132, "Java": 1369, "HTML": 197}
|
package de.iteratec.kotlin.basic.solutions
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Test
import java.util.*
import kotlin.properties.ReadWriteProperty
import kotlin.reflect.KProperty
class CustomLazy<V>(val generator: () -> V) : ReadWriteProperty<Any, V> {
var storedValue: V? = null
override operator fun getValue(thisRef: Any, property: KProperty<*>): V {
return storedValue ?: run {
storedValue = generator()
storedValue!!
}
}
override operator fun setValue(thisRef: Any, property: KProperty<*>, value: V) {
this.storedValue = value
}
}
class DisallowRepetition<V>(private val initial: V) : ReadWriteProperty<Any, V> {
var historicValues: LinkedList<V> = LinkedList(listOf(initial))
override operator fun getValue(thisRef: Any, property: KProperty<*>): V {
return historicValues.last
}
override operator fun setValue(thisRef: Any, property: KProperty<*>, value: V) {
if (historicValues.contains(value)) {
throw RepetitionException()
} else {
historicValues.addLast(value)
}
}
}
class DelegationTasks {
/**
* ## customLazyPropertyDelate
* Replace the call to "lazy" in lazyDelegationExample with a call to a custom class written by yourself.
* The test log "Constructed instance" and afterwards "Evaluated lazy generator." once.
*/
@Test
fun customLazyPropertyDelate() {
val lazyDelegator = LazyDelegationExample()
println("Constructed instance")
lazyDelegator.property
lazyDelegator.property
}
/**
* ## disallowRepetitionDelegate
* Replace the code of DisallowRepetition such that it disallows setting the property to a previous value.
*/
@Test
fun disallowRepetitionDelegate() {
val initialPassword = "<PASSWORD>"
val newPassword = "<PASSWORD>!"
val example = RepetitionDisallowedDelegationExample(initialPassword)
assertEquals(initialPassword, example.password)
example.password = <PASSWORD>
assertEquals(newPassword, example.password)
assertThrows(RepetitionException::class.java) {
example.password = <PASSWORD>
}
}
}
class LazyDelegationExample {
val property: String by CustomLazy {
println("Evaluated lazy generator.")
"Lazy property"
}
}
class RepetitionDisallowedDelegationExample(initialPassword: String) {
var password: String by DisallowRepetition(initialPassword)
}
class RepetitionException: RuntimeException("Setting to a previous value is not allowed")
| 1
|
Kotlin
|
1
| 6
|
388f833f0c7c3693eb65708e6e5f77e032ac156b
| 2,683
|
kotlin-training-playground
|
Apache License 2.0
|
feature/login/src/main/java/dev/enesky/feature/login/navigation/LoginDestination.kt
|
enesky
| 708,119,546
| false
| null |
package dev.enesky.feature.login.navigation
import androidx.navigation.NavGraphBuilder
import androidx.navigation.NavHostController
import androidx.navigation.compose.composable
import androidx.navigation.navigation
import dev.enesky.core.navigation.DoodleNavigationDestination
import dev.enesky.core.navigation.composableWithAnimation
import dev.enesky.feature.login.signin.SignInScreenRoute
import dev.enesky.feature.login.signup.SignUpScreenRoute
/**
* Created by <NAME> on 10/11/2023
*/
object LoginDestination : DoodleNavigationDestination {
override val route = "login_route"
override val destination = "login_destination"
}
object SignInDestination : DoodleNavigationDestination {
override val route = "sign_in_route"
override val destination = "sign_in_destination"
}
object SignUpDestination : DoodleNavigationDestination {
override val route = "sign_up_route"
override val destination = "sign_up_destination"
}
fun NavGraphBuilder.loginGraph(
navController: NavHostController,
onNavigateToHomeDestination: () -> Unit,
) {
navigation(
route = LoginDestination.route,
startDestination = SignInDestination.route,
) {
composable(
route = SignInDestination.route,
) {
SignInScreenRoute(
navigateHome = onNavigateToHomeDestination,
navigateSignUp = {
navController.navigate(SignUpDestination.route)
},
)
}
composableWithAnimation(route = SignUpDestination.route) {
SignUpScreenRoute(
onNavigateToHome = onNavigateToHomeDestination,
onNavigateToSignIn = {
navController.navigate(SignInDestination.route)
},
)
}
}
}
| 28
| null |
0
| 9
|
1341678e0974fc0e0292836e9a8571da679150d9
| 1,822
|
Doodle
|
Apache License 2.0
|
ki-shell/src/main/kotlin/kotlinx/cli/PositionalArguments.kt
|
Kotlin
| 88,049,426
| false
| null |
package kotlinx.cli
abstract class PositionalActionBase(
override val name: String,
private val help: String,
override val minArgs: Int,
override val maxArgs: Int
) : PositionalArgument, ArgumentAction, HelpEntry {
override val action: ArgumentAction get() = this
override fun printHelp(helpPrinter: HelpPrinter) {
helpPrinter.printEntry(name, help)
}
}
abstract class PositionalArgumentBase<T>(
name: String,
help: String,
initialValue: T,
minArgs: Int,
maxArgs: Int
) : PositionalActionBase(name, help, minArgs, maxArgs), ArgumentValue<T> {
protected var value: T = initialValue
override fun getValue(thisRef: Any?, prop: Any?): T = value
}
abstract class SinglePositionalArgumentBase<T>(
name: String,
help: String,
initialValue: T,
minArgs: Int = 0
) : PositionalArgumentBase<T>(name, help, initialValue, minArgs, 1)
abstract class ListPositionalArgumentBase<T>(
name: String,
help: String,
destination: MutableList<T>,
minArgs: Int = 0,
maxArgs: Int = Int.MAX_VALUE
) : PositionalActionBase(name, help, minArgs, maxArgs), ArgumentValue<List<T>> {
protected val value = destination
override fun getValue(thisRef: Any?, prop: Any?): List<T> = value
}
fun <T : PositionalActionBase> CommandLineBuilder.registerAction(action: T): T =
action.also {
addUsageEntry(it.name)
addHelpEntry(it)
addPositionalArgument(it)
}
fun <T> CommandLineBuilder.registerArgument(positionalArgument: PositionalArgumentBase<T>): ArgumentValue<T> =
registerAction(positionalArgument)
fun CommandLineBuilder.positionalAction(name: String, help: String, minArgs: Int = 0, maxArgs: Int = 1, action: (String) -> Unit) {
registerAction(object : PositionalActionBase(name, help, minArgs, maxArgs) {
override fun invoke(argument: String) {
action(argument)
}
})
}
fun CommandLineBuilder.positionalArgument(name: String, help: String, minArgs: Int = 0) =
positionalArgument(name, help, minArgs, { it })
fun CommandLineBuilder.positionalArgument(name: String, help: String, initialValue: String, minArgs: Int = 0) =
positionalArgument(name, help, initialValue, minArgs, { it })
fun <T : Any> CommandLineBuilder.positionalArgument(name: String, help: String, minArgs: Int = 0, mapping: (String) -> T) =
registerArgument(object : SinglePositionalArgumentBase<T?>(name, help, null, minArgs) {
override fun invoke(argument: String) {
value = mapping(argument)
}
})
fun <T : Any> CommandLineBuilder.positionalArgument(name: String, help: String, initialValue: T, minArgs: Int = 0, mapping: (String) -> T) =
registerArgument(object : SinglePositionalArgumentBase<T>(name, help, initialValue, minArgs) {
override fun invoke(argument: String) {
value = mapping(argument)
}
})
fun CommandLineBuilder.positionalArgumentsList(
name: String, help: String,
destination: MutableList<String> = ArrayList(),
minArgs: Int = 0, maxArgs: Int = Int.MAX_VALUE
): ArgumentValue<List<String>> =
positionalArgumentsList(name, help, destination, minArgs, maxArgs, { it })
fun <T> CommandLineBuilder.positionalArgumentsList(
name: String, help: String,
destination: MutableList<T> = ArrayList(),
minArgs: Int = 0, maxArgs: Int = Int.MAX_VALUE,
mapping: (String) -> T
): ArgumentValue<List<T>> =
registerAction(object : ListPositionalArgumentBase<T>(name, help, destination, minArgs, maxArgs) {
override fun invoke(argument: String) {
value.add(mapping(argument))
}
})
fun <T> CommandLineBuilder.foldPositionalArguments(
name: String, help: String,
initialValue: T,
minArgs: Int = 0, maxArgs: Int = Int.MAX_VALUE,
fn: (T, String) -> T
) =
registerArgument(object : PositionalArgumentBase<T>(name, help, initialValue, minArgs, maxArgs) {
override fun invoke(argument: String) {
value = fn(value, argument)
}
})
| 32
| null |
38
| 573
|
5b1ff4d821895f5881a7d389ee92dedff189d2a0
| 4,299
|
kotlin-interactive-shell
|
Apache License 2.0
|
ui/feature/search/src/main/kotlin/com/francescsoftware/weathersample/ui/feature/search/weather/ui/TodayWeather.kt
|
fvilarino
| 355,724,548
| false
|
{"Kotlin": 622612, "Shell": 60}
|
package com.francescsoftware.weathersample.ui.feature.search.weather.ui
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.tooling.preview.PreviewParameter
import com.francescsoftware.weathersample.ui.feature.search.R
import com.francescsoftware.weathersample.ui.feature.search.weather.presenter.WeatherScreen
import com.francescsoftware.weathersample.ui.shared.composable.common.widget.LoadingButton
import com.francescsoftware.weathersample.ui.shared.composable.weather.TodayWeatherCard
import com.francescsoftware.weathersample.ui.shared.styles.MarginDouble
import com.francescsoftware.weathersample.ui.shared.styles.MarginQuad
import com.francescsoftware.weathersample.ui.shared.styles.PhonePreviews
import com.francescsoftware.weathersample.ui.shared.styles.WeatherSampleTheme
@Composable
internal fun TodayWeather(
state: WeatherScreen.Weather.Loaded,
refreshing: Boolean,
todayRefreshCallback: () -> Unit,
modifier: Modifier = Modifier,
) {
Column(
modifier = modifier,
horizontalAlignment = Alignment.CenterHorizontally,
) {
TodayWeatherCard(
state = state.current,
modifier = Modifier.width(WeatherCardWidth),
)
LoadingButton(
onClick = todayRefreshCallback,
modifier = Modifier.padding(top = MarginQuad),
loading = refreshing,
) {
Text(text = stringResource(id = R.string.refresh))
}
}
}
@PhonePreviews
@Composable
private fun PreviewTodayWeather(
@PreviewParameter(
provider = LoadedWeatherStateWrapperProvider::class,
limit = 1,
) stateWrapper: LoadedWeatherStateWrapper,
) {
WeatherSampleTheme {
Surface(
color = MaterialTheme.colorScheme.background,
) {
TodayWeather(
state = stateWrapper.state,
refreshing = false,
todayRefreshCallback = {},
modifier = Modifier
.fillMaxWidth()
.padding(all = MarginDouble),
)
}
}
}
| 1
|
Kotlin
|
5
| 57
|
3a3795e83c579a4dc4d0e6507e96aa68b96fe645
| 2,555
|
Weather-Sample
|
Apache License 2.0
|
android-fragment/src/main/kotlin/com/source/bricks/fragment/argument/ArgumentDelegate.kt
|
krzysiek-zgondek
| 216,539,257
| false
| null |
package com.source.bricks.fragment.argument
import androidx.fragment.app.Fragment
import com.medizzy.android.libs.bricks.android.arguments.FragmentArgument
import kotlin.reflect.KProperty
/**
* Creates delegation for argument of type [Type]
* Internal use only
* */
@PublishedApi
internal inline fun <reified Type> createArgumentDelegate(
name: String,
crossinline decoder: (Fragment, String) -> Type? = ::defaultArgumentDecoder,
crossinline encoder: (Fragment, String, Type) -> Unit = ::defaultArgumentEncoder,
crossinline default: () -> Type
): FragmentArgument<Type> {
return object : FragmentArgument<Type> {
override val name: String = name
override fun getValue(thisRef: Fragment, property: KProperty<*>): Type {
return decoder(thisRef, name) ?: default()
}
override fun setValue(thisRef: Fragment, property: KProperty<*>, value: Type) {
encoder(thisRef, name, value)
}
}
}
| 0
|
Kotlin
|
0
| 4
|
80c5548d7efe70afe1648a448c9f2a535114b531
| 975
|
bricks
|
MIT License
|
src/main/kotlin/com/leetcode/P485.kt
|
antop-dev
| 229,558,170
| false
|
{"Kotlin": 703706, "Java": 210671}
|
package com.leetcode
import kotlin.math.max
class P485 {
fun findMaxConsecutiveOnes(nums: IntArray): Int {
if (nums.isEmpty()) return 0
var max = 0
var c = 0
for (n in nums) {
if (n == 1) {
c++
} else {
max = max(max, c)
c = 0
}
}
return max(max, c)
}
}
| 4
|
Kotlin
|
0
| 0
|
a9dd7cfa4f6cfc5186a86f6e2c8aefc489f5c028
| 398
|
algorithm
|
MIT License
|
xsolla-store-sdk/src/main/java/com/xsolla/android/store/callbacks/GetPhysicalItemsCallback.kt
|
xsolla
| 233,092,015
| false
| null |
package com.xsolla.android.store.callbacks
import com.xsolla.android.store.entity.response.items.PhysicalItemsResponse
interface GetPhysicalItemsCallback {
fun onSuccess(response: PhysicalItemsResponse)
fun onError(throwable: Throwable?, errorMessage: String?)
}
| 1
|
Kotlin
|
5
| 9
|
5f14ce11e41ab638145bbf394d215b7333824e27
| 272
|
store-android-sdk
|
Apache License 2.0
|
rest-api/internal/weather/infrastructure/src/main/kotlin/github/makeitvsolo/kweather/weather/infrastructure/configure/sql/ConfigureJdbcDatasource.kt
|
makeitvsolo
| 743,151,452
| false
|
{"Kotlin": 294456, "TypeScript": 606, "JavaScript": 469, "HTML": 354}
|
package github.makeitvsolo.kweather.user.access.infrastructure.configure.sql
import github.makeitvsolo.kweather.core.error.handling.Result
import github.makeitvsolo.kweather.user.access.infrastructure.configure.sql.error.ConfigureJdbcDatasourceError
import com.zaxxer.hikari.HikariConfig
import com.zaxxer.hikari.HikariDataSource
import javax.sql.DataSource
class ConfigureJdbcDatasource internal constructor(
private var url: String? = null,
private var username: String? = null,
private var password: String? = null
) {
fun url(url: String) = apply { this.url = url }
fun username(username: String) = apply { this.username = username }
fun password(password: String) = apply { this.password = password }
fun configured(): Result<DataSource, ConfigureJdbcDatasourceError> {
val appliedUrl = url
val appliedUsername = username
val appliedPassword = password
appliedUrl ?: return Result.error(
ConfigureJdbcDatasourceError.DataSourceUrlError("missing datasource url")
)
appliedUsername ?: return Result.error(
ConfigureJdbcDatasourceError.InvalidCredentialsError("missing username")
)
appliedPassword ?: return Result.error(
ConfigureJdbcDatasourceError.InvalidCredentialsError("missing password")
)
val config = HikariConfig().apply {
jdbcUrl = appliedUrl
username = appliedUsername
password = appliedPassword
}
return Result.ok(HikariDataSource(config))
}
companion object {
fun with(): ConfigureJdbcDatasource = ConfigureJdbcDatasource()
}
}
| 1
|
Kotlin
|
0
| 0
|
2664ab660be3047a27e32b0f56e7cc8da7df13cd
| 1,673
|
kweather
|
MIT License
|
rxaidl/src/main/java/com/timweng/lib/rxaidl/ClientData.kt
|
WeiTingWeng
| 144,450,435
| false
| null |
package com.timweng.lib.rxaidl
import io.reactivex.disposables.Disposable
internal class ClientData(id: String, version: Long, callback: IBaseCallback) {
val id: String = id
val version: Long = version
val callback: IBaseCallback = callback
val disposableMap: MutableMap<Long, Disposable> = mutableMapOf()
}
| 1
| null |
1
| 4
|
59bac55c7d9bce6115d22cc4bb236cde19364114
| 325
|
RxAIDL
|
Apache License 2.0
|
lovebird-api/src/main/kotlin/com/lovebird/api/config/JwtConfig.kt
|
wooda-ege
| 722,352,043
| false
| null |
package com.lovebird.security.config
import io.jsonwebtoken.io.Decoders
import io.jsonwebtoken.security.Keys
import org.springframework.beans.factory.annotation.Value
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import java.security.Key
@Configuration
class JwtConfig(
@Value("\${jwt.secret}")
private val secretKey: String
) {
@Bean
fun key(): Key {
return Keys.hmacShaKeyFor(Decoders.BASE64.decode(secretKey))
}
}
| 7
| null |
0
| 9
|
c8b1bbcd0eb7e4f8f4ea464e114db76c9c8f1905
| 491
|
lovebird-server
|
MIT License
|
app/src/main/java/io/github/amanshuraikwar/howmuch/ui/monthlybudget/MonthlyBudgetContract.kt
|
amanshuraikwar
| 124,106,668
| false
| null |
package io.github.amanshuraikwar.howmuch.ui.monthlybudget
import android.util.Log
import io.github.amanshuraikwar.howmuch.R
import io.github.amanshuraikwar.howmuch.base.bus.AppBus
import io.github.amanshuraikwar.howmuch.base.data.DataManager
import io.github.amanshuraikwar.howmuch.base.ui.base.BasePresenter
import io.github.amanshuraikwar.howmuch.base.ui.base.BaseView
import io.github.amanshuraikwar.howmuch.base.ui.base.LoadingView
import io.github.amanshuraikwar.howmuch.base.ui.base.UiMessageView
import io.github.amanshuraikwar.howmuch.base.util.Util
import io.github.amanshuraikwar.howmuch.graph.BudgetLineView
import io.github.amanshuraikwar.howmuch.protocol.Category
import io.github.amanshuraikwar.howmuch.protocol.Transaction
import io.github.amanshuraikwar.howmuch.protocol.TransactionType
import io.github.amanshuraikwar.howmuch.ui.HowMuchBasePresenterImpl
import io.github.amanshuraikwar.howmuch.ui.list.items.*
import io.github.amanshuraikwar.multiitemlistadapter.ListItem
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import javax.inject.Inject
interface MonthlyBudgetContract {
interface View : BaseView, UiMessageView, LoadingView {
fun submitList(list: List<ListItem<*, *>>)
fun startHistoryActivity(
category: Category,
month: Int,
year: Int
)
fun updateMonth(previousMonth: Boolean, monthName: String, nextMonth: Boolean)
}
interface Presenter : BasePresenter<View> {
fun onRetryClicked()
fun onRefreshClicked()
fun onPreviousMonthClicked()
fun onNextMonthClicked()
}
class PresenterImpl @Inject constructor(appBus: AppBus,
dataManager: DataManager)
: HowMuchBasePresenterImpl<View>(appBus, dataManager), Presenter {
private val tag = Util.getTag(this)
private var curMonth = 0
private var curYear = 0
private var displayedMonth = 0
private var displayedYear = 0
override fun onAttach(wasViewRecreated: Boolean) {
super.onAttach(wasViewRecreated)
if (wasViewRecreated) {
curMonth = Util.getCurMonthNumber()
curYear = Util.getCurYearNumber()
displayedMonth = curMonth
displayedYear = curYear
fetchItems()
}
}
private fun List<Transaction>.filterByDate(month: Int,
year: Int)
: List<Transaction> {
return this.filter {
val parts = it.date.split("-")
parts[1].toInt() == month && parts[2].toInt() == year
}
}
private fun List<Transaction>.getMonthlyExpenseLimitItem(limit: Double)
: ListItem<*, *> {
val spentAmount = this.sumByDouble { it.amount }
return Limit.Item(
Limit(
spentAmount.money(),
limit.money(),
R.color.monthlyBudgetLimitPrimary,
R.color.monthlyBudgetLimitSecondary
)
)
}
private fun List<Transaction>.getGraphItem(limit: Double)
: ListItem<*, *> {
val data =
this
.groupBy { it.date }
.mapValues { it.value.sumByDouble { it.amount } }
.map {
BudgetLineView.Item(
it.key.split("-")[0].toInt(),
it.value.toFloat()
)
}
.sortedBy { it.x }
val curDayOfMonth = Util.getDayOfMonth()
return MonthlyBudgetGraph.Item(
MonthlyBudgetGraph(
data,
limit.toFloat(),
curDayOfMonth.toFloat(),
displayedMonth == curMonth
)
)
}
private fun Double.money(): Double = "%.2f".format(this).toDouble()
@Suppress("MoveLambdaOutsideParentheses")
private fun List<Transaction>.getCategoryItems(categories: List<Category>)
: List<ListItem<*, *>> {
val debitCategories = categories.filter { it.type == TransactionType.DEBIT }
val categoryAmountMap = {
val categoryIdTxnListMap = this.groupBy { it.categoryId }
debitCategories
.groupBy { it }
.mapValues {
entry ->
(categoryIdTxnListMap[entry.key.id]?.sumByDouble { it.amount }
?: 0.0).money()
}
}.invoke()
val list = mutableListOf<ListItem<*, *>>()
categoryAmountMap
.map {
entry ->
StatCategoryPadded.Item(
StatCategoryPadded(
entry.key,
entry.value,
{
getView()?.startHistoryActivity(
it,
displayedMonth,
displayedYear
)
}
)
)
}
.forEachIndexed {
index, item ->
list.add(item)
if (index != debitCategories.size - 1) {
list.add(DividerFrontPadded.Item())
}
}
return list
}
private fun fetchItems() {
getDataManager()
.getAllTransactions()
.map {
it.toList()
.filter { txn -> txn.type == TransactionType.DEBIT }
.filterByDate(
month = displayedMonth,
year = displayedYear
)
}
.flatMap {
txnList ->
Observable
.fromCallable {
mutableListOf<ListItem<*, *>>()
}
.map {
it.add(
IconTitle.Item(
IconTitle(
"Monthly Budget",
R.drawable.round_date_range_24,
R.color.monthlyBudgetLimitPrimary,
R.color.monthlyBudgetLimitSecondary
)
)
)
it
}
.map {
it.add(Divider.Item())
it
}
.flatMap {
listItems ->
getDataManager()
.getAllCategories()
.map { it.filter { it.type == TransactionType.DEBIT } }
.map {
val total = it.sumByDouble { it.monthlyLimit }
listItems.add(txnList.getMonthlyExpenseLimitItem(total))
listItems.add(Divider.Item())
listItems.add(txnList.getGraphItem(total))
listItems.add(Divider.Item())
listItems.add(
StatHeader.Item(
StatHeader("Categories")
)
)
listItems.addAll(txnList.getCategoryItems(it))
listItems
}
}
}
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.doOnSubscribe {
getView()?.run{
showLoading("Fetching items...")
clearSyncError()
updateMonth(
true,
"${Util.getMonthName(displayedMonth)} $displayedYear",
!(displayedMonth == curMonth && displayedYear == curYear)
)
}
}
.subscribe(
{
Log.d(tag, "fetchItems: Items: $it ")
getView()?.run {
submitList(it)
hideLoading()
}
},
{
it.printStackTrace()
Log.e(tag, "fetchItems: Error: ${it.message}")
getView()?.run {
showError(it.message ?: "Please try again!")
hideLoading()
setSyncError()
}
}
)
.addToCleanup()
}
override fun onRetryClicked() {
fetchItems()
}
override fun onRefreshClicked() {
fetchItems()
}
override fun onPreviousMonthClicked() {
if (displayedMonth == 1) {
displayedMonth = 12
displayedYear--
} else {
displayedMonth--
}
fetchItems()
}
override fun onNextMonthClicked() {
if (displayedMonth == 12) {
displayedMonth = 1
displayedYear++
} else {
displayedMonth++
}
fetchItems()
}
}
}
| 1
| null |
3
| 5
|
69248734bb5f764ca702880e28c4f1cfaf893648
| 11,530
|
HowMuch
|
Apache License 2.0
|
src/main/kotlin/com/everdonor/everdonorbackend/model/DonationTypeDeserializer.kt
|
Everdonor
| 291,569,924
| false
| null |
package com.everdonor.everdonorbackend.model
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonDeserializer
import com.fasterxml.jackson.databind.JsonNode
class DonationTypeDeserializer : JsonDeserializer<DonationType>() {
override fun deserialize(p: JsonParser, ctxt: DeserializationContext): DonationType? {
val oc = p.codec
val node = oc.readTree<JsonNode>(p) ?: return null
val text = node.textValue() ?: return null
return DonationType.valueOf(text.toUpperCase())
}
}
| 0
|
Kotlin
|
0
| 0
|
97118a0c22892dd4c64022730b3e41a6aba11eb5
| 614
|
everdonor-backend
|
MIT License
|
cornea/src/main/java/arcus/cornea/helpers/DeviceModelExt.kt
|
arcus-smart-home
| 168,191,380
| false
| null |
/*
* Copyright 2019 Arcus 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.
*/
@file:JvmName("DeviceModelExt")
package arcus.cornea.helpers
import com.iris.client.event.ClientFuture
import com.iris.client.event.Futures
import com.iris.client.model.DeviceModel
/**
* Attempts to use [DeviceModel] as [clazz] and if that's not possible, will return a failed future
*/
fun <T, U> DeviceModel.laterAs(clazz: Class<T>, action: (T) -> ClientFuture<U>) : ClientFuture<U> {
return if (clazz.isAssignableFrom(this::class.java)) {
action(clazz.cast(this)!!)
} else {
Futures.failedFuture(RuntimeException("[${this::class.java.name}] is not assignable from [${clazz.name}]"))
}
}
/**
* Attempts to use [DeviceModel] as [clazz] and if that's not possible, will return null
*
* @param clazz the class to try to use the device model as
* @param action the action to perform which receives the casted type as it's value
*/
fun <T, U> DeviceModel.nowAs(clazz: Class<T>, action: (T) -> U?) : U? {
return if (clazz.isAssignableFrom(this::class.java)) {
action(clazz.cast(this)!!)
} else {
null
}
}
| 6
|
Java
|
27
| 27
|
845b23b6ee913c58e009914e920242e29d0b137a
| 1,676
|
arcusandroid
|
Apache License 2.0
|
layout-inspector/src/com/android/tools/idea/layoutinspector/resource/ResourceLookup.kt
|
JetBrains
| 60,701,247
| false
|
{"Kotlin": 43855938, "Java": 36698280, "HTML": 1216565, "Starlark": 735324, "C++": 216476, "Python": 101594, "C": 71515, "Lex": 66026, "NSIS": 58516, "AIDL": 32502, "Shell": 28591, "CMake": 21034, "JavaScript": 18437, "Batchfile": 7774, "Smali": 7580, "RenderScript": 4411, "Makefile": 2298, "IDL": 269, "QMake": 18}
|
/*
* 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.layoutinspector.resource
import com.android.annotations.concurrency.Slow
import com.android.ide.common.rendering.api.ResourceReference
import com.android.ide.common.resources.ResourceResolver
import com.android.ide.common.resources.ResourceResolver.MAX_RESOURCE_INDIRECTION
import com.android.ide.common.resources.configuration.FolderConfiguration
import com.android.resources.Density.DEFAULT_DENSITY
import com.android.tools.idea.appinspection.inspector.api.process.ProcessDescriptor
import com.android.tools.idea.configurations.ConfigurationManager
import com.android.tools.idea.layoutinspector.common.StringTable
import com.android.tools.idea.layoutinspector.model.ComposeViewNode
import com.android.tools.idea.layoutinspector.model.ViewNode
import com.android.tools.idea.layoutinspector.properties.InspectorPropertyItem
import com.android.tools.idea.layoutinspector.resource.data.AppContext
import com.android.tools.idea.res.RESOURCE_ICON_SIZE
import com.android.tools.idea.res.parseColor
import com.google.common.annotations.VisibleForTesting
import com.intellij.openapi.application.ReadAction
import com.intellij.openapi.project.Project
import com.intellij.pom.Navigatable
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.psi.util.ClassUtil
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.ui.ColorIcon
import org.jetbrains.android.facet.AndroidFacet
import java.awt.Dimension
import javax.swing.Icon
const val DEFAULT_FONT_SCALE = 1.0f
/**
* Utility for looking up resources in a project.
*
* This class contains facilities for finding property values and to navigate to
* the property definition or property assignment.
*/
class ResourceLookup(private val project: Project) {
private val composeResolver = LambdaResolver(project)
@VisibleForTesting
var resolver: ResourceLookupResolver? = null
private set
val hasResolver: Boolean
get() = resolver != null
/**
* The dpi of the device we are currently inspecting or -1 if unknown.
*/
var dpi: Int = DEFAULT_DENSITY
@VisibleForTesting set
/**
* The fontScale currently used on the device.
*/
var fontScale: Float = DEFAULT_FONT_SCALE
@VisibleForTesting set
/**
* The screen dimension in pixels
*/
var screenDimension: Dimension = Dimension()
private set
/**
* Updates the configuration after a possible configuration change detected on the device.
*/
@Slow
fun updateConfiguration(
folderConfig: FolderConfiguration,
fontScaleFromConfig: Float,
appContext: AppContext,
stringTable: StringTable,
process: ProcessDescriptor
) {
dpi = folderConfig.densityQualifier?.value?.dpiValue ?: DEFAULT_DENSITY
fontScale = if (fontScaleFromConfig != 0.0f) fontScaleFromConfig else DEFAULT_FONT_SCALE
resolver = createResolver(folderConfig, appContext, stringTable, process)
screenDimension = Dimension(appContext.screenWidth, appContext.screenHeight)
}
/**
* Update the configuration after a legacy reload.
*/
fun updateLegacyConfiguration(deviceDpi: Int) {
dpi = deviceDpi
fontScale = DEFAULT_FONT_SCALE
resolver = null
screenDimension = Dimension()
}
@Slow
private fun createResolver(
folderConfig: FolderConfiguration,
appContext: AppContext,
stringTable: StringTable,
process: ProcessDescriptor
): ResourceLookupResolver? {
val facet = ReadAction.compute<AndroidFacet?, RuntimeException> { findFacetFromPackage(project, process.name) } ?: return null
val theme = appContext.theme.createReference(stringTable)
val themeStyle = mapReference(facet, theme)?.resourceUrl?.toString() ?: return null
val mgr = ConfigurationManager.getOrCreateInstance(facet)
val cache = mgr.resolverCache
val resourceResolver = ReadAction.compute<ResourceResolver, RuntimeException> {
cache.getResourceResolver(mgr.target, themeStyle, folderConfig)
}
return ResourceLookupResolver(project, facet, folderConfig, resourceResolver)
}
/**
* Find the file locations for a [property].
*
* The list of file locations will start from [InspectorPropertyItem.source]. If that is a reference
* the definition of that reference will be next etc.
* The [max] guards against recursive indirection in the resources.
* Each file location is specified by:
* - a string containing the file name and a line number
* - a [Navigatable] that can be used to goto the source location
*/
fun findFileLocations(property: InspectorPropertyItem, view: ViewNode, max: Int = MAX_RESOURCE_INDIRECTION): List<SourceLocation> =
resolver?.findFileLocations(property, view, property.source, max) ?: emptyList()
/**
* Find the location of the specified [view].
*/
fun findFileLocation(view: ViewNode): SourceLocation? =
resolver?.findFileLocation(view)
/**
* Find the attribute value from resource reference.
*/
fun findAttributeValue(property: InspectorPropertyItem, view: ViewNode, location: ResourceReference): String? =
resolver?.findAttributeValue(property, view, location)
/**
* Find the lambda source location.
*/
fun findLambdaLocation(
packageName: String,
fileName: String,
lambdaName: String,
functionName: String,
startLine: Int,
endLine: Int
): SourceLocation =
composeResolver.findLambdaLocation(packageName, fileName, lambdaName, functionName, startLine, endLine)
/**
* Find the source navigatable of a composable function.
*/
@Slow
fun findComposableNavigatable(composable: ComposeViewNode): Navigatable? =
composeResolver.findComposableNavigatable(composable)
/**
* Find the icon from this drawable property.
*/
fun resolveAsIcon(property: InspectorPropertyItem, view: ViewNode): Icon? {
resolver?.resolveAsIcon(property, view)?.let { return it }
val value = property.value
val color = value?.let { parseColor(value) } ?: return null
return JBUIScale.scaleIcon(ColorIcon(RESOURCE_ICON_SIZE, color, false))
}
/**
* Convert a class name to a source location.
*/
fun resolveClassNameAsSourceLocation(className: String): SourceLocation? {
val psiClass = JavaPsiFacade.getInstance(project).findClass(className, GlobalSearchScope.allScope(project))
val navigatable = psiClass?.let { findNavigatable(psiClass) } ?: return null
val source = ClassUtil.extractClassName(className)
return SourceLocation(source, navigatable)
}
/**
* Is this attribute a dimension according to the resource manager.
*/
@Slow
fun isDimension(view: ViewNode, attributeName: String): Boolean =
ReadAction.compute<Boolean, Nothing> { resolver?.isDimension(view, attributeName) ?: false }
}
| 2
|
Kotlin
|
230
| 876
|
9c0a89784cca3c01ab99cf251b71a26cdb87cc47
| 7,402
|
android
|
Apache License 2.0
|
mulighetsrommet-api/src/main/kotlin/no/nav/mulighetsrommet/api/domain/dto/SanityMutateDto.kt
|
navikt
| 435,813,834
| false
|
{"Kotlin": 1192202, "TypeScript": 993440, "SCSS": 39443, "JavaScript": 24814, "PLpgSQL": 10327, "HTML": 1504, "Dockerfile": 683, "CSS": 437, "Shell": 95}
|
package no.nav.mulighetsrommet.api.domain.dto
import kotlinx.serialization.EncodeDefault
import kotlinx.serialization.ExperimentalSerializationApi
import kotlinx.serialization.Serializable
@Serializable
data class Mutations<T>(
val mutations: List<Mutation<T>>,
)
@Serializable
data class Mutation<T>(
val createIfNotExists: T? = null,
val createOrReplace: T? = null,
val patch: T? = null,
val delete: Delete? = null,
)
@Serializable
data class Delete(
val id: String,
)
@Serializable
data class Patch<T>(
val id: String,
val set: T,
)
@OptIn(ExperimentalSerializationApi::class)
@Serializable
data class CreateSanityTiltaksgjennomforingDto(
val _id: String,
@EncodeDefault
val _type: String = "tiltaksgjennomforing",
val tiltaksgjennomforingNavn: String,
val fylke: FylkeRef? = null,
val enheter: List<EnhetRef>? = null,
val tiltakstype: TiltakstypeRef? = null,
val tiltaksnummer: TiltaksnummerSlug? = null,
val stedForGjennomforing: String? = null,
)
@Serializable
data class SanityTiltaksgjennomforingFields(
val tiltaksgjennomforingNavn: String,
val fylke: FylkeRef? = null,
val enheter: List<EnhetRef>? = null,
val tiltakstype: TiltakstypeRef? = null,
val tiltaksnummer: TiltaksnummerSlug? = null,
val stedForGjennomforing: String? = null,
) {
fun toSanityTiltaksgjennomforing(id: String) = CreateSanityTiltaksgjennomforingDto(
_id = id,
tiltaksgjennomforingNavn = this.tiltaksgjennomforingNavn,
fylke = this.fylke,
enheter = this.enheter,
tiltakstype = this.tiltakstype,
tiltaksnummer = this.tiltaksnummer,
stedForGjennomforing = this.stedForGjennomforing,
)
}
@OptIn(ExperimentalSerializationApi::class)
@Serializable
data class SanityEnhet(
val _id: String,
@EncodeDefault
val _type: String = "enhet",
val navn: String,
val nummer: EnhetSlug,
val type: String,
val status: String,
val fylke: FylkeRef?,
)
@OptIn(ExperimentalSerializationApi::class)
@Serializable
data class EnhetSlug(
@EncodeDefault
val _type: String = "slug",
val current: String,
)
@OptIn(ExperimentalSerializationApi::class)
@Serializable
data class TiltakstypeRef(
@EncodeDefault
val _type: String = "reference",
val _ref: String,
val _key: String? = null,
)
@Serializable
data class TiltakstypeIdResponse(
val _id: String,
)
@OptIn(ExperimentalSerializationApi::class)
@Serializable
data class FylkeRef(
@EncodeDefault
val _type: String = "reference",
val _ref: String,
val _key: String? = null,
)
| 4
|
Kotlin
|
1
| 6
|
f46a03dff0bd99d89a0e16c298fa8d62cbf5e5f8
| 2,626
|
mulighetsrommet
|
MIT License
|
Android/app/src/main/java/ademar/bitac/ext/Retrofit.kt
|
ademar111190
| 111,263,585
| false
| null |
package ademar.bitac.ext
import ademar.bitac.model.FieldProperty
import ademar.bitac.model.StandardErrors
import io.reactivex.Observable
import retrofit2.Call
import retrofit2.Retrofit
import java.io.IOException
var Retrofit.standardErrors: StandardErrors by FieldProperty()
fun <T> Retrofit.observeBody(call: Call<T>): Observable<T> = Observable.create<T> {
val response = try {
call.execute()
} catch (e: IOException) {
if (!it.isDisposed) {
it.onError(standardErrors.noConnection)
} else {
it.onComplete()
}
return@create
}
if (response != null) {
when (response.code()) {
200 -> {
val body = response.body()
if (body != null) {
it.onNext(body)
it.onComplete()
} else {
it.onError(standardErrors.unknown)
}
}
401 -> it.onError(standardErrors.unauthorized)
500 -> {
val errorMessage = response.errorBody()?.string()
it.onError(if (errorMessage != null) Error(errorMessage) else standardErrors.unknown)
}
else -> {
val errorBody = response.errorBody()
if (errorBody != null) {
val converter = responseBodyConverter<Error>(Error::class.java, arrayOf<Annotation>())
val error: Error? = converter.convert(errorBody)
it.onError(if (error?.message?.isNotEmpty() == true) error else standardErrors.unknown)
} else {
it.onError(standardErrors.unknown)
}
}
}
}
}
| 3
| null |
4
| 8
|
2520c0d641a17bbfe0b0b76593781289faa2d2c8
| 1,743
|
BitAC
|
MIT License
|
plugins/kotlin/code-insight/impl-base/resources/inlayProviders/kotlin.references.types.hints/hints.type.function.return.kt
|
JetBrains
| 2,489,216
| false
| null |
fun square(arg: Int)/*<# :Int #>*/ = arg * arg
| 284
| null |
5162
| 16,707
|
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
| 47
|
intellij-community
|
Apache License 2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.