path
stringlengths 4
280
| owner
stringlengths 2
39
| repo_id
int64 21.1k
879M
| is_fork
bool 2
classes | languages_distribution
stringlengths 13
1.95k
⌀ | content
stringlengths 7
482k
| issues
int64 0
13.9k
| main_language
stringclasses 121
values | forks
stringlengths 1
5
| stars
int64 0
111k
| commit_sha
stringlengths 40
40
| size
int64 7
482k
| name
stringlengths 1
100
| license
stringclasses 93
values |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
app/src/main/java/com/fracta7/crafter/ui/navigation/Screens.kt | fracta7 | 749,375,185 | false | {"Kotlin": 384208} | package com.fracta7.crafter.ui.navigation
sealed class Screens(val route: String) {
object MainScreen : Screens("main_screen")
object CraftingScreen : Screens("crafting_screen")
object RootCraftingScreen : Screens("root_crafting_screen")
fun withArgs(vararg args: String): String {
return buildString {
append(route)
args.forEach { arg ->
append("/$arg")
}
}
}
} | 0 | Kotlin | 0 | 2 | bc067fec85e71afcab4c140789e8bb67ef2ee1f3 | 451 | crafter | MIT License |
app/src/main/java/com/financialchecker/ui/expense/ExpenseViewHolder.kt | userddssilva | 750,118,533 | false | {"Kotlin": 34957} | /*
* MIT License
*
* Copyright (c) 2024 Financial Checker
*
* 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.financialchecker.presenter.adapter.viewholder
import android.view.View
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import com.financialchecker.R
class ExpenseViewHolder(itemView: View) : ViewHolder(itemView) {
var description: TextView = itemView.findViewById(R.id.tv_expense_description)
var date: TextView = itemView.findViewById(R.id.tv_expense_date)
var value: TextView = itemView.findViewById(R.id.tv_expense_value)
var category: TextView = itemView.findViewById(R.id.tv_expense_cate)
var isPaid: TextView = itemView.findViewById(R.id.tv_is_paid)
} | 0 | Kotlin | 0 | 0 | b4ea9a8573b7ff459722b3267615752ecb7e1450 | 1,775 | financial-checker-mobile | MIT License |
src/main/kotlin/assetFile/MetaData.kt | Kleiark | 239,992,352 | true | {"Kotlin": 137223} | package assetFile
import beatwalls.readBpm
import beatwalls.readHjsDuration
import beatwalls.readOffset
class MetaData(val bpm: Double, val hjd: Double, val offset: Double)
fun readAsset() =
MetaData(
readBpm(),
readHjsDuration(),
readOffset()
)
| 0 | null | 0 | 0 | f8b0587ad1d170376b2f26d693075c7f0ab1c9a4 | 283 | beatwalls-1 | MIT License |
src/main/kotlin/assetFile/MetaData.kt | Kleiark | 239,992,352 | true | {"Kotlin": 137223} | package assetFile
import beatwalls.readBpm
import beatwalls.readHjsDuration
import beatwalls.readOffset
class MetaData(val bpm: Double, val hjd: Double, val offset: Double)
fun readAsset() =
MetaData(
readBpm(),
readHjsDuration(),
readOffset()
)
| 0 | null | 0 | 0 | f8b0587ad1d170376b2f26d693075c7f0ab1c9a4 | 283 | beatwalls-1 | MIT License |
core/src/main/kotlin/id/shaderboi/koffie/core/data/auth/User.kt | gadostudio | 476,396,630 | false | {"Kotlin": 123765} | package id.shaderboi.koffie.core.data.auth
data class User(
val displayName: String?,
val phoneNumber: String,
) {
val isRegistered get() = displayName?.isNotBlank() == true
}
| 0 | Kotlin | 0 | 0 | f3203daabe647ebb052e7d431c14cc4f29449ada | 189 | koffie-mobile | MIT License |
kotlin-mui-icons/src/main/generated/mui/icons/material/CropSquareRounded.kt | JetBrains | 93,250,841 | false | null | // Automatically generated - do not modify!
@file:JsModule("@mui/icons-material/CropSquareRounded")
@file:JsNonModule
package mui.icons.material
@JsName("default")
external val CropSquareRounded: SvgIconComponent
| 10 | Kotlin | 5 | 983 | 7ef1028ba3e0982dc93edcdfa6ee1edb334ddf35 | 216 | kotlin-wrappers | Apache License 2.0 |
features/game/settings/ui/src/main/java/com/ruslan/hlushan/game/settings/ui/di/SettingsOutScreenCreator.kt | game-x50 | 361,364,864 | false | null | package com.ruslan.hlushan.game.settings.ui.di
import com.github.terrakok.cicerone.Screen
interface SettingsOutScreenCreator {
fun createProfileScreen(): Screen
fun createTopScreen(): Screen
}
interface SettingsOutScreenCreatorProvider {
fun provideSettingsOutScreenCreator(): SettingsOutScreenCreator
} | 26 | Kotlin | 0 | 0 | 155c9ae3e60bb24141823837b2dddf041f71ff89 | 321 | android_client_app | Apache License 2.0 |
src/main/kotlin/com/sk/topicWise/monotonicStack/907. Sum of Subarray Minimums.kt | sandeep549 | 262,513,267 | false | null | package com.sk.topicWise.monotonicStack
import kotlin.math.abs
class Solution907 {
fun sumSubarrayMins(arr: IntArray): Int {
val MAX = 1_000_000_007
val M = 3_000_1
var ans = 0
val dp = Array(arr.size) { IntArray(arr.size) { M } }
for (i in arr.indices) {
for (j in 0..i) {
if (j == i) {
dp[j][i] = arr[i]
} else {
dp[j][i] = minOf(dp[j][i - 1], arr[i])
}
ans = ((ans + dp[j][i]) % MAX).toInt()
//println("j=$j, i=$i, min=${dp[j][i]}")
}
}
return ans
}
fun sumSubarrayMins2(A: IntArray): Int {
val stack = ArrayDeque<Int>()
val dp = IntArray(A.size + 1)
stack.addLast(-1)
var result = 0
val M = 1e9.toInt() + 7
for (i in A.indices) {
while (stack.last() != -1 && A[stack.last()] >= A[i] ) { // monotone increasing stack
stack.removeLast()
}
dp[i + 1] = (dp[stack.last() + 1] + (i - stack.last()) * A[i]) % M
stack.addLast(i)
result += dp[i + 1]
result %= M
}
return result
}
fun minimumPushes(word: String): Int {
val list = word.groupBy { it }.map { it.value.size }
// val arr = IntArray(26)
// for(ch in word.toCharArray()) {
// arr[ch-'a']++
// }
// val list = arr.sorted().reversed().toList()
val q = list.size/8
val r = list.size % 8
var ans = 0
for (i in 1..q) {
ans += (i*8)
}
ans += (r*8)
return ans
}
fun countOfPairs(n: Int, x: Int, y: Int): IntArray {
val mat = Array(n+1) { IntArray(n+1) }
for (i in 1.. mat.lastIndex) {
for (j in 1.. mat[0].lastIndex) {
mat[i][j] = abs(i-j)
mat[j][i] = abs(i-j)
}
}
mat[x][y] = 1
mat[y][x] = 1
for (i in 1..minOf(x, y)) {
for (j in maxOf(x, y) .. n) {
mat[i][j] = mat[i][j] - abs(x-y)
mat[j][i] = mat[j][i] - abs(x-y)
}
}
val ans = IntArray(n)
for (i in 1.. mat.lastIndex) {
for (j in 1.. mat[0].lastIndex) {
ans[mat[i][j]-1]++
ans[mat[j][i]-1]++
}
}
return ans
}
}
| 1 | null | 1 | 1 | 67688ec01551e9981f4be07edc11e0ee7c0fab4c | 2,478 | leetcode-answers-kotlin | Apache License 2.0 |
base/src/main/java/br/com/programadorthi/base/extension/ViewExt.kt | programadorthi | 165,963,379 | false | null | package br.com.programadorthi.base.extension
import android.view.View
fun View.setVisible(visible: Boolean) {
visibility = if (visible) {
View.VISIBLE
} else {
View.GONE
}
} | 0 | Kotlin | 0 | 12 | 3547af32de09f6dbdaf22c921c0e9c63421d327e | 203 | Anarchitecturetry | MIT License |
app/src/main/java/com/patloew/countries/util/RealmListPaperParcelTypeConverter.kt | KishoreBabuIN | 139,934,644 | true | {"Kotlin": 147165, "Java": 18618} | package com.patloew.countries.util
import android.os.Parcel
import io.realm.RealmList
import paperparcel.TypeAdapter
/* Copyright 2017 <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. */
class RealmListPaperParcelTypeConverter<T>(val itemAdapter : TypeAdapter<T>) : TypeAdapter<RealmList<T>> {
override fun readFromParcel(source: Parcel): RealmList<T> {
val size = source.readInt()
val realmList = RealmList<T>()
for (i in 0 until size) { realmList.add(itemAdapter.readFromParcel(source)) }
return realmList
}
override fun writeToParcel(value: RealmList<T>, dest: Parcel, flags: Int) {
dest.writeInt(value.size)
for (i in 0 until value.size) { itemAdapter.writeToParcel(value[i], dest, flags) }
}
}
| 0 | Kotlin | 0 | 0 | 615fa4851705bd48c1dd73f4147bc46a52a7d55c | 1,283 | countries | Apache License 2.0 |
dp-inntekt-api/src/test/kotlin/no/nav/dagpenger/inntekt/mapping/PosteringsTypeMappingTest.kt | navikt | 165,044,758 | false | {"Kotlin": 435266, "Dockerfile": 108} | package no.nav.dagpenger.inntekt.mapping
import no.nav.dagpenger.inntekt.inntektskomponenten.v1.InntektBeskrivelse
import no.nav.dagpenger.inntekt.inntektskomponenten.v1.InntektType
import no.nav.dagpenger.inntekt.inntektskomponenten.v1.SpesielleInntjeningsforhold
import no.nav.dagpenger.inntekt.v1.PosteringsType
import org.junit.jupiter.api.Test
import kotlin.test.assertEquals
internal class PosteringsTypeMappingTest {
@Test
fun `test toPosteringsType håndterer UNKNOWN forhold`() {
val posteringsType = PosteringsType.L_FASTLØNN
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.FASTLOENN, SpesielleInntjeningsforhold.UNKNOWN)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
}
@Test
fun `test posteringstype-mapping for Aksjer_grunnfondsbevis til underkurs`() {
val posteringsType = PosteringsType.L_AKSJER_GRUNNFONDSBEVIS_TIL_UNDERKURS
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.AKSJER_GRUNNFONDSBEVIS_TIL_UNDERKURS,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Annen arbeidsinntekt`() {
val posteringsType = PosteringsType.L_ANNET
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.ANNET, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Annen arbeidsinntekt - Ikke skattepliktig`() {
val posteringsType = PosteringsType.L_ANNET_IKKE_SKATTEPLIKTIG
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.ANNET,
SpesielleInntjeningsforhold.LOENN_OG_ANNEN_GODTGJOERELSE_SOM_IKKE_ER_SKATTEPLIKTIG,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Annen arbeidsinntekt - Utlandet`() {
val posteringsType = PosteringsType.L_ANNET_UTLANDET
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.ANNET,
SpesielleInntjeningsforhold.LOENN_UTBETALT_FRA_DEN_NORSKE_STAT_OPPTJENT_I_UTLANDET,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Annen arbeidsinntekt - Konkurs`() {
val posteringsType = PosteringsType.L_ANNET_KONKURS
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.ANNET,
SpesielleInntjeningsforhold.LOENN_VED_KONKURS_ELLER_STATSGARANTI_OSV,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Arbeidsopphold kost`() {
val posteringsType = PosteringsType.L_ARBEIDSOPPHOLD_KOST
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.ARBEIDSOPPHOLD_KOST, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Arbeidsopphold losji`() {
val posteringsType = PosteringsType.L_ARBEIDSOPPHOLD_LOSJI
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.ARBEIDSOPPHOLD_LOSJI, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Beregnet skatt`() {
val posteringsType = PosteringsType.L_BEREGNET_SKATT
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.BEREGNET_SKATT, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Besøksreiser hjemmet annet`() {
val posteringsType = PosteringsType.L_BESØKSREISER_HJEMMET_ANNET
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.BESOEKSREISER_HJEMMET_ANNET, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Besøksreiser hjemmet kilometergodtgjørelse bil`() {
val posteringsType = PosteringsType.L_BESØKSREISER_HJEMMET_KILOMETERGODTGJØRELSE_BIL
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.BESOEKSREISER_HJEMMET_KILOMETERGODTGJOERELSE_BIL,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Betalt utenlandsk skatt`() {
val posteringsType = PosteringsType.L_BETALT_UTENLANDSK_SKATT
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.BETALT_UTENLANDSK_SKATT, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Bil`() {
val posteringsType = PosteringsType.L_BIL
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.BIL, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Bolig`() {
val posteringsType = PosteringsType.L_BOLIG
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.BOLIG, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Bonus`() {
val posteringsType = PosteringsType.L_BONUS
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.BONUS, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Bonus fra forsvaret`() {
val posteringsType = PosteringsType.L_BONUS_FRA_FORSVARET
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.BONUS_FRA_FORSVARET, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Elektronisk kommunikasjon`() {
val posteringsType = PosteringsType.L_ELEKTRONISK_KOMMUNIKASJON
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.ELEKTRONISK_KOMMUNIKASJON, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Fast bilgodtgjørelse`() {
val posteringsType = PosteringsType.L_FAST_BILGODTGJØRELSE
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.FAST_BILGODTGJOERELSE, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Faste tillegg`() {
val posteringsType = PosteringsType.L_FAST_TILLEGG
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.FAST_TILLEGG, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Fastlønn`() {
val posteringsType = PosteringsType.L_FASTLØNN
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.FASTLOENN, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Feriepenger`() {
val posteringsType = PosteringsType.L_FERIEPENGER
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.FERIEPENGER, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test at inntjeningsforhold uten mapping er det samme som null`() {
val posteringsTypeWithNull = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.FERIEPENGER, null)
val posteringsTypeWithoutMapping =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.FERIEPENGER,
SpesielleInntjeningsforhold.STATSANSATT_UTLANDET,
)
assertEquals(toPosteringsType(posteringsTypeWithNull), toPosteringsType(posteringsTypeWithoutMapping))
}
@Test
fun `test at ukjent inntjeningsforhold er det samme som null`() {
val posteringsTypeWithNull = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.FERIEPENGER, null)
val posteringsTypeWithUnknown =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.FERIEPENGER, SpesielleInntjeningsforhold.UNKNOWN)
assertEquals(toPosteringsType(posteringsTypeWithNull), toPosteringsType(posteringsTypeWithUnknown))
}
@Test
fun `test posteringstype-mapping for Fond for idrettsutøvere`() {
val posteringsType = PosteringsType.L_FOND_FOR_IDRETTSUTØVERE
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.FOND_FOR_IDRETTSUTOEVERE, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Foreldrepenger fra folketrygden`() {
val posteringsType = PosteringsType.Y_FORELDREPENGER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.YTELSE_FRA_OFFENTLIGE, InntektBeskrivelse.FORELDREPENGER, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for feriepenger som gjelder foreldrepenger fra folketrygden`() {
val posteringsType = PosteringsType.Y_FORELDREPENGER_FERIEPENGER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.YTELSE_FRA_OFFENTLIGE, InntektBeskrivelse.FORELDREPENGER_FERIEPENGER, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Helligdagstillegg`() {
val posteringsType = PosteringsType.L_HELLIGDAGSTILLEGG
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.HELLIGDAGSTILLEGG, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Honorar, akkord, prosent eller provisjonslønn`() {
val posteringsType = PosteringsType.L_HONORAR_AKKORD_PROSENT_PROVISJON
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.HONORAR_AKKORD_PROSENT_PROVISJON,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Hyre - Honorar, akkord, prosent eller provisjonslønn`() {
val posteringsType = PosteringsType.L_HONORAR_AKKORD_PROSENT_PROVISJON_H
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.HONORAR_AKKORD_PROSENT_PROVISJON,
SpesielleInntjeningsforhold.HYRE_TIL_MANNSKAP_PAA_FISKE_SMAAHVALFANGST_OG_SELFANGSTFARTOEY,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Hyretillegg`() {
val posteringsType = PosteringsType.L_HYRETILLEGG
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.HYRETILLEGG, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Innbetaling til utenlandsk pensjonsordning`() {
val posteringsType = PosteringsType.L_INNBETALING_TIL_UTENLANDSK_PENSJONSORDNING
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.INNBETALING_TIL_UTENLANDSK_PENSJONSORDNING,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Kilometergodtgjørelse bil`() {
val posteringsType = PosteringsType.L_KILOMETERGODTGJØRELSE_BIL
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.KILOMETERGODTGJOERELSE_BIL, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Kommunal omsorgslønn og fosterhjemsgodtgjørelse`() {
val posteringsType = PosteringsType.L_KOMMUNAL_OMSORGSLØNN_OG_FOSTERHJEMSGODTGJØRELSE
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.KOMMUNAL_OMSORGSLOENN_OG_FOSTERHJEMSGODTGJOERELSE,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Kost (dager)`() {
val posteringsType = PosteringsType.L_KOST_DAGER
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.KOST_DAGER, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Kost (døgn)`() {
val posteringsType = PosteringsType.L_KOST_DØGN
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.KOST_DOEGN, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Kostbesparelse i hjemmet`() {
val posteringsType = PosteringsType.L_KOSTBESPARELSE_I_HJEMMET
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.KOSTBESPARELSE_I_HJEMMET, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Losji`() {
val posteringsType = PosteringsType.L_LOSJI
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.LOSJI, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Lønn mv som ikke er skattepliktig i Norge fra utenlandsk diplomatisk eller konsulær stasjon`() {
val posteringsType = PosteringsType.L_IKKE_SKATTEPLIKTIG_LØNN_FRA_UTENLANDSK_DIPLOM_KONSUL_STASJON
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.IKKE_SKATTEPLIKTIG_LOENN_FRA_UTENLANDSK_DIPLOM_KONSUL_STASJON,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Lønn og godtgjørelse til dagmamma eller praktikant som passer barn i barnets hjem`() {
val posteringsType = PosteringsType.L_LØNN_FOR_BARNEPASS_I_BARNETS_HJEM
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.LOENN_FOR_BARNEPASS_I_BARNETS_HJEM,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Lønn og godtgjørelse til privatpersoner for arbeidsoppdrag i oppdragsgivers hjem`() {
val posteringsType = PosteringsType.L_LØNN_TIL_PRIVATPERSONER_FOR_ARBEID_I_HJEMMET
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.LOENN_TIL_PRIVATPERSONER_FOR_ARBEID_I_HJEMMET,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Lønn og godtgjørelse utbetalt av veldedig eller allmennyttig institusjon eller organisasjon`() {
val posteringsType = PosteringsType.L_LØNN_UTBETALT_AV_VELDEDIG_ELLER_ALLMENNYTTIG_INSTITUSJON_ELLER_ORGANISASJON
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.LOENN_UTBETALT_AV_VELDEDIG_ELLER_ALLMENNYTTIG_INSTITUSJON_ELLER_ORGANISASJON,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Lønn til verge fra Statsforvalteren`() {
val posteringsType = PosteringsType.L_LØNN_TIL_VERGE_FRA_STATSFORVALTEREN
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.LOENN_TIL_VERGE_FRA_STATSFORVALTEREN,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Lønn til verge fra Fylkesmannen`() {
val posteringsType = PosteringsType.L_LØNN_TIL_VERGE_FRA_FYLKESMANNEN
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.LOENN_TIL_VERGE_FRA_FYLKESMANNEN,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Opsjoner`() {
val posteringsType = PosteringsType.L_OPSJONER
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.OPSJONER, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Overtidsgodtgjørelse`() {
val posteringsType = PosteringsType.L_OVERTIDSGODTGJØRELSE
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.OVERTIDSGODTGJOERELSE, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Reise annet`() {
val posteringsType = PosteringsType.L_REISE_ANNET
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.REISE_ANNET, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Reise kost`() {
val posteringsType = PosteringsType.L_REISE_KOST
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.REISE_KOST, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Reise losji`() {
val posteringsType = PosteringsType.L_REISE_LOSJI
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.REISE_LOSJI, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Rentefordel lån`() {
val posteringsType = PosteringsType.L_RENTEFORDEL_LÅN
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.RENTEFORDEL_LAAN, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Skattepliktig del av visse typer forsikringer`() {
val posteringsType = PosteringsType.L_SKATTEPLIKTIG_DEL_FORSIKRINGER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.SKATTEPLIKTIG_DEL_FORSIKRINGER,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Skattepliktig personalrabatt`() {
val posteringsType = PosteringsType.L_SKATTEPLIKTIG_PERSONALRABATT
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.SKATTEPLIKTIG_PERSONALRABATT,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Skattepliktig godtgjørelse særavtale utland"`() {
val posteringsType = PosteringsType.L_SKATTEPLIKTIG_GODTGJOERELSE_SAERAVTALE_UTLAND
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.SKATTEPLIKTIG_GODTGJOERELSE_SAERAVTALE_UTLAND,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Sluttvederlag`() {
val posteringsType = PosteringsType.L_SLUTTVEDERLAG
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.SLUTTVEDERLAG, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Smusstillegg`() {
val posteringsType = PosteringsType.L_SMUSSTILLEGG
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.SMUSSTILLEGG, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Stipend`() {
val posteringsType = PosteringsType.L_STIPEND
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.STIPEND, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Styrehonorar og godtgjørelse i forbindelse med verv`() {
val posteringsType = PosteringsType.L_STYREHONORAR_OG_GODTGJØRELSE_VERV
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.STYREHONORAR_OG_GODTGJOERELSE_VERV,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Svangerskapspenger`() {
val posteringsType = PosteringsType.Y_SVANGERSKAPSPENGER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.YTELSE_FRA_OFFENTLIGE, InntektBeskrivelse.SVANGERSKAPSPENGER, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for feriepenger som gjelder svangerskapspenger`() {
val posteringsType = PosteringsType.Y_SVANGERSKAPSPENGER_FERIEPENGER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.YTELSE_FRA_OFFENTLIGE, InntektBeskrivelse.SVANGERSKAPSPENGER_FERIEPENGER, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Timelønn`() {
val posteringsType = PosteringsType.L_TIMELØNN
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.TIMELOENN, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Tips`() {
val posteringsType = PosteringsType.L_TIPS
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.TIPS, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Trekk i lønn for ferie`() {
val posteringsType = PosteringsType.L_TREKK_I_LØNN_FOR_FERIE
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.LOENNSINNTEKT, InntektBeskrivelse.TREKK_I_LOENN_FOR_FERIE, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Uregelmessige tillegg knyttet til arbeidet tid`() {
val posteringsType = PosteringsType.L_UREGELMESSIGE_TILLEGG_KNYTTET_TIL_ARBEIDET_TID
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.UREGELMESSIGE_TILLEGG_KNYTTET_TIL_ARBEIDET_TID,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Uregelmessige tillegg knyttet til ikke-arbeidet tid`() {
val posteringsType = PosteringsType.L_UREGELMESSIGE_TILLEGG_KNYTTET_TIL_IKKE_ARBEIDET_TID
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.UREGELMESSIGE_TILLEGG_KNYTTET_TIL_IKKE_ARBEIDET_TID,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Yrkebil tjenestligbehov kilometer`() {
val posteringsType = PosteringsType.L_YRKEBIL_TJENESTLIGBEHOV_KILOMETER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.YRKEBIL_TJENESTLIGBEHOV_KILOMETER,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Yrkebil tjenestligbehov listepris`() {
val posteringsType = PosteringsType.L_YRKEBIL_TJENESTLIGBEHOV_LISTEPRIS
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.YRKEBIL_TJENESTLIGBEHOV_LISTEPRIS,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Dagpenger ved arbeidsløshet`() {
val posteringsType = PosteringsType.Y_DAGPENGER_VED_ARBEIDSLØSHET
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.YTELSE_FRA_OFFENTLIGE,
InntektBeskrivelse.DAGPENGER_VED_ARBEIDSLOESHET,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for ferietillegg som gjelder dagpenger ved arbeidsløshet`() {
val posteringsType = PosteringsType.Y_DAGPENGER_VED_ARBEIDSLØSHET_FERIETILLEGG
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.YTELSE_FRA_OFFENTLIGE,
InntektBeskrivelse.DAGPENGER_VED_ARBEIDSLOESHET_FERIETILLEGG,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Dagpenger til fisker`() {
val posteringsType = PosteringsType.N_DAGPENGER_TIL_FISKER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.NAERINGSINNTEKT, InntektBeskrivelse.DAGPENGER_TIL_FISKER, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Dagpenger til fisker som bare har hyre`() {
val posteringsType = PosteringsType.Y_DAGPENGER_TIL_FISKER_SOM_BARE_HAR_HYRE
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.YTELSE_FRA_OFFENTLIGE,
InntektBeskrivelse.DAGPENGER_TIL_FISKER_SOM_BARE_HAR_HYRE,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for ferietillegg som gjelder dagpenger til fisker som bare har hyre`() {
val posteringsType = PosteringsType.Y_DAGPENGER_TIL_FISKER_SOM_BARE_HAR_HYRE_FERIETILLEGG
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.YTELSE_FRA_OFFENTLIGE,
InntektBeskrivelse.DAGPENGER_TIL_FISKER_SOM_BARE_HAR_HYRE_FERIETILLEGG,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for omsorgspenger`() {
val posteringsType = PosteringsType.Y_OMSORGSPENGER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.YTELSE_FRA_OFFENTLIGE,
InntektBeskrivelse.OMSORGSPENGER,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for feriepenger som gjelder omsorgspenger`() {
val posteringsType = PosteringsType.Y_OMSORGSPENGER_FERIEPENGER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.YTELSE_FRA_OFFENTLIGE,
InntektBeskrivelse.OMSORGSPENGER_FERIEPENGER,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for opplæringspenger`() {
val posteringsType = PosteringsType.Y_OPPLÆRINGSPENGER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.YTELSE_FRA_OFFENTLIGE,
InntektBeskrivelse.OPPLÆRINGSPENGER,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for fereipenger som gjelder opplæringspenger`() {
val posteringsType = PosteringsType.Y_OPPLÆRINGSPENGER_FERIEPENGER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.YTELSE_FRA_OFFENTLIGE,
InntektBeskrivelse.OPPLÆRINGSPENGER_FERIEPENGER,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for pleiepenger`() {
val posteringsType = PosteringsType.Y_PLEIEPENGER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.YTELSE_FRA_OFFENTLIGE,
InntektBeskrivelse.PLEIEPENGER,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for fereipenger som gjelder pleiepenger`() {
val posteringsType = PosteringsType.Y_PLEIEPENGER_FERIEPENGER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.YTELSE_FRA_OFFENTLIGE,
InntektBeskrivelse.PLEIEPENGER_FERIEPENGER,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Sykepenger fra folketrygden`() {
val posteringsType = PosteringsType.Y_SYKEPENGER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.YTELSE_FRA_OFFENTLIGE, InntektBeskrivelse.SYKEPENGER, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for feriepenger som gjelder sykepenger fra folketrygden`() {
val posteringsType = PosteringsType.Y_SYKEPENGER_FERIEPENGER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.YTELSE_FRA_OFFENTLIGE, InntektBeskrivelse.SYKEPENGER_FERIEPENGER, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Sykepenger til fisker`() {
val posteringsType = PosteringsType.N_SYKEPENGER_TIL_FISKER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.NAERINGSINNTEKT, InntektBeskrivelse.SYKEPENGER_TIL_FISKER, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Sykepenger til fisker som bare har hyre`() {
val posteringsType = PosteringsType.Y_SYKEPENGER_TIL_FISKER_SOM_BARE_HAR_HYRE
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.YTELSE_FRA_OFFENTLIGE,
InntektBeskrivelse.SYKEPENGER_TIL_FISKER_SOM_BARE_HAR_HYRE,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for feriepenger som gjelder sykepenger til fisker som bare har hyre`() {
val posteringsType = PosteringsType.Y_SYKEPENGER_TIL_FISKER_SOM_BARE_HAR_HYRE_FERIEPENGER
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.YTELSE_FRA_OFFENTLIGE,
InntektBeskrivelse.SYKEPENGER_TIL_FISKER_SOM_BARE_HAR_HYRE_FERIEPENGER,
null,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Hyre - Annet`() {
val posteringsType = PosteringsType.L_ANNET_H
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.ANNET,
SpesielleInntjeningsforhold.HYRE_TIL_MANNSKAP_PAA_FISKE_SMAAHVALFANGST_OG_SELFANGSTFARTOEY,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Hyre - Bonus`() {
val posteringsType = PosteringsType.L_BONUS_H
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.BONUS,
SpesielleInntjeningsforhold.HYRE_TIL_MANNSKAP_PAA_FISKE_SMAAHVALFANGST_OG_SELFANGSTFARTOEY,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Hyre - Faste tillegg`() {
val posteringsType = PosteringsType.L_FAST_TILLEGG_H
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.FAST_TILLEGG,
SpesielleInntjeningsforhold.HYRE_TIL_MANNSKAP_PAA_FISKE_SMAAHVALFANGST_OG_SELFANGSTFARTOEY,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Hyre - Fastlønn`() {
val posteringsType = PosteringsType.L_FASTLØNN_H
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.FASTLOENN,
SpesielleInntjeningsforhold.HYRE_TIL_MANNSKAP_PAA_FISKE_SMAAHVALFANGST_OG_SELFANGSTFARTOEY,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Hyre - Feriepenger`() {
val posteringsType = PosteringsType.L_FERIEPENGER_H
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.FERIEPENGER,
SpesielleInntjeningsforhold.HYRE_TIL_MANNSKAP_PAA_FISKE_SMAAHVALFANGST_OG_SELFANGSTFARTOEY,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Hyre - Helligdagstillegg`() {
val posteringsType = PosteringsType.L_HELLIGDAGSTILLEGG_H
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.HELLIGDAGSTILLEGG,
SpesielleInntjeningsforhold.HYRE_TIL_MANNSKAP_PAA_FISKE_SMAAHVALFANGST_OG_SELFANGSTFARTOEY,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Hyre - Overtidsgodtgjørelse`() {
val posteringsType = PosteringsType.L_OVERTIDSGODTGJØRELSE_H
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.OVERTIDSGODTGJOERELSE,
SpesielleInntjeningsforhold.HYRE_TIL_MANNSKAP_PAA_FISKE_SMAAHVALFANGST_OG_SELFANGSTFARTOEY,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Hyre - Sluttvederlag`() {
val posteringsType = PosteringsType.L_SLUTTVEDERLAG_H
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.SLUTTVEDERLAG,
SpesielleInntjeningsforhold.HYRE_TIL_MANNSKAP_PAA_FISKE_SMAAHVALFANGST_OG_SELFANGSTFARTOEY,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Hyre - Timelønn`() {
val posteringsType = PosteringsType.L_TIMELØNN_H
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.TIMELOENN,
SpesielleInntjeningsforhold.HYRE_TIL_MANNSKAP_PAA_FISKE_SMAAHVALFANGST_OG_SELFANGSTFARTOEY,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Hyre - Uregelmessige tillegg knyttet til arbeidet tid`() {
val posteringsType = PosteringsType.L_UREGELMESSIGE_TILLEGG_KNYTTET_TIL_ARBEIDET_TID_H
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.UREGELMESSIGE_TILLEGG_KNYTTET_TIL_ARBEIDET_TID,
SpesielleInntjeningsforhold.HYRE_TIL_MANNSKAP_PAA_FISKE_SMAAHVALFANGST_OG_SELFANGSTFARTOEY,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Hyre - Uregelmessige tillegg knyttet til ikke-arbeidet tid`() {
val posteringsType = PosteringsType.L_UREGELMESSIGE_TILLEGG_KNYTTET_TIL_IKKE_ARBEIDET_TID_H
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.UREGELMESSIGE_TILLEGG_KNYTTET_TIL_IKKE_ARBEIDET_TID,
SpesielleInntjeningsforhold.HYRE_TIL_MANNSKAP_PAA_FISKE_SMAAHVALFANGST_OG_SELFANGSTFARTOEY,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Lott det skal beregnes trygdeavgift av`() {
val posteringsType = PosteringsType.N_LOTT_KUN_TRYGDEAVGIFT
val posteringsTypeInfo =
PosteringsTypeGrunnlag(InntektType.NAERINGSINNTEKT, InntektBeskrivelse.LOTT_KUN_TRYGDEAVGIFT, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Trekk i lønn for ferie - Hyre`() {
val posteringsType = PosteringsType.L_TREKK_I_LØNN_FOR_FERIE_H
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.TREKK_I_LOENN_FOR_FERIE,
SpesielleInntjeningsforhold.HYRE_TIL_MANNSKAP_PAA_FISKE_SMAAHVALFANGST_OG_SELFANGSTFARTOEY,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Vederlag lott`() {
val posteringsType = PosteringsType.N_VEDERLAG
val posteringsTypeInfo = PosteringsTypeGrunnlag(InntektType.NAERINGSINNTEKT, InntektBeskrivelse.VEDERLAG, null)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Tiltak - Annet`() {
val posteringsType = PosteringsType.L_ANNET_T
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.ANNET,
SpesielleInntjeningsforhold.LOENN_VED_ARBEIDSMARKEDSTILTAK,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Tiltak - Bonus`() {
val posteringsType = PosteringsType.L_BONUS_T
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.BONUS,
SpesielleInntjeningsforhold.LOENN_VED_ARBEIDSMARKEDSTILTAK,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Tiltak - Faste tillegg`() {
val posteringsType = PosteringsType.L_FAST_TILLEGG_T
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.FAST_TILLEGG,
SpesielleInntjeningsforhold.LOENN_VED_ARBEIDSMARKEDSTILTAK,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Tiltak - Fastlønn`() {
val posteringsType = PosteringsType.L_FASTLØNN_T
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.FASTLOENN,
SpesielleInntjeningsforhold.LOENN_VED_ARBEIDSMARKEDSTILTAK,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Tiltak - Feriepenger`() {
val posteringsType = PosteringsType.L_FERIEPENGER_T
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.FERIEPENGER,
SpesielleInntjeningsforhold.LOENN_VED_ARBEIDSMARKEDSTILTAK,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Tiltak - Helligdagstillegg`() {
val posteringsType = PosteringsType.L_HELLIGDAGSTILLEGG_T
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.HELLIGDAGSTILLEGG,
SpesielleInntjeningsforhold.LOENN_VED_ARBEIDSMARKEDSTILTAK,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Tiltak - Overtidsgodtgjørelse`() {
val posteringsType = PosteringsType.L_OVERTIDSGODTGJØRELSE_T
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.OVERTIDSGODTGJOERELSE,
SpesielleInntjeningsforhold.LOENN_VED_ARBEIDSMARKEDSTILTAK,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Tiltak - Sluttvederlag`() {
val posteringsType = PosteringsType.L_SLUTTVEDERLAG_T
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.SLUTTVEDERLAG,
SpesielleInntjeningsforhold.LOENN_VED_ARBEIDSMARKEDSTILTAK,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Tiltak - Timelønn`() {
val posteringsType = PosteringsType.L_TIMELØNN_T
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.TIMELOENN,
SpesielleInntjeningsforhold.LOENN_VED_ARBEIDSMARKEDSTILTAK,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Tiltak - Uregelmessige tillegg knyttet til arbeidet tid`() {
val posteringsType = PosteringsType.L_UREGELMESSIGE_TILLEGG_KNYTTET_TIL_ARBEIDET_TID_T
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.UREGELMESSIGE_TILLEGG_KNYTTET_TIL_ARBEIDET_TID,
SpesielleInntjeningsforhold.LOENN_VED_ARBEIDSMARKEDSTILTAK,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Tiltak - Uregelmessige tillegg knyttet til ikke-arbeidet tid`() {
val posteringsType = PosteringsType.L_UREGELMESSIGE_TILLEGG_KNYTTET_TIL_IKKE_ARBEIDET_TID_T
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.UREGELMESSIGE_TILLEGG_KNYTTET_TIL_IKKE_ARBEIDET_TID,
SpesielleInntjeningsforhold.LOENN_VED_ARBEIDSMARKEDSTILTAK,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
@Test
fun `test posteringstype-mapping for Trekk i lønn for ferie - Tiltak`() {
val posteringsType = PosteringsType.L_TREKK_I_LØNN_FOR_FERIE_T
val posteringsTypeInfo =
PosteringsTypeGrunnlag(
InntektType.LOENNSINNTEKT,
InntektBeskrivelse.TREKK_I_LOENN_FOR_FERIE,
SpesielleInntjeningsforhold.LOENN_VED_ARBEIDSMARKEDSTILTAK,
)
assertEquals(posteringsType, toPosteringsType(posteringsTypeInfo))
assertEquals(posteringsTypeInfo, toPosteringsTypeGrunnlag(posteringsType))
}
}
| 1 | Kotlin | 1 | 0 | 20419b190c23fa91391c3d2acbb3b1792fee4c1d | 55,939 | dp-inntekt | MIT License |
helm-plugin/src/main/kotlin/org/unbrokendome/gradle/plugins/helm/command/internal/HelmValueOptions.kt | unbroken-dome | 145,379,286 | false | {"Kotlin": 525796} | package org.unbrokendome.gradle.plugins.helm.command.internal
import org.gradle.api.file.ConfigurableFileCollection
import org.gradle.api.file.FileCollection
import org.gradle.api.model.ObjectFactory
import org.gradle.api.provider.MapProperty
import org.gradle.api.provider.Provider
import org.gradle.api.resources.TextResource
import org.slf4j.LoggerFactory
import org.unbrokendome.gradle.plugins.helm.command.ConfigurableHelmValueOptions
import org.unbrokendome.gradle.plugins.helm.command.HelmExecSpec
import org.unbrokendome.gradle.plugins.helm.command.HelmOptions
import org.unbrokendome.gradle.plugins.helm.command.HelmValueOptions
import org.unbrokendome.gradle.pluginutils.mapProperty
import java.util.concurrent.Callable
data class HelmValueOptionsHolder(
override val values: MapProperty<String, Any>,
override val fileValues: MapProperty<String, Any>,
override val valueFiles: ConfigurableFileCollection
) : ConfigurableHelmValueOptions {
constructor(objects: ObjectFactory) : this(
values = objects.mapProperty(),
fileValues = objects.mapProperty(),
valueFiles = objects.fileCollection()
)
}
object HelmValueOptionsApplier : HelmOptionsApplier {
private val logger = LoggerFactory.getLogger(javaClass)
override fun apply(spec: HelmExecSpec, options: HelmOptions) {
if (options is HelmValueOptions) {
logger.debug("Applying options: {}", options)
with(spec) {
val (stringValues, otherValues) = options.values.getOrElse(emptyMap()).toList()
.partition { it.second is String }
.toList()
.map { items ->
items.joinToString(separator = ",") { (key, value) -> "$key=$value" }
}
if (stringValues.isNotEmpty()) {
option("--set-string", stringValues)
}
if (otherValues.isNotEmpty()) {
option("--set", otherValues)
}
buildFileValuesArg(options).takeIf { it.isNotBlank() }?.let { arg ->
option("--set-file", arg)
}
options.valueFiles.takeUnless { it.isEmpty }
?.let { valueFiles ->
option("--values", valueFiles.joinToString(",") { it.absolutePath })
}
}
}
}
private fun buildFileValuesArg(options: HelmValueOptions): String =
options.fileValues.getOrElse(emptyMap())
.entries
.joinToString(separator = ",") { (key, value) ->
val valueRepresentation = when (val resolvedValue = resolveValue(value)) {
is FileCollection -> resolvedValue.singleFile
is TextResource -> resolvedValue.asFile()
else -> resolvedValue
}
"$key=$valueRepresentation"
}
private fun resolveValue(value: Any?): Any? =
when (value) {
is Provider<*> -> resolveValue(value.orNull)
is Callable<*> -> resolveValue(value.call())
else -> value
}
}
fun ConfigurableHelmValueOptions.mergeValues(toMerge: HelmValueOptions) = apply {
values.putAll(toMerge.values)
fileValues.putAll(toMerge.fileValues)
valueFiles.from(toMerge.valueFiles)
}
| 28 | Kotlin | 50 | 51 | 9c913b4a8de8e44fd69f06b6b61a615b41265da2 | 3,408 | gradle-helm-plugin | MIT License |
tabler/src/commonMain/kotlin/com/woowla/compose/icon/collections/tabler/tabler/outline/AugmentedReality2.kt | walter-juan | 868,046,028 | false | {"Kotlin": 34345428} | package com.woowla.compose.icon.collections.tabler.tabler.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.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import com.woowla.compose.icon.collections.tabler.tabler.OutlineGroup
import androidx.compose.ui.graphics.StrokeCap.Companion.Round as strokeCapRound
import androidx.compose.ui.graphics.StrokeJoin.Companion.Round as strokeJoinRound
public val OutlineGroup.AugmentedReality2: ImageVector
get() {
if (_augmentedReality2 != null) {
return _augmentedReality2!!
}
_augmentedReality2 = Builder(name = "AugmentedReality2", defaultWidth = 24.0.dp,
defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply {
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(10.0f, 21.0f)
horizontalLineToRelative(-2.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, -2.0f, -2.0f)
verticalLineToRelative(-14.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, -2.0f)
horizontalLineToRelative(8.0f)
arcToRelative(2.0f, 2.0f, 0.0f, false, true, 2.0f, 2.0f)
verticalLineToRelative(3.5f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(17.0f, 17.0f)
lineToRelative(-4.0f, -2.5f)
lineToRelative(4.0f, -2.5f)
lineToRelative(4.0f, 2.5f)
verticalLineToRelative(4.5f)
lineToRelative(-4.0f, 2.5f)
close()
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(13.0f, 14.5f)
verticalLineToRelative(4.5f)
lineToRelative(4.0f, 2.5f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(17.0f, 17.0f)
lineToRelative(4.0f, -2.5f)
}
path(fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)),
strokeLineWidth = 2.0f, strokeLineCap = strokeCapRound, strokeLineJoin =
strokeJoinRound, strokeLineMiter = 4.0f, pathFillType = NonZero) {
moveTo(11.0f, 4.0f)
horizontalLineToRelative(2.0f)
}
}
.build()
return _augmentedReality2!!
}
private var _augmentedReality2: ImageVector? = null
| 0 | Kotlin | 0 | 3 | eca6c73337093fbbfbb88546a88d4546482cfffc | 3,585 | compose-icon-collections | MIT License |
test/src/me/anno/bugs/done/UnityTarInsideZip.kt | AntonioNoack | 456,513,348 | false | {"Kotlin": 10736182, "C": 236426, "Java": 6754, "Lua": 4404, "C++": 3070, "GLSL": 2698} | package me.anno.tests.bugs.done
import me.anno.engine.OfficialExtensions
import me.anno.io.files.Reference.getReference
/**
* stuff was broken :( -> because there was a inputStreamSync(), which was closed too soon
* (I didn't test tars inside zips before)
* */
fun main() {
OfficialExtensions.initForTests()
val ref = getReference(
"E:/Assets/Animpic Studio/POLY-LiteSurvivalForest_Unity_UE.zip/" +
"POLY-LiteSurvivalForest.unitypackage"
)
println(ref.listChildren())
} | 0 | Kotlin | 3 | 24 | 63377c2e684adf187a31af0f4e5dd0bfde1d050e | 514 | RemsEngine | Apache License 2.0 |
weatherapp/app/src/androidTest/java/fr/ekito/myweatherapp/room_test_modules.kt | Ekito | 129,068,321 | false | null | package fr.ekito.myweatherapp
import android.arch.persistence.room.Room
import fr.ekito.myweatherapp.data.datasource.room.WeatherDatabase
import org.koin.dsl.module.applicationContext
/**
* In-Memory Room Database definition
*/
val roomTestModule = applicationContext {
bean {
Room.inMemoryDatabaseBuilder(get(), WeatherDatabase::class.java)
.allowMainThreadQueries()
.build()
}
} | 0 | Kotlin | 6 | 60 | be37b060c9abe61717f26367e6957bd6e601dd64 | 424 | mvvm-coroutines | Creative Commons Attribution 4.0 International |
binary-compatibility-validator/src/test/kotlin/cases/localClasses/fromStdlib.kt | sahlone | 141,607,927 | true | {"Kotlin": 1836603, "CSS": 8706, "JavaScript": 3487, "Ruby": 1927, "HTML": 1675, "Shell": 1308, "Java": 245} | package cases.localClasses
private val COMPARER = compareBy<String> { it.length } | 0 | Kotlin | 0 | 1 | dae510bba39181b93978f7878c033a50dccad62b | 82 | kotlinx.coroutines | Apache License 2.0 |
src/main/kotlin/tidinari/mbpunish/sources/rules/RulesFileSource.kt | Tidinari | 746,877,292 | false | {"Kotlin": 119708, "Java": 517} | package tidinari.mbpunish.sources.rules
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import net.fabricmc.loader.api.FabricLoader
import tidinari.mbpunish.MineBlazePunishments
import tidinari.mbpunish.data.Rule
import tidinari.mbpunish.sources.rules.data.EditableRules
import tidinari.mbpunish.sources.rules.data.Rules
import java.nio.file.Files
import kotlin.io.path.exists
import kotlin.io.path.readText
class RulesFileSource: RulesSource {
override fun init() {
val config = FabricLoader.getInstance().configDir.resolve("mb-config.json")
if (!config.exists()) {
try {
val stream = MineBlazePunishments.javaClass.classLoader.getResourceAsStream("config.json")
Files.copy(stream, config)
} catch (exception: Exception) {
exception.printStackTrace()
}
}
}
override fun read(): List<Rule> {
val config = FabricLoader.getInstance().configDir.resolve("mb-config.json")
val jsonString = config.readText()
return Json.decodeFromString<Rules>(jsonString).rules
}
override fun save(rules: EditableRules) {
val config = FabricLoader.getInstance().configDir.resolve("mb-config.json")
val jsonString = Json.encodeToString(rules.asNormalRules())
config.toFile().writeText(jsonString)
}
} | 0 | Kotlin | 0 | 0 | 5c20d0a9a4332a954d1cde062bcd994373ad6fa6 | 1,398 | mineblaze-punishments-1201 | Creative Commons Zero v1.0 Universal |
swan-android-lib/src/main/java/com/bomber/swan/util/SerializableIntent.kt | YoungTr | 469,053,611 | false | {"C++": 866022, "Kotlin": 767975, "Java": 322150, "C": 302325, "CMake": 18112, "Shell": 389} | package com.bomber.swan.util
import android.content.Intent
import java.io.Serializable
/**
* @author youngtr
* @data 2022/4/17
*/
class SerializableIntent(intent: Intent) : Serializable {
private val uri = intent.toUri(0)
@Transient
private var _intent: Intent? = intent
val intent: Intent
get() = _intent.run {
this ?: Intent.parseUri(uri, 0)
.apply { _intent = this }
}
} | 0 | C++ | 1 | 8 | 65169f46a5af9af3ce097d2cbb67b8f34e9df3f1 | 440 | Swan | Apache License 2.0 |
libs/canvas-api-2/src/test/java/com/instructure/canvasapi2/unit/StreamUnitTest.kt | instructure | 179,290,947 | false | null | /*
* Copyright (C) 2017 - present Instructure, Inc.
*
* 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.instructure.canvasapi2.unit
import com.instructure.canvasapi2.models.StreamItem
import com.instructure.canvasapi2.utils.parse
import junit.framework.Assert
import org.intellij.lang.annotations.Language
import org.junit.Test
class StreamUnitTest : Assert() {
@Test
fun personalStreamTest() {
val personalStream: Array<StreamItem> = personalStreamJSON.parse()
Assert.assertNotNull(personalStream)
val streamItem = personalStream[0]
Assert.assertNotNull(streamItem)
Assert.assertTrue(streamItem.id == 98502910L)
Assert.assertTrue(StreamItem.Type.isDiscussionTopic(streamItem))
Assert.assertTrue(streamItem.courseId == 1393179L)
}
@Test
fun testStreamItemCourse() {
val streamItem: StreamItem = courseStreamItemJSON.parse()
Assert.assertNotNull(streamItem)
Assert.assertNotNull(streamItem.htmlUrl)
Assert.assertNotNull(streamItem.contextType)
Assert.assertNotNull(streamItem.type)
Assert.assertTrue(streamItem.id > 0)
}
/**
* personal stream
* @GET("/users/self/activity_stream")
* void getUserStream(Callback<StreamItem[]> callback);
*/
@Language("JSON")
private val personalStreamJSON = """
[
{
"created_at": "2014-07-15T21:46:46Z",
"updated_at": "2014-07-15T21:46:50Z",
"id": 98502910,
"title": "new discussion threaded 1",
"message": "<p>new discussion threaded 1</p>",
"type": "DiscussionTopic",
"read_state": false,
"context_type": "Course",
"course_id": 1393179,
"discussion_topic_id": 5919006,
"html_url": "https://mobileqa.instructure.com/courses/1393179/discussion_topics/5919006",
"total_root_discussion_entries": 0,
"require_initial_post": false,
"user_has_posted": null,
"root_discussion_entries": []
},
{
"created_at": "2014-07-15T19:09:45Z",
"updated_at": "2014-07-15T19:12:00Z",
"id": 98491440,
"title": "yyyy",
"message": "<p>yyyy</p>",
"type": "DiscussionTopic",
"read_state": false,
"context_type": "Course",
"course_id": 1393179,
"discussion_topic_id": 5918712,
"html_url": "https://mobileqa.instructure.com/courses/1393179/discussion_topics/5918712",
"total_root_discussion_entries": 0,
"require_initial_post": false,
"user_has_posted": null,
"root_discussion_entries": []
},
{
"created_at": "2014-07-10T17:23:35Z",
"updated_at": "2014-07-10T17:23:35Z",
"id": 98218837,
"title": "Assignment Created - The world cup write up, IOS Topdown 4 (Old Data)",
"message": " \nA new assignment has been created for your course, IOS Topdown 4 (Old Data)\n\nThe world cup write up\n\n due: No Due Date\n\nClick here to view the assignment: \nhttps://mobileqa.instructure.com/courses/1098050/assignments/5152053\n\n\n\n\n\n\n ________________________________________\n\n You received this email because you are participating in one or more classes using Canvas. To change or turn off email notifications, visit:\nhttps://mobileqa.instructure.com/profile/communication\n\n\n",
"type": "Message",
"read_state": true,
"context_type": "Course",
"course_id": 1098050,
"message_id": null,
"notification_category": "Due Date",
"url": "https://mobileqa.instructure.com/courses/1098050/assignments/5152053",
"html_url": "https://mobileqa.instructure.com/courses/1098050/assignments/5152053"
},
{
"created_at": "2014-07-02T20:59:54Z",
"updated_at": "2014-07-02T20:59:54Z",
"id": 97859114,
"title": null,
"message": null,
"type": "Conversation",
"read_state": true,
"context_type": "Course",
"course_id": 1098050,
"conversation_id": 3058273,
"private": false,
"participant_count": 2,
"html_url": "https://mobileqa.instructure.com/conversations/3058273"
},
{
"created_at": "2014-06-30T16:10:07Z",
"updated_at": "2014-06-30T16:10:07Z",
"id": 97736706,
"title": "Assignment Created - Media Submission 2, IOS Topdown 4 (Old Data)",
"message": " \nA new assignment has been created for your course, IOS Topdown 4 (Old Data)\n\nMedia Submission 2\n\n due: No Due Date\n\nClick here to view the assignment: \nhttps://mobileqa.instructure.com/courses/1098050/assignments/5111404\n\n\n\n\n\n\n ________________________________________\n\n You received this email because you are participating in one or more classes using Canvas. To change or turn off email notifications, visit:\nhttps://mobileqa.instructure.com/profile/communication\n\n\n",
"type": "Message",
"read_state": true,
"context_type": "Course",
"course_id": 1098050,
"message_id": null,
"notification_category": "Due Date",
"url": "https://mobileqa.instructure.com/courses/1098050/assignments/5111404",
"html_url": "https://mobileqa.instructure.com/courses/1098050/assignments/5111404"
},
{
"created_at": "2014-06-30T16:04:05Z",
"updated_at": "2014-06-30T16:04:11Z",
"id": 97736153,
"title": "Media Submission 1",
"message": "<p>testing media submission 1</p>",
"type": "DiscussionTopic",
"read_state": true,
"context_type": "Course",
"course_id": 1098050,
"discussion_topic_id": 5844224,
"html_url": "https://mobileqa.instructure.com/courses/1098050/discussion_topics/5844224",
"total_root_discussion_entries": 0,
"require_initial_post": false,
"user_has_posted": null,
"root_discussion_entries": []
},
{
"created_at": "2014-06-23T19:19:26Z",
"updated_at": "2014-06-23T19:19:26Z",
"id": 97404523,
"title": " Test B, Graded, Group Assignment, Grades by group, Manually Created",
"message": "<p> Test B, Graded, Group Assignment, Grades by group, Manually Created</p>",
"type": "DiscussionTopic",
"read_state": true,
"context_type": "Group",
"group_id": 157240,
"discussion_topic_id": 4974242,
"html_url": "https://mobileqa.instructure.com/groups/157240/discussion_topics/4974242",
"total_root_discussion_entries": 4,
"require_initial_post": null,
"user_has_posted": null,
"root_discussion_entries": [
{
"user": {
"user_id": 3558540,
"user_name": "S3First S3Last(5C)"
},
"message": "Sssss3"
},
{
"user": {
"user_id": 3564934,
"user_name": "S5First S5Last(4X)"
},
"message": "Ssss5"
},
{
"user": {
"user_id": 3558540,
"user_name": "S3First S3Last(5C)"
},
"message": "discuss"
}
]
}
]"""
@Language("JSON")
private var courseStreamItemJSON = """
{
"created_at": "2015-02-23T23:41:16Z",
"updated_at": "2015-02-23T23:41:16Z",
"id": 129486849,
"title": "post a discussion from a ta perspective",
"message": "hasjdf;lk alksjdfa;k sfal;jdflaksjdflas f;ljaslf kajsfl;ajsf",
"type": "DiscussionTopic",
"read_state": false,
"context_type": "Course",
"course_id": 836357,
"discussion_topic_id": 9834412,
"html_url": "https://mobiledev.instructure.com/courses/836357/discussion_topics/9834412",
"total_root_discussion_entries": 0,
"require_initial_post": null,
"user_has_posted": null,
"root_discussion_entries": []
}"""
}
| 2 | Kotlin | 85 | 99 | 1bac9958504306c03960bdce7fbb87cc63bc6845 | 8,909 | canvas-android | Apache License 2.0 |
app/src/main/java/pt/pl/estg/ei/regulapp/chat/ChatActivity.kt | bb1e | 610,523,307 | false | null | package pt.pl.estg.ei.regulapp.chat
import android.widget.TextView
import com.mikhaellopez.circularimageview.CircularImageView
import android.widget.ImageButton
import android.widget.EditText
import com.google.firebase.auth.FirebaseAuth
import com.google.firebase.database.DatabaseReference
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.storage.StorageTask
import android.app.ProgressDialog
import android.os.Bundle
import pt.pl.estg.ei.regulapp.R
import pt.pl.estg.ei.regulapp.GlobalSettings
import com.google.firebase.database.FirebaseDatabase
import com.bumptech.glide.Glide
import com.bumptech.glide.signature.MediaStoreSignature
import android.content.Intent
import com.google.firebase.database.ChildEventListener
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.storage.FirebaseStorage
import android.widget.Toast
import com.google.firebase.database.ValueEventListener
import android.text.TextUtils
import android.app.AlertDialog
import pt.pl.estg.ei.regulapp.R.layout
import android.net.Uri
import android.view.*
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import com.google.android.gms.tasks.*
import com.google.firebase.storage.UploadTask
import pt.pl.estg.ei.regulapp.classes.Analytics
import pt.pl.estg.ei.regulapp.classes.AnalyticsEvent
import java.text.SimpleDateFormat
import java.util.*
import kotlin.collections.HashMap
class ChatActivity : AppCompatActivity() {
private var messageRecieverId: String? = null
private var getMessageRecievername: String? = null
private var messagereceiverimage: String? = null
private var messageSenderId: String? = null
private var username: TextView? = null
private var userlastseen: TextView? = null
private var userprofile: CircularImageView? = null
private var chattoolbar: Toolbar? = null
private var sendMessageButton: ImageButton? = null
private var sendFileButton: ImageButton? = null
private var messagesentinput: EditText? = null
private var mauth: FirebaseAuth? = null
private var RootRef: DatabaseReference? = null
private val messagesList: MutableList<Messages?>? = ArrayList()
private var linearLayoutManager: LinearLayoutManager? = null
private var messageAdapter: MessageAdapter? = null
private var usermessagerecyclerview: RecyclerView? = null
private var savecurrentTime: String? = null
private var savecurrentDate: String? = null
private var checker: String? = ""
private var myUrl: String? = ""
private var uploadTask: StorageTask<*>? = null
private var fileuri: Uri? = null
private var loadingBar: ProgressDialog? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(layout.activity_chat)
loadingBar = ProgressDialog(this)
mauth = FirebaseAuth.getInstance()
messageSenderId = (application as GlobalSettings).session?.id
RootRef = FirebaseDatabase.getInstance().reference
messageRecieverId = intent.extras?.get("visit_user_id").toString()
getMessageRecievername = intent.extras?.get("visit_user_name").toString()
messagereceiverimage = intent.extras?.get("visit_image").toString()
chattoolbar = findViewById(R.id.chat_toolbar)
setSupportActionBar(chattoolbar)
val actionBar = supportActionBar
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true)
actionBar.setDisplayShowCustomEnabled(true)
val layoutInflater = this.getSystemService(LAYOUT_INFLATER_SERVICE) as LayoutInflater
val actionbarview = layoutInflater.inflate(layout.custom_chat_bar, null)
actionBar.customView = actionbarview
}
username = findViewById(R.id.custom_profile_name)
userlastseen = findViewById(R.id.custom_user_last_seen)
userprofile = findViewById(R.id.custom_profile_image)
sendMessageButton = findViewById(R.id.send_message_btn)
sendFileButton = findViewById(R.id.send_files_btn)
userlastseen?.setVisibility(View.GONE)
messagesentinput = findViewById(R.id.input_messages)
messageAdapter = MessageAdapter(messagesList, messageSenderId)
usermessagerecyclerview = findViewById(R.id.private_message_list_of_users)
linearLayoutManager = LinearLayoutManager(this)
usermessagerecyclerview?.setLayoutManager(linearLayoutManager)
usermessagerecyclerview?.setAdapter(messageAdapter)
val calendar = Calendar.getInstance()
val currentDate = SimpleDateFormat("dd/MM/yyyy")
savecurrentDate = currentDate.format(calendar.time)
val currentTime = SimpleDateFormat("hh:mm a")
savecurrentTime = currentTime.format(calendar.time)
username?.setText(getMessageRecievername)
Glide.with(this@ChatActivity).load(messagereceiverimage).signature(MediaStoreSignature("",
System.currentTimeMillis(), 0)).error(R.drawable.doctor).into(userprofile!!)
val window = window
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.statusBarColor = resources.getColor(R.color.vermelho_chat)
Displaylastseen()
sendMessageButton?.setOnClickListener(View.OnClickListener { SendMessage() })
sendFileButton?.setOnClickListener(View.OnClickListener {
val options = arrayOf<CharSequence?>(
"Imagens", "Ficheiros PDF", "Ficheiros Word"
)
val builder = AlertDialog.Builder(this@ChatActivity)
builder.setTitle("Escolher ficheiro")
builder.setItems(options) { dialog, which ->
if (which == 0) {
checker = "image"
val intent = Intent()
intent.action = Intent.ACTION_GET_CONTENT
intent.type = "image/*"
startActivityForResult(Intent.createChooser(intent, "Escolher imagem"), 555)
} else if (which == 1) {
checker = "pdf"
val intent = Intent()
intent.action = Intent.ACTION_GET_CONTENT
intent.type = "application/pdf"
startActivityForResult(Intent.createChooser(intent, "Escolher ficheiro PDF"), 555)
} else if (which == 2) {
checker = "docx"
val intent = Intent()
intent.action = Intent.ACTION_GET_CONTENT
intent.type = "application/msword"
startActivityForResult(Intent.createChooser(intent, "Escolher ficheiro Word"), 555)
}
}
builder.show()
})
RootRef?.child("Messages")?.child(messageSenderId!!)?.child(messageRecieverId!!)?.addChildEventListener(object : ChildEventListener {
override fun onChildAdded(dataSnapshot: DataSnapshot, s: String?) {
val messages = dataSnapshot.getValue(Messages::class.java)
messagesList?.add(messages)
messageAdapter?.notifyDataSetChanged()
usermessagerecyclerview?.smoothScrollToPosition(usermessagerecyclerview?.getAdapter()?.getItemCount()!!)
}
override fun onChildChanged(dataSnapshot: DataSnapshot, s: String?) {}
override fun onChildRemoved(dataSnapshot: DataSnapshot) {}
override fun onChildMoved(dataSnapshot: DataSnapshot, s: String?) {}
override fun onCancelled(databaseError: DatabaseError) {}
})
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == 555 && resultCode == RESULT_OK && data != null && data.data != null) {
loadingBar?.setTitle("Sending File")
loadingBar?.setMessage("please wait, we are sending that file...")
loadingBar?.setCanceledOnTouchOutside(false)
loadingBar?.show()
fileuri = data.data
if (checker != "image") {
val storageReference = FirebaseStorage.getInstance().reference.child("Document Files")
val messageSenderRef = "Messages/$messageSenderId/$messageRecieverId"
val messageReceiverRef = "Messages/$messageRecieverId/$messageSenderId"
val Usermessagekeyref = RootRef?.child("Messages")?.child(messageSenderId!!)?.child(messageRecieverId!!)?.push()!!
val messagePushID = Usermessagekeyref.key
val filepath = storageReference.child("$messagePushID.$checker")
filepath.putFile(fileuri!!).addOnSuccessListener {
filepath.downloadUrl.addOnSuccessListener { uri ->
val downloadUrl = uri.toString()
val messageDocsBody: MutableMap<String, String> = HashMap<String, String>()
messageDocsBody["message"] = downloadUrl
messageDocsBody["name"] = fileuri?.getLastPathSegment()!!
messageDocsBody["type"] = checker!!
messageDocsBody["from"] = messageSenderId!!
messageDocsBody["to"] = messageRecieverId!!
messageDocsBody["messageID"] = messagePushID!!
messageDocsBody["time"] = savecurrentTime!!
messageDocsBody["date"] = savecurrentDate!!
val messageBodyDDetail: MutableMap<String,MutableMap<String,String>> = HashMap<String, MutableMap<String,String>>()
messageBodyDDetail["${messageSenderRef}/${messagePushID}"] = messageDocsBody
messageBodyDDetail["$messageReceiverRef/$messagePushID"] = messageDocsBody
RootRef?.updateChildren(messageBodyDDetail as Map<String, Any>)
loadingBar?.dismiss()
}.addOnFailureListener { e ->
loadingBar?.dismiss()
Toast.makeText(this@ChatActivity, e.message, Toast.LENGTH_SHORT).show()
}
}.addOnProgressListener { taskSnapshot ->
val p = 100.0 * taskSnapshot.bytesTransferred / taskSnapshot.totalByteCount
loadingBar?.setMessage((p as Int).toString() + " % Uploading...")
}
} else if (checker == "image") {
val storageReference = FirebaseStorage.getInstance().reference.child("Image Files")
val messageSenderRef = "Messages/$messageSenderId/$messageRecieverId"
val messageReceiverRef = "Messages/$messageRecieverId/$messageSenderId"
val Usermessagekeyref = RootRef?.child("Messages")?.child(messageSenderId!!)?.child(messageRecieverId!!)?.push()
val messagePushID = Usermessagekeyref?.key
val filepath = storageReference.child("$messagePushID.jpg")
uploadTask = filepath.putFile(fileuri!!)
(uploadTask as UploadTask).continueWithTask { continuation -> if(!continuation.isSuccessful){
throw continuation.exception!!
} else {
filepath.downloadUrl
}
} .addOnCompleteListener(OnCompleteListener<Uri?> { task ->
if (task.isSuccessful) {
val downloadUrl = task.result
myUrl = downloadUrl.toString()
val messageTextBody: MutableMap<String,String > = HashMap<String,String>()
messageTextBody["message"] = myUrl!!
messageTextBody["name"] = fileuri?.getLastPathSegment()!!
messageTextBody["type"] = checker!!
messageTextBody["from"] = messageSenderId!!
messageTextBody["to"] = messageRecieverId!!
messageTextBody["messageID"] = messagePushID!!
messageTextBody["time"] = savecurrentTime!!
messageTextBody["date"] = savecurrentDate!!
val messageBodyDetails: MutableMap<String,MutableMap<String,String>> = HashMap<String,MutableMap<String,String>>()
messageBodyDetails["$messageSenderRef/$messagePushID"] = messageTextBody
messageBodyDetails["$messageReceiverRef/$messagePushID"] = messageTextBody
RootRef?.updateChildren(messageBodyDetails as Map<String, Any>)?.addOnCompleteListener { task ->
if (task.isSuccessful) {
loadingBar?.dismiss()
//Toast.makeText(ChatActivity.this,"Message sent Successfully...",Toast.LENGTH_SHORT).show();
} else {
loadingBar?.dismiss()
Toast.makeText(this@ChatActivity, "Error:", Toast.LENGTH_SHORT)
.show()
}
messagesentinput?.setText("")
}
}
})
} else {
loadingBar?.dismiss()
Toast.makeText(this, "please select file", Toast.LENGTH_SHORT).show()
}
}
}
fun Displaylastseen() {
RootRef?.child("Users")?.child(messageRecieverId!!)?.addValueEventListener(object : ValueEventListener {
override fun onDataChange(dataSnapshot: DataSnapshot) {
if (dataSnapshot.child("userState").hasChild("state")) {
val state = dataSnapshot.child("userState").child("state").value.toString()
//String date=dataSnapshot.child("userState").child("date").getValue().toString();
//String time=dataSnapshot.child("userState").child("time").getValue().toString();
/*if(state.equals("online"))
{
userlastseen.setText("online");
}
else if(state.equals("offline"))
{
userlastseen.setText("offline");
}*/
} else {
// userlastseen.setText("offline");
}
}
override fun onCancelled(databaseError: DatabaseError) {}
})
}
private fun SendMessage() {
val messagetext = messagesentinput?.getText().toString()
if (TextUtils.isEmpty(messagetext)) {
Toast.makeText(this, "Please enter message first..", Toast.LENGTH_SHORT).show()
} else {
val messageSenderRef = "Messages/$messageSenderId/$messageRecieverId"
val messageReceiverRef = "Messages/$messageRecieverId/$messageSenderId"
val Usermessagekeyref = RootRef?.child("Messages")?.child(messageSenderId!!)?.child(messageRecieverId!!)?.push()
val messagePushID = Usermessagekeyref?.key
val messageTextBody: MutableMap<String,String> = HashMap<String,String>()
messageTextBody["message"] = messagetext
messageTextBody["type"] = "text"
messageTextBody["from"] = messageSenderId!!
messageTextBody["to"] = messageRecieverId!!
messageTextBody["messageID"] = messagePushID!!
messageTextBody["time"] = savecurrentTime!!
messageTextBody["date"] = savecurrentDate!!
val messageBodyDetails: MutableMap<String, Map<String,String>> = HashMap<String,Map<String,String>>()
messageBodyDetails["$messageSenderRef/$messagePushID"] = messageTextBody
messageBodyDetails["$messageReceiverRef/$messagePushID"] = messageTextBody
RootRef?.updateChildren(messageBodyDetails as Map<String, Any>)?.addOnCompleteListener { task ->
if (task.isSuccessful) {
// Toast.makeText(ChatActivity.this,"Message sent Successfully...",Toast.LENGTH_SHORT).show();
Analytics.fireEvent(AnalyticsEvent.CHAT_MESSAGE_SUCCESS)
} else {
Toast.makeText(this@ChatActivity, "Error:", Toast.LENGTH_SHORT).show()
Analytics.fireEvent(AnalyticsEvent.CHAT_MESSAGE_FAILED(task.exception.toString()))
}
messagesentinput?.setText("")
}
}
}
} | 0 | Kotlin | 0 | 0 | 24b1b3c0bf2e466645cfd8089121306fb39b7874 | 16,750 | RegulA3.0-AndroidApp | MIT License |
LuraPlayerSampleApp/src/main/java/com/akta/luraplayersampleapp/modern/custom/PieProgressBar.kt | ramdevblim | 816,915,917 | false | {"Kotlin": 333757} | package com.akta.luraplayersampleapp.modern.custom
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.view.View
import androidx.core.content.ContextCompat
import com.akta.luraplayersampleapp.R
class PieProgressBar(context: Context, attrs: AttributeSet?) : View(context, attrs) {
private var progress = 0
private val maxProgress = 100
private val progressPaint = Paint().apply {
isAntiAlias = true
style = Paint.Style.FILL
color = ContextCompat.getColor(context, R.color.white)
}
private val backgroundPaint = Paint().apply {
isAntiAlias = true
style = Paint.Style.FILL
color = ContextCompat.getColor(context, com.akta.luraplayercontrols.R.color.transparent)
}
@SuppressLint("DrawAllocation")
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val centerX = width / 2f
val centerY = height / 2f
val radius = (width.coerceAtMost(height) / 2 * 0.8).toFloat()
val oval = RectF(
centerX - radius,
centerY - radius,
centerX + radius,
centerY + radius
)
// Draw background circle
canvas.drawCircle(centerX, centerY, radius, backgroundPaint)
// Calculate the angle based on the progress
val angle = 360 * (progress.toFloat() / maxProgress)
// Draw progress arc
canvas.drawArc(oval, -90f, angle, true, progressPaint)
}
fun setProgress(progress: Int) {
this.progress = progress.coerceIn(0, maxProgress)
invalidate()
}
} | 0 | Kotlin | 0 | 0 | 708586303f1206d1eaa3515bf836ba725d248246 | 1,739 | akta-v4-downloads | MIT License |
libraries/log/core/src/test/kotlin/com/log/vastgui/core/SimpleLogger.kt | SakurajimaMaii | 353,212,367 | false | null | package com.log.vastgui.core/*
* Copyright 2021-2024 VastGui
*
* 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.
*
*/
import com.log.vastgui.core.base.LogFormat
import com.log.vastgui.core.base.LogInfo
import com.log.vastgui.core.base.Logger
import com.log.vastgui.core.format.DEFAULT_MAX_PRINT_TIMES
import com.log.vastgui.core.format.DEFAULT_MAX_SINGLE_LOG_LENGTH
import com.log.vastgui.core.format.TableFormat
// Author: <NAME>
// Email: <EMAIL>
// Date: 2024/5/19 23:32
// Documentation: https://ave.entropy2020.cn/documents/log/log-core/develop/
class SimpleLogger(
override val logFormat: LogFormat = TableFormat(
DEFAULT_MAX_SINGLE_LOG_LENGTH,
DEFAULT_MAX_PRINT_TIMES,
TableFormat.LogHeader.default
)
) : Logger {
override fun log(logInfo: LogInfo) {
println(logFormat.format(logInfo))
}
} | 8 | null | 6 | 64 | 81c5ca59680143d9523c01852d9587a8d926c1c3 | 1,356 | Android-Vast-Extension | Apache License 2.0 |
app/src/main/java/com/skydoves/waterdays/models/ShortWeather.kt | jacky2010 | 128,081,643 | true | {"Kotlin": 118713, "Java": 33865} | package com.skydoves.waterdays.models
/**
* Developed by skydoves on 2017-08-19.
* Copyright (c) 2017 skydoves rights reserved.
*/
data class ShortWeather (var reh: String? = null)
| 0 | Kotlin | 0 | 0 | 7841883d47967d440be6bbad4ca6d59cf221efd6 | 186 | WaterDrink | Apache License 2.0 |
transektcount/src/main/java/com/wmstein/transektcount/widgets/CountingWidget_head2.kt | wistein | 54,684,722 | false | null | /*
* Copyright (c) 2016. Wilhelm Stein, Bonn, Germany.
*/
package com.wmstein.transektcount.widgets
import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.ImageButton
import android.widget.RelativeLayout
import android.widget.TextView
import com.wmstein.transektcount.R
import com.wmstein.transektcount.database.Count
import java.util.Objects
/****************************************************
* Interface for widget_counting_head2.xml
* Created by wmstein 18.12.2016
* Last edited in Java on 2023-05-09
* converted to Kotlin on 2023-06-26
*/
class CountingWidget_head2(context: Context, attrs: AttributeSet?) :
RelativeLayout(context, attrs) {
private val countHead2: TextView
init {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
Objects.requireNonNull(inflater).inflate(R.layout.widget_counting_head2, this, true)
countHead2 = findViewById(R.id.countHead2)
}
fun setCountHead2(count: Count) {
// set TextView countHead2
countHead2.text = context.getString(R.string.countInternalHint)
// set ImageButton Edit
val editButton = findViewById<ImageButton>(R.id.buttonEdit)
editButton.tag = count.id
}
} | 0 | Kotlin | 2 | 5 | 6a25db5989c9e2582273b62a3552d0c862f6fc14 | 1,312 | TransektCount | Apache License 2.0 |
app/src/stages/stage0/java/co/temy/securitysample/encryption/KeyStoreWrapper.kt | temyco | 100,974,782 | false | null | package java.co.temy.securitysample.encryption
import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.security.KeyPairGeneratorSpec
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import co.temy.securitysample.authentication.SystemServices
import java.math.BigInteger
import java.security.KeyPair
import java.security.KeyPairGenerator
import java.security.KeyStore
import java.security.PrivateKey
import java.util.*
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.security.auth.x500.X500Principal
/**
* This class wraps [KeyStore] class apis with some additional possibilities.
*/
class KeyStoreWrapper(private val context: Context) {
}
| 3 | Kotlin | 92 | 315 | 876d8b07980eb38ded120623a483e56c58f9bc5f | 774 | security-workshop-sample | Apache License 2.0 |
ExMCL Branding/src/main/kotlin/com/n9mtq4/exmcl/branding/FrameTitleChanger.kt | ExMCL | 51,719,505 | false | null | package com.n9mtq4.exmcl.branding
import com.n9mtq4.exmcl.api.BUILD_NUMBER
import com.n9mtq4.logwindow.BaseConsole
import com.n9mtq4.logwindow.events.ObjectEvent
import com.n9mtq4.logwindow.listener.ObjectListener
import javax.swing.JFrame
/**
* Created by will on 11/25/16 at 11:48 PM.
*
* @author Will "n9Mtq4" Bresnahan
*/
class FrameTitleChanger : ObjectListener {
override fun objectReceived(e: ObjectEvent, baseConsole: BaseConsole) {
if (e.message != "jframe") return
if (e.obj !is JFrame) return
val frame = e.obj as JFrame
frame.title += " (ExMCL $BUILD_NUMBER)"
}
}
| 1 | null | 1 | 1 | 4dad612c259938560842c224aaefd6c1e677736f | 608 | ExMCL | MIT License |
src/main/kotlin/com/baulsupp/okscript/logging.kt | yschimke | 282,818,653 | false | {"Kotlin": 16329, "Shell": 197} | package com.baulsupp.okscript
import java.util.logging.Formatter
import java.util.logging.Level
import java.util.logging.LogManager
import java.util.logging.LogRecord
import java.util.logging.Logger
val activeLoggers = mutableListOf<Logger>()
fun getLogger(name: String): Logger {
val logger = Logger.getLogger(name)
activeLoggers.add(logger)
return logger
}
fun initLogging() {
LogManager.getLogManager().reset()
val activeLogger = getLogger("")
val handler = java.util.logging.ConsoleHandler()
handler.level = Level.ALL
handler.formatter = object : Formatter() {
override fun format(record: LogRecord?): String = record?.message ?: ""
}
activeLogger.addHandler(handler)
getLogger("").level = Level.SEVERE
}
| 0 | Kotlin | 0 | 2 | d6db660c7d6cb3ced07993b7f1f3bbd18e2b6679 | 741 | okurl-script | Apache License 2.0 |
lib-semantic-api/src/commonMain/kotlin/fr/outadoc/semantique/api/model/DayStats.kt | outadoc | 478,272,052 | false | {"Kotlin": 70253} | package fr.outadoc.semantique.api.model
data class DayStats(
/**
* Day number, i.e. since number of days since the game has been running.
*/
val dayNumber: Long,
/**
* Number of people who solved the word today.
*/
val solverCount: Long
)
| 1 | Kotlin | 0 | 3 | 4c912c5af3a13850b4df0c5061307de455196898 | 278 | semantique | Apache License 2.0 |
src/main/kotlin/com/springboot/book/HomeController.kt | juanmendez | 748,008,158 | false | {"Kotlin": 3465, "Mustache": 327} | package com.springboot.book
import org.springframework.stereotype.Controller
import org.springframework.ui.Model
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.ModelAttribute
import org.springframework.web.bind.annotation.PostMapping
/**
* @Controller: Spring MVC’s annotation to communicate that this class is a web controller.
* When the application starts, Spring Boot will automatically detect this class through
* component scanning and will create an instance.
*/
@Controller
class HomeController(private val videoService: VideoService) {
// Spring MVC’s annotation to map HTTP GET / calls to this method.
@GetMapping("/")
fun index(model: Model): String {
model.addAttribute("videos", videoService.getVideos())
return "index"
}
@GetMapping("/react")
fun react(): String {
return "react"
}
@PostMapping("/new-video") // Spring MVC’s annotation to capture POST /new-video calls and route them to this method.
fun newVideo(
@ModelAttribute newVideo: Video // Spring MVC’s annotation to parse an incoming HTML form and unpack it into a Video object.
): String? {
videoService.create(newVideo)
return "redirect:/" // Spring MVC directive that sends the browser an HTTP 302 Found to URL /.
}
}
| 0 | Kotlin | 0 | 0 | 1d42e0d8604f8423f6a1328925258f51bbcde669 | 1,368 | learning-spring-boot-3.0 | The Unlicense |
app/src/main/kotlin/advent/of/code/day19/Rule.kt | dbubenheim | 321,117,765 | false | null | package advent.of.code.day19
data class Rule(val id: RuleId, val regex: Char? = null, val ruleSets: List<RuleSet> = emptyList()) | 0 | Kotlin | 0 | 0 | 3447e4737fb1e1e33f3dc493b9f525c18783899c | 129 | advent-of-code-2020 | MIT License |
DesignSystem/src/main/java/com/yourssu/design/system/foundation/ItemColor.kt | yourssu | 364,290,281 | false | null | package com.yourssu.design.system.foundation
// 백엔드와의 동일한 컬러값 통신을 위해서 사용
enum class ItemColor {
Mono,
Green,
Emerald,
Aqua,
Blue,
Indigo,
Violet,
Purple,
Pink
} | 2 | Kotlin | 0 | 9 | 58364077175f882def5108e654f51667b9d3af36 | 197 | YDS-Android | MIT License |
app/src/androidTest/java/com/jawad/newsapp/util/TestUnits.kt | Jawad52 | 247,662,918 | false | null | package com.jawad.newsapp.util
import com.jawad.newsapp.data.local.model.NewsItem
/**
* The class TestUnit
*
* @author <NAME>
* @web www.jawadusman.com
* @version 1.0
* @since 21 Mar 2020
*/
val testString = "test"
val testNewsListA = NewsItem(
1, "Title A", testString, testString, testString, testString, testString, testString,
testString, testString, testString, testString, "12.04.2020", testString, testString,
emptyList()
)
val testNewsListB = NewsItem(
2, "Title B", testString, testString, testString, testString, testString, testString,
testString, testString, testString, testString, "11.04.2020", testString, testString,
emptyList()
) | 1 | Kotlin | 1 | 1 | 261929c52377f75502af000660d8fd2b229e39c3 | 683 | News-App | Apache License 2.0 |
services/entity/src/test/kotlin/micro/apps/service/ProjectConfig.kt | xmlking | 236,108,779 | false | null | package com.example.test
import io.kotest.core.config.AbstractProjectConfig
import io.kotest.extensions.spring.SpringExtension
class ProjectConfig : AbstractProjectConfig() {
override fun extensions() = listOf(SpringExtension)
}
| 9 | null | 11 | 48 | 135c0f6b8ccfe17121a367bbfdd8024c77ea3c51 | 235 | micro-apps | MIT License |
app/src/main/java/com/crazzyghost/stockmonitor/ui/viewstock/ViewStockModule.kt | crazzyghost | 266,583,849 | false | null | package com.crazzyghost.stockmonitor.ui.viewstock
import com.crazzyghost.stockmonitor.data.DatabaseManager
import com.crazzyghost.stockmonitor.data.repo.WatchListRepository
import dagger.Module
import dagger.Provides
@Module
class ViewStockModule{
@Provides
fun presenter(repository: WatchListRepository) : ViewStockContract.Presenter{
return ViewStockPresenter(repository)
}
@Provides
fun watchListRepository(database: DatabaseManager): WatchListRepository {
return WatchListRepository(database)
}
} | 0 | Kotlin | 1 | 6 | d8e273d0a5b440bc693188a3fb3b5534b3e5e07f | 544 | stockmonitor | MIT License |
app/src/main/java/com/elementary/tasks/core/view_models/places/PlacesViewModel.kt | naz013 | 165,067,747 | false | null | package com.elementary.tasks.core.view_models.places
import com.elementary.tasks.core.data.AppDb
import com.elementary.tasks.core.data.models.Place
import com.elementary.tasks.core.data.models.ShareFile
import com.elementary.tasks.core.utils.BackupTool
import com.elementary.tasks.core.utils.Prefs
import com.elementary.tasks.core.utils.launchDefault
import com.elementary.tasks.core.utils.mutableLiveDataOf
class PlacesViewModel(
appDb: AppDb,
prefs: Prefs,
private val backupTool: BackupTool
) : BasePlacesViewModel(appDb, prefs) {
val places = appDb.placesDao().loadAll()
val shareFile = mutableLiveDataOf<ShareFile<Place>>()
fun sharePlace(place: Place) = launchDefault {
shareFile.postValue(ShareFile(place, backupTool.placeToFile(place)))
}
}
| 0 | Kotlin | 3 | 0 | a39e5d94ff77809d3e1c7f5225840c657b2c65e8 | 771 | reminder-kotlin | Apache License 2.0 |
app/src/main/java/com/bayraktar/healthybackandneck/ui/Food/FoodAdapter.kt | OzerBAYRAKTAR | 681,364,096 | false | {"Kotlin": 352122} | package com.bayraktar.healthybackandneck.ui.Food
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.bayraktar.healthybackandneck.ui.Food.TablayoutAdapters.FreshFragment
import com.bayraktar.healthybackandneck.ui.Food.TablayoutAdapters.FruitFragment
import com.bayraktar.healthybackandneck.ui.Food.TablayoutAdapters.LegumesFragment
import com.bayraktar.healthybackandneck.ui.Food.TablayoutAdapters.MeetFragment
import com.bayraktar.healthybackandneck.ui.Food.TablayoutAdapters.MilkProductsFragment
class FoodAdapter(
fm: FragmentManager, lifecycle: Lifecycle
) : FragmentStateAdapter(fm, lifecycle) {
override fun getItemCount(): Int {
return 5
}
override fun createFragment(position: Int): Fragment {
when (position) {
0 -> return MeetFragment()
1 -> return MilkProductsFragment()
2 -> return LegumesFragment()
3 -> return FruitFragment()
4 -> return FreshFragment()
// 5 -> {
// return MeetFragment()
// }
else -> throw IllegalArgumentException("Invalid position: $position")
}
}
}
| 0 | Kotlin | 0 | 0 | ffff5bab67a36818fa49b9993b33d1f8842e3ac6 | 1,284 | HealthyBackandNeck | MIT License |
ui/revenuecatui/src/test/kotlin/com/revenuecat/purchases/ui/revenuecatui/snapshottests/BasePaparazziTest.kt | RevenueCat | 127,346,826 | false | {"Kotlin": 3187935, "Java": 82657, "Ruby": 28079, "Shell": 443} | package com.revenuecat.purchases.ui.revenuecatui.snapshottests
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.platform.LocalInspectionMode
import app.cash.paparazzi.DeviceConfig
import app.cash.paparazzi.Paparazzi
import com.android.resources.NightMode
import com.android.resources.ScreenOrientation
import org.junit.Rule
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
data class TestConfig(
val name: String,
val deviceConfig: DeviceConfig,
) {
override fun toString(): String {
return name
}
}
/**
* Base class for RevenueCat Snapshot tests
*
* ### Automation:
* - To run them locally you need:
* `bundle exec fastlane verify_revenuecatui_snapshot_tests`
* - If your PR requires updating snapshots, you can generate them on CI:
* `bundle exec fastlane generate_snapshots_RCUI`
* - Once those PRs are merged in `purchases-android-snapshots`, you can update the commit:
* `bundle exec fastlane update_snapshots_repo`
*/
@RunWith(Parameterized::class)
abstract class BasePaparazziTest(testConfig: TestConfig) {
@get:Rule
val paparazzi = Paparazzi(
deviceConfig = testConfig.deviceConfig,
)
companion object {
private val landscapePixel6Device = DeviceConfig.PIXEL_6.copy(
screenHeight = 1080,
screenWidth = 2400,
xdpi = 411,
ydpi = 406,
orientation = ScreenOrientation.LANDSCAPE
)
internal val testConfigs = listOf(
TestConfig("pixel6", DeviceConfig.PIXEL_6),
TestConfig("pixel6_landscape", landscapePixel6Device),
TestConfig("pixel6_dark_mode", DeviceConfig.PIXEL_6.copy(nightMode = NightMode.NIGHT)),
TestConfig("pixel6_spanish", DeviceConfig.PIXEL_6.copy(locale = "es")),
TestConfig("nexus7", DeviceConfig.NEXUS_7),
TestConfig("nexus10", DeviceConfig.NEXUS_10),
)
@JvmStatic
@Parameterized.Parameters(name = "{0}")
fun data(): Collection<Array<Any>> {
return testConfigs.map { arrayOf(it) }
}
}
fun screenshotTest(content: @Composable () -> Unit) {
paparazzi.snapshot {
// Note that this means we will use the preview views instead of the real views.
// This is to avoid using real images for the screenshots (which doesn't work).
CompositionLocalProvider(LocalInspectionMode provides true) {
content.invoke()
}
}
}
}
| 30 | Kotlin | 52 | 253 | dad31133777389a224e9a570daec17f5c4c795ca | 2,590 | purchases-android | MIT License |
shared/src/commonMain/kotlin/presentation/tabs/list/composable/CountryItem.kt | marazmone | 632,133,133 | false | null | package presentation.tabs.list.composable
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.FavoriteBorder
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
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.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.vector.rememberVectorPainter
import androidx.compose.ui.unit.dp
import domain.model.CountryModel
import org.jetbrains.compose.resources.ExperimentalResourceApi
import presentation.ui.AppTheme
import presentation.util.AsyncImage
@OptIn(ExperimentalResourceApi::class)
@Composable
fun CountryItem(
model: CountryModel,
onClickItem: (id: String) -> Unit,
onClickFavorite: (id: String, isFavorite: Boolean) -> Unit,
) {
Card(
colors = CardDefaults.cardColors(
containerColor = MaterialTheme.colorScheme.secondaryContainer,
contentColor = MaterialTheme.typography.titleLarge.color,
),
elevation = CardDefaults.cardElevation(
defaultElevation = 6.dp,
),
modifier = Modifier
.padding(horizontal = 16.dp)
.fillMaxWidth()
.height(60.dp),
shape = MaterialTheme.shapes.large,
) {
Row(
modifier = Modifier
.fillMaxSize()
.clickable {
onClickItem.invoke(model.name)
},
verticalAlignment = Alignment.CenterVertically,
) {
Spacer(
modifier = Modifier
.width(16.dp)
)
AsyncImage(
imageUrl = model.imageUrl,
loadingPlaceHolder = {
Box(
modifier = Modifier
.size(44.dp),
) {
CircularProgressIndicator(
modifier = Modifier
.align(Alignment.Center),
)
}
},
errorPlaceHolder = {
Box(
modifier = Modifier
.size(44.dp)
.background(Color.Gray)
.align(Alignment.Center),
)
},
modifier = Modifier
.width(60.dp)
.heightIn(max = 44.dp)
.wrapContentHeight()
.align(Alignment.CenterVertically),
)
Spacer(
Modifier
.width(12.dp),
)
Text(
text = model.name,
style = MaterialTheme.typography.titleLarge,
color = Color.Black,
modifier = Modifier
.weight(1f),
)
val painter = if (model.isFavorite) {
rememberVectorPainter(Icons.Default.Favorite)
} else {
rememberVectorPainter(Icons.Default.FavoriteBorder)
}
Image(
painter = painter,
contentDescription = null,
modifier = Modifier
.size(40.dp)
.clip(CircleShape)
.clickable {
onClickFavorite.invoke(model.name, !model.isFavorite)
},
)
Spacer(
modifier = Modifier
.width(16.dp)
)
}
}
}
@Composable
fun CountryItemPreview() {
AppTheme {
CountryItem(
model = CountryModel.mockItem,
onClickItem = {},
onClickFavorite = { _, _ -> },
)
}
} | 3 | Kotlin | 0 | 22 | e8231a2311ebf371d569d807bd5a9490781be107 | 4,879 | ios-compose-showcase | Apache License 2.0 |
src/main/kotlin/me/bscal/runecraft/stats/SpellStat.kt | bscal | 414,444,966 | false | null | package me.bscal.runecraft.stats
import it.unimi.dsi.fastutil.objects.Object2ObjectOpenHashMap
import me.bscal.runecraft.utils.RomanNumber
import me.bscal.runecraft.utils.setSpell
import net.axay.kspigot.data.NBTData
import net.axay.kspigot.data.NBTDataType
import org.bukkit.NamespacedKey
import org.bukkit.attribute.AttributeModifier
import org.bukkit.entity.Entity
import org.bukkit.inventory.ItemStack
import kotlin.math.floor
object SpellRegistry
{
val Registry = Object2ObjectOpenHashMap<NamespacedKey, SpellStat>()
fun Register(spell: SpellStat): SpellStat
{
Registry[spell.Id] = spell
return spell
}
}
enum class SpellType
{
PASSIVE, CASTED, LEFT_CLICKED, RIGHT_CLICKED, DAMAGE_DONE, DAMAGE_RECEIVED
}
interface SpellCastAction
{
fun OnCast(caster: Entity, instance: StatInstance, targets: List<Entity>?)
}
interface SpellTarget
{
fun GetTargets(caster: Entity, instance: StatInstance): List<Entity>?
}
interface SpellCondition
{
fun CanCast(caster: Entity, instance: StatInstance): Boolean
}
open class SpellStat(namespacedKey: NamespacedKey, val Name: String, val MaxLevel: Int, val Type: SpellType, val Condition: SpellCondition?,
val Target: SpellTarget, val CastAction: SpellCastAction) : BaseStat(namespacedKey)
{
companion object
{
const val LEVEL_KEY = "spell_level"
}
fun Process(caster: Entity, instance: StatInstance)
{
val canCast: Boolean = Condition?.CanCast(caster, instance) ?: true
if (canCast) CastAction.OnCast(caster, instance, Target.GetTargets(caster, instance))
}
override fun ApplyToItemStack(instance: StatInstance, itemStack: ItemStack)
{
itemStack.itemMeta.setSpell(instance)
}
override fun GetLocalName(instance: StatInstance): String
{
return "$Name ${RomanNumber.toRoman(instance.Value.toInt())}"
}
override fun CombineInstance(instance: StatInstance, other: StatInstance): StatInstance
{
if (!IsSame(instance, other)) return instance
instance.Value = floor((instance.Value + other.Value).coerceAtMost(MaxLevel.toDouble()))
return instance
}
fun NewStatInstance(level: Int): StatInstance
{
val data = NBTData()
data[LEVEL_KEY, NBTDataType.INT] = level
return super.NewStatInstance(level.toDouble(), AttributeModifier.Operation.ADD_NUMBER, data)
}
inline fun IncrementLevel(instance: StatInstance) = SetLevel(instance, GetLevel(instance) + 1)
fun SetLevel(instance: StatInstance, level: Int)
{
instance.AdditionalData[LEVEL_KEY, NBTDataType.INT] = level.coerceAtMost(MaxLevel)
}
fun GetLevel(instance: StatInstance): Int = instance.AdditionalData[LEVEL_KEY, NBTDataType.INT] ?: 0
} | 0 | Kotlin | 0 | 0 | 29470ea09d74e83a3fabe0789d8f169de6a3fc20 | 2,594 | RuneCraft | MIT License |
feature-wallet-api/src/main/java/com/dfinn/wallet/feature_wallet_api/data/cache/AssetCache.kt | finn-exchange | 500,972,990 | false | null | package com.dfinn.wallet.feature_wallet_api.data.cache
import com.dfinn.wallet.core_db.dao.AssetDao
import com.dfinn.wallet.core_db.dao.AssetReadOnlyCache
import com.dfinn.wallet.core_db.dao.TokenDao
import com.dfinn.wallet.core_db.model.AssetLocal
import com.dfinn.wallet.core_db.model.TokenLocal
import com.dfinn.wallet.feature_account_api.domain.interfaces.AccountRepository
import com.dfinn.wallet.runtime.multiNetwork.chain.model.Chain
import jp.co.soramitsu.fearless_utils.runtime.AccountId
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.withContext
class AssetCache(
private val tokenDao: TokenDao,
private val accountRepository: AccountRepository,
private val assetDao: AssetDao,
) : AssetReadOnlyCache by assetDao {
private val assetUpdateMutex = Mutex()
/**
* @return true if asset was changed. false if it remained the same
*/
suspend fun updateAsset(
metaId: Long,
chainAsset: Chain.Asset,
builder: (local: AssetLocal) -> AssetLocal,
): Boolean = withContext(Dispatchers.IO) {
val assetId = chainAsset.id
val chainId = chainAsset.chainId
assetUpdateMutex.withLock {
tokenDao.ensureToken(chainAsset.symbol)
val cachedAsset = assetDao.getAsset(metaId, chainId, assetId)?.asset ?: AssetLocal.createEmpty(assetId, chainId, metaId)
val newAsset = builder.invoke(cachedAsset)
assetDao.insertAsset(newAsset)
cachedAsset != newAsset
}
}
/**
* @see updateAsset
*/
suspend fun updateAsset(
accountId: AccountId,
chainAsset: Chain.Asset,
builder: (local: AssetLocal) -> AssetLocal,
): Boolean = withContext(Dispatchers.IO) {
val applicableMetaAccount = accountRepository.findMetaAccount(accountId)
applicableMetaAccount?.let {
updateAsset(it.id, chainAsset, builder)
} ?: false
}
suspend fun insertTokens(tokens: List<TokenLocal>) = tokenDao.insertTokens(tokens)
}
| 0 | Kotlin | 0 | 0 | 6cc7a0a4abb773daf3da781b7bd1dda5dbf9b01d | 2,120 | dfinn-android-wallet | Apache License 2.0 |
src/main/kotlin/io/codegeet/sandbox/coderunner/model/Model.kt | codegeet | 701,910,396 | false | {"Kotlin": 4358} | package io.codegeet.sandbox.coderunner.model
import io.codegeet.sandbox.coderunner.Language
data class RunInstructions(
val build: Array<String>,
val run: String
)
data class ApplicationInput(
val language: Language,
val files: Array<InputFile>
//todo add stdin
//todo add command
)
data class InputFile(
var name: String,
var content: String,
)
data class ApplicationOutput (
val stdout: String,
val stderr: String,
val error: String,
)
| 0 | Kotlin | 0 | 0 | c8fef3b5b00639cf694df407a7148cd50cfc57fc | 487 | coderunner | MIT License |
odyssey-compose/src/macosMain/kotlin/ru/alexgladkov/odyssey/compose/setup/Odyssey + Setup.kt | AlexGladkov | 409,687,153 | false | {"Kotlin": 124395} | package ru.alexgladkov.odyssey.compose.setup
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import ru.alexgladkov.odyssey.compose.base.Navigator
import ru.alexgladkov.odyssey.compose.local.LocalRootController
import ru.alexgladkov.odyssey.compose.navigation.RootComposeBuilder
import ru.alexgladkov.odyssey.compose.navigation.modal_navigation.ModalNavigator
import ru.alexgladkov.odyssey.compose.navigation.modal_navigation.configuration.DefaultModalConfiguration
import ru.alexgladkov.odyssey.core.configuration.DisplayType
@Composable
actual fun setNavigationContent(configuration: OdysseyConfiguration, onApplicationFinish: () -> Unit, navigationGraph: RootComposeBuilder.() -> Unit) {
val rootController = RootComposeBuilder().apply(navigationGraph).build()
rootController.backgroundColor = configuration.backgroundColor
CompositionLocalProvider(
LocalRootController provides rootController
) {
ModalNavigator(configuration = DefaultModalConfiguration(configuration.backgroundColor, DisplayType.EdgeToEdge)) {
when (val startScreen = configuration.startScreen) {
is StartScreen.Custom -> Navigator(startScreen = startScreen.startName)
StartScreen.First -> Navigator(startScreen = rootController.getFirstScreenName())
}
}
}
} | 21 | Kotlin | 22 | 256 | 5c5d33d4f0cc47919d3eafb226d8bec3aa777eb0 | 1,384 | Odyssey | MIT License |
card/src/main/java/com/adyen/checkout/card/internal/util/DualBrandedCardUtils.kt | Adyen | 91,104,663 | false | null | /*
* Copyright (c) 2023 Adyen N.V.
*
* This file is open source and available under the MIT license. See the LICENSE file for more info.
*
* Created by oscars on 15/2/2023.
*/
package com.adyen.checkout.card.internal.util
import com.adyen.checkout.card.CardBrand
import com.adyen.checkout.card.CardType
import com.adyen.checkout.card.internal.data.model.DetectedCardType
internal object DualBrandedCardUtils {
fun sortBrands(cards: List<DetectedCardType>): List<DetectedCardType> {
return if (cards.size <= 1) {
cards
} else {
val hasCarteBancaire = cards.any { it.cardBrand == CardBrand(cardType = CardType.CARTEBANCAIRE) }
val hasVisa = cards.any { it.cardBrand == CardBrand(cardType = CardType.VISA) }
val hasPlcc = cards.any {
it.cardBrand.txVariant.contains("plcc") ||
it.cardBrand.txVariant.contains("cbcc")
}
when {
hasCarteBancaire && hasVisa -> cards.sortedByDescending {
it.cardBrand == CardBrand(cardType = CardType.VISA)
}
hasPlcc -> cards.sortedByDescending {
it.cardBrand.txVariant.contains("plcc") ||
it.cardBrand.txVariant.contains("cbcc")
}
else -> cards
}
}
}
}
| 28 | Kotlin | 59 | 96 | 1f000e27e07467f3a30bb3a786a43de62be003b2 | 1,387 | adyen-android | MIT License |
src/main/kotlin/com/valjapan/competitionprogramming/AOJ1_7_B.kt | valjapan | 256,530,542 | false | null | package com.valjapan.competitionprogramming
fun main(args: Array<String>) {
while (true) {
val (n, x) = readLine()!!.split(" ").map(String::toInt)
if ((n == 0) and (x == 0)) {
break
}
var combinationNum = 0
for (a in (1..n)) {
for (b in (1 until a)) {
if (x <= a + b) {
break
}
val c = x - (a + b)
if (c < b) {
combinationNum += 1
} else {
continue
}
}
}
println("$combinationNum")
}
}
| 0 | Kotlin | 0 | 0 | dfceeecbea88581dd634e15311694eed718f3cfa | 648 | CompetionProgramming | MIT License |
src/commonMain/kotlin/io/grule/matcher/MatcherShadow.kt | 7hens | 376,845,987 | false | null | package io.grule.matcher
internal class MatcherShadow<T : Status<T>> : ReversedMatcher<T> {
override val reverser: Matcher<T> = this
override fun match(status: T): T {
throw MatcherException(status)
}
override fun not(): Matcher<T> {
return this
}
override fun test(): Matcher<T> {
return this
}
override fun plus(matcher: Matcher<T>): Matcher<T> {
return matcher
}
override fun or(matcher: Matcher<T>): Matcher<T> {
return matcher
}
override fun times(minTimes: Int, maxTimes: Int): Matcher<T> {
return this
}
override fun join(separator: Matcher<T>): Matcher<T> {
return this
}
override fun interlace(separator: Matcher<T>): Matcher<T> {
return separator.optional()
}
override fun until(terminal: Matcher<T>): Matcher<T> {
return terminal
}
override fun till(terminal: Matcher<T>): Matcher<T> {
return terminal
}
override fun toString(): String {
return "()"
}
} | 0 | Kotlin | 0 | 1 | 3c00cfd151e78515a93f20a90369e43dd3b75f73 | 1,057 | grule | Apache License 2.0 |
src/main/kotlin/io/foxcapades/lib/cli/builder/flag/ref/xeResolvedFlag.kt | Foxcapades | 850,780,005 | false | {"Kotlin": 251181} | @file:JvmName("InternalResolvedFlagExtensions")
@file:Suppress("NOTHING_TO_INLINE")
package io.foxcapades.lib.cli.builder.flag.ref
import io.foxcapades.lib.cli.builder.CliSerializationException
import io.foxcapades.lib.cli.builder.InvalidFlagFormException
import io.foxcapades.lib.cli.builder.serial.CliSerializationConfig
// region Validation
internal fun ResolvedFlag<*>.validateFlagNames(config: CliSerializationConfig) {
if (hasShortForm) {
val sv = config.targetShell.isFlagSafe(shortForm)
if (hasLongForm) {
var lv = true
for (c in longForm) {
if (!config.targetShell.isFlagSafe(c)) {
lv = false
break
}
}
if (!sv) {
throw if (!lv)
InvalidFlagFormException.invalidBothForms(this)
else
InvalidFlagFormException.invalidShortForm(this)
}
}
} else if (hasLongForm) {
var lv = true
for (c in longForm) {
if (!config.targetShell.isFlagSafe(c)) {
lv = false
break
}
}
if (!lv)
throw InvalidFlagFormException.invalidLongForm(this)
} else if (!valueSource.hasName) {
throw CliSerializationException("Flag instance has no short or long form defined; sourced from ${parentComponent.qualifiedName}")
}
}
// endregion Validation
// region Unsafe Casting
@Suppress("UNCHECKED_CAST")
internal inline fun ResolvedFlag<*>.forceAny() = this as ResolvedFlag<Any?>
// endregion Unsafe Casting
| 8 | Kotlin | 0 | 0 | 1b45c0e4ffa914ecc9c53356aa9d276a6d5aa6b7 | 1,469 | lib-kt-cli-builder | MIT License |
src/main/java/io/pemassi/pata/annotations/FixedDataField.kt | pemassi | 334,450,447 | false | null | /*
* Copyright (c) 2021 <NAME>(pemassi).
* All rights reserved.
*/
package io.pemassi.pata.annotations
/**
* Declare this property is part of data model(FixedLengthDataModel).
*
* @param order This data field order, all data field will be sorted by [order].
* @param name Data name
* @param size Data Size(expected size)
*/
@Retention(AnnotationRetention.RUNTIME)
@Target(AnnotationTarget.PROPERTY)
annotation class DividedDataField(
val order: Int,
val name: String,
)
| 0 | Kotlin | 0 | 3 | 7a28898bec2c65b101d967ff6957e0d7e565f16c | 489 | Pata | MIT License |
app/src/main/java/vn/edu/usth/mobile_app/ui/admin/FragmentAdminAnalyticsViewModel.kt | ChloroProject-2023 | 691,451,114 | false | {"Kotlin": 29173} | package vn.edu.usth.mobile_app.ui.admin
import android.util.Log
import androidx.lifecycle.ViewModel
class FragmentAdminAnalyticsViewModel: ViewModel(){
private var _requestFreqData: Array<Any> = emptyArray()
private var _top5ModelData: Map<String, Int> = emptyMap()
private var _last24hRequest: Int = 0
private var _last24hUsers: Int = 0
val requestFreqData: Array<Any> get() = _requestFreqData
val top5ModelData: Map<String, Int> get() = _top5ModelData
val last24hRequest: Int get() = _last24hRequest
val last24hUsers: Int get() = _last24hUsers
init {
Log.d("AdminAnalyticsViewModel", "ViewModel created")
_requestFreqData = arrayOf(1, 2, 3, 4, 5)
_top5ModelData = mapOf(
"Model 1" to 1,
"Model 2" to 2,
"Model 3" to 3,
"Model 4" to 4,
"Model 5" to 5,)
}
override fun onCleared() {
super.onCleared()
Log.d("AdminAnalyticsViewModel", "ViewModel destroyed")
}
} | 1 | Kotlin | 0 | 0 | b5635b2a3896108abbe6a2c010f6e45a330fab4f | 1,014 | mobile-app | MIT License |
tezos-core/src/main/kotlin/it/airgap/tezos/core/internal/converter/encoded/SignatureToGenericSignatureConverter.kt | airgap-it | 460,351,851 | false | null | package it.airgap.tezos.core.internal.converter.encoded
import it.airgap.tezos.core.coder.encoded.decodeFromBytes
import it.airgap.tezos.core.internal.coder.ConsumingBytesCoder
import it.airgap.tezos.core.internal.coder.encoded.EncodedBytesCoder
import it.airgap.tezos.core.internal.context.withTezosContext
import it.airgap.tezos.core.internal.converter.Converter
import it.airgap.tezos.core.type.encoded.GenericSignature
import it.airgap.tezos.core.type.encoded.Signature
internal class SignatureToGenericSignatureConverter(
private val signatureBytesCoder: ConsumingBytesCoder<Signature>,
private val encodedBytesCoder: EncodedBytesCoder,
) : Converter<Signature, GenericSignature> {
override fun convert(value: Signature): GenericSignature = withTezosContext {
if (value is GenericSignature) return value
val bytes = signatureBytesCoder.encode(value)
return GenericSignature.decodeFromBytes(bytes, encodedBytesCoder)
}
} | 0 | Kotlin | 2 | 1 | c5af5ffdd4940670bd66842580d82c2b9d682d84 | 967 | tezos-kotlin-sdk | MIT License |
rider-fsharp/src/test/kotlin/projectModel/ReferencesOrderTest.kt | JetBrains | 81,554,746 | false | null | package projectModel
import com.jetbrains.rider.plugins.fsharp.test.fcsHost
import com.jetbrains.rider.test.annotations.TestEnvironment
import com.jetbrains.rider.test.base.BaseTestWithSolution
import com.jetbrains.rider.test.enums.CoreVersion
import com.jetbrains.rider.test.enums.ToolsetVersion
import org.testng.annotations.Test
@Test
@TestEnvironment(toolset = ToolsetVersion.TOOLSET_16_CORE, coreVersion = CoreVersion.DEFAULT)
class ReferencesOrder : BaseTestWithSolution() {
override fun getSolutionDirectoryName() = "ReferencesOrder"
override val waitForCaches = true
override val restoreNuGetPackages = true
@Test()
fun testReferencesOrder() {
val references = project.fcsHost.dumpSingleProjectLocalReferences.sync(Unit)
assert(references == listOf("Library1.dll", "Library2.dll"))
}
}
| 43 | F# | 38 | 251 | 955e3c373f3965903542ef5f0d41753c82f61858 | 839 | fsharp-support | Apache License 2.0 |
library/src/main/java/com/suddenh4x/ratingdialog/preferences/RatingThreshold.kt | nyberesnev | 301,658,985 | true | {"Kotlin": 117773} | package com.suddenh4x.ratingdialog.preferences
enum class RatingThreshold {
NONE, HALF, ONE, ONE_AND_A_HALF, TWO, TWO_AND_A_HALF, THREE, THREE_AND_A_HALF, FOUR, FOUR_AND_A_HALF, FIVE;
}
fun RatingThreshold.toFloat() = this.ordinal / 2f
| 0 | Kotlin | 1 | 0 | 7606272d42428a22841b0dd8c7448a8a1c6733bb | 242 | awesome-app-rating | Apache License 2.0 |
cosec-spring-boot-starter/src/test/kotlin/me/ahoo/cosec/spring/boot/starter/actuate/CoSecPolicyGeneratorEndpointTest.kt | Ahoo-Wang | 567,999,401 | false | {"Kotlin": 588793, "Dockerfile": 594} | package me.ahoo.cosec.spring.boot.starter.generator
import io.mockk.every
import io.mockk.mockk
import io.swagger.v3.oas.models.OpenAPI
import io.swagger.v3.oas.models.Paths
import org.hamcrest.MatcherAssert.*
import org.hamcrest.Matchers.*
import org.junit.jupiter.api.Test
class CoSecPolicyGeneratorEndpointTest {
@Test
fun generate() {
val policy = CoSecPolicyGeneratorEndpoint(
mockk {
every { getIfAvailable() } returns OpenAPI().paths(Paths())
}
).generate()
assertThat(policy, notNullValue())
}
@Test
fun generateIfNull() {
val policy = CoSecPolicyGeneratorEndpoint(
mockk {
every { getIfAvailable() } returns null
}
).generate()
assertThat(policy, nullValue())
}
}
| 2 | Kotlin | 4 | 32 | b0edd6e0b096a76d17363778b1aec8dd2c19c9b3 | 831 | CoSec | Apache License 2.0 |
app/src/main/java/com/example/learnwithme/data/datasource/character/remote/api/CharacterApi.kt | fsalom | 677,505,777 | false | null | package com.example.learnwithme.data.datasource.character.remote.api
import com.example.learnwithme.data.datasource.character.remote.dto.CharactersInfoDTO
import retrofit2.Response
import retrofit2.http.GET
import retrofit2.http.Query
interface CharacterApiInterface {
@GET("api/character")
suspend fun getCharacters(@Query("page") page: Int): Response<CharactersInfoDTO>
} | 0 | Kotlin | 0 | 0 | e18d27779847b03858a99f56b3f41397180ead44 | 383 | android-compose | MIT License |
app/src/main/java/io/github/ytam/githubusers/domain/repository/UserRepository.kt | ytam | 482,583,043 | false | null | package io.github.ytam.githubusers.domain.repository
import androidx.paging.PagingData
import io.github.ytam.githubusers.domain.model.User
import io.github.ytam.githubusers.domain.model.UserDetail
import kotlinx.coroutines.flow.Flow
interface UserRepository {
fun getAllUser(): Flow<PagingData<User>>
suspend fun getUserDetailsByUsername(username: String): Flow<UserDetail>
}
| 0 | Kotlin | 0 | 0 | 404e048975cea26b5888747638fb36b1b40f551e | 388 | Jet-Users | Apache License 2.0 |
src/test/code/trypp/support/math/CardinalDirectionTest.kt | d9n | 56,415,500 | false | null | package trypp.support.math
import com.google.common.truth.Truth.assertThat
import org.testng.annotations.Test
class CardinalDirectionTest {
@Test fun getForAngleWorks() {
assertThat(CardinalDirection.getForAngle(Angle.ofDegrees(0f))).isEqualTo(
CardinalDirection.E)
assertThat(CardinalDirection.getForAngle(Angle.ofDegrees(45f))).isEqualTo(
CardinalDirection.N)
assertThat(CardinalDirection.getForAngle(Angle.ofDegrees(90f))).isEqualTo(
CardinalDirection.N)
assertThat(CardinalDirection.getForAngle(Angle.ofDegrees(135f))).isEqualTo(
CardinalDirection.W)
assertThat(CardinalDirection.getForAngle(Angle.ofDegrees(180f))).isEqualTo(
CardinalDirection.W)
assertThat(CardinalDirection.getForAngle(Angle.ofDegrees(225f))).isEqualTo(
CardinalDirection.S)
assertThat(CardinalDirection.getForAngle(Angle.ofDegrees(270f))).isEqualTo(
CardinalDirection.S)
assertThat(CardinalDirection.getForAngle(Angle.ofDegrees(315f))).isEqualTo(
CardinalDirection.E)
}
@Test fun angleIsCorrect() {
assertThat(CardinalDirection.E.angle.getDegrees()).isWithin(0f).of(0f)
assertThat(CardinalDirection.N.angle.getDegrees()).isWithin(0f).of(90f)
assertThat(CardinalDirection.W.angle.getDegrees()).isWithin(0f).of(180f)
assertThat(CardinalDirection.S.angle.getDegrees()).isWithin(0f).of(270f)
}
@Test fun directionFacingWorks() {
assertThat(CardinalDirection.E.faces(Angle.ofDegrees(10f))).isTrue()
assertThat(CardinalDirection.S.faces(Angle.ofDegrees(180f))).isFalse()
assertThat(CardinalDirection.E.faces(Angle.ofDegrees(350f))).isTrue()
}
} | 0 | Kotlin | 0 | 0 | 08c2781c2fe8d42c22fbafcfef1ba9d66cc60df2 | 1,757 | trypp.support | MIT License |
modulecheck-core/src/main/kotlin/modulecheck/core/rule/android/DisableAndroidResourcesRule.kt | jeremiahvanofferen | 397,332,342 | true | {"Kotlin": 440018, "JavaScript": 9458, "CSS": 3037} | /*
* Copyright (C) 2021 <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 modulecheck.core.rule.android
import modulecheck.api.AndroidProject2
import modulecheck.api.Project2
import modulecheck.api.settings.ModuleCheckSettings
import modulecheck.core.rule.ModuleCheckRule
import modulecheck.psi.DslBlockVisitor
import net.swiftzer.semver.SemVer
internal val androidBlockParser = DslBlockVisitor("android")
internal val androidBlockRegex = "^android \\{".toRegex()
private val MINIMUM_ANDROID_RESOURCES_VERSION = SemVer(major = 4, minor = 1, patch = 0)
class DisableAndroidResourcesRule(
override val settings: ModuleCheckSettings
) : ModuleCheckRule<UnusedResourcesGenerationFinding>() {
override val id = "DisableAndroidResources"
override val description =
"Finds modules which have android resources R file generation enabled, " +
"but don't actually use any resources from the module"
@Suppress("ReturnCount")
override fun check(project: Project2): List<UnusedResourcesGenerationFinding> {
val androidProject = project as? AndroidProject2 ?: return emptyList()
// grabs the AGP version of the client project - not this plugin
val agpVersion = androidProject.agpVersion
// minimum AGP version for this feature is 4.1.0, so don't bother checking below that
if (agpVersion < MINIMUM_ANDROID_RESOURCES_VERSION) return emptyList()
@Suppress("UnstableApiUsage")
if (!androidProject.androidResourcesEnabled) return emptyList()
val noResources = androidProject.resourceFiles.isEmpty()
return if (noResources) {
listOf(UnusedResourcesGenerationFinding(project.path, project.buildFile))
} else {
emptyList()
}
}
}
| 0 | null | 0 | 0 | 65455e246ffcfe398335af0ca87348d561348c54 | 2,224 | ModuleCheck | Apache License 2.0 |
src/test/kotlin/Solution1Test.kt | AndreySmirdin | 170,665,827 | false | null | import Solution1.solve
import org.apache.commons.lang3.StringUtils
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
class Solution1Test {
@Test
fun solveImpossibleBecauseOfPrefixName() {
assertEquals(solve(arrayListOf("hello", "abcd", "abc")).size, 0)
}
@Test
fun solveImpossibleBecauseOfCycle() {
assertEquals(solve(arrayListOf("a", "b", "a")).size, 0)
assertEquals(solve(arrayListOf("a", "b", "c", "db", "da")).size, 0)
}
@Test
fun solvePossible() {
var names = arrayListOf("a", "b", "c")
validate(names, solve(names))
names = arrayListOf("a", "b", "c", "ca", "cb")
validate(names, solve(names))
names = arrayListOf("c", "b", "a", "dx", "da")
validate(names, solve(names))
names = arrayListOf("andrey", "alex", "vladimir", "semen", "egor", "masha")
validate(names, solve(names))
}
private fun validate(names: ArrayList<String>, permutation: List<Char>) {
for (i in 1 until names.size) {
val diff_position = StringUtils.indexOfDifference(names[i - 1], names[i])
if (diff_position == -1) {
continue
}
assertTrue(diff_position < names[i].length)
if (diff_position == names[i - 1].length) {
continue
}
val char1 = permutation.indexOf(names[i - 1][diff_position])
val char2 = permutation.indexOf(names[i][diff_position])
assertTrue(char1 < char2)
}
}
}
| 0 | Kotlin | 0 | 0 | 27465d19f5413a06948fc32d789ac7c35a80682f | 1,593 | Task_for_Groovy_project | MIT License |
sample-desktop/src/jvmMain/kotlin/com/github/panpf/zoomimage/sample/ui/model/ImageResource.kt | panpf | 647,222,866 | false | {"Kotlin": 3004367, "Shell": 724} | package com.github.panpf.zoomimage.sample.ui.model
data class ImageResource(val resourcePath: String, val thumbnailResourcePath: String = resourcePath) | 1 | Kotlin | 7 | 98 | bdc00e862498830df39a205de5d3d490a5f04444 | 152 | zoomimage | Apache License 2.0 |
becafe/app/src/main/java/hr/ferit/gabrielveselovac/becafe/HelpFragment.kt | v-gabriel | 555,912,719 | false | null | package hr.ferit.gabrielveselovac.becafe
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageButton
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
class HelpFragment : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_help, container, false)
val backButton = view.findViewById<ImageButton>(R.id.backButtonHelp)
backButton.setOnClickListener {
backButton.setBackgroundColor(resources.getColor(R.color.gray))
val handler = Handler()
handler.postDelayed(Runnable {
backButton.setBackgroundColor(resources.getColor(R.color.transparent))
}, 50)
val mainFragment = MainFragment()
val fragmentTransaction: FragmentTransaction? =
activity?.supportFragmentManager?.beginTransaction()
fragmentTransaction?.setCustomAnimations(R.anim.enter_from_above,R.anim.exit_to_below)
fragmentTransaction?.replace(R.id.mainFragment, mainFragment)
fragmentTransaction?.commit()
}
return view
}
} | 0 | Kotlin | 0 | 2 | 0d79a8dc0013e8423f7a5841705a4c801c113c1c | 1,370 | becafe | MIT License |
app/src/main/java/com/cusufcan/fotografpaylasma/adapter/PostAdapter.kt | cusufcan | 836,783,240 | false | {"Kotlin": 17688} | package com.cusufcan.fotografpaylasma.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.cusufcan.fotografpaylasma.databinding.PostItemBinding
import com.cusufcan.fotografpaylasma.model.Post
import com.squareup.picasso.Picasso
class PostAdapter(private val posts: List<Post>) : RecyclerView.Adapter<PostAdapter.PostHolder>() {
inner class PostHolder(val binding: PostItemBinding) : RecyclerView.ViewHolder(binding.root)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PostHolder {
val binding = PostItemBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return PostHolder(binding)
}
override fun getItemCount(): Int {
return posts.size
}
override fun onBindViewHolder(holder: PostHolder, position: Int) {
val post = posts[position]
holder.binding.postEmailText.text = post.email
holder.binding.postCommentText.text = post.comment
Picasso.get().load(post.downloadUrl).into(holder.binding.postImage)
}
} | 0 | Kotlin | 0 | 0 | f477111b782b38c23066df4992ccec1bcc5b2695 | 1,109 | upload_image | MIT License |
compiler/testData/diagnostics/tests/sealed/interfaces/inheritorInDifferentModule.kt | JetBrains | 3,432,266 | false | null | // ISSUE: KT-20423
// !LANGUAGE: +SealedInterfaces +AllowSealedInheritorsInDifferentFilesOfSamePackage
// MODULE: m1
// FILE: a.kt
package a
sealed interface Base
interface A : Base
// MODULE: m2(m1)
// FILE: b.kt
package a
interface B : <!SEALED_INHERITOR_IN_DIFFERENT_MODULE!>Base<!>
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 292 | kotlin | Apache License 2.0 |
src/commonMain/kotlin/com/epam/drill/test/agent/AgentConfig.kt | Drill4J | 250,085,937 | false | null | package com.epam.drill.test.agent
expect object AgentConfig {
fun proxyUrl(): String?
fun adminAddress(): String?
fun agentId(): String?
fun groupId(): String?
fun devToolsProxyAddress(): String?
fun withJsCoverage(): Boolean
}
| 1 | Kotlin | 4 | 4 | 635eca21cd59f0ee29ed8eaf3f1904ab14467f56 | 253 | autotest-agent | Apache License 2.0 |
svg-to-compose/src/commonMain/kotlin/dev/tonholo/s2c/domain/svg/SvgDefsNode.kt | rafaeltonholo | 659,782,425 | false | {"Kotlin": 518715, "Shell": 5365} | package dev.tonholo.s2c.domain.svg
import dev.tonholo.s2c.domain.xml.XmlNode
import dev.tonholo.s2c.domain.xml.XmlParentNode
class SvgDefsNode(
parent: XmlParentNode,
override val children: MutableSet<XmlNode>,
attributes: MutableMap<String, String>,
) : SvgElementNode<SvgDefsNode>(parent, children, attributes, tagName = TAG_NAME), SvgNode {
override val constructor = ::SvgDefsNode
companion object {
const val TAG_NAME = "defs"
}
}
| 5 | Kotlin | 2 | 61 | b3e7c5ffa041d5d31c686d72b9119661b5e4ce7b | 470 | svg-to-compose | MIT License |
mtproto/src/main/kotlin/com/github/badoualy/telegram/mtproto/tl/MTRpcError.kt | Miha-x64 | 436,587,061 | true | {"Kotlin": 3919807, "Java": 75352} | package com.github.badoualy.telegram.mtproto.tl
import com.github.badoualy.telegram.mtproto.exception.RpcError
import com.github.badoualy.telegram.tl.core.TLObject
import com.github.badoualy.telegram.tl.serialization.TLDeserializer
import com.github.badoualy.telegram.tl.serialization.TLSerializer
import java.io.IOException
class MTRpcError @JvmOverloads constructor(var code: Int = 0,
var message: String = "") : TLObject() {
val error: RpcError by lazy {
RpcError(code, message.replace(NUMBER_REGEX, "X"), "")
}
override val constructorId: Int = CONSTRUCTOR_ID
@Throws(IOException::class)
override fun serializeBody(tlSerializer: TLSerializer) = with(tlSerializer) {
writeInt(code)
writeString(message)
}
@Throws(IOException::class)
override fun deserializeBody(tlDeserializer: TLDeserializer) = with(tlDeserializer) {
code = readInt()
message = readString()
}
override fun toString() = "rpc_error#2144ca19"
companion object {
val TYPE_REGEX = "[A-Z_0-9]+".toRegex()
val NUMBER_REGEX = "[0-9]+".toRegex()
@JvmField
val CONSTRUCTOR_ID = 558156313
}
}
| 1 | Kotlin | 2 | 3 | 1a8963dce921c1e9ef05b9d1e56d8fbcb1ea1c4b | 1,226 | kotlogram-resurrected | MIT License |
feature/employee_attendance/src/main/java/com/niyaj/feature/employee_attendance/AttendanceScreen.kt | skniyajali | 579,613,644 | false | {"Kotlin": 2202790} | package com.niyaj.feature.employee_attendance
import androidx.activity.compose.BackHandler
import androidx.compose.animation.Crossfade
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.material.FabPosition
import androidx.compose.material.ScaffoldState
import androidx.compose.material.rememberScaffoldState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavController
import com.niyaj.common.tags.AbsentScreenTestTags.ABSENT_NOT_AVAILABLE
import com.niyaj.common.tags.AbsentScreenTestTags.ABSENT_SCREEN_TITLE
import com.niyaj.common.tags.AbsentScreenTestTags.ABSENT_SEARCH_PLACEHOLDER
import com.niyaj.common.tags.AbsentScreenTestTags.CREATE_NEW_ABSENT
import com.niyaj.common.tags.AbsentScreenTestTags.DELETE_ABSENT_MESSAGE
import com.niyaj.common.tags.AbsentScreenTestTags.DELETE_ABSENT_TITLE
import com.niyaj.common.tags.AbsentScreenTestTags.NO_ITEMS_IN_ABSENT
import com.niyaj.common.utils.toMonthAndYear
import com.niyaj.designsystem.theme.SpaceSmall
import com.niyaj.feature.employee_attendance.components.AbsentEmployees
import com.niyaj.feature.employee_attendance.destinations.AddEditAbsentScreenDestination
import com.niyaj.ui.components.ItemNotAvailable
import com.niyaj.ui.components.LoadingIndicator
import com.niyaj.ui.components.ScaffoldNavActions
import com.niyaj.ui.components.StandardFAB
import com.niyaj.ui.components.StandardScaffoldNew
import com.niyaj.ui.event.UiEvent
import com.niyaj.ui.event.UiState
import com.niyaj.ui.util.Screens
import com.niyaj.ui.util.isScrolled
import com.ramcosta.composedestinations.annotation.Destination
import com.ramcosta.composedestinations.annotation.RootNavGraph
import com.ramcosta.composedestinations.navigation.navigate
import com.ramcosta.composedestinations.result.NavResult
import com.ramcosta.composedestinations.result.ResultRecipient
import com.vanpra.composematerialdialogs.MaterialDialog
import com.vanpra.composematerialdialogs.message
import com.vanpra.composematerialdialogs.rememberMaterialDialogState
import com.vanpra.composematerialdialogs.title
import kotlinx.coroutines.launch
/**
* Attendance Screen
* @author Sk Niyaj Ali
* @param navController
* @param scaffoldState
* @param viewModel
* @param resultRecipient
* @see AddEditAbsentScreenDestination
* @see AttendanceViewModel
*/
@RootNavGraph(start = true)
@Destination(route = Screens.ATTENDANCE_SCREEN)
@Composable
fun AttendanceScreen(
navController: NavController,
scaffoldState: ScaffoldState = rememberScaffoldState(),
viewModel: AttendanceViewModel = hiltViewModel(),
resultRecipient: ResultRecipient<AddEditAbsentScreenDestination, String>,
) {
val lazyListState = rememberLazyListState()
val dialogState = rememberMaterialDialogState()
val scope = rememberCoroutineScope()
val uiState = viewModel.absents.collectAsStateWithLifecycle().value
val showFab = viewModel.totalItems.isNotEmpty()
val selectedItems = viewModel.selectedItems.toList()
val selectedEmployee = viewModel.selectedEmployee.collectAsStateWithLifecycle().value
val showSearchBar = viewModel.showSearchBar.collectAsStateWithLifecycle().value
val searchText = viewModel.searchText.value
LaunchedEffect(key1 = true) {
viewModel.eventFlow.collect { event ->
when (event) {
is UiEvent.Success -> {
scaffoldState.snackbarHostState.showSnackbar(event.successMessage)
}
is UiEvent.Error -> {
scaffoldState.snackbarHostState.showSnackbar(event.errorMessage)
}
}
}
}
BackHandler(true) {
if (showSearchBar) {
viewModel.closeSearchBar()
} else if (selectedItems.isNotEmpty()) {
viewModel.deselectItems()
} else {
navController.navigateUp()
}
}
resultRecipient.onNavResult { result ->
when (result) {
is NavResult.Canceled -> {
if (selectedItems.isNotEmpty()) {
viewModel.deselectItems()
}
}
is NavResult.Value -> {
if (selectedItems.isNotEmpty()) {
viewModel.deselectItems()
}
scope.launch {
scaffoldState.snackbarHostState.showSnackbar(result.value)
}
}
}
}
StandardScaffoldNew(
navController = navController,
scaffoldState = scaffoldState,
selectionCount = selectedItems.size,
showBackButton = selectedItems.isEmpty(),
onBackClick = {
if (showSearchBar) {
viewModel.closeSearchBar()
} else {
navController.navigateUp()
}
},
title = if (selectedItems.isEmpty()) ABSENT_SCREEN_TITLE else "${selectedItems.size} Selected",
showFab = showFab,
floatingActionButton = {
StandardFAB(
showScrollToTop = lazyListState.isScrolled,
fabText = CREATE_NEW_ABSENT,
fabVisible = (showFab && selectedItems.isEmpty() && !showSearchBar),
onFabClick = {
navController.navigate(AddEditAbsentScreenDestination())
},
onClickScroll = {
scope.launch {
lazyListState.animateScrollToItem(0)
}
}
)
},
fabPosition = if (lazyListState.isScrolled) FabPosition.End else FabPosition.Center,
navActions = {
ScaffoldNavActions(
placeholderText = ABSENT_SEARCH_PLACEHOLDER,
selectionCount = selectedItems.size,
showSearchIcon = showFab,
showSearchBar = showSearchBar,
searchText = searchText,
onEditClick = {
navController.navigate(AddEditAbsentScreenDestination(selectedItems.first()))
},
onDeleteClick = {
dialogState.show()
},
onSelectAllClick = viewModel::selectAllItems,
onClearClick = viewModel::clearSearchText,
onSearchClick = viewModel::openSearchBar,
onSearchTextChanged = viewModel::searchTextChanged
)
},
onDeselect = viewModel::deselectItems
) {
Crossfade(
targetState = uiState,
label = "Absent State"
) { state ->
when (state) {
is UiState.Loading -> LoadingIndicator()
is UiState.Empty -> {
ItemNotAvailable(
text = if (searchText.isEmpty()) ABSENT_NOT_AVAILABLE else NO_ITEMS_IN_ABSENT,
buttonText = CREATE_NEW_ABSENT,
onClick = {
navController.navigate(AddEditAbsentScreenDestination())
}
)
}
is UiState.Success -> {
LazyColumn(
state = lazyListState,
modifier = Modifier
.fillMaxSize()
.padding(SpaceSmall),
) {
item(key = "employeeAbsents") {
val groupedEmployeeAbsent = remember(state.data) {
state.data.groupBy { it.employee }
}
groupedEmployeeAbsent.forEach { (employee, employeeAttendances) ->
employee?.let { emp ->
AbsentEmployees(
employee = employee,
groupedAttendances = employeeAttendances.groupBy {
toMonthAndYear(
it.absentDate
)
},
isExpanded = selectedEmployee == emp.employeeId,
doesSelected = { selectedItems.contains(it) },
onClick = {
if (selectedItems.isNotEmpty()){
viewModel.selectItem(it)
}
},
onLongClick = viewModel::selectItem,
onSelectEmployee = viewModel::selectEmployee,
onExpandChange = viewModel::selectEmployee,
onAbsentEntry = {
navController.navigate(
AddEditAbsentScreenDestination(employeeId = it)
)
},
)
}
}
}
}
}
}
}
}
MaterialDialog(
dialogState = dialogState,
buttons = {
positiveButton(
text = "Delete",
onClick = viewModel::deleteItems
)
negativeButton(
text = "Cancel",
onClick = {
dialogState.hide()
viewModel.deselectItems()
},
)
}
) {
title(text = DELETE_ABSENT_TITLE)
message(text = DELETE_ABSENT_MESSAGE)
}
} | 25 | Kotlin | 0 | 1 | 8067efcc5dc377f7161fee2f372c5be35e98e678 | 10,380 | POS-Application | MIT License |
app/src/main/java/org/mikyegresl/newsaggregator/feature/news_list/NewsListViewModel.kt | slvkim | 847,815,382 | false | {"Kotlin": 97955} | package org.mikyegresl.newsaggregator.feature.news_list
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import org.mikyegresl.domain.business.news.NewsRepository
import javax.inject.Inject
@HiltViewModel
internal class NewsListViewModel @Inject constructor(
private val repository: NewsRepository
) : ViewModel() {
private val _newsListState = MutableStateFlow(NewsListState.defaultState())
val newsListState: StateFlow<NewsListState> = _newsListState.asStateFlow()
init {
viewModelScope.launch {
repository.observeNews().distinctUntilChanged().collect {
val uiModel = it.map { it.toUiModel() }
_newsListState.update { it.copy(news = it.news + uiModel) }
}
}
}
fun fetchData() {
viewModelScope.launch {
try {
repository.fetchNews()
} catch (e: Exception) {
_newsListState.update { it.copy(errorMessage = e.message) }
}
}
}
} | 0 | Kotlin | 0 | 0 | 1b68417aff52ce40dc954610cb612b46e2b5f0e6 | 1,372 | news-api | Apache License 2.0 |
LifeCanvas/app/src/main/java/com/example/lifecanvas/screen/calendarEvent/EventEditScreen.kt | atakanozkan | 796,305,153 | false | {"Kotlin": 148766} | package com.example.lifecanvas.screen.calendarEvent
import android.content.Context
import android.widget.Toast
import androidx.compose.foundation.layout.Column
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.navigation.NavController
import com.example.lifecanvas.R
import com.example.lifecanvas.model.EventModel
import com.example.lifecanvas.screen.filter.DatePicker
import com.example.lifecanvas.screen.filter.isValidTitle
import com.example.lifecanvas.viewModel.EventViewModel
import java.util.Date
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EventEditScreen(eventId: Int, eventViewModel: EventViewModel, navController: NavController,context: Context) {
val event by eventViewModel.getEventById(eventId).observeAsState()
var title by remember { mutableStateOf(event?.title ?: "") }
var description by remember { mutableStateOf(event?.description ?: "") }
var startTime by remember { mutableStateOf(event?.startTime ?: Date()) }
var endTime by remember { mutableStateOf(event?.endTime ?: Date()) }
val isTitleValid = remember(title) { isValidTitle(title) }
Column {
TopAppBar(
title = { Text("Edit Event") },
navigationIcon = {
IconButton(onClick = { navController.popBackStack() }) {
Icon(Icons.Filled.ArrowBack, contentDescription = "Back")
}
},
actions = {
IconButton(onClick = {
if (isTitleValid && endTime.after(startTime)) {
val updatedEvent = event?.let {
EventModel(
id = eventId,
title = title,
description = description,
startTime = startTime,
endTime = endTime,
createdDate = it.createdDate,
modifiedDate = Date()
)
}
if (updatedEvent != null) {
eventViewModel.update(updatedEvent)
Toast.makeText(context, "Event is updated!", Toast.LENGTH_SHORT).show()
}
navController.popBackStack()
}
}) {
Icon(painterResource(R.drawable.save_icon), contentDescription = "Save")
}
IconButton(onClick = {
event?.let { eventViewModel.delete(it) }
Toast.makeText(context, "Event is deleted!", Toast.LENGTH_SHORT).show()
navController.popBackStack()
}) {
Icon(painterResource(R.drawable.delete_icon), contentDescription = "Delete")
}
}
)
Column {
OutlinedTextField(
value = title,
onValueChange = { title = it },
label = { Text("Title") },
isError = !isTitleValid
)
if (!isTitleValid) {
Text("Title must be at least 3 characters and start with a letter", color = Color.Red)
}
OutlinedTextField(
value = description,
onValueChange = { description = it },
label = { Text("Description") }
)
DatePicker(
label = "Start Time",
selectedDate = startTime,
icon = Icons.Default.DateRange,
onDateSelected = { newDate -> startTime = newDate ?: startTime }
)
DatePicker(
label = "End Time",
selectedDate = endTime,
icon = Icons.Default.DateRange,
onDateSelected = { newDate -> endTime = newDate ?: endTime }
)
}
}
}
| 0 | Kotlin | 0 | 0 | 47469657b2eaa511215a421f2231202313a045b3 | 4,721 | lifecanvas-app | MIT License |
shared/src/commonMain/kotlin/com/myapplication/pressentation/list/CharactersListViewModel.kt | mobidroid92 | 642,819,457 | false | {"Kotlin": 26750, "Swift": 580, "Shell": 228, "Ruby": 101} | package com.myapplication.pressentation.list
import androidx.lifecycle.ViewModel
import com.myapplication.model.dto.toCharacterUiModelList
import com.myapplication.model.dataSource.CharactersPaginator
import com.myapplication.model.repostries.CharactersRepository
import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
class CharactersListViewModel(
charactersRepository: CharactersRepository,
private val scope: CoroutineScope,
private val ioDispatcher: CoroutineDispatcher
) : ViewModel() {
private val _state = MutableStateFlow(CharactersListUiState())
val state = _state.asStateFlow()
private val charactersPaginator = CharactersPaginator(
charactersRepository = charactersRepository,
onLoadUpdated = { isLoading, isFullRefresh ->
_state.update {
it.copy(isLoading = isLoading, isFullRefresh = isFullRefresh)
}
},
onSuccess = { characterDto, isFullRefresh ->
_state.update {
it.copy(
charactersList = if (isFullRefresh) {
characterDto.results.toCharacterUiModelList()
} else {
it.charactersList.plus(
characterDto.results.toCharacterUiModelList()
)
},
isFullRefresh = isFullRefresh,
isShowError = false
)
}
},
onError = {
_state.update {
it.copy(isShowError = true)
}
}
)
init {
handleActions(Actions.ReloadCharacters)
}
fun handleActions(action: Actions) {
when (action) {
Actions.ReloadCharacters -> getCharacters(isFullRefresh = true)
Actions.LoadNextCharactersPage -> getCharacters(isFullRefresh = false)
}
}
private fun getCharacters(isFullRefresh: Boolean) {
scope.launch(ioDispatcher) {
charactersPaginator.loadNextItems(isFullRefresh)
}
}
}
sealed interface Actions {
data object ReloadCharacters : Actions
data object LoadNextCharactersPage : Actions
} | 0 | Kotlin | 0 | 1 | 3c234f078b79d00e244452f0c7b95f716f2c588f | 2,396 | Compose-Multiplatform-Demo | Apache License 2.0 |
mapboxpluginoffline/src/main/java/io/github/xit0c/mapboxpluginoffline/model/OfflineDownloadJob.kt | xit0c | 182,125,295 | false | null | package io.github.xit0c.mapboxpluginoffline.model
import android.app.Notification
import android.app.PendingIntent
import android.content.Context
import androidx.core.app.NotificationCompat
import com.mapbox.mapboxsdk.maps.Style
import com.mapbox.mapboxsdk.offline.OfflineRegion
import com.mapbox.mapboxsdk.snapshotter.MapSnapshotter
import io.github.xit0c.mapboxpluginoffline.OfflineService
import io.github.xit0c.mapboxpluginoffline.utils.NotificationUtils
/**
* This model is for internal usage only and represents a download "job" managed by the [OfflineService].
*
* It holds all the objects related to a single download: the `region` to download, the notification builders
* (`notificationDownload` and `notificationCancel`) for download and cancel operations and the `snapshotter`
* (if requested) that generates the bitmaps used as notifications' large icons.
*
* @param context Context used for notifications and snapshotter.
* @param options Options used to start the download.
* @property region The `OfflineRegion` to download.
* @constructor Creates a `OfflineDownloadJob` with the given values.
*/
internal class OfflineDownloadJob(
context: Context,
options: OfflineDownloadOptions,
val region: OfflineRegion
) {
private val notificationCancel: NotificationCompat.Builder =
NotificationUtils.baseNotificationBuilder(context, options.notificationOptions, region.id)
.setContentText(options.notificationOptions.cancelContentText)
.setProgress(100, 0, true)
private val notificationDownload: NotificationCompat.Builder =
NotificationUtils.baseNotificationBuilder(context, options.notificationOptions, region.id)
.setContentText(options.notificationOptions.downloadContentText)
.addAction(0, options.notificationOptions.cancelActionText, PendingIntent.getService(
context,
region.id.toInt(),
OfflineService.createIntent(context, OfflineService.ACTION_CANCEL, region.id),
NotificationUtils.withFlagImmutable(PendingIntent.FLAG_CANCEL_CURRENT)
))
private val snapshotter: MapSnapshotter? = if (!options.notificationOptions.requestMapSnapshot) null else
MapSnapshotter(context, MapSnapshotter.Options(
context.resources.getDimension(android.R.dimen.notification_large_icon_width).toInt(),
context.resources.getDimension(android.R.dimen.notification_large_icon_height).toInt()
).apply {
withStyleBuilder(Style.Builder().fromUri(options.definition.styleURL))
withRegion(options.definition.bounds)
}).apply {
start {
notificationCancel.setLargeIcon(it.bitmap)
notificationDownload.setLargeIcon(it.bitmap)
}
}
/**
* The `OfflineDownload` instance.
*/
val download = OfflineDownload(region.id, options)
/**
* Calls `MapSnapshotter.cancel()` method of the snapshotter instance.
*/
fun cancelSnapshotter() = snapshotter?.cancel()
/**
* Returns the `Notification` to show during cancellation.
* @return the `Notification` to show during cancellation.
*/
fun getNotificationCancel(): Notification =
notificationCancel.build()
/**
* Returns the `Notification` to show during download.
* @return the `Notification` to show during download.
*/
fun getNotificationDownload(): Notification =
notificationDownload.setProgress(100, download.getPercentage(), false).build()
} | 0 | null | 0 | 4 | 8239f3a0444e417c819b0521ca253d5c010e3efe | 3,584 | mapbox-plugin-offline | MIT License |
korge/common/src/main/kotlin/com/soywiz/korge/render/BitmapExt.kt | egorz-eng | 107,608,023 | true | {"Kotlin": 958944, "Java": 182756, "ActionScript": 7295, "HTML": 174} | package com.soywiz.korge.render
import com.soywiz.korim.bitmap.Bitmap32
import com.soywiz.korma.numeric.isPowerOfTwo
import com.soywiz.korma.numeric.nextPowerOfTwo
fun Bitmap32.ensurePowerOfTwo(): Bitmap32 {
if (this.width.isPowerOfTwo && this.height.isPowerOfTwo) {
return this
} else {
val out = Bitmap32(this.width.nextPowerOfTwo, this.height.nextPowerOfTwo)
out.put(this)
return out
}
}
| 0 | Kotlin | 0 | 0 | cee8132dd63f168cdcc186c5510afd6985a53b3f | 404 | korge | Apache License 2.0 |
rest/src/main/kotlin/org/jetbrains/intellij/pluginRepository/internal/api/PluginRepositoryService.kt | JetBrains | 33,556,602 | false | null | package org.jetbrains.intellij.pluginRepository.internal.api
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.ResponseBody
import org.jetbrains.intellij.pluginRepository.internal.utils.CompatibleUpdateRequest
import org.jetbrains.intellij.pluginRepository.model.*
import retrofit2.Call
import retrofit2.http.*
interface PluginRepositoryService {
@Multipart
@POST("/plugin/uploadPlugin")
@Headers("Accept: text/plain")
@Deprecated("Use JSON API")
fun upload(
@Part("pluginId") pluginId: Int,
@Part("channel") channel: RequestBody?,
@Part("notes") notes: RequestBody?,
@Part file: MultipartBody.Part
): Call<ResponseBody>
@Multipart
@Headers("Accept: text/plain")
@POST("/plugin/uploadPlugin")
@Deprecated("Use JSON API")
fun uploadByXmlId(
@Part("xmlId") pluginXmlId: RequestBody,
@Part("channel") channel: RequestBody?,
@Part("notes") notes: RequestBody?,
@Part file: MultipartBody.Part
): Call<ResponseBody>
@Multipart
@POST("/api/updates/upload")
fun uploadById(
@Part("pluginId") pluginId: Int,
@Part("channel") channel: RequestBody?,
@Part("notes") notes: RequestBody?,
@Part file: MultipartBody.Part
): Call<PluginUpdateBean>
@Multipart
@POST("/api/updates/upload")
fun uploadByStringId(
@Part("xmlId") pluginXmlId: RequestBody,
@Part("channel") channel: RequestBody?,
@Part("notes") notes: RequestBody?,
@Part file: MultipartBody.Part
): Call<PluginUpdateBean>
@Multipart
@POST("/api/plugins/{family}/upload")
fun uploadNewPlugin(
@Part file: MultipartBody.Part,
@Path("family") family: String,
@Part("licenseUrl") licenseUrl: RequestBody,
@Part("cid") category: Int
): Call<PluginBean>
@Multipart
@POST("/api/plugins/{family}/upload")
fun uploadNewPlugin(
@Part file: MultipartBody.Part,
@Path("family") family: String,
@Part("licenseUrl") licenseUrl: RequestBody,
@Part("tags") tags: ArrayList<RequestBody>
): Call<PluginBean>
@Streaming
@GET("/plugin/download")
fun download(
@Query("pluginId") pluginId: String,
@Query("version") version: String,
@Query("channel") channel: String?
): Call<ResponseBody>
@Streaming
@GET("/plugin/download")
fun download(@Query("updateId") updateId: Int): Call<ResponseBody>
@Streaming
@GET("/pluginManager?action=download")
fun downloadCompatiblePlugin(
@Query("id") pluginId: String,
@Query("build") ideBuild: String,
@Query("channel") channel: String?
): Call<ResponseBody>
@GET("/plugins/list/")
fun listPlugins(
@Query("build") ideBuild: String,
@Query("channel") channel: String?,
@Query("pluginId") pluginId: String?
): Call<XmlPluginRepositoryBean>
@GET("/api/plugins/{family}/{pluginXmlId}")
fun getPluginByXmlId(@Path("family") family: String, @Path("pluginXmlId") pluginXmlId: String): Call<PluginBean>
@GET("/api/plugins/{id}")
fun getPluginById(@Path("id") id: Int): Call<PluginBean>
@GET("/api/plugins/{id}/developers")
fun getPluginDevelopers(@Path("id") id: Int): Call<List<PluginUserBean>>
@GET("/api/plugins/{id}/channels")
fun getPluginChannels(@Path("id") id: Int): Call<List<String>>
@GET("/api/plugins/{id}/compatible-products")
fun getPluginCompatibleProducts(@Path("id") id: Int): Call<List<ProductEnum>>
@GET("/api/plugins")
fun getPluginXmlIdByDependency(
@Query("dependency") dependency: String,
@Query("includeOptional") includeOptional: Boolean
): Call<List<String>>
@GET("/api/search")
fun searchPluginsXmlIds(
@Query("build") build: String,
@Query("max") max: Int,
@Query("offset") offset: Int,
@Query("search") query: String
): Call<List<String>>
@GET("/api/search/updates")
fun searchUpdates(
@Query("build") build: String,
@Query("pluginXMLId") stringPluginId: StringPluginId
): Call<List<UpdateBean>>
@GET("/files/pluginsXMLIds.json")
fun getPluginsXmlIds(): Call<List<String>>
@POST("/api/search/compatibleUpdates")
@Headers("Content-Type: application/json")
fun searchLastCompatibleUpdate(@Body body: CompatibleUpdateRequest): Call<List<UpdateBean>>
@GET("/api/plugins/{id}/updates")
fun getUpdatesByVersionAndFamily(
@Path("id") xmlId: String,
@Query("version") version: String,
@Query("family") family: String
): Call<List<PluginUpdateBean>>
@GET("/api/updates/{id}")
fun getUpdateById(@Path("id") id: Int): Call<PluginUpdateBean>
@GET("/api/plugins/{id}/updateVersions")
fun getPluginVersions(@Path("id") id: Int): Call<List<PluginUpdateVersion>>
@GET("/files/{pluginId}/{updateId}/meta.json")
fun getIntelliJUpdateMeta(
@Path("pluginId") pluginId: Int,
@Path("updateId") updateId: Int
): Call<IntellijUpdateMetadata>
}
| 7 | null | 15 | 21 | 3220975f5dd69fc8f186128cddf185e06248c596 | 4,786 | plugin-repository-rest-client | Apache License 2.0 |
src/main/kotlin/guildwars2/api/misc/build/BuildExtension.kt | nusphere | 436,877,433 | false | null | package guildwars2.api.misc.build
import kotlinx.coroutines.runBlocking
import okhttp3.Headers
import retrofit2.Response
import retrofit2.Retrofit
interface BuildExtension {
val retrofit: Retrofit
private val api: BuildApi get() = retrofit.create(BuildApi::class.java)
fun getBuild(): Build? = runBlocking { getAccountResponse()?.body() }
fun getBuildHeaders(): Headers? = runBlocking { getAccountResponse()?.headers() }
suspend fun getAccountResponse(): Response<Build>? = api.getBuildAsync()
} | 0 | Kotlin | 1 | 1 | 59e9c70fae2717502ffcf2e762d408c76f944bb9 | 520 | kotlin-gw2-api | MIT License |
projects/soc-and-delius/src/dev/kotlin/uk/gov/justice/digital/hmpps/data/DataLoader.kt | ministryofjustice | 500,855,647 | false | {"Kotlin": 3955601, "HTML": 68645, "D2": 30565, "Ruby": 25392, "Shell": 15576, "SCSS": 6240, "HCL": 2712, "Dockerfile": 2414, "JavaScript": 1344, "Python": 268} | package uk.gov.justice.digital.hmpps.data
import jakarta.annotation.PostConstruct
import jakarta.persistence.EntityManager
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.boot.context.event.ApplicationReadyEvent
import org.springframework.context.ApplicationListener
import org.springframework.stereotype.Component
import org.springframework.transaction.annotation.Transactional
import uk.gov.justice.digital.hmpps.data.generator.*
import uk.gov.justice.digital.hmpps.user.AuditUserRepository
@Component
@ConditionalOnProperty("seed.database")
class DataLoader(
private val auditUserRepository: AuditUserRepository,
private val em: EntityManager
) : ApplicationListener<ApplicationReadyEvent> {
@PostConstruct
fun saveAuditUser() {
auditUserRepository.save(UserGenerator.AUDIT_USER)
}
@Transactional
override fun onApplicationEvent(are: ApplicationReadyEvent) {
em.saveAll(
ProbationAreaGenerator.DEFAULT_PA,
ProbationAreaGenerator.DEFAULT_BOROUGH,
ProbationAreaGenerator.DEFAULT_LDU,
ProbationAreaGenerator.DEFAULT_LDU2,
ProbationAreaGenerator.NON_SELECTABLE_PA,
ProbationAreaGenerator.NON_SELECTABLE_BOROUGH,
ProbationAreaGenerator.NON_SELECTABLE_LDU,
CourtAppearanceGenerator.DEFAULT_OUTCOME,
CourtAppearanceGenerator.DEFAULT_CA_TYPE,
CourtAppearanceGenerator.DEFAULT_COURT,
CourtAppearanceGenerator.DEFAULT_PERSON,
CourtAppearanceGenerator.DEFAULT_EVENT,
CourtAppearanceGenerator.DEFAULT_CA,
ConvictionEventGenerator.PERSON,
ConvictionEventGenerator.ADDITIONAL_OFFENCE_TYPE,
ConvictionEventGenerator.OFFENCE_MAIN_TYPE,
ConvictionEventGenerator.DEFAULT_EVENT,
ConvictionEventGenerator.INACTIVE_EVENT,
ConvictionEventGenerator.MAIN_OFFENCE,
ConvictionEventGenerator.OTHER_OFFENCE,
ConvictionEventGenerator.DISPOSAL_TYPE,
ConvictionEventGenerator.DISPOSAL,
ConvictionEventGenerator.COURT_APPEARANCE,
DetailsGenerator.INSTITUTION,
DetailsGenerator.RELIGION,
DetailsGenerator.NATIONALITY,
DetailsGenerator.MALE,
DetailsGenerator.FEMALE,
DetailsGenerator.PERSON,
DetailsGenerator.ALIAS_1,
DetailsGenerator.ALIAS_2,
DetailsGenerator.DEFAULT_PA,
DetailsGenerator.DISTRICT,
DetailsGenerator.TEAM,
DetailsGenerator.STAFF,
DetailsGenerator.PERSON_MANAGER,
DetailsGenerator.RELEASE_TYPE,
DetailsGenerator.RELEASE,
DetailsGenerator.RECALL_REASON,
DetailsGenerator.RECALL,
NSIGenerator.BREACH_TYPE,
NSIGenerator.RECALL_TYPE,
NSIGenerator.BREACH_NSI,
NSIGenerator.RECALL_NSI,
ConvictionEventGenerator.PERSON_2,
ConvictionEventGenerator.EVENT_2,
ConvictionEventGenerator.MAIN_OFFENCE_2,
ConvictionEventGenerator.OTHER_OFFENCE_2,
ConvictionEventGenerator.DISPOSAL_2,
KeyDateGenerator.CUSTODY_STATUS,
KeyDateGenerator.SED_KEYDATE,
KeyDateGenerator.CUSTODY,
KeyDateGenerator.KEYDATE,
KeyDateGenerator.CUSTODY_1,
KeyDateGenerator.KEYDATE_1
)
em.createNativeQuery(
"""
update event set offender_id = ${DetailsGenerator.PERSON.id}
where event_id = ${ConvictionEventGenerator.EVENT_2.id}
""".trimMargin()
)
.executeUpdate()
}
fun EntityManager.saveAll(vararg any: Any) = any.forEach { persist(it) }
}
| 9 | Kotlin | 0 | 2 | ed7a7e2d4580b68ed77264e93f9961ca87448b40 | 3,844 | hmpps-probation-integration-services | MIT License |
app/src/main/java/com/example/mywiki/data/model/DescriptionData.kt | uditbhaskar | 368,022,314 | false | null | package com.example.mywiki.data.model
import com.google.gson.annotations.Expose
import com.google.gson.annotations.SerializedName
data class DescriptionData(
@Expose
@SerializedName("description")
val description: List<String>?
)
| 0 | Kotlin | 6 | 8 | 952fe8a9493d5821cb3a2584f0a3ae21dfb9cec0 | 244 | MyWiki | MIT License |
app/src/main/java/com/mikelau/notes/util/LoggingInterceptor.kt | mike14u | 712,886,790 | false | null | package com.mikelau.notes.util
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.internal.http2.Http2Reader.Companion.logger
import java.io.IOException
class LoggingInterceptor : Interceptor {
@Throws(IOException::class)
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val t1 = System.nanoTime()
logger.info(
String.format(
"Sending request %s on %s%n%s",
request.url, chain.connection(), request.headers
)
)
val response = chain.proceed(request)
val t2 = System.nanoTime()
logger.info(
String.format(
"Received response for %s in %.1fms%n%s",
response.request.url, (t2 - t1) / 1e6, response.headers
)
)
return response
}
} | 0 | Kotlin | 0 | 0 | 36e90224db9288a34afb628939540af119927230 | 884 | exoplayer_streaming | MIT License |
app/src/main/java/com/alharoof/diabetracker/data/logbook/model/DateTimeRange.kt | arslanshoukat | 202,784,451 | false | null | package com.alharoof.diabetracker.data.logbook.model
import org.threeten.bp.OffsetDateTime
/**
* Created by <NAME> on Sep 28, 2019 12:24 AM.
*/
class DateTimeRange(val startDateTime: OffsetDateTime, val endDateTime: OffsetDateTime) | 1 | Kotlin | 11 | 22 | 2569689ac7213002108c8fc804696375d5d69542 | 236 | DiabeTracker | Apache License 2.0 |
src/main/kotlin/khome/extending/entities/actuators/light/RGBLight.kt | dennisschroeder | 183,795,935 | false | null | package khome.extending.entities.actuators.light
import khome.KhomeApplication
import khome.communicating.DefaultResolvedServiceCommand
import khome.communicating.DesiredServiceData
import khome.communicating.EntityIdOnlyServiceData
import khome.communicating.ServiceCommandResolver
import khome.entities.State
import khome.entities.devices.Actuator
import khome.extending.entities.SwitchableValue
import khome.extending.entities.actuators.onStateValueChangedFrom
import khome.observability.Switchable
import khome.values.Brightness
import khome.values.ColorName
import khome.values.HSColor
import khome.values.ObjectId
import khome.values.RGBColor
import khome.values.XYColor
import khome.values.service
typealias RGBLight = Actuator<RGBLightState, LightAttributes>
@Suppress("FunctionName")
fun KhomeApplication.RGBLight(objectId: ObjectId): RGBLight =
Light(
objectId,
ServiceCommandResolver { desiredState ->
when (desiredState.value) {
SwitchableValue.OFF -> {
DefaultResolvedServiceCommand(
service = "turn_off".service,
serviceData = EntityIdOnlyServiceData()
)
}
SwitchableValue.ON -> {
desiredState.hsColor?.let {
DefaultResolvedServiceCommand(
service = "turn_on".service,
serviceData = RGBLightServiceData(
hsColor = it
)
)
} ?: desiredState.rgbColor?.let {
DefaultResolvedServiceCommand(
service = "turn_on".service,
serviceData = RGBLightServiceData(
rgbColor = it
)
)
} ?: desiredState.brightness?.let {
DefaultResolvedServiceCommand(
service = "turn_on".service,
serviceData = RGBLightServiceData(
brightness = it
)
)
} ?: desiredState.xyColor?.let {
DefaultResolvedServiceCommand(
service = "turn_on".service,
serviceData = RGBLightServiceData(
xyColor = it
)
)
} ?: DefaultResolvedServiceCommand(
service = "turn_on".service,
serviceData = EntityIdOnlyServiceData()
)
}
SwitchableValue.UNAVAILABLE -> throw IllegalStateException("State cannot be changed to UNAVAILABLE")
}
}
)
data class RGBLightServiceData(
private val brightness: Brightness? = null,
private val hsColor: HSColor? = null,
private val rgbColor: RGBColor? = null,
private val xyColor: XYColor? = null
) : DesiredServiceData()
data class RGBLightState(
override val value: SwitchableValue,
val brightness: Brightness? = null,
val hsColor: HSColor? = null,
val rgbColor: RGBColor? = null,
val xyColor: XYColor? = null
) : State<SwitchableValue>
val RGBLight.isOn
get() = actualState.value == SwitchableValue.ON
val RGBLight.isOff
get() = actualState.value == SwitchableValue.OFF
fun RGBLight.turnOn() {
desiredState = RGBLightState(SwitchableValue.ON)
}
fun RGBLight.turnOff() {
desiredState = RGBLightState(SwitchableValue.OFF)
}
fun RGBLight.setBrightness(level: Brightness) {
desiredState = RGBLightState(SwitchableValue.ON, level)
}
fun RGBLight.setRGB(red: Int, green: Int, blue: Int) {
desiredState = RGBLightState(SwitchableValue.ON, rgbColor = RGBColor.from(red, green, blue))
}
fun RGBLight.setHS(hue: Double, saturation: Double) {
desiredState = RGBLightState(SwitchableValue.ON, hsColor = HSColor.from(hue, saturation))
}
fun RGBLight.setXY(x: Double, y: Double) {
desiredState = RGBLightState(SwitchableValue.ON, xyColor = XYColor.from(x, y))
}
fun RGBLight.setColor(name: ColorName) =
callService("turn_on".service, NamedColorServiceData(name))
fun RGBLight.onTurnedOn(f: RGBLight.(Switchable) -> Unit) =
onStateValueChangedFrom(SwitchableValue.OFF to SwitchableValue.ON, f)
fun RGBLight.onTurnedOff(f: RGBLight.(Switchable) -> Unit) =
onStateValueChangedFrom(SwitchableValue.ON to SwitchableValue.OFF, f)
| 21 | Kotlin | 6 | 99 | d9da9436978c8e9600394e1819a33d49b5f0e2ea | 4,647 | khome | MIT License |
collector/src/main/java/com/bitmovin/analytics/data/EventDataFactory.kt | bitmovin | 120,633,749 | false | null | package com.bitmovin.analytics.data
import com.bitmovin.analytics.api.AnalyticsConfig
import com.bitmovin.analytics.api.DefaultMetadata
import com.bitmovin.analytics.api.SourceMetadata
import com.bitmovin.analytics.data.manipulators.EventDataManipulator
import com.bitmovin.analytics.data.manipulators.EventDataManipulatorPipeline
import com.bitmovin.analytics.license.InstantLicenseKeyProvider
import com.bitmovin.analytics.license.LicenseKeyProvider
import com.bitmovin.analytics.license.licenseKeyOrNull
import com.bitmovin.analytics.ssai.SsaiService
import com.bitmovin.analytics.utils.ApiV3Utils
import com.bitmovin.analytics.utils.UserAgentProvider
class EventDataFactory(
private val config: AnalyticsConfig,
private val userIdProvider: UserIdProvider,
private val userAgentProvider: UserAgentProvider,
private val licenseKeyProvider: LicenseKeyProvider = InstantLicenseKeyProvider(config.licenseKey),
private val ssaiService: SsaiService,
) : EventDataManipulatorPipeline {
private val eventDataManipulators = mutableListOf<EventDataManipulator>()
fun create(
impressionId: String,
sourceMetadata: SourceMetadata,
defaultMetadata: DefaultMetadata,
deviceInformation: DeviceInformation,
playerInfo: PlayerInfo,
): EventData {
var mergedCustomData = ApiV3Utils.mergeCustomData(sourceMetadata.customData, defaultMetadata.customData)
mergedCustomData = ApiV3Utils.mergeCustomData(ssaiService.adMetadata?.customData, mergedCustomData)
val mergedCdnProvider = sourceMetadata.cdnProvider ?: defaultMetadata.cdnProvider
val eventData =
EventData(
deviceInformation,
playerInfo,
mergedCustomData,
impressionId,
userIdProvider.userId(),
licenseKeyProvider.licenseKeyOrNull,
sourceMetadata.videoId,
sourceMetadata.title,
defaultMetadata.customUserId,
sourceMetadata.path,
mergedCdnProvider,
userAgentProvider.userAgent,
)
for (decorator in eventDataManipulators) {
decorator.manipulate(eventData)
}
return eventData
}
override fun clearEventDataManipulators() {
eventDataManipulators.clear()
}
override fun registerEventDataManipulator(manipulator: EventDataManipulator) {
eventDataManipulators.add(manipulator)
}
}
| 1 | null | 6 | 9 | c7c1b9a7016534c0e07620d3d7e863ca99575c86 | 2,513 | bitmovin-analytics-collector-android | Amazon Digital Services License |
app/src/main/java/com/zaki/mvvm_base/di/modules/StorageModule.kt | iammohdzaki | 245,803,859 | false | null | package com.zaki.mvvm_base.di.modules
import com.zaki.mvvm_base.local.SharedPreferencesStorage
import com.zaki.mvvm_base.local.Storage
import org.koin.dsl.module
val storageModule = module {
single { SharedPreferencesStorage(get()) as Storage }
} | 0 | Kotlin | 0 | 0 | 67ffc7f5f785ae98f2396c3d98576174c84b2c22 | 252 | MVVM-Base | MIT License |
lib_base/src/main/java/com/coolone/lib_base/data/callback/databind/StringObservableField.kt | freesonwill | 675,241,719 | false | {"Kotlin": 50592, "Java": 5729} | package com.coolone.lib_base.data.callback.databind
import androidx.databinding.ObservableField
/**
* 作者 : zb
*
* 描述 :自定义的String类型 ObservableField 提供了默认值,避免取值的时候还要判空
*/
open class StringObservableField(value: String = "") : ObservableField<String>(value) {
override fun get(): String {
return super.get()!!
}
} | 0 | Kotlin | 0 | 0 | cbd80f17b5efbcdce1851cc6d09909d3f5f11ed6 | 336 | EasyMvvm | Apache License 2.0 |
data/src/main/java/com/pthw/data/model/Language.kt | PhyoThihaWin | 551,899,842 | false | {"Kotlin": 328147, "Java": 3279} | package com.pthw.data.model
enum class Language(val languageCode: String) {
MYANMAR_UNICODE("mm"),
ENGLISH("en");
companion object {
private const val LANGUAGE_CODE_UNICODE = "mm"
private const val LANGUAGE_CODE_ENGLISH = "en"
fun getLanguageFromCode(code: String): Language {
return when (code) {
LANGUAGE_CODE_UNICODE -> MYANMAR_UNICODE
LANGUAGE_CODE_ENGLISH -> ENGLISH
else -> throw IllegalArgumentException()
}
}
}
} | 1 | Kotlin | 1 | 4 | f64626fb6e101659693ac76d8d9ca5489ac9e821 | 541 | MyPagingThree | Apache License 2.0 |
src/com/blogspot/jesfre/kotlin/controlflow/ifexpression/Triangle.kt | jesfre | 175,801,113 | false | null | package com.blogspot.jesfre.controlflow.ifexpression
import java.util.*
/*
Given three natural numbers A, B, C. Define if the triangle with such sides exists.
If the triangle exists - output the YES string, otherwise - output NO.
Note, a triangle is formed by three connected points that are not located on a single straight line.
Sample Input 1:
3
4
5
Sample Output 1:
YES
* */
fun main(args:Array<String>) {
val scanner = Scanner(System.`in`)
val a = scanner.nextDouble()
val b = scanner.nextDouble()
val c = scanner.nextDouble()
if(a < 1.0 || b < 1.0 || c < 1.0) println("NO")
else if(a + b > c && a + c > b && b + c > a) println("YES")
else println("NO")
} | 0 | Kotlin | 0 | 1 | 6b6d9ec830c45c76efdfc9081d62e3854b25f2d9 | 694 | Hyperskill-Kotlin-Solutions | The Unlicense |
src/main/kotlin/com/mercadolivro/config/SecurityConfig.kt | AlexWilliam | 471,513,092 | false | null | package com.mercadolivro.config
import com.mercadolivro.enums.Roles
import com.mercadolivro.repository.CustomerRepository
import com.mercadolivro.security.*
import com.mercadolivro.service.UserDetailsCustomService
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.http.HttpMethod
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.builders.WebSecurity
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
import org.springframework.security.config.http.SessionCreationPolicy
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder
import org.springframework.web.cors.CorsConfiguration
import org.springframework.web.cors.UrlBasedCorsConfigurationSource
import org.springframework.web.filter.CorsFilter
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
class SecurityConfig(
private val customerRepository: CustomerRepository,
private val userDetails: UserDetailsCustomService,
private val jwtUtil: JWTUtil,
private val customEntryPoint: CustomAuthenticationEntryPoint
): WebSecurityConfigurerAdapter() {
private val publicPostMatchers = arrayOf(
"/customers"
)
private val publicGetMatchers = arrayOf(
"/books"
)
private val adminMatchers = arrayOf(
"/admin/**"
)
override fun configure(auth: AuthenticationManagerBuilder) {
auth.userDetailsService(userDetails).passwordEncoder(bCryptPasswordEncoder())
}
override fun configure(http: HttpSecurity) {
http.cors().and().csrf().disable()
http.authorizeHttpRequests()
.antMatchers(HttpMethod.POST, *publicPostMatchers).permitAll()
.antMatchers(HttpMethod.GET, *publicGetMatchers).permitAll()
.antMatchers(*adminMatchers).hasAuthority(Roles.ADMIN.description)
.anyRequest().authenticated()
http.addFilter(AuthenticationFilter(authenticationManager(), customerRepository, jwtUtil))
http.addFilter(AuthorizationFilter(authenticationManager(), userDetails, jwtUtil))
http.exceptionHandling().authenticationEntryPoint(customEntryPoint)
http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
}
override fun configure(web: WebSecurity) {
web.ignoring().antMatchers(
"/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/configuration/**",
"/swagger-ui/**",
"/webjars/**"
)
}
@Bean
fun corsConfig(): CorsFilter{
val source = UrlBasedCorsConfigurationSource()
val config = CorsConfiguration()
config.allowCredentials = true
config.addAllowedOriginPattern("*")
config.addAllowedHeader("*")
config.addAllowedMethod("*")
source.registerCorsConfiguration("/**", config)
return CorsFilter(source)
}
@Bean
fun bCryptPasswordEncoder(): BCryptPasswordEncoder{
return BCryptPasswordEncoder()
}
} | 0 | Kotlin | 0 | 0 | 436450531ce6b6edbf7d730af9dc05d0a96c037c | 3,520 | MercadoLivro | MIT License |
src/main/kotlin/com/bawer/tasks/revolut/ewallet/service/impl/AccountServiceImpl.kt | febael | 185,681,437 | false | {"Kotlin": 67008} | package com.bawer.tasks.revolut.ewallet.service.impl
import com.bawer.tasks.revolut.ewallet.model.Account
import com.bawer.tasks.revolut.ewallet.repository.AccountRepository
import com.bawer.tasks.revolut.ewallet.model.request.AccountRequest
import com.bawer.tasks.revolut.ewallet.model.request.TransferDirection
import com.bawer.tasks.revolut.ewallet.service.AccountService
import java.util.concurrent.atomic.AtomicInteger
import javax.inject.Inject
class AccountServiceImpl @Inject constructor(private val repository: AccountRepository) : AccountService {
private val idGenerator = AtomicInteger(0)
private val nextId get() = idGenerator.incrementAndGet()
override fun getAll() = repository.getAll()
override fun create(request: AccountRequest) = Account.from(request, nextId).apply { repository.insert(this) }
/**
* TODO : nullify transfers, they should be requested with [getTransfers]
*/
override fun get(id: Int) = repository.get(id)
override fun getTransfers(id: Int, direction: TransferDirection, limit: Int, after: Int) = TODO("not implemented")
} | 0 | Kotlin | 0 | 0 | 96cdf95831839a7e32d61f81c3c5030aaf4ff81f | 1,103 | ewallet-2 | Apache License 2.0 |
src/main/kotlin/org/crystal/intellij/lang/ast/CstLiteralExpanderBase.kt | asedunov | 353,165,557 | false | {"Kotlin": 1661507, "Java": 554445, "Crystal": 245131, "Lex": 192822, "HTML": 445} | package org.crystal.intellij.lang.ast
import it.unimi.dsi.fastutil.ints.Int2ObjectMap
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap
import org.crystal.intellij.lang.ast.nodes.*
import org.crystal.intellij.lang.resolve.CrResolveFacade
abstract class CstLiteralExpanderBase(protected val resolveFacade: CrResolveFacade) : CstTransformer() {
protected val resolveCache
get() = resolveFacade.resolveCache
protected fun complexElementsTempVars(
elements: List<CstNode<*>>
): Int2ObjectMap<CstVar> = complexElementsTempVars(elements) { it }
protected fun <T> complexElementsTempVars(
elements: List<T>,
node: (T) -> CstNode<*>
): Int2ObjectMap<CstVar> {
val tempVars = Int2ObjectOpenHashMap<CstVar>()
for((i, e) in elements.withIndex()) {
var elem = node(e)
if (elem is CstSplat) elem = elem.expression
if (elem is CstVar || elem is CstInstanceVar || elem is CstClassVar || elem is CstSimpleLiteral) continue
tempVars.put(i, resolveCache.newTempVar(elem.location))
}
return tempVars
}
protected fun typeOfExp(node: CstArrayLiteral, tempVars: Int2ObjectMap<CstVar>): CstTypeOf {
val loc = node.location
val typeExps = node.elements.mapIndexed { i: Int, elem: CstNode<*> ->
val tempVar = tempVars[i]
if (elem is CstSplat) {
CstCall(
obj = CstPath.global("Enumerable", loc),
name = "element_type",
arg = tempVar ?: elem.expression,
location = loc
)
}
else {
tempVar ?: elem
}
}
return CstTypeOf(typeExps, loc)
}
} | 11 | Kotlin | 4 | 33 | 2e255da6c56a33109b8c58a0aa1a692abf977da2 | 1,783 | intellij-crystal-lang | Apache License 2.0 |
base/build-system/aaptcompiler/src/main/java/com/android/aaptcompiler/ResourceCompiler.kt | qiangxu1996 | 301,210,525 | false | {"Gradle Kotlin DSL": 2, "Shell": 29, "Markdown": 39, "Batchfile": 10, "Text": 287, "Ignore List": 47, "Java": 4790, "INI": 19, "XML": 1725, "Gradle": 543, "Starlark": 149, "JAR Manifest": 3, "Kotlin": 1462, "Ant Build System": 3, "HTML": 6, "Makefile": 12, "XSLT": 6, "CSS": 10, "Git Attributes": 2, "Protocol Buffer": 35, "Java Properties": 43, "C++": 479, "RenderScript": 32, "C": 32, "Proguard": 29, "JavaScript": 2, "Checksums": 8, "Filterscript": 11, "Prolog": 1, "CMake": 3, "GLSL": 2, "AIDL": 6, "JSON": 53, "PureBasic": 1, "SVG": 201, "YAML": 4, "Python": 9, "Dockerfile": 2, "Emacs Lisp": 1, "FreeMarker": 173, "Fluent": 314} |
package com.android.aaptcompiler
import java.util.logging.Logger
class ResourceCompiler(
val compilationPackage: String,
val logger: Logger? = null) | 1 | null | 1 | 1 | 3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4 | 155 | vmtrace | Apache License 2.0 |
backend/src/main/kotlin/de/debuglevel/walkingdinner/backend/location/locator/Geolocator.kt | debuglevel | 133,810,544 | false | null | package de.debuglevel.walkingdinner.backend.location.locator
import de.debuglevel.walkingdinner.backend.location.Location
interface Geolocator {
fun getLocation(address: String?, city: String): Location
}
| 36 | Kotlin | 0 | 0 | 2ddc1054723e79282320eb5aa950dcfe50f407ef | 211 | walkingdinner-geneticplanner | The Unlicense |
src/main/kotlin/com/anahoret/home_server/config/SecurityConfig.kt | mikhalchenko-alexander | 93,540,975 | false | null | package com.anahoret.home_server.config
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.annotation.Configuration
import org.springframework.security.config.annotation.web.builders.HttpSecurity
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter
@Configuration
@EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {
override fun configure(http: HttpSecurity) {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.permitAll()
}
@Autowired
fun configureGlobal(auth: AuthenticationManagerBuilder) {
auth
.inMemoryAuthentication()
.withUser("norby").password("<PASSWORD>").roles("USER")
}
}
| 0 | Kotlin | 0 | 0 | 7d39e7db434808a0de1ff462ba1cb9fc4d08baf3 | 1,094 | home-server | Apache License 2.0 |
frontend/app/src/main/java/com/tec/frontend/util/ImageUploader.kt | pedroalonsoms | 701,575,731 | false | {"Kotlin": 300410, "TypeScript": 18271} | package com.tec.frontend.util
import android.content.Context
import android.net.Uri
import android.widget.Toast
import com.google.firebase.ktx.Firebase
import com.google.firebase.storage.StorageReference
import com.google.firebase.storage.ktx.storage
class ImageUploader{
companion object {
fun uploadToStorage(uri: Uri, context: Context, userFolder: String, category: String, imageTitle: String ) {
val storage = Firebase.storage
// Create a storage reference from our app
var storageRef = storage.reference
var spaceRef: StorageReference
spaceRef = storageRef.child("$userFolder/$category/$imageTitle.jpg")
val byteArray: ByteArray? = context.contentResolver
.openInputStream(uri)
?.use { it.readBytes() }
byteArray?.let{
var uploadTask = spaceRef.putBytes(byteArray)
uploadTask.addOnFailureListener {
Toast.makeText(
context,
"upload failed",
Toast.LENGTH_SHORT
).show()
// Handle unsuccessful uploads
}.addOnSuccessListener { taskSnapshot ->
// taskSnapshot.metadata contains file metadata such as size, content-type, etc.
// ...
Toast.makeText(
context,
"upload successed",
Toast.LENGTH_SHORT
).show()
}
}
}
}
} | 1 | Kotlin | 4 | 0 | 663ed05f18d349d5f94373d5e771730f7adc3697 | 1,625 | mypictograms | MIT License |
src/main/kotlin/icu/windea/pls/localisation/references/ParadoxLocalisationCommandFieldPsiReference.kt | DragonKnightOfBreeze | 328,104,626 | false | null | package icu.windea.pls.localisation.references
import com.intellij.openapi.editor.colors.*
import com.intellij.openapi.util.*
import com.intellij.psi.*
import icu.windea.pls.*
import icu.windea.pls.config.cwt.*
import icu.windea.pls.core.collections.*
import icu.windea.pls.core.psi.*
import icu.windea.pls.core.search.*
import icu.windea.pls.core.selector.*
import icu.windea.pls.core.selector.chained.*
import icu.windea.pls.localisation.psi.*
import icu.windea.pls.script.highlighter.*
/**
* @see icu.windea.pls.localisation.codeInsight.completion.ParadoxLocalisationCommandFieldCompletionProvider
*/
class ParadoxLocalisationCommandFieldPsiReference(
element: ParadoxLocalisationCommandField,
rangeInElement: TextRange
) : PsiPolyVariantReferenceBase<ParadoxLocalisationCommandField>(element, rangeInElement), PsiNodeReference {
override fun handleElementRename(newElementName: String): PsiElement {
//重命名当前元素
return element.setName(newElementName)
}
override fun resolve(): PsiElement? {
return resolve(true)
}
override fun resolve(exact: Boolean): PsiElement? {
val name = element.name
val project = element.project
val gameType = selectGameType(element) ?: return null
val configGroup = getCwtConfig(project).getValue(gameType)
//尝试识别为预定义的localisation_command
val localisationCommand = CwtConfigHandler.resolveLocalisationCommand(name, configGroup)
if(localisationCommand != null) return localisationCommand
//尝试识别为<scripted_loc>
val selector = definitionSelector().gameType(gameType).preferRootFrom(element, exact)
val scriptedLoc = ParadoxDefinitionSearch.search(name, "scripted_loc", project, selector = selector).find(exact)
if(scriptedLoc != null) return scriptedLoc
//尝试识别为value[variable]
val variableSelector = valueSetValueSelector().gameType(gameType).preferRootFrom(element, exact)
val variable = ParadoxValueSetValueSearch.search(name, "variable", project, selector = variableSelector).findFirst()
if(variable != null) return ParadoxValueSetValueElement(element, name, "variable", project, gameType)
return null
}
override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
val name = element.name
val project = element.project
val gameType = selectGameType(element) ?: return ResolveResult.EMPTY_ARRAY
val configGroup = getCwtConfig(project).getValue(gameType)
//尝试识别为预定义的localisation_command
val localisationCommand = CwtConfigHandler.resolveLocalisationCommand(name, configGroup)
if(localisationCommand != null) return localisationCommand.let { arrayOf(PsiElementResolveResult(it)) }
//尝试识别为<scripted_loc>
val selector = definitionSelector().gameType(gameType).preferRootFrom(element)
val scriptedLocs = ParadoxDefinitionSearch.search(name, "scripted_loc", project, selector = selector).findAll()
if(scriptedLocs.isNotEmpty()) return scriptedLocs.mapToArray { PsiElementResolveResult(it) }
//尝试识别为value[variable]
val variableSelector = valueSetValueSelector().gameType(gameType).preferRootFrom(element)
val variables = ParadoxValueSetValueSearch.search(name, "variable", project, selector = variableSelector).findAll()
if(variables.isNotEmpty()) return variables.mapToArray { PsiElementResolveResult(ParadoxValueSetValueElement(element, name, "variable", project, gameType)) }
return ResolveResult.EMPTY_ARRAY
}
override fun getTextAttributesKey(): TextAttributesKey? {
val name = element.name
val project = element.project
val gameType = selectGameType(element) ?: return null
val configGroup = getCwtConfig(project).getValue(gameType)
//尝试识别为预定义的localisation_command
val localisationCommand = CwtConfigHandler.resolveLocalisationCommand(name, configGroup)
if(localisationCommand != null) return null //no highlight
//尝试识别为<scripted_loc>
val selector = definitionSelector().gameType(gameType)
val scriptedLoc = ParadoxDefinitionSearch.search(name, "scripted_loc", project, selector = selector).findFirst()
if(scriptedLoc != null) return ParadoxScriptAttributesKeys.DEFINITION_REFERENCE_KEY //definition reference
//尝试识别为value[variable]
val variableSelector = valueSetValueSelector().gameType(gameType)
val variable = ParadoxValueSetValueSearch.search(name, "variable", project, selector = variableSelector).findFirst()
if(variable != null) return ParadoxScriptAttributesKeys.VARIABLE_KEY
return null
}
}
| 2 | Kotlin | 2 | 13 | 97b0df8a6c176e97d239a0a4be9a451e70a44777 | 4,403 | Paradox-Language-Support | MIT License |
app/src/main/java/com/marouane/laghrib/weatherapp/data/datasource/DataTransferObjects.kt | laghribmarouane | 801,213,958 | false | {"Kotlin": 33705} | package com.marouane.laghrib.weatherapp.network
import com.marouane.laghrib.weatherapp.entities.CurrentWeather
import com.marouane.laghrib.weatherapp.entities.ForecastItem
import com.marouane.laghrib.weatherapp.entities.WeatherItem
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class CurrentWeatherDTO(
@Json(name = "name") val city: String,
@Json(name = "dt") val dateTime: Long,
val main: MainDTO,
val wind: WindDTO,
@Json(name = "weather") val weathers: List<WeatherItemDTO>
)
@JsonClass(generateAdapter = true)
data class MainDTO(
val temp: Double,
val pressure: Double,
val humidity: Double,
@Json(name = "temp_min") val minTemp: Double,
@Json(name = "temp_max") val maxTemp: Double
)
@JsonClass(generateAdapter = true)
data class WindDTO(val speed: Double)
@JsonClass(generateAdapter = true)
data class TemperatureDTO(
@Json(name = "day") val tempDay: Double,
@Json(name = "night") val tempNight: Double
)
@JsonClass(generateAdapter = true)
data class ForecastDTO(@Json(name = "list") val forecasts: List<ForecastItemDTO>)
@JsonClass(generateAdapter = true)
data class ForecastItemDTO(
val temp: TemperatureDTO,
@Json(name = "dt") val dateTime: Long,
@Json(name = "weather") val weathers: List<WeatherItemDTO>
)
@JsonClass(generateAdapter = true)
data class WeatherItemDTO(
val description: String,
@Json(name = "icon") val iconId: String
)
fun CurrentWeatherDTO.asDomainModel(): CurrentWeather {
return CurrentWeather(
city = city,
dateTime = dateTime,
temp = main.temp,
pressure = main.pressure,
humidity = main.humidity,
minTemp = main.minTemp,
maxTemp = main.maxTemp,
windSpeed = wind.speed,
weathers = weathers.map {
WeatherItem(
description = it.description,
iconId = it.iconId
)
}
)
}
fun ForecastDTO.asDomainModel(): List<ForecastItem> {
return forecasts.map {
ForecastItem(
tempDay = it.temp.tempDay,
tempNight = it.temp.tempNight,
dateTime = it.dateTime,
weathers = it.weathers.map { weatherItem ->
WeatherItem(
description = weatherItem.description,
iconId = weatherItem.iconId
)
}
)
}
} | 0 | Kotlin | 0 | 0 | f62515ed2e65c43747cb09cea71ec24e288bd014 | 2,444 | WeatherApp | Apache License 2.0 |
app/src/main/java/io/outblock/lilico/page/nft/nftlist/model/NftLoadMoreModel.kt | Outblock | 435,317,689 | false | {"Kotlin": 1563313, "Java": 104099} | package io.outblock.lilico.page.nft.nftlist.model
class NftLoadMoreModel(
val isGridLoadMore: Boolean? = null,
val isListLoadMore: Boolean? = null,
) | 63 | Kotlin | 0 | 4 | a238e4f9db0d93a9c87fc9682860f2ea265c798b | 158 | Lilico-Android | Apache License 2.0 |
src/commonMain/kotlin/character/classes/shaman/abilities/WrathOfAirTotem.kt | marisa-ashkandi | 332,658,265 | false | null | package character.classes.shaman.abilities
import character.Ability
import character.Buff
import character.Mutex
import character.Stats
import character.classes.shaman.talents.MentalQuickness
import character.classes.shaman.talents.TotemicFocus
import data.itemsets.CycloneRegalia
import mechanics.General
import sim.SimParticipant
class WrathOfAirTotem : Ability() {
companion object {
const val name = "Wrath of Air Totem"
}
override val id: Int = 3738
override val name: String = Companion.name
override val icon: String = "spell_nature_slowingtotem.jpg"
override fun gcdMs(sp: SimParticipant): Int = sp.totemGcd().toInt()
override fun resourceCost(sp: SimParticipant): Double {
val tf = sp.character.klass.talents[TotemicFocus.name] as TotemicFocus?
val tfRed = tf?.totemCostReduction() ?: 0.0
val mq = sp.character.klass.talents[MentalQuickness.name] as MentalQuickness?
val mqRed = mq?.instantManaCostReduction() ?: 0.0
val baseCost = 320.0
return General.resourceCostReduction(baseCost, listOf(tfRed, mqRed))
}
override fun available(sp: SimParticipant): Boolean {
return true
}
val buff = object : Buff() {
override val name: String = "Wrath of Air Totem"
override val icon: String = "spell_nature_slowingtotem.jpg"
override val durationMs: Int = 120000
override val mutex: List<Mutex> = listOf(Mutex.AIR_TOTEM)
override fun modifyStats(sp: SimParticipant): Stats {
// Extra sp from T4 set
val t4BonusBuff = sp.buffs[CycloneRegalia.TWO_SET_BUFF_NAME] != null
val t4BonusSpellDamage = if(t4BonusBuff) { CycloneRegalia.twoSetWrathOfAirBonus() } else 0
return Stats(
spellDamage = 101 + t4BonusSpellDamage
)
}
}
override fun cast(sp: SimParticipant) {
sp.addBuff(buff)
}
}
| 21 | null | 11 | 25 | 9cb6a0e51a650b5d04c63883cb9bf3f64057ce73 | 1,942 | tbcsim | MIT License |
src/main/kotlin/eventichs/api/eventichs_api/DAO/InvitationOrganisationDAO.kt | WildBabaloo | 745,768,557 | false | {"Kotlin": 223537} | package eventichs.api.eventichs_api.DAO
import eventichs.api.eventichs_api.Modèle.InvitationOrganisation
import eventichs.api.eventichs_api.Modèle.Utilisateur
interface InvitationOrganisationDAO : DAO<InvitationOrganisation> {
override fun chercherTous(): List<InvitationOrganisation> {
TODO("Not yet implemented")
}
override fun chercherParID(id: Int): InvitationOrganisation? {
TODO("Not yet implemented")
}
override fun ajouter(element: InvitationOrganisation): InvitationOrganisation? {
TODO("Not yet implemented")
}
override fun modifier(element: InvitationOrganisation): InvitationOrganisation? {
TODO("Not yet implemented")
}
override fun supprimerParID(id: Int): InvitationOrganisation?
fun chercherParOrganisation(idOrganisation: Int) : List<InvitationOrganisation>
fun chercherParParticipant(codeParticipant: String) : List<InvitationOrganisation>
fun changerStatus(idInvitationOrganisation : Int, status : String) : InvitationOrganisation?
fun créerJeton(idOrganisation : Int) : InvitationOrganisation?
fun saisirJeton(jeton : String, code_util : String) : InvitationOrganisation?
fun validerUtilisateur(id : Int, code_util : String) : Boolean
fun validerOrganisationInvitation(idInvitation : Int, code_util : String) : Boolean
fun validerOrganisation(idOrganisation : Int, code_util : String) : Boolean
} | 0 | Kotlin | 0 | 0 | ccf4a85bef55e64a0d4b279499f0003e5cc42764 | 1,429 | eventichs_api | The Unlicense |
src/test/kotlin/de/gmuth/ipp/client/IppClientTests.kt | gmuth | 247,626,449 | false | {"Kotlin": 241344} | package de.gmuth.ipp.client
/**
* Copyright (c) 2023 <NAME>
*/
import de.gmuth.ipp.core.IppOperation.GetPrinterAttributes
import org.junit.Test
import java.net.URI
import kotlin.test.assertEquals
class IppClientTests {
val ippClient = IppClientMock()
@Test
fun sendRequestToURIWithEncodedWhitespaces() {
ippClient.ippRequest(GetPrinterAttributes, URI.create("ipp://0/PDF%20Printer")).run {
assertEquals("/PDF%20Printer", printerUri.rawPath)
assertEquals("/PDF Printer", printerUri.path)
}
}
}
| 0 | Kotlin | 8 | 54 | 13b133f775f6784e9bb509a86a35f5ce147da86f | 555 | ipp-client-kotlin | MIT License |
app/src/test/java/fr/azhot/realestatemanager/LoanCalculatorFragmentViewModelTest.kt | Azhot | 317,513,160 | false | {"Gradle": 3, "Markdown": 2, "Shell": 1, "Ignore List": 3, "Batchfile": 1, "Java Properties": 1, "Proguard": 1, "Kotlin": 55, "XML": 101, "JSON": 1, "Java": 1} | package fr.azhot.realestatemanager
import fr.azhot.realestatemanager.viewmodel.LoanCalculatorFragmentViewModel
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import kotlin.math.pow
class LoanCalculatorFragmentViewModelTest {
private lateinit var viewModel: LoanCalculatorFragmentViewModel
@Before
fun init() {
viewModel = LoanCalculatorFragmentViewModel()
}
@Test
fun calculateMonthlyPayment_isCorrect() {
val amountToFind = (100f * ((1f + 0.1f) / 100 / 12)) /
(1 - (1 + ((1f + 0.1f) / 100 / 12)).pow(-120f))
assertEquals(amountToFind, viewModel.calculateMonthlyPayment(100f, 1f, 0.1f, 120f))
}
} | 1 | null | 1 | 1 | 3bb6b80dba9c6715c8ee29319788c8ac6fc15416 | 707 | RealEstateManager | MIT License |
src/main/kotlin/app/sakuracad/packet/incoming/BroadcastPacket.kt | SakuraCAD | 289,523,188 | false | null | package app.sakuracad.packet.incoming
import app.sakuracad.SakuraCAD
import app.sakuracad.Session
import app.sakuracad.packet.IncomingPacket
import app.sakuracad.packet.OutgoingPacket
import app.sakuracad.packet.RODPacket
import app.sakuracad.packet.outgoing.MessagePacket
class BroadcastPacket(val message: String) : IncomingPacket() {
override suspend fun handle(session: Session): OutgoingPacket {
SakuraCAD.sessions.filter { s -> s.sessionType == Session.SessionType.USER }.forEach {
session.connection.send(RODPacket(null, "msg", MessagePacket("broadcast:$message")).toFrame())
}
return MessagePacket("sent")
}
} | 0 | Kotlin | 0 | 0 | 713d1109256169cc1608fd5515a98a3804bcb3b4 | 663 | backend | MIT License |
agp-7.1.0-alpha01/tools/base/build-system/gradle-core/src/apiTest/kotlin/com/android/build/api/apiTest/groovy/DisableTests.kt | jomof | 502,039,754 | false | {"Java": 35519326, "Kotlin": 22849138, "C++": 2171001, "HTML": 1377915, "Starlark": 915536, "C": 141955, "Shell": 110207, "RenderScript": 58853, "Python": 25635, "CMake": 18109, "Batchfile": 12180, "Perl": 9310, "Dockerfile": 5690, "Makefile": 4535, "CSS": 4148, "JavaScript": 3488, "PureBasic": 2359, "GLSL": 1628, "AIDL": 1117, "Prolog": 277} | /*
* Copyright (C) 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.build.api.apiTest.groovy
import com.android.build.api.apiTest.VariantApiBaseTest
import com.google.common.truth.Truth
import org.junit.Test
import kotlin.test.assertNotNull
class DisableTests: VariantApiBaseTest(TestType.Script, ScriptingLanguage.Groovy) {
@Test
fun disableUnitTest() {
given {
tasksToInvoke.add("tasks")
addModule(":app") {
buildFile = """
plugins {
id 'com.android.application'
}
android {
${testingElements.addCommonAndroidBuildLogic()}
}
androidComponents {
beforeVariants(selector().all(), { variantBuilder ->
variantBuilder.enableUnitTest = false
})
onVariants(selector().withName("debug"), { variant ->
if (variant.unitTest != null) {
throw new RuntimeException("UnitTest is active while it was deactivated")
}
if (variant.androidTest == null) {
throw new RuntimeException("AndroidTest is not active, it should be")
}
})
}
""".trimIndent()
testingElements.addManifest(this)
}
}
withDocs {
index =
// language=markdown
"""
# Test get operation
This sample shows how to use the get operation, which provides the final version of the artifact.
It shows the location of the apk for the all variants.
## To Run
./gradlew debugDisplayApks
""".trimIndent()
}
check {
assertNotNull(this)
Truth.assertThat(output).contains("BUILD SUCCESSFUL")
}
}
@Test
fun disableAndroidTest() {
given {
tasksToInvoke.add("tasks")
addModule(":app") {
buildFile = """
plugins {
id 'com.android.application'
}
android {
${testingElements.addCommonAndroidBuildLogic()}
}
androidComponents {
beforeVariants(selector().withName("debug"), { variantBuilder ->
variantBuilder.enableAndroidTest = false
})
onVariants(selector().withName("debug"), { variant ->
if (variant.unitTest == null) {
throw new RuntimeException("Unit test is not active, it should be")
}
if (variant.androidTest != null) {
throw new RuntimeException("AndroidTest is active while it was deactivated")
}
})
}
""".trimIndent()
testingElements.addManifest(this)
}
}
withDocs {
index =
// language=markdown
"""
# Test get operation
This sample shows how to use the get operation, which provides the final version of the artifact.
It shows the location of the apk for the all variants.
## To Run
./gradlew debugDisplayApks
""".trimIndent()
}
check {
assertNotNull(this)
Truth.assertThat(output).contains("BUILD SUCCESSFUL")
}
}
}
| 1 | Java | 1 | 0 | 9e3475f6d94cb3239f27ed8f8ee81b0abde4ef51 | 4,033 | CppBuildCacheWorkInProgress | Apache License 2.0 |
shared/domain/episodes/api/src/commonMain/kotlin/com/thomaskioko/tvmaniac/episodes/api/EpisodesCache.kt | c0de-wizard | 361,393,353 | false | null | package com.thomaskioko.tvmaniac.episodes.api
import com.thomaskioko.tvmaniac.core.db.EpisodeArtByShowId
import kotlinx.coroutines.flow.Flow
import com.thomaskioko.tvmaniac.core.db.EpisodesByShowId
import com.thomaskioko.tvmaniac.core.db.Episode as EpisodeCache
interface EpisodesCache {
fun insert(entity: EpisodeCache)
fun insert(list: List<EpisodeCache>)
fun observeEpisodesByShowId(id: Int): Flow<List<EpisodesByShowId>>
fun observeEpisodeArtByShowId(id: Int): Flow<List<EpisodeArtByShowId>>
}
| 3 | Kotlin | 8 | 81 | 9df7429257c4cff0346734392c89b8017b90bd45 | 520 | tv-maniac | Apache License 2.0 |
jetpackpractice/src/main/java/com/yaman/jetpackpractice/ui/pages/LoginPage.kt | Yamanaswal | 709,261,798 | false | {"Kotlin": 224228, "Java": 7494} | package com.yaman.jetpackpractice.ui.pages
import android.widget.Toast
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.material3.TextFieldColors
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
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.graphics.RectangleShape
import androidx.compose.ui.input.key.Key
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.colorResource
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import com.yaman.jetpackpractice.R
import com.yaman.jetpackpractice.ui.components.LoginAppBar
import com.yaman.jetpackpractice.view_model.LoginViewModel
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun LoginPage(
navController: NavController = rememberNavController(),
modifier: Modifier = Modifier
) {
val context = LocalContext.current
var email by rememberSaveable { mutableStateOf("") }
var mobile by rememberSaveable { mutableStateOf("") }
var password by rememberSaveable { mutableStateOf("") }
var passwordVisible by rememberSaveable { mutableStateOf(false) } //rememberSaveable in survived configuration change and save state in bundle.
var showEmailField by rememberSaveable { mutableStateOf(false) }
var showMobileField by rememberSaveable { mutableStateOf(true) }
val maxLengthMobileNumber = 10
var loginTypeMsg by rememberSaveable { mutableStateOf("Login with email") }
val viewModel: LoginViewModel = viewModel()
val data by viewModel.loginResponse.observeAsState()
Column(
modifier = Modifier
.fillMaxSize(),
) {
LoginAppBar()
AnimatedVisibility(visible = showMobileField) {
TextField(
value = mobile,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Phone),
onValueChange = { if (it.length <= maxLengthMobileNumber) mobile = it },
singleLine = true,
shape = RoundedCornerShape(30.dp),
colors = TextFieldDefaults.textFieldColors(
textColor = Color.Black,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent
),
placeholder = { Text("Mobile Number") },
modifier = Modifier
.fillMaxWidth()
.padding(start = 12.dp, end = 12.dp, top = 30.dp, bottom = 0.dp)
)
}
AnimatedVisibility(visible = showEmailField) {
TextField(
value = email,
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Email),
onValueChange = { email = it },
singleLine = true,
shape = RoundedCornerShape(30.dp),
colors = TextFieldDefaults.textFieldColors(
textColor = Color.Black,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent
),
placeholder = { Text("Enter Address") },
modifier = Modifier
.fillMaxWidth()
.padding(start = 12.dp, end = 12.dp, top = 30.dp, bottom = 0.dp)
)
}
TextField(
value = password,
onValueChange = { password = it },
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
placeholder = { Text("Password") },
singleLine = true,
shape = RoundedCornerShape(30.dp),
colors = TextFieldDefaults.textFieldColors(
textColor = Color.Black,
focusedIndicatorColor = Color.Transparent,
unfocusedIndicatorColor = Color.Transparent,
disabledIndicatorColor = Color.Transparent
),
trailingIcon = {
val image = if (passwordVisible) {
R.drawable.lock_close
} else {
R.drawable.lock_open
}
Icon(painter = painterResource(id = image), contentDescription = "",
Modifier.clickable {
passwordVisible = !passwordVisible
})
},
visualTransformation = if (passwordVisible) {
VisualTransformation.None
} else {
PasswordVisualTransformation()
},
modifier = Modifier
.fillMaxWidth()
.padding(start = 12.dp, end = 12.dp, top = 12.dp, bottom = 14.dp)
)
Text(
text = "Forget Password?",
modifier = Modifier
.align(alignment = Alignment.End)
.padding(start = 12.dp, end = 12.dp, top = 12.dp, bottom = 12.dp)
.clickable(
indication = null, // This is mandatory stop ripple effect
interactionSource = remember { MutableInteractionSource() } // This is mandatory stop ripple effect
) {
Toast
.makeText(context, "CLicked Here...", Toast.LENGTH_SHORT)
.show()
}
)
Button(
onClick = { /*TODO*/ },
modifier = Modifier
.fillMaxWidth()
.padding(start = 12.dp, end = 12.dp, top = 20.dp, bottom = 20.dp),
colors = ButtonDefaults.buttonColors(containerColor = Color.Red)
) {
Text(
"Login",
modifier = Modifier.fillMaxWidth(),
textAlign = TextAlign.Center
)
}
Text(
text = loginTypeMsg,
modifier = Modifier
.align(alignment = Alignment.CenterHorizontally)
.padding(start = 12.dp, end = 12.dp, top = 0.dp, bottom = 20.dp)
.clickable(
indication = null, // This is mandatory stop ripple effect
interactionSource = remember { MutableInteractionSource() } // This is mandatory stop ripple effect
) {
if (showMobileField) {
showEmailField = true
showMobileField = false
loginTypeMsg = "Login with mobile number"
} else {
showEmailField = false
showMobileField = true
loginTypeMsg = "Login with email"
}
}
)
}
}
@Preview(showBackground = true)
@Composable
fun LoginPagePreview() {
LoginPage()
} | 0 | Kotlin | 0 | 0 | bed25e2ec3a86ab713ad8ab2c2b5e0bf7caa3765 | 8,530 | Tutorials_Android | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.