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
rxpm/src/main/kotlin/me/dmdev/rxpm/base/PmController.kt
asrovnov
240,532,607
true
{"Kotlin": 113968}
package me.dmdev.rxpm.base import android.os.* import com.bluelinelabs.conductor.* import me.dmdev.rxpm.* import me.dmdev.rxpm.delegate.* /** * Predefined [Conductor's Controller][RestoreViewOnCreateController] implementing the [PmView][PmView]. * * Just override the [providePresentationModel] and [onBindPresentationModel] methods and you are good to go. * * If extending is not possible you can implement [PmView], * create a [PmControllerDelegate] and pass the lifecycle callbacks to it. * See this class's source code for the example. */ abstract class PmController<PM : PresentationModel>(args: Bundle? = null) : RestoreViewOnCreateController(args), PmView<PM> { @Suppress("LeakingThis") private val delegate = PmControllerDelegate(this) final override val presentationModel get() = delegate.presentationModel }
0
null
0
0
817f73bf9f2ed19e23f6284ec38a2c565f93e105
849
RxPM
MIT License
compose-mds/src/main/java/ch/sbb/compose_mds/sbbicons/small/FreightWagonWeightSmall.kt
SchweizerischeBundesbahnen
853,290,161
false
{"Kotlin": 6728512}
package ch.sbb.compose_mds.sbbicons.small import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.EvenOdd import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import ch.sbb.compose_mds.sbbicons.SmallGroup public val SmallGroup.FreightWagonWeightSmall: ImageVector get() { if (_freightWagonWeightSmall != null) { return _freightWagonWeightSmall!! } _freightWagonWeightSmall = Builder(name = "FreightWagonWeightSmall", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = EvenOdd) { moveTo(11.0f, 4.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, true, 2.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, -2.0f, 0.0f) moveToRelative(2.732f, 1.0f) arcToRelative(2.0f, 2.0f, 0.0f, true, false, -3.465f, 0.0f) lineTo(6.09f, 5.0f) lineToRelative(-0.08f, 0.402f) lineToRelative(-2.0f, 10.0f) lineToRelative(-0.12f, 0.598f) horizontalLineToRelative(16.22f) lineToRelative(-0.12f, -0.598f) lineToRelative(-2.0f, -10.0f) lineTo(17.91f, 5.0f) horizontalLineToRelative(-4.178f) moveTo(12.0f, 6.0f) lineTo(6.91f, 6.0f) lineToRelative(-1.8f, 9.0f) horizontalLineToRelative(13.78f) lineToRelative(-1.8f, -9.0f) close() moveTo(3.0f, 20.0f) verticalLineToRelative(-1.0f) horizontalLineToRelative(1.0f) verticalLineToRelative(1.0f) horizontalLineToRelative(1.0f) curveToRelative(0.0f, 1.106f, 0.894f, 2.0f, 2.0f, 2.0f) reflectiveCurveToRelative(2.0f, -0.894f, 2.0f, -2.0f) horizontalLineToRelative(6.0f) curveToRelative(0.0f, 1.106f, 0.894f, 2.0f, 2.0f, 2.0f) reflectiveCurveToRelative(2.0f, -0.894f, 2.0f, -2.0f) horizontalLineToRelative(1.0f) verticalLineToRelative(-1.0f) horizontalLineToRelative(1.0f) verticalLineToRelative(1.0f) horizontalLineToRelative(1.0f) verticalLineToRelative(-3.0f) horizontalLineToRelative(-1.0f) verticalLineToRelative(1.0f) horizontalLineToRelative(-1.0f) verticalLineToRelative(-1.0f) lineTo(4.0f, 17.0f) verticalLineToRelative(1.0f) lineTo(3.0f, 18.0f) verticalLineToRelative(-1.0f) lineTo(2.0f, 17.0f) verticalLineToRelative(3.0f) close() moveTo(6.0f, 20.0f) curveToRelative(0.0f, 0.554f, 0.446f, 1.0f, 1.0f, 1.0f) reflectiveCurveToRelative(1.0f, -0.446f, 1.0f, -1.0f) close() moveTo(17.0f, 21.0f) curveToRelative(-0.554f, 0.0f, -1.0f, -0.446f, -1.0f, -1.0f) horizontalLineToRelative(2.0f) curveToRelative(0.0f, 0.554f, -0.446f, 1.0f, -1.0f, 1.0f) moveTo(5.0f, 18.0f) verticalLineToRelative(1.0f) horizontalLineToRelative(14.0f) verticalLineToRelative(-1.0f) close() moveTo(11.8f, 8.11f) lineTo(11.79f, 8.12f) horizontalLineToRelative(-1.3f) lineToRelative(-1.87f, 1.97f) lineTo(8.62f, 8.12f) lineTo(7.58f, 8.12f) verticalLineToRelative(4.77f) horizontalLineToRelative(1.04f) verticalLineToRelative(-1.54f) lineToRelative(0.6f, -0.6f) lineToRelative(1.45f, 2.14f) horizontalLineToRelative(1.31f) lineTo(9.93f, 10.0f) lineToRelative(1.86f, -1.88f) horizontalLineToRelative(0.02f) close() moveTo(16.37f, 12.88f) verticalLineToRelative(-2.57f) horizontalLineToRelative(-2.01f) verticalLineToRelative(0.76f) horizontalLineToRelative(1.06f) quadToRelative(-0.015f, 0.48f, -0.33f, 0.78f) reflectiveQuadToRelative(-0.81f, 0.3f) curveToRelative(-0.45f, 0.0f, -0.8f, -0.17f, -1.03f, -0.51f) curveToRelative(-0.18f, -0.28f, -0.28f, -0.64f, -0.28f, -1.13f) reflectiveCurveToRelative(0.1f, -0.87f, 0.3f, -1.16f) curveToRelative(0.23f, -0.33f, 0.56f, -0.49f, 0.98f, -0.49f) curveToRelative(0.28f, 0.0f, 0.51f, 0.08f, 0.69f, 0.22f) reflectiveCurveToRelative(0.3f, 0.34f, 0.35f, 0.6f) horizontalLineToRelative(1.01f) quadToRelative(-0.075f, -0.63f, -0.51f, -1.08f) curveToRelative(-0.39f, -0.41f, -0.9f, -0.61f, -1.53f, -0.61f) curveToRelative(-0.68f, 0.0f, -1.23f, 0.23f, -1.66f, 0.68f) curveToRelative(-0.46f, 0.47f, -0.69f, 1.09f, -0.69f, 1.84f) curveToRelative(0.0f, 0.66f, 0.18f, 1.22f, 0.53f, 1.67f) curveToRelative(0.43f, 0.54f, 1.0f, 0.81f, 1.73f, 0.81f) curveToRelative(0.6f, 0.0f, 1.08f, -0.22f, 1.43f, -0.66f) lineToRelative(0.1f, 0.55f) close() } } .build() return _freightWagonWeightSmall!! } private var _freightWagonWeightSmall: ImageVector? = null
0
Kotlin
0
1
090a66a40e1e5a44d4da6209659287a68cae835d
6,283
mds-android-compose
MIT License
extension/src/main/java/com/remember/extension/string.kt
KhomDrake
389,448,929
false
null
package com.remember.extension import android.util.Patterns import java.util.regex.Pattern fun String.isValidEmail() : Boolean { return Patterns.EMAIL_ADDRESS.matcher(this).matches() } fun String.isValidDate() : Boolean { val date = this.split('/') if(date.count() != 3) return false if((date[0].toInt() in 1..31).not()) return false if((date[1].toInt() in 1..12).not()) return false if((date[2].toInt() in 1960..2019).not()) return false return true } fun String.validDDD(): Boolean { val regex = "[1-9]{2}" val pattern = Pattern.compile(regex) val matcher = pattern.matcher(this) return matcher.matches() } fun String.validPhoneNumber() : Boolean { val regex = "^[\\s9]?\\d{4}-?\\d{4}\$" val pattern = Pattern.compile(regex) val matcher = pattern.matcher(this) return matcher.matches() } fun String.isValidPassword() : Boolean { val regex = "^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%^&+=_?:-])(?=\\S+$).{4,}$" val pattern = Pattern.compile(regex) val matcher = pattern.matcher(this) return matcher.matches() } fun String.toDateUS() : String { val date = this.split('/') return "${date[2]}-${date[1]}-${date[0]}" }
0
Kotlin
0
0
aabcb32a28a667b52be924bea2a845453d4a6d75
1,248
Remember
MIT License
framework/src/main/kotlin/pt/isel/SHORT/html/attribute/Color.kt
48276AntonioMarques
762,862,793
false
{"Kotlin": 290899, "CSS": 6361, "JavaScript": 2091, "HTML": 587}
package pt.isel.SHORT.html.attribute import pt.isel.SHORT.html.base.attribute.Attribute import pt.isel.SHORT.html.base.attribute.add /** * Represents the HTML color attribute. * Description: This attribute sets the text color using either a named color or a color specified in the hexadecimal #RRGGBB format. Note: This is a legacy attribute. Please use the CSS color property instead.. * Supported elements: <font>, <hr> */ fun Attribute.Companion.color(value: String) = add("color", value) /** * Represents the HTML color attribute. * Description: This attribute sets the text color using either a named color or a color specified in the hexadecimal #RRGGBB format. Note: This is a legacy attribute. Please use the CSS color property instead.. * Supported elements: <font>, <hr> */ fun List<Attribute>.color(value: String) = add("color", value)
0
Kotlin
0
1
0457515ab97855e4f42f7eeacec53f2919908918
858
short
Apache License 2.0
src/main/kotlin/cn/zhlh6/api/chinaholiday/config/GlobalReturnConfig.kt
ZHLHZHU
426,508,859
false
{"Kotlin": 7681, "Dockerfile": 700}
package cn.zhlh6.api.chinaholiday.config import cn.zhlh6.api.chinaholiday.exception.FeedbackException import com.fasterxml.jackson.databind.ObjectMapper import org.springframework.core.MethodParameter import org.springframework.http.MediaType import org.springframework.http.converter.HttpMessageConverter import org.springframework.http.server.ServerHttpRequest import org.springframework.http.server.ServerHttpResponse import org.springframework.lang.Nullable import org.springframework.web.bind.annotation.ExceptionHandler import org.springframework.web.bind.annotation.RestControllerAdvice import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice /** * create 2021/11/10 15:33 * 统一返回格式 * @author LH */ @RestControllerAdvice class GlobalReturnConfig( val objectMapper: ObjectMapper ) : ResponseBodyAdvice<Any> { override fun supports( methodParameter: MethodParameter, converterType: Class<out HttpMessageConverter<*>>, ): Boolean { return true } override fun beforeBodyWrite( @Nullable body: Any?, methodParameter: MethodParameter, mediaType: MediaType, selectedConverterType: Class<out HttpMessageConverter<*>>, serverHttpRequest: ServerHttpRequest, serverHttpResponse: ServerHttpResponse ): Any? { return when (body) { is Result<*> -> body is String -> objectMapper.writeValueAsString(Result.success(body)) else -> Result.success(body) } } @ExceptionHandler(FeedbackException::class) fun handleFeedbackException(e: FeedbackException): Result<*> { return e.message.let { Result.fail(e.code, e.msg) } } @ExceptionHandler(Exception::class) fun handleException(e: Exception): Result<*> { return e.message?.let { Result.fail(500, it) } ?: Result.fail(500, "unknown error") } } data class Result<T>( val code: Int, val msg: String, val data: T? = null ) { companion object { fun <T> success(data: T): Result<T> { return Result(200, "success", data) } fun fail(code: Int, msg: String): Result<Any> { return Result(code, msg) } } }
0
Kotlin
0
0
8169152541c9bf80416aaca5c16182739bb92be5
2,235
china-holiday
MIT License
src/main/kotlin/io/teamif/rpgstats/tribe/JinnTribe.kt
Team-IF
261,671,062
false
null
package io.teamif.rpgstats.tribe import io.teamif.rpgstats.role.AbstractRole class JinnTribe(role: AbstractRole) : AbstractTribe(TribeType.Jinn, TribeType.Monster, role)
0
Kotlin
0
1
65cdaa787aec78c2ceb87a059e3864227c5290b7
171
RPGStats
MIT License
extensions/src/commonMain/kotlin/jp/pois/oxacillin/extensions/Via.kt
pois0
339,318,315
true
{"Kotlin": 1970084}
/* * The MIT License (MIT) * * Copyright (c) 2017-2020 StarryBlueSky * Copyright (c) 2021 poispois * * 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. */ @file:Suppress("UNUSED") package jp.pois.oxacillin.extensions import kotlinx.serialization.KSerializer import kotlinx.serialization.Serializable import kotlinx.serialization.descriptors.PrimitiveKind import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor import kotlinx.serialization.descriptors.SerialDescriptor import kotlinx.serialization.encoding.Decoder import kotlinx.serialization.encoding.Encoder /** * Represents <a> tag in "source". */ @Serializable(with = Via.Serializer::class) public class Via( /** * Source application url. */ public val url: String, /** * Source application name. */ public val name: String, /** * Source <a> tag attributes. */ public val attributes: Map<String, String> ) { private companion object { val tagPattern = "^<a (.+?)>(.+?)</a>$".toRegex() val attributePattern = "^(.+?)=\"(.+?)\"$".toRegex() } public object Serializer: KSerializer<Via> { override val descriptor: SerialDescriptor = PrimitiveSerialDescriptor("via", PrimitiveKind.STRING) override fun deserialize(decoder: Decoder): Via { val matches = tagPattern.matchEntire(decoder.decodeString()) val tagAttributes = matches?.groupValues?.getOrNull(1)?.split(" ")?.map { val (k, v) = attributePattern.matchEntire(it)!!.destructured k to v }?.toMap() val tagValue = matches?.groupValues?.getOrNull(2) val href = tagAttributes?.get("href") require(tagAttributes != null && tagValue != null && href != null) { "Invalid source html passed." } return Via(href, tagValue, tagAttributes) } override fun serialize(encoder: Encoder, value: Via) { val attributes = value.attributes.entries.joinToString(separator = " ") { (k, v) -> "$k=\"$v\"" } encoder.encodeString("<a $attributes>${value.name}</a>") } } }
0
Kotlin
0
0
bc33905228c2a1ecf954fbeed53b08323cde6d41
3,206
Oxacillin
MIT License
app/src/main/java/com/persival/k_lory/MainApplication.kt
persival001
762,632,257
false
{"Kotlin": 46504}
package com.persival.k_lory import android.app.Activity import android.app.Application import android.os.Bundle import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MainApplication : Application(), Application.ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {} override fun onActivityStarted(activity: Activity) {} override fun onActivityResumed(activity: Activity) {} override fun onActivityPaused(activity: Activity) {} override fun onActivityStopped(activity: Activity) {} override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} override fun onActivityDestroyed(activity: Activity) {} }
0
Kotlin
1
1
a6719b3ab96ab2f430d471c5033d1f425ec66e30
724
K-Lory
MIT License
app/src/main/java/com/persival/k_lory/MainApplication.kt
persival001
762,632,257
false
{"Kotlin": 46504}
package com.persival.k_lory import android.app.Activity import android.app.Application import android.os.Bundle import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class MainApplication : Application(), Application.ActivityLifecycleCallbacks { override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {} override fun onActivityStarted(activity: Activity) {} override fun onActivityResumed(activity: Activity) {} override fun onActivityPaused(activity: Activity) {} override fun onActivityStopped(activity: Activity) {} override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) {} override fun onActivityDestroyed(activity: Activity) {} }
0
Kotlin
1
1
a6719b3ab96ab2f430d471c5033d1f425ec66e30
724
K-Lory
MIT License
libfsp/src/main/kotlin/libfsp/reference/FSPReferenceDispatcher.kt
freemlang
658,320,863
false
{"Kotlin": 43579}
package libfsp.reference import java.util.UUID class FSPReferenceDispatcher internal constructor(private val uuid: UUID) { context(FSPReferenceDispatcher) val <Type> FSPValue<Type>.value: Type get() = get(uuid) context(FSPReferenceDispatcher) var <Type> FSPVariance<Type>.value: Type get() = get(uuid) set(value) { set(uuid, value) } }
0
Kotlin
0
0
3c8e1c1398785be2102bd9774650a505dfdaf33f
379
Freem
Apache License 2.0
app/src/main/java/com/vixiloc/vixgpt/domain/model/Settings.kt
vixiloc
665,395,128
false
{"Kotlin": 50790}
package com.vixiloc.vixgpt.domain.model import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey @Entity data class Settings( @PrimaryKey(autoGenerate = true) val id: Int? = null, @ColumnInfo(name = "api_key") val apiKey: String?, @ColumnInfo(name = "model") val model: String? )
1
Kotlin
0
2
69be3fe59fb8b474a703155b67078d08d9c556f6
329
vixgpt
Apache License 2.0
parser/src/main/kotlin/gay/pizza/pork/parser/Highlighter.kt
GayPizzaSpecifications
680,636,847
false
{"Kotlin": 277930}
package gay.pizza.pork.parser class Highlighter(val scheme: HighlightScheme) { fun highlight(stream: TokenStream): List<Highlight> = stream.tokens.map { scheme.highlight(it) } }
0
Kotlin
1
0
9338b01b4832f838bda54cedb54893a13f37f418
185
pork
MIT License
app/src/main/java/com/appsolute/pokedex/presentation/state/PokemonListState.kt
braveheart3208
638,147,646
false
null
package com.appsolute.pokedex.presentation.state import com.appsolute.pokedex.application.core.UiText import com.appsolute.pokedex.domain.model.PokemonSummary /** * Created by <NAME><NAME>. * This project Pokedex belongs to Appsolute. * Do Not Copy * Please Contact <EMAIL> for more information */ data class PokemonListState( val isLoading: Boolean = false, val pokemons: List<PokemonSummary> = emptyList(), val error: UiText? = null )
0
Kotlin
0
0
1b4702dbe451f229762d22e92e6ca55f9c96e2dd
457
Pokedex
MIT License
verifiable-credentials-library/src/main/java/org/idp/wallet/verifiable_credentials_library/ui/component/System.kt
hirokazu-kobayashi-koba-hiro
752,660,337
false
{"Kotlin": 380792, "Mermaid": 497}
package org.idp.wallet.verifiable_credentials_library.ui.component import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.fadeIn import androidx.compose.animation.fadeOut import androidx.compose.animation.slideInHorizontally import androidx.compose.animation.slideOutHorizontally import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.IntrinsicSize import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.AlertDialog import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import org.idp.wallet.verifiable_credentials_library.ui.viewmodel.SystemDialogState @Composable fun SystemDialog(systemDialogState: SystemDialogState) { if (systemDialogState.visible) { AlertDialog( onDismissRequest = { systemDialogState.onClickNegativeButton() }, confirmButton = { TextButton(onClick = { systemDialogState.onClickPositiveButton() }) { Text("OK") } }, title = { Text(text = systemDialogState.title) }, text = { Text(text = systemDialogState.message) }) } } @Composable fun FloatingView( visible: Boolean, content: @Composable () -> Unit, onDismiss: () -> Unit, start: Dp = Dp(0F), end: Dp = Dp(0F), top: Dp = Dp(0F), bottom: Dp = Dp(0F) ) { AnimatedVisibility( visible = visible, enter = slideInHorizontally(initialOffsetX = { it }) + fadeIn(), exit = slideOutHorizontally(targetOffsetX = { it }) + fadeOut(), content = { Box( modifier = Modifier.fillMaxSize() .clickable( onClick = onDismiss, indication = null, interactionSource = remember { MutableInteractionSource() }), contentAlignment = Alignment.TopEnd, ) { Surface( modifier = Modifier.fillMaxWidth() .padding(start = start, end = end, top = top, bottom = bottom) .background(color = Color.Transparent) .height(IntrinsicSize.Min), shape = RoundedCornerShape(Dp(8.0F)), ) { Column( modifier = Modifier.padding(Dp(16.0F)).background(color = Color.White), ) { content() } } } }) }
1
Kotlin
2
0
fcad17e4e3391619b4d5b7c80333cefbd53a7e38
3,139
vc-wallet-android-app
Apache License 2.0
app/src/main/java/ch/abwesend/privatecontacts/domain/service/interfaces/TelephoneService.kt
fgubler
462,182,037
false
{"Kotlin": 1123936, "Java": 369326}
/* * Private Contacts * Copyright (c) 2022. * Florian Gubler */ package ch.abwesend.privatecontacts.domain.service.interfaces interface TelephoneService { val telephoneDefaultCountryIso: String fun formatPhoneNumberForDisplay(number: String): String fun formatPhoneNumberForMatching(number: String): String }
2
Kotlin
1
9
fe855a8b3154186f255435f7f6847b00014bf101
328
PrivateContacts
Apache License 2.0
app/src/main/java/dev/abbasian/applyhistory/ui/theme/AppString.kt
MahdiAbbasian
776,492,945
false
{"Kotlin": 66706}
package dev.abbasian.applyhistory.ui.theme object AppString { const val SEARCH = "search" const val EXPORT_TO_FILE = "Export to file" const val IMPORT_FROM_FILE = "Import from file" const val IMPORT_FILE_SUCCESS = "Import file Success" const val IMPORT_FILE_FAILED = "Import file Failed" const val TOTAL_APPLICATIONS = "Total Applications:" const val COMPANY_NAME = "Company name" const val COMPANY_WEBSITE = "Company website" const val DESCRIPTION = "Description" const val ADD_COMPANY = "Add company" const val UPDATE_DATA = "Update data" const val APPLY_STATUS = "Apply status" const val EDIT_COMPANY = "Edit company" const val DELETE_COMPANY = "Delete company" const val COMPANY_NOT_FOUND = "Company not found" val statusOptions = listOf("None", "Applied", "Rejected", "Interview", "Accepted") }
0
Kotlin
0
0
dc1bc8d690a55aa68c4a566659929a91cb241db1
865
ApplyHistory
MIT License
src/main/kotlin/io/github/smiley4/ktorswaggerui/dsl/OpenApiLicense.kt
SMILEY4
526,907,299
false
{"Kotlin": 337858}
package io.github.smiley4.ktorswaggerui.dsl import io.github.smiley4.ktorswaggerui.data.DataUtils import io.github.smiley4.ktorswaggerui.data.LicenseData /** * License information for the exposed API. */ @OpenApiDslMarker class OpenApiLicense { /** * The license name used for the API */ var name: String? = LicenseData.DEFAULT.name /** * A URL to the license used for the API. MUST be in the format of a URL. */ var url: String? = LicenseData.DEFAULT.url fun build(base: LicenseData) = LicenseData( name = DataUtils.merge(base.name, name), url = DataUtils.merge(base.url, url), ) }
4
Kotlin
19
93
6ae057d68bf0b93099201e59c4f4310cdc51ba9e
652
ktor-swagger-ui
Apache License 2.0
app/src/main/java/com/tevinjeffrey/rutgersct/ui/sectioninfo/SectionInfoSubcomponent.kt
tevjef
29,270,889
false
null
package com.tevinjeffrey.rutgersct.ui.sectioninfo import dagger.Subcomponent import dagger.android.AndroidInjector @Subcomponent interface SectionInfoSubcomponent : AndroidInjector<SectionInfoFragment> { fun inject(sectionInfoViewModel: SectionInfoViewModel) @Subcomponent.Builder abstract class Builder : AndroidInjector.Builder<SectionInfoFragment>() { abstract override fun build(): SectionInfoSubcomponent } }
0
Kotlin
4
56
7c38f16b1e6d284381e215e2ab46ea73e4e59cc5
430
Rutgers-Course-Tracker
Apache License 2.0
app/src/main/java/com/escalondev/adaptativelayout/MainActivity.kt
rescalon34
510,105,724
false
{"Kotlin": 20299}
package com.escalondev.adaptativelayout import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.navigation.NavController import androidx.navigation.Navigation import androidx.navigation.ui.setupActionBarWithNavController import com.escalondev.adaptativelayout.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { lateinit var binding: ActivityMainBinding private lateinit var navController: NavController override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setupNavigation() } private fun setupNavigation() { navController = Navigation.findNavController(this, R.id.root_nav_host_fragment) setupActionBarWithNavController(navController) } override fun onSupportNavigateUp(): Boolean { return navController.navigateUp() || super.onSupportNavigateUp() } }
0
Kotlin
0
0
172ff3e98d2f530560f24c8cf66118a38039cf03
1,021
adaptative-layout-android
Apache License 2.0
data/src/main/java/reactivecircus/releaseprobe/data/artifactcollection/mapper/ArtifactCollectionMappers.kt
ReactiveCircus
142,655,149
false
null
package reactivecircus.releaseprobe.data.artifactcollection.mapper import reactivecircus.releaseprobe.domain.artifactcollection.model.ArtifactCollection import reactivecircus.releaseprobe.persistence.artifactcollection.entity.ArtifactCollectionEntity fun ArtifactCollectionEntity.toModel(): ArtifactCollection = ArtifactCollection( name = name, description = description, themeColor = themeColor, keywords = keywords )
7
Kotlin
4
8
b97fb5b8f161f29b70db1de6446af76166f42aa4
461
release-probe
MIT License
src/test/kotlin/fr/o80/aoc/day01/part2/input1.kt
olivierperez
310,899,127
false
null
package fr.o80.aoc.day01.part2 const val result_d1_p2_1 = 2 const val input_d1_p2_1 = """14"""
0
Kotlin
1
2
c92001b5d4651e67e17c20eb8ddc2ac62b14f2c2
96
AdventOfCode-KotlinStarterKit
Apache License 2.0
src/Day01.kt
kecolk
572,819,860
false
null
fun main() { fun elvesCalories(input: List<Int?>): Collection<Int> { return input .scan( Pair<Int, Int?>( 0, 0 ) ) { acc, value -> Pair(if (value == null) acc.first + 1 else acc.first, value) } .groupingBy { it.first } .fold(0) { acc, element -> element.second?.let { acc + it } ?: acc } .values } fun part1(input: List<Int?>): Int = elvesCalories(input).max() fun part2(input: List<Int?>): Int = elvesCalories(input).sorted().takeLast(3).sum() // test if implementation meets criteria from the description, like: val testInput = readInput("Day01_test") check(part1(testInput) == 24000) check(part2(testInput) == 45000) val input = readInput("Day01") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
72b3680a146d9d05be4ee209d5ba93ae46a5cb13
893
kotlin_aoc_22
Apache License 2.0
erikflowers-weather-icons/src/commonMain/kotlin/compose/icons/weathericons/WindBeaufort1.kt
DevSrSouza
311,134,756
false
null
package compose.icons.weathericons import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Butt import androidx.compose.ui.graphics.StrokeJoin.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import compose.icons.WeatherIcons public val WeatherIcons.WindBeaufort1: ImageVector get() { if (_windBeaufort1 != null) { return _windBeaufort1!! } _windBeaufort1 = Builder(name = "WindBeaufort1", defaultWidth = 30.0.dp, defaultHeight = 30.0.dp, viewportWidth = 30.0f, viewportHeight = 30.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(5.76f, 13.5f) curveToRelative(0.0f, 0.18f, 0.06f, 0.31f, 0.17f, 0.4f) curveToRelative(0.12f, 0.11f, 0.26f, 0.17f, 0.42f, 0.17f) horizontalLineToRelative(10.4f) curveToRelative(0.17f, 0.0f, 0.33f, 0.06f, 0.46f, 0.19f) curveToRelative(0.13f, 0.12f, 0.2f, 0.28f, 0.2f, 0.46f) reflectiveCurveToRelative(-0.07f, 0.34f, -0.2f, 0.47f) reflectiveCurveToRelative(-0.28f, 0.2f, -0.46f, 0.2f) curveToRelative(-0.18f, 0.0f, -0.34f, -0.07f, -0.47f, -0.21f) curveToRelative(-0.12f, -0.11f, -0.26f, -0.16f, -0.4f, -0.16f) curveToRelative(-0.16f, 0.0f, -0.3f, 0.05f, -0.41f, 0.16f) curveToRelative(-0.11f, 0.11f, -0.16f, 0.24f, -0.16f, 0.39f) curveToRelative(0.0f, 0.16f, 0.06f, 0.3f, 0.17f, 0.41f) curveToRelative(0.36f, 0.36f, 0.78f, 0.53f, 1.27f, 0.53f) reflectiveCurveToRelative(0.91f, -0.17f, 1.26f, -0.52f) curveToRelative(0.35f, -0.35f, 0.52f, -0.77f, 0.52f, -1.27f) curveToRelative(0.0f, -0.49f, -0.17f, -0.92f, -0.52f, -1.27f) curveToRelative(-0.35f, -0.35f, -0.77f, -0.53f, -1.26f, -0.53f) horizontalLineTo(6.35f) curveToRelative(-0.16f, 0.0f, -0.3f, 0.06f, -0.42f, 0.17f) curveTo(5.81f, 13.21f, 5.76f, 13.34f, 5.76f, 13.5f) close() moveTo(5.76f, 11.48f) curveToRelative(0.0f, 0.17f, 0.06f, 0.3f, 0.17f, 0.39f) curveToRelative(0.12f, 0.11f, 0.26f, 0.16f, 0.42f, 0.16f) horizontalLineToRelative(13.81f) curveToRelative(0.49f, 0.0f, 0.92f, -0.18f, 1.27f, -0.52f) curveToRelative(0.35f, -0.35f, 0.52f, -0.77f, 0.52f, -1.27f) curveToRelative(0.0f, -0.49f, -0.17f, -0.91f, -0.52f, -1.26f) reflectiveCurveToRelative(-0.77f, -0.52f, -1.27f, -0.52f) curveToRelative(-0.49f, 0.0f, -0.91f, 0.17f, -1.27f, 0.51f) curveToRelative(-0.11f, 0.12f, -0.16f, 0.27f, -0.16f, 0.42f) curveToRelative(0.0f, 0.16f, 0.05f, 0.3f, 0.16f, 0.4f) curveToRelative(0.11f, 0.1f, 0.24f, 0.15f, 0.4f, 0.15f) curveToRelative(0.15f, 0.0f, 0.29f, -0.05f, 0.41f, -0.16f) curveToRelative(0.12f, -0.12f, 0.27f, -0.18f, 0.45f, -0.18f) curveToRelative(0.17f, 0.0f, 0.33f, 0.06f, 0.46f, 0.18f) curveToRelative(0.13f, 0.12f, 0.2f, 0.27f, 0.2f, 0.45f) curveToRelative(0.0f, 0.18f, -0.07f, 0.34f, -0.2f, 0.47f) curveToRelative(-0.13f, 0.13f, -0.28f, 0.2f, -0.46f, 0.2f) horizontalLineTo(6.35f) curveToRelative(-0.16f, 0.0f, -0.3f, 0.06f, -0.42f, 0.17f) curveTo(5.81f, 11.18f, 5.76f, 11.32f, 5.76f, 11.48f) close() moveTo(18.65f, 21.85f) horizontalLineToRelative(2.47f) lineToRelative(1.65f, -7.98f) horizontalLineTo(20.3f) lineTo(18.65f, 21.85f) close() } } .build() return _windBeaufort1!! } private var _windBeaufort1: ImageVector? = null
17
null
25
571
a660e5f3033e3222e3553f5a6e888b7054aed8cd
4,413
compose-icons
MIT License
feature/profile/data/src/main/java/com/montfel/pokfinder/feature/profile/data/mapper/PokemonSpeciesMapper.kt
Montfel
489,497,209
false
{"Kotlin": 179677}
package com.montfel.pokfinder.feature.profile.data.mapper import com.montfel.pokfinder.feature.profile.data.model.dto.PokemonSpeciesDto import com.montfel.pokfinder.feature.profile.domain.model.HatchCounter import com.montfel.pokfinder.feature.profile.domain.model.PokemonSpecies fun PokemonSpeciesDto.toPokemonSpecies(): PokemonSpecies { return PokemonSpecies( baseHappiness = baseHappiness, captureRate = captureRate, eggGroups = eggGroups?.sortedBy { it.name }?.map { it.toEggGroup() }, flavorTexts = flavorTexts ?.map { it.toFlavorText() } ?.filter { it.language == "en" || it.language == "pt-BR" }, genderRate = genderRate, genera = genera ?.map { it.toGenera() } ?.filter { it.language == "en" || it.language == "pt-BR" }, growthRate = growthRate?.toGrowthRate()?.name, hatchCounter = HatchCounter( cycles = hatchCounter, steps = hatchCounter?.plus(1)?.times(255) ), evolutionChainId = evolutionChain?.url ?.dropLastWhile { it == '/' } ?.takeLastWhile { it.isDigit() } ?.toInt(), gender = if (genderRate == null || genderRate == -1) { "Genderless" } else { "♂ ${(8 - genderRate.toFloat()).div(8).times(100)}% | " + "♀ ${genderRate.toFloat().div(8).times(100)}% " } ) }
24
Kotlin
1
10
9eaa88c7c1c049e180e6097a9ad28a69fecd4c62
1,441
pokfinder
MIT License
domain/src/main/java/com/redcatgames/movies/domain/model/PrimaryTranslation.kt
v-kravchenko
484,328,569
false
null
package com.redcatgames.movies.domain.model data class PrimaryTranslation(val name: String)
0
Kotlin
0
1
b06edc260f656e07fa220eefcb4333f8478c7204
93
android-movie-lib
MIT License
src/main/kotlin/me/cunzai/plugin/itembound/database/MySQLHandler.kt
EmptyIrony
862,101,964
false
{"Kotlin": 23570}
package me.cunzai.plugin.itembound.database import taboolib.common.LifeCycle import taboolib.common.platform.Awake import taboolib.module.configuration.Config import taboolib.module.configuration.Configuration import taboolib.module.database.ColumnTypeSQL import taboolib.module.database.Index import taboolib.module.database.Table import taboolib.module.database.getHost import java.util.UUID object MySQLHandler { @Config("database.yml") lateinit var config: Configuration val host by lazy { config.getHost("mysql") } val datasource by lazy { host.createDataSource() } val table by lazy { Table("item_bound_data", host) { add ("bound_uuid"){ type(ColumnTypeSQL.VARCHAR, 36) } add("bounder") { type(ColumnTypeSQL.VARCHAR, 36) } add("version_id") { type(ColumnTypeSQL.INT) } add("item_data") { type(ColumnTypeSQL.LONGBLOB) } } } @Awake(LifeCycle.ENABLE) fun i() { table.workspace(datasource) { createTable(checkExists = true) createIndex(Index(("idx_bound_uuid"), listOf("bound_uuid"), checkExists = true)) }.run() } fun delete(uuid: UUID) { table.delete(datasource) { where { "bound_uuid" eq uuid.toString() } } } }
0
Kotlin
0
0
330cacf7b88e96e1617de65fa13a3e01bf91fd69
1,468
ItemBound
Creative Commons Zero v1.0 Universal
chat-core/src/main/java/com/fzm/chat/core/net/source/impl/NetGroupDataSource.kt
txchat
507,831,442
false
{"Kotlin": 2234450, "Java": 384844}
package com.fzm.chat.core.net.source.impl import com.fzm.chat.core.data.bean.GroupInfoTO import com.fzm.chat.core.data.bean.GroupUserTO import com.fzm.chat.core.data.bean.StringList import com.fzm.chat.core.data.bean.toPO import com.fzm.chat.core.data.po.GroupUserPO import com.fzm.chat.core.net.api.GroupService import com.fzm.chat.core.net.source.GroupDataSource import com.zjy.architecture.data.Result import com.zjy.architecture.ext.apiCall /** * @author zhengjy * @since 2021/05/11 * Description: */ class NetGroupDataSource( private val service: GroupService ) : GroupDataSource { override suspend fun createGroup( url: String, name: String, users: List<String> ): Result<GroupInfoTO> { return apiCall { service.createGroup( "$url${GroupService.API_CREATE_GROUP}", mapOf( "name" to name, "memberIds" to users ) ) } } override suspend fun editGroupAvatar(url: String?, gid: Long, avatar: String): Result<Any> { return apiCall { service.editGroupAvatar( "$url${GroupService.API_EDIT_GROUP_AVATAR}", mapOf( "id" to gid, "avatar" to avatar ) ) } } override suspend fun editGroupName(url: String?, gid: Long, name: String): Result<Any> { return apiCall { service.editGroupName( "$url${GroupService.API_EDIT_GROUP_NAME}", mapOf( "id" to gid, "name" to name ) ) } } override suspend fun editGroupNames(url: String?, gid: Long, name: String, publicName: String): Result<Any> { return apiCall { service.editGroupName( "$url${GroupService.API_EDIT_GROUP_NAME}", mapOf( "id" to gid, "name" to name, "publicName" to publicName ) ) } } override suspend fun editNicknameInGroup(url: String?, gid: Long, name: String): Result<Any> { return apiCall { service.editNicknameInGroup( "$url${GroupService.API_EDIT_NICKNAME_IN_GROUP}", mapOf( "id" to gid, "memberName" to name ) ) } } override suspend fun inviteMembers( url: String?, gid: Long, members: List<String> ): Result<Any> { return apiCall { service.inviteMembers( "$url${GroupService.API_INVITE_MEMBERS}", mapOf( "id" to gid, "newMemberIds" to members ) ) } } override suspend fun removeMembers( url: String?, gid: Long, members: List<String> ): Result<StringList> { return apiCall { service.removeMembers( "$url${GroupService.API_REMOVE_MEMBERS}", mapOf( "id" to gid, "memberIds" to members ) ) } } override suspend fun getGroupUser( url: String?, gid: Long, address: String ): Result<GroupUserPO> { val result = apiCall { service.getGroupUser( "$url${GroupService.API_GROUP_USER_INFO}", mapOf("id" to gid, "memberId" to address) ) } return if (result.isSucceed()) { Result.Success(result.data().toPO(gid)) } else { Result.Error(result.error()) } } override suspend fun getGroupUserList(url: String?, gid: Long): Result<List<GroupUserPO>> { val result = apiCall { service.getGroupUserList( "$url${GroupService.API_GROUP_USER_LIST}", mapOf("id" to gid) ) } return if (result.isSucceed()) { Result.Success(result.data().members.map { it.toPO(gid) }) } else { Result.Error(result.error()) } } override suspend fun getGroupInfo(url: String?, gid: Long): Result<GroupInfoTO> { return apiCall { service.getGroupInfo( "$url${GroupService.API_GROUP_INFO}", mapOf("id" to gid) ) } } override suspend fun getGroupPubInfo( url: String?, gid: Long, ): Result<GroupInfoTO> { return apiCall { service.getGroupPubInfo( "$url${GroupService.API_GROUP_PUB_INFO}", mapOf("id" to gid) ) } } override suspend fun joinGroup(url: String?, gid: Long, inviterId: String?): Result<Any> { return apiCall { service.getGroupPubInfo( "$url${GroupService.API_JOIN_GROUP}", mapOf("id" to gid, "inviterId" to inviterId.orEmpty()) ) } } override suspend fun getGroupList(url: String): Result<GroupInfoTO.Wrapper> { return apiCall { service.getGroupList("$url${GroupService.API_GROUP_LIST}") } } override suspend fun changeGroupOwner(url: String?, gid: Long, address: String): Result<Any> { return apiCall { service.changeGroupOwner( "$url${GroupService.API_CHANGE_OWNER}", mapOf( "id" to gid, "memberId" to address ) ) } } override suspend fun changeGroupUserRole( url: String?, gid: Long, address: String, role: Int ): Result<Any> { return apiCall { service.changeGroupUserRole( "$url${GroupService.API_GROUP_ROLE}", mapOf( "id" to gid, "memberId" to address, "memberType" to role ) ) } } override suspend fun changeFriendType(url: String?, gid: Long, friendType: Int): Result<Any> { return apiCall { service.changeFriendType( "$url${GroupService.API_FRIEND_TYPE}", mapOf( "id" to gid, "friendType" to friendType ) ) } } override suspend fun changeJoinType(url: String?, gid: Long, joinType: Int): Result<Any> { return apiCall { service.changeJoinType( "$url${GroupService.API_JOIN_TYPE}", mapOf( "id" to gid, "joinType" to joinType ) ) } } override suspend fun changeMuteType(url: String?, gid: Long, muteType: Int): Result<Any> { return apiCall { service.changeMuteType( "$url${GroupService.API_MUTE_TYPE}", mapOf( "id" to gid, "muteType" to muteType ) ) } } override suspend fun changeMuteTime( url: String?, gid: Long, muteTime: Long, members: List<String> ): Result<GroupUserTO.Wrapper> { return apiCall { service.changeMuteTime( "$url${GroupService.API_MUTE_TIME}", mapOf( "id" to gid, "muteTime" to muteTime, "memberIds" to members ) ) } } override suspend fun exitGroup(url: String?, gid: Long): Result<Any> { return apiCall { service.exitGroup( "$url${GroupService.API_GROUP_EXIT}", mapOf("id" to gid) ) } } override suspend fun disbandGroup(url: String?, gid: Long): Result<Any> { return apiCall { service.disbandGroup( "$url${GroupService.API_GROUP_DISBAND}", mapOf("id" to gid) ) } } }
0
Kotlin
1
1
6a3c6edf6ae341199764d4d08dffd8146877678b
7,877
ChatPro-Android
MIT License
chat-core/src/main/java/com/fzm/chat/core/net/source/impl/NetGroupDataSource.kt
txchat
507,831,442
false
{"Kotlin": 2234450, "Java": 384844}
package com.fzm.chat.core.net.source.impl import com.fzm.chat.core.data.bean.GroupInfoTO import com.fzm.chat.core.data.bean.GroupUserTO import com.fzm.chat.core.data.bean.StringList import com.fzm.chat.core.data.bean.toPO import com.fzm.chat.core.data.po.GroupUserPO import com.fzm.chat.core.net.api.GroupService import com.fzm.chat.core.net.source.GroupDataSource import com.zjy.architecture.data.Result import com.zjy.architecture.ext.apiCall /** * @author zhengjy * @since 2021/05/11 * Description: */ class NetGroupDataSource( private val service: GroupService ) : GroupDataSource { override suspend fun createGroup( url: String, name: String, users: List<String> ): Result<GroupInfoTO> { return apiCall { service.createGroup( "$url${GroupService.API_CREATE_GROUP}", mapOf( "name" to name, "memberIds" to users ) ) } } override suspend fun editGroupAvatar(url: String?, gid: Long, avatar: String): Result<Any> { return apiCall { service.editGroupAvatar( "$url${GroupService.API_EDIT_GROUP_AVATAR}", mapOf( "id" to gid, "avatar" to avatar ) ) } } override suspend fun editGroupName(url: String?, gid: Long, name: String): Result<Any> { return apiCall { service.editGroupName( "$url${GroupService.API_EDIT_GROUP_NAME}", mapOf( "id" to gid, "name" to name ) ) } } override suspend fun editGroupNames(url: String?, gid: Long, name: String, publicName: String): Result<Any> { return apiCall { service.editGroupName( "$url${GroupService.API_EDIT_GROUP_NAME}", mapOf( "id" to gid, "name" to name, "publicName" to publicName ) ) } } override suspend fun editNicknameInGroup(url: String?, gid: Long, name: String): Result<Any> { return apiCall { service.editNicknameInGroup( "$url${GroupService.API_EDIT_NICKNAME_IN_GROUP}", mapOf( "id" to gid, "memberName" to name ) ) } } override suspend fun inviteMembers( url: String?, gid: Long, members: List<String> ): Result<Any> { return apiCall { service.inviteMembers( "$url${GroupService.API_INVITE_MEMBERS}", mapOf( "id" to gid, "newMemberIds" to members ) ) } } override suspend fun removeMembers( url: String?, gid: Long, members: List<String> ): Result<StringList> { return apiCall { service.removeMembers( "$url${GroupService.API_REMOVE_MEMBERS}", mapOf( "id" to gid, "memberIds" to members ) ) } } override suspend fun getGroupUser( url: String?, gid: Long, address: String ): Result<GroupUserPO> { val result = apiCall { service.getGroupUser( "$url${GroupService.API_GROUP_USER_INFO}", mapOf("id" to gid, "memberId" to address) ) } return if (result.isSucceed()) { Result.Success(result.data().toPO(gid)) } else { Result.Error(result.error()) } } override suspend fun getGroupUserList(url: String?, gid: Long): Result<List<GroupUserPO>> { val result = apiCall { service.getGroupUserList( "$url${GroupService.API_GROUP_USER_LIST}", mapOf("id" to gid) ) } return if (result.isSucceed()) { Result.Success(result.data().members.map { it.toPO(gid) }) } else { Result.Error(result.error()) } } override suspend fun getGroupInfo(url: String?, gid: Long): Result<GroupInfoTO> { return apiCall { service.getGroupInfo( "$url${GroupService.API_GROUP_INFO}", mapOf("id" to gid) ) } } override suspend fun getGroupPubInfo( url: String?, gid: Long, ): Result<GroupInfoTO> { return apiCall { service.getGroupPubInfo( "$url${GroupService.API_GROUP_PUB_INFO}", mapOf("id" to gid) ) } } override suspend fun joinGroup(url: String?, gid: Long, inviterId: String?): Result<Any> { return apiCall { service.getGroupPubInfo( "$url${GroupService.API_JOIN_GROUP}", mapOf("id" to gid, "inviterId" to inviterId.orEmpty()) ) } } override suspend fun getGroupList(url: String): Result<GroupInfoTO.Wrapper> { return apiCall { service.getGroupList("$url${GroupService.API_GROUP_LIST}") } } override suspend fun changeGroupOwner(url: String?, gid: Long, address: String): Result<Any> { return apiCall { service.changeGroupOwner( "$url${GroupService.API_CHANGE_OWNER}", mapOf( "id" to gid, "memberId" to address ) ) } } override suspend fun changeGroupUserRole( url: String?, gid: Long, address: String, role: Int ): Result<Any> { return apiCall { service.changeGroupUserRole( "$url${GroupService.API_GROUP_ROLE}", mapOf( "id" to gid, "memberId" to address, "memberType" to role ) ) } } override suspend fun changeFriendType(url: String?, gid: Long, friendType: Int): Result<Any> { return apiCall { service.changeFriendType( "$url${GroupService.API_FRIEND_TYPE}", mapOf( "id" to gid, "friendType" to friendType ) ) } } override suspend fun changeJoinType(url: String?, gid: Long, joinType: Int): Result<Any> { return apiCall { service.changeJoinType( "$url${GroupService.API_JOIN_TYPE}", mapOf( "id" to gid, "joinType" to joinType ) ) } } override suspend fun changeMuteType(url: String?, gid: Long, muteType: Int): Result<Any> { return apiCall { service.changeMuteType( "$url${GroupService.API_MUTE_TYPE}", mapOf( "id" to gid, "muteType" to muteType ) ) } } override suspend fun changeMuteTime( url: String?, gid: Long, muteTime: Long, members: List<String> ): Result<GroupUserTO.Wrapper> { return apiCall { service.changeMuteTime( "$url${GroupService.API_MUTE_TIME}", mapOf( "id" to gid, "muteTime" to muteTime, "memberIds" to members ) ) } } override suspend fun exitGroup(url: String?, gid: Long): Result<Any> { return apiCall { service.exitGroup( "$url${GroupService.API_GROUP_EXIT}", mapOf("id" to gid) ) } } override suspend fun disbandGroup(url: String?, gid: Long): Result<Any> { return apiCall { service.disbandGroup( "$url${GroupService.API_GROUP_DISBAND}", mapOf("id" to gid) ) } } }
0
Kotlin
1
1
6a3c6edf6ae341199764d4d08dffd8146877678b
7,877
ChatPro-Android
MIT License
sdk/src/main/kotlin/org/arnhold/sdk/tools/shacl/ShaclValidationService.kt
larnhold
695,175,294
false
null
package org.arnhold.sdk.tools.shacl import org.apache.jena.rdf.model.Model import org.apache.jena.rdf.model.ModelFactory import org.apache.jena.riot.Lang import org.apache.jena.riot.RDFDataMgr import org.apache.jena.shacl.ShaclValidator import org.apache.jena.shacl.Shapes import org.apache.jena.shacl.ValidationReport import org.apache.jena.shacl.validation.ReportEntry import org.apache.jena.vocabulary.XSD import org.arnhold.sdk.model.SoftareAgents import org.arnhold.sdk.vocab.dqv.* import org.springframework.stereotype.Service import java.io.FileInputStream import java.nio.file.Path @Service class ShaclValidationService { fun validateShape(dmp: Model, shapesPath: Path, metric: Metric, dmpRoot: DMPLocation, lifecycle: DmpLifecycle ): List<Measurement> { val shapesModel = ModelFactory.createOntologyModel() val extensionInputStream = FileInputStream(shapesPath.toFile()) RDFDataMgr.read(shapesModel, extensionInputStream, Lang.TURTLE) val shapes = Shapes.parse(shapesModel) val graph = dmp.graph val report: ValidationReport = ShaclValidator.get().validate(shapes, graph) return if (report.conforms()) { listOf(getConformsMetric(lifecycle, dmpRoot, metric)) } else { report.entries.map { createNotConfirmMeasurement(dmp, lifecycle, metric, it)} } } private fun getConformsMetric(lifecycle: DmpLifecycle, dmpRoot: DMPLocation, metric: Metric): Measurement { return Measurement( lifecycle, metric, null, dmpRoot, true, SoftareAgents.SHACL_AGENT, ArrayList() ) } private fun createNotConfirmMeasurement(dmp: Model, lifecycle: DmpLifecycle, metric: Metric, report: ReportEntry): Measurement { val missingProperty = report.resultPath().toString() val guidance = Guidance("SHACL Report", missingProperty + ": " + report.message()) val location = DMPLocation(report.focusNode().toString(), null) val shaclTestDefinition = MetricTestDefinition( identifier = report.source().toString(), title = "SHACL Shape", description = "A reference to the SHACL shape used for evaluation", expectedDataType = XSD.xboolean.toString() ) val testResult = TestResult( testDefinition = shaclTestDefinition, value = false ) //metric.metricTests.add(shaclTestDefinition) return Measurement( lifecycle, metric, guidance, location, false, SoftareAgents.SHACL_AGENT, null ) } }
0
null
0
2
8551cab14415f90af8a91e6325814e9c0dd6e6a9
2,815
maDMP-Assesment
MIT License
app/src/main/java/com/nambv/android_mvvm/data/model/CarSearchResponse.kt
nambv
837,487,074
false
{"Kotlin": 36092}
package com.nambv.android_mvvm.data.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class CarSearchResponseItem( @SerialName("colour") val colour: String? = null, @SerialName("description") val description: String = "", @SerialName("firstRegistration") val firstRegistration: String?? = null, @SerialName("fuel") val fuel: String = "", @SerialName("id") val id: Int = 0, @SerialName("make") val make: String = "", @SerialName("mileage") val mileage: Int? = null, @SerialName("model") val model: String = "", @SerialName("modelline") val modelline: String = "", @SerialName("price") val price: Int = 0, @SerialName("seller") val seller: Seller? = null, @SerialName("images") val images: List<Image>? = null, ) @Serializable data class Image( @SerialName("url") val url: String? = null, ) @Serializable data class Seller( @SerialName("city") val city: String? = null, @SerialName("phone") val phone: String? = null, @SerialName("type") val type: String? = null, )
0
Kotlin
0
0
cdf3e22e672f4159473cf8c3dade9b2390750618
1,088
android_mvvm_jetpack
Apache License 2.0
src/main/kotlin/ru/demo/ConsumerApp.kt
BornToNight
712,992,688
false
{"Kotlin": 4934}
package ru.demo import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.runApplication @SpringBootApplication class ConsumerApp fun main(args: Array<String>) { runApplication<ConsumerApp>(*args) }
0
Kotlin
0
0
9402064c31fdbbb8e2d5296dfab9569e1d94b290
247
spring-kafka-kotlin-consumer-example
Apache License 2.0
app/src/main/java/com/arthurivanets/demo/util/providers/PersonProvider.kt
arthur3486
172,364,974
false
null
/* * Copyright 2017 <NAME>, <EMAIL> * * 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.arthurivanets.demo.util.providers import com.arthurivanets.demo.R import com.arthurivanets.demo.model.Person object PersonProvider { fun getPeople() : List<Person> { return listOf( Person( id = 1L, username = "danicajohns", fullName = "<NAME>", imageResourceId = R.drawable.ic_woman_1 ), Person( id = 2L, username = "harryaguilar", fullName = "<NAME>", imageResourceId = R.drawable.ic_man_2 ), Person( id = 3L, username = "houstonroth", fullName = "<NAME>", imageResourceId = R.drawable.ic_man_3 ), Person( id = 4L, username = "george41", fullName = "<NAME>", imageResourceId = R.drawable.ic_man_4 ) ) } }
4
Java
11
77
761fd76b1f0bcec119c34a7ad41468c847816522
1,599
bottomsheets
Apache License 2.0
src/main/kotlin/com/bastronaut/traderboard/exchange/binance/BinanceExchangeClient.kt
bastronaut
127,566,728
false
null
package com.bastronaut.traderboard.exchange.binance import com.bastronaut.traderboard.exchange.ExchangeClient import com.bastronaut.traderboard.exchange.OrderBook import com.bastronaut.traderboard.exchange.OrderBookEntryImpl import com.bastronaut.traderboard.exchange.OrderBookImpl import com.binance.api.client.BinanceApiClientFactory import com.binance.api.client.BinanceApiRestClient class BinanceExchangeClient (private val apiKey: String, private val apiSecret: String) : ExchangeClient { private val client: BinanceApiRestClient private val DEFAULTORDERBOOKLIMIT = 10 init { val factory = BinanceApiClientFactory.newInstance(apiKey, apiSecret) val client = factory.newRestClient() this.client = client } override fun getServerTime() { val serverTime = this.client.serverTime print(serverTime) } override fun ping() { this.client.ping() } override fun getOrderBook(symbol: String): OrderBook { val orderBook = this.client.getOrderBook(symbol, DEFAULTORDERBOOKLIMIT) val asks = orderBook.asks val bids = orderBook.bids val wrappedAsks = asks.map{ OrderBookEntryImpl(it.price, it.qty) } val wrappedBids = bids.map { OrderBookEntryImpl(it.price, it.qty) } // val ask = OrderBookEntryImpl("5", "1") // val bid = OrderBookEntryImpl("5", "1") return OrderBookImpl(wrappedAsks, wrappedBids) // return OrderBookImpl(listOf(ask), listOf(bid)) } }
0
Kotlin
0
0
5ba1c9e2969eddcf2ba62e026fbbf68999cdd417
1,562
traderboard
MIT License
SERVER/src/main/kotlin/com/konix/util/OrderExceptionHandler.kt
singhtwenty2
809,094,089
false
{"Kotlin": 369846, "Dockerfile": 414}
package com.konix.util class InsufficientBalanceException(message: String) : Exception(message) class DematAccountNotFoundException(message: String) : Exception(message) class InsufficientStockException(message: String) : Exception(message) class OrderNotFoundException(message: String) : Exception(message) class OrderAlreadyExistsException(message: String) : Exception(message) class OrderStatusChangeException(message: String) : Exception(message) class OrderTypeChangeException(message: String) : Exception(message) class OrderQuantityChangeException(message: String) : Exception(message) class OrderPriceChangeException(message: String) : Exception(message) class OrderCompanyChangeException(message: String) : Exception(message) class OrderUserChangeException(message: String) : Exception(message) class OrderCreationException(message: String) : Exception(message) class OrderUpdateException(message: String) : Exception(message) class OrderDeletionException(message: String) : Exception(message)
0
Kotlin
0
1
b744b0797548d2c1dbec21ba684b4691471dbfc4
1,003
konix-TEP
MIT License
data/src/main/java/com/semicolon/data/local/entity/user/UserMyPageRoomEntity.kt
Walkhub
443,006,389
false
null
package com.semicolon.data.local.entity.user import androidx.room.Embedded import androidx.room.Entity import androidx.room.PrimaryKey import com.semicolon.data.remote.response.users.FetchUserProfileResponse import com.semicolon.domain.entity.users.UserMyPageEntity import com.semicolon.domain.entity.users.UserProfileEntity @Entity(tableName = "userMyPage") data class UserMyPageRoomEntity( @PrimaryKey val userId: Int, val name: String, val profileImageUrl: String, val schoolName: String, val grade: Int, val classNum: Int, @Embedded val titleBadge: TitleBadge, @Embedded val level: Level ) { data class TitleBadge( val badgeId: Int, val badgeName: String, val badgeImageUrl: String ) data class Level( val levelName: String, val levelImageUrl: String ) fun TitleBadge.toEntity() = UserMyPageEntity.TitleBadge( badgeId = badgeId, badgeName = badgeName, badgeImageUrl = badgeImageUrl ) fun Level.toEntity() = UserMyPageEntity.Level( levelName = levelName, levelImageUrl = levelImageUrl ) } fun UserMyPageRoomEntity.toEntity() = UserMyPageEntity( userId = userId, name = name, profileImageUrl = profileImageUrl, schoolName = schoolName, grade = grade, classNum = classNum, titleBadge = titleBadge.toEntity(), level = level.toEntity() ) fun UserMyPageEntity.TitleBadge.toDbEntity() = UserMyPageRoomEntity.TitleBadge( badgeId = badgeId, badgeName = badgeName, badgeImageUrl = badgeImageUrl ) fun UserMyPageEntity.Level.toDbEntity() = UserMyPageRoomEntity.Level( levelName = levelName, levelImageUrl = levelImageUrl ) fun UserMyPageEntity.toDbEntity() = UserMyPageRoomEntity( userId = userId, name = name, profileImageUrl = profileImageUrl, schoolName = schoolName, grade = grade, classNum = classNum, titleBadge = titleBadge.toDbEntity(), level = level.toDbEntity() )
30
Kotlin
1
15
c2d85ebb9ae8b200be22e9029dcfdcbfed19e473
2,163
walkhub_android
MIT License
testapp/src/main/java/info/ljungqvist/yaol/testapp/MainActivity.kt
ljungqvist
153,159,722
false
null
package info.ljungqvist.yaol.testapp import android.content.Context import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.databinding.ObservableField import info.ljungqvist.yaol.android.observableField import info.ljungqvist.yaol.android.preferences.createObservablePreferenceFactory import info.ljungqvist.yaol.lazyMutableWrapper import info.ljungqvist.yaol.testapp.databinding.ActivityMainBinding import info.ljungqvist.yaol.toData class MainActivity : AppCompatActivity() { private val prefHolder by lazy { PrefHolder(this) } private var testProperty by lazyMutableWrapper { prefHolder.testProperty } private var testProperty2 by lazyMutableWrapper { prefHolder.testProperty2 } private var combo by lazyMutableWrapper { prefHolder.combo } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding: ActivityMainBinding = DataBindingUtil.setContentView(this, R.layout.activity_main) binding.data = Data( prefHolder.testProperty.observableField(), prefHolder.testProperty.join(prefHolder.testProperty2, prefHolder.combo) { text1, text2, (textcombo1, textcombo2) -> "$text1, $text2, ($textcombo1, $textcombo2)" }.observableField() ) binding.button1.setOnClickListener { testProperty = "text 1" } binding.button2.setOnClickListener { testProperty2 = "text 2" } binding.button3.setOnClickListener { combo = "first text 3" to "second text 3" } } data class Data( val value: ObservableField<String>, val value2: ObservableField<String> ) } private class PrefHolder(context: Context) { private val prefFactory = context.createObservablePreferenceFactory("TEST") val testProperty = prefFactory.stringPreference("property") { "" } val testProperty2 = prefFactory.stringOptPreference("property2") val combo = testProperty.twoWayJoin( testProperty2, ::Pair ) { _, pair -> pair.toData() } }
0
Kotlin
0
0
ba08b17572844619fba64a04558fed7278ad9863
2,212
yaol
Apache License 2.0
app/src/main/java/com/test/currentweather/model/Clouds.kt
hardz
527,451,828
false
null
package com.test.currentweather.model import com.squareup.moshi.Json import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Clouds( @Json(name = "all") val all: Int )
0
Kotlin
0
0
c7e7e4ae04474df6235c0a7ce73964ed5753f817
204
Weather
Apache License 2.0
presentation/src/main/java/com/ragdroid/mvi/main/MainFragment.kt
ragdroid
113,446,060
false
null
package com.ragdroid.mvi.main import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.ragdroid.mvvmi.core.NavigationState import com.fueled.reclaim.ItemPresenterProvider import com.fueled.reclaim.ItemsViewAdapter import com.google.android.material.snackbar.Snackbar import com.jakewharton.rxbinding2.support.v4.widget.refreshes import com.ragdroid.mvi.R import com.ragdroid.mvi.databinding.FragmentMainBinding import com.ragdroid.mvi.helpers.BindFragment import com.ragdroid.mvi.items.CharacterItem import com.ragdroid.mvi.models.CharacterItemPresenter import com.ragdroid.mvi.viewmodel.MainFragmentViewModel import com.ragdroid.mvvmi.core.MviView import dagger.android.support.DaggerFragment import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.processors.PublishProcessor import timber.log.Timber import javax.inject.Inject /** * A placeholder fragment containing a simple view. */ class MainFragment : DaggerFragment(), ItemPresenterProvider<CharacterItemPresenter>, CharacterItemPresenter, MviView<MainAction, MainViewState> { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory //delegate the binding initialization to BindFragment delegate private val binding: FragmentMainBinding by BindFragment(R.layout.fragment_main) private val adapter: ItemsViewAdapter by lazy(LazyThreadSafetyMode.NONE) { ItemsViewAdapter(context) } private val descriptionClickProcessor: PublishProcessor<MainAction.LoadDescription> = PublishProcessor.create() override lateinit var viewModel: MainFragmentViewModel override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val manager = LinearLayoutManager(context) val decoration = DividerItemDecoration(context, RecyclerView.VERTICAL) manager.orientation = RecyclerView.VERTICAL binding.listView.layoutManager = manager binding.listView.adapter = adapter binding.listView.addItemDecoration(decoration) setupViewModel() super.onMviViewCreated(savedInstanceState) } override fun provideActions() = Flowable.merge(loadingIntent(), pullToRefreshIntent(), loadDescription()) private fun setupViewModel() { viewModel = ViewModelProviders.of(this, viewModelFactory).get(MainFragmentViewModel::class.java) } override fun onCharacterDescriptionClicked(itemId: Long) { descriptionClickProcessor.onNext(MainAction.LoadDescription(itemId)) } override fun getItemPresenter(): CharacterItemPresenter { return this } private fun pullToRefreshIntent(): Flowable<MainAction.PullToRefresh> = binding.refreshLayout.refreshes().toFlowable(BackpressureStrategy.DROP).map { MainAction.PullToRefresh } private fun loadingIntent(): Flowable<MainAction.LoadData> = Flowable.just(MainAction.LoadData) private fun loadDescription(): Flowable<MainAction.LoadDescription> { return descriptionClickProcessor } override fun render(state: MainViewState) { Timber.d("got state $state") binding.model = state when { state.pullToRefreshError != null -> return state.loadingError != null -> { adapter.clearAllRecyclerItems() return } else -> { val characterModelList = state.characters.map { CharacterItem(it, this) } adapter.replaceItems(characterModelList, true) } } } override val lifecycleOwner: LifecycleOwner get() = this override fun navigate(navigationState: NavigationState) { when (navigationState) { is MainNavigation.Snackbar -> Snackbar.make(binding.root, navigationState.message, Snackbar.LENGTH_SHORT) else -> {//do nothing } } } }
3
Kotlin
7
82
b4b8faa15cffe48c985da1da0463a8a2b67c21a4
4,555
klayground
MIT License
presentation/src/main/java/com/ragdroid/mvi/main/MainFragment.kt
ragdroid
113,446,060
false
null
package com.ragdroid.mvi.main import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.ViewModelProvider import androidx.lifecycle.ViewModelProviders import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.ragdroid.mvvmi.core.NavigationState import com.fueled.reclaim.ItemPresenterProvider import com.fueled.reclaim.ItemsViewAdapter import com.google.android.material.snackbar.Snackbar import com.jakewharton.rxbinding2.support.v4.widget.refreshes import com.ragdroid.mvi.R import com.ragdroid.mvi.databinding.FragmentMainBinding import com.ragdroid.mvi.helpers.BindFragment import com.ragdroid.mvi.items.CharacterItem import com.ragdroid.mvi.models.CharacterItemPresenter import com.ragdroid.mvi.viewmodel.MainFragmentViewModel import com.ragdroid.mvvmi.core.MviView import dagger.android.support.DaggerFragment import io.reactivex.BackpressureStrategy import io.reactivex.Flowable import io.reactivex.processors.PublishProcessor import timber.log.Timber import javax.inject.Inject /** * A placeholder fragment containing a simple view. */ class MainFragment : DaggerFragment(), ItemPresenterProvider<CharacterItemPresenter>, CharacterItemPresenter, MviView<MainAction, MainViewState> { @Inject lateinit var viewModelFactory: ViewModelProvider.Factory //delegate the binding initialization to BindFragment delegate private val binding: FragmentMainBinding by BindFragment(R.layout.fragment_main) private val adapter: ItemsViewAdapter by lazy(LazyThreadSafetyMode.NONE) { ItemsViewAdapter(context) } private val descriptionClickProcessor: PublishProcessor<MainAction.LoadDescription> = PublishProcessor.create() override lateinit var viewModel: MainFragmentViewModel override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val manager = LinearLayoutManager(context) val decoration = DividerItemDecoration(context, RecyclerView.VERTICAL) manager.orientation = RecyclerView.VERTICAL binding.listView.layoutManager = manager binding.listView.adapter = adapter binding.listView.addItemDecoration(decoration) setupViewModel() super.onMviViewCreated(savedInstanceState) } override fun provideActions() = Flowable.merge(loadingIntent(), pullToRefreshIntent(), loadDescription()) private fun setupViewModel() { viewModel = ViewModelProviders.of(this, viewModelFactory).get(MainFragmentViewModel::class.java) } override fun onCharacterDescriptionClicked(itemId: Long) { descriptionClickProcessor.onNext(MainAction.LoadDescription(itemId)) } override fun getItemPresenter(): CharacterItemPresenter { return this } private fun pullToRefreshIntent(): Flowable<MainAction.PullToRefresh> = binding.refreshLayout.refreshes().toFlowable(BackpressureStrategy.DROP).map { MainAction.PullToRefresh } private fun loadingIntent(): Flowable<MainAction.LoadData> = Flowable.just(MainAction.LoadData) private fun loadDescription(): Flowable<MainAction.LoadDescription> { return descriptionClickProcessor } override fun render(state: MainViewState) { Timber.d("got state $state") binding.model = state when { state.pullToRefreshError != null -> return state.loadingError != null -> { adapter.clearAllRecyclerItems() return } else -> { val characterModelList = state.characters.map { CharacterItem(it, this) } adapter.replaceItems(characterModelList, true) } } } override val lifecycleOwner: LifecycleOwner get() = this override fun navigate(navigationState: NavigationState) { when (navigationState) { is MainNavigation.Snackbar -> Snackbar.make(binding.root, navigationState.message, Snackbar.LENGTH_SHORT) else -> {//do nothing } } } }
3
Kotlin
7
82
b4b8faa15cffe48c985da1da0463a8a2b67c21a4
4,555
klayground
MIT License
src/main/kotlin/de/sambalmueslie/openevent/core/model/EventInfo.kt
Black-Forrest-Development
542,810,521
false
null
package de.sambalmueslie.openevent.core.model import io.micronaut.serde.annotation.Serdeable @Serdeable data class EventInfo( val event: Event, val location: Location?, val registration: Registration?, val categories: List<Category> )
0
Kotlin
0
1
170c860ce1ac4499a8e7ee63cf4134fb38d29924
253
open-event
Apache License 2.0
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/filled/PersonArrowLeft.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.filled import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Filled.PersonArrowLeft: ImageVector get() { if (_personArrowLeft != null) { return _personArrowLeft!! } _personArrowLeft = fluentIcon(name = "Filled.PersonArrowLeft") { fluentPath { moveTo(17.5f, 12.0f) arcToRelative(5.5f, 5.5f, 0.0f, true, true, 0.0f, 11.0f) arcToRelative(5.5f, 5.5f, 0.0f, false, true, 0.0f, -11.0f) close() moveTo(12.02f, 14.0f) arcToRelative(6.47f, 6.47f, 0.0f, false, false, 0.6f, 7.8f) curveToRelative(-0.8f, 0.13f, -1.68f, 0.2f, -2.62f, 0.2f) curveToRelative(-2.89f, 0.0f, -5.13f, -0.66f, -6.7f, -2.0f) arcTo(3.75f, 3.75f, 0.0f, false, true, 2.0f, 17.16f) verticalLineToRelative(-0.91f) curveTo(2.0f, 15.01f, 3.01f, 14.0f, 4.25f, 14.0f) horizontalLineToRelative(7.77f) close() moveTo(16.72f, 14.59f) lineToRelative(-0.07f, 0.06f) lineToRelative(-2.52f, 2.51f) lineToRelative(-0.04f, 0.05f) lineToRelative(-0.03f, 0.06f) lineToRelative(-0.03f, 0.08f) lineToRelative(-0.01f, 0.04f) lineToRelative(-0.02f, 0.09f) verticalLineToRelative(0.09f) lineToRelative(0.03f, 0.08f) lineToRelative(0.03f, 0.08f) lineToRelative(0.02f, 0.04f) lineToRelative(0.05f, 0.07f) lineToRelative(2.52f, 2.51f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.76f, -0.63f) lineToRelative(-0.05f, -0.07f) lineTo(15.7f, 18.0f) horizontalLineToRelative(4.79f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.5f, -0.41f) verticalLineToRelative(-0.09f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.41f, -0.5f) horizontalLineToRelative(-4.88f) lineToRelative(1.65f, -1.65f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, 0.05f, -0.63f) lineToRelative(-0.05f, -0.07f) arcToRelative(0.5f, 0.5f, 0.0f, false, false, -0.64f, -0.06f) close() moveTo(10.0f, 2.0f) arcToRelative(5.0f, 5.0f, 0.0f, true, true, 0.0f, 10.0f) arcToRelative(5.0f, 5.0f, 0.0f, false, true, 0.0f, -10.0f) close() } } return _personArrowLeft!! } private var _personArrowLeft: ImageVector? = null
0
Kotlin
0
24
336c85b59b6a6ad97a522a25a0042cd8e0750474
2,886
compose-fluent-ui
Apache License 2.0
src/commonTest/kotlin/io/github/nomisrev/Arb.kt
nomisRev
486,725,431
false
{"Kotlin": 40730}
package io.github.nomisrev import io.kotest.property.Arb import io.kotest.property.arbitrary.boolean import io.kotest.property.arbitrary.choice import io.kotest.property.arbitrary.constant import io.kotest.property.arbitrary.double import io.kotest.property.arbitrary.filterNot import io.kotest.property.arbitrary.float import io.kotest.property.arbitrary.int import io.kotest.property.arbitrary.list import io.kotest.property.arbitrary.long import io.kotest.property.arbitrary.map import io.kotest.property.arbitrary.string import kotlinx.serialization.SerializationStrategy import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.serializer fun Arb.Companion.street(): Arb<Street> = Arb.string().map(::Street) fun Arb.Companion.city(): Arb<City> = Arb.list(street()).map(::City) fun Arb.Companion.jsInt(): Arb<JsonPrimitive> = int().map(::JsonPrimitive) fun Arb.Companion.jsLong(): Arb<JsonPrimitive> = long().map(::JsonPrimitive) fun Arb.Companion.jsFloat(): Arb<JsonPrimitive> = float().filterNot(Float::isNaN).map(::JsonPrimitive) fun Arb.Companion.jsDouble(): Arb<JsonPrimitive> = double().filterNot(Double::isNaN).map(::JsonPrimitive) fun Arb.Companion.jsString(): Arb<JsonPrimitive> = Arb.string().map(::JsonPrimitive) fun Arb.Companion.jsBoolean(): Arb<JsonPrimitive> = boolean().map(::JsonPrimitive) fun Arb.Companion.jsNull(): Arb<JsonNull> = constant(JsonNull) private fun genJson(): Arb<JsonElement> = Arb.choice(Arb.jsInt(), Arb.jsLong(), Arb.jsDouble(), Arb.jsString(), Arb.jsNull()) fun Arb.Companion.jsArray(): Arb<JsonArray> = list(genJson()).map(::JsonArray) fun <T> Arb.Companion.jsArray(valid: Arb<T>, EN: SerializationStrategy<T>): Arb<JsonArray> = list(valid).map { list -> JsonArray(list.map { elem -> Json.encodeToJsonElement(EN, elem) }) } inline fun <reified T> Arb.Companion.jsArray(valid: Arb<T>): Arb<JsonArray> = jsArray(valid, serializer()) fun Arb.Companion.jsObject(): Arb<JsonObject> = map(Arb.string(), genJson()).map(::JsonObject) fun <T> Arb.Companion.json(valid: Arb<T>, EN: SerializationStrategy<T>): Arb<JsonElement> = valid.map { Json.encodeToJsonElement(EN, it) } inline fun <reified T> Arb.Companion.json(valid: Arb<T>): Arb<JsonElement> = json(valid, serializer()) fun Arb.Companion.json(): Arb<JsonElement> = choice( Arb.jsInt(), Arb.jsLong(), Arb.jsDouble(), Arb.jsString(), Arb.jsNull(), Arb.jsArray(), Arb.jsObject(), )
9
Kotlin
2
35
9d3125957cf45958e7d3de843503f07de98200d8
2,671
kotlinx-serialization-jsonpath
Apache License 2.0
app/src/main/java/com/justwayward/reader/bean/ChapterRead.kt
petma
198,171,907
true
{"Kotlin": 1560776, "Java": 34640, "JavaScript": 31488, "HTML": 5286, "CSS": 4040}
/** * Copyright 2016 JustWayward Team * * * 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.justwayward.reader.bean import com.justwayward.reader.bean.base.Base import java.io.Serializable /** * @author yuyh. * @date 2016/8/4. */ class ChapterRead : Base() { /** * title : 1,相亲 * body : 月湾咖啡厅,苏锦一进门就瞧见了那个相亲对象。 * 他正坐在向阳的9号桌上。 * 身上穿的是一件大海蓝的衬衫,没系领带,发型清爽,五官端正,淡淡的阳光照在他脸上,衬得他冷峻毕露。 * 乍一看,威势十足,竟惹得边上几个年轻小姑娘频频侧目。 * 这人,的确长着一副好皮囊,怪不得王阿婆一个劲儿的向她夸: * “你只要见,保管觉得好。那种人,只有他挑人,没人会挑他的。” * 现在看来好像有点道理。 * 门口,有道长廊镜,苏锦转头看了看自己这身打扮。 * 长款黑色雪纺衬衣,底下配一条白色九分裤,露着白藕似的胳膊,最能显示女性魅力的中发被她扎成了马尾,清水芙蓉似的脸孔,没上妆,显得素净清秀。 * 先头,王阿婆一个劲儿的叮嘱她:“去的时候,打扮打扮!那孩子眼界高着呢!” * 她没打扮,素面朝天,这才是最真实的她。 * “你好,我叫苏锦!你是靳恒远先生吗?” * 苏锦走了过去,声音温温婉婉。 * 正在用手机看着股市行情的男人抬起头,看到她时,目光闪了一下,站起时收了手机微一笑。 * 这一笑,让他那显得疏离的脸孔多了几分亲切。 * “对,我是靳恒远!苏小姐是吗?请坐!” * 靳恒远很绅士的给她拉开椅子,嗓音低低富有磁性,极为好听。 * “谢谢!” * 苏锦坐下,点了一杯咖啡,呷了几口,才说话:“靳先生的一些生平,我多少听王阿婆说了一些。” * 男人正打量她,她有点不自在的捋了捋耳边的发。 * 相亲相亲,总得让人看的。 * 好在,他的目光并不让人觉得讨厌。 * “哦,不知道王婆是怎么自卖自夸的?” * 靳恒远挺风趣的反问。 * 苏锦扯了扯嘴角。 * 其实她所知甚少。 * “靳先生今年三十二岁了是吗?” * 比她大了足足六岁,算是个老男人了。 * 不过见到本人,看着挺年轻。 * “嗯!” * “像靳先生这样仪表堂堂的男士,怎么会至今未婚?” * “工作太忙,耽误了,等到想要结婚的时候,才发现和自己年纪相仿的异性,孩子都满地跑了……” * 靳恒远微一笑,喝了一口咖啡。 * “苏小姐对相亲对象有什么要求吗?” * “我要求不高!”苏锦说:“品性要正,责任感要强,必须忠于婚姻。” * “对车房没要求?” * 靳恒远睨了一眼,那一眼,好像很有深意。 * 苏锦微微笑了一个。 * 现在女性找老公,车房已经成了标配,哪怕在这样一个小县城:女孩子谁不想嫁个家境好的男人,把日子过舒坦了。 * 要不然怎么会说结婚是女人第二次投胎? * 第一次谁也没得选择,第二次必须千挑万选,这要选错了,那一辈子就全毁了。 * 只是苏锦的心,早死了,如今的她,相亲,只是为了给母亲一个交代。 * “没要求。” * 她吐出三字。 * …… * 淡淡的咖啡香,飘散在空气中,两个陌生的男女,不咸不淡聊着天。 * 过了一会儿,苏锦看了一下手表: * “靳先生,该了解的,我们都已经谈了,如果你认为我们合适,我想明天就去领证。” * 靳恒远眉一挑,但笑不笑:“苏小姐就这么急着结婚,不怕我是骗子?” * 苏锦淡一笑:“王阿婆眼光一向很挑,她介绍的人,一定不差。” * “苏小姐就这么相信王阿婆?” * “我信。另外,我妈妈得了肝癌,晚期。她希望在临走之前看到我找到一个好归宿。在时间上,我耗不起。” * 一般来说,没有人肯这么草率同意婚事的。 * 苏锦以为他会拒绝,这样她就可以顺水推舟了,王阿婆那边也好交待。 * “明天不行。明天我要出差,这几天都会在外地。要领下午就去。” * 靳恒远看了看手机上的钟点。 * “你要没意见,我现在回去拿证件,两点半,我们在民政局见。” * 苏锦:“……” * - - - 题外话 * - - - * 待续…… * 新文,全新尝试,喜欢的亲请多多支持,谢谢! */ var chapter: Chapter? = null class Chapter : Serializable { var title: String var body: String var cpContent: String constructor(title: String, body: String) { this.title = title this.body = body } constructor(title: String, body: String, cpContent: String) { this.title = title this.body = body this.cpContent = cpContent } } }
0
Kotlin
0
0
d011466692aae7c583ab8a264f760f7ff7d17458
3,140
BookReader-1
Apache License 2.0
src/test/kotlin/io/pivotal/intellij/jasmine/JasmineConfigIconProviderTest.kt
jasmine
120,975,529
false
null
package io.pivotal.intellij.jasmine import com.intellij.json.JsonFileType import com.intellij.openapi.util.IconLoader.CachedImageIcon import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase import org.hamcrest.CoreMatchers.endsWith import org.junit.Assert.assertThat class JasmineConfigIconProviderTest : LightPlatformCodeInsightFixtureTestCase() { fun `test shows jasmine icon for jasmine config file`() { val jasmineConfigFile = myFixture.configureByText("jasmine.json", "") val jasmineIcon = JasmineConfigIconProvider().getIcon(jasmineConfigFile, 0) as CachedImageIcon assertThat(jasmineIcon.toString(), endsWith("/icons/jasmine.png")) } fun `test does not show jasmine icon on other files`() { val jsonFile = myFixture.configureByText(JsonFileType.INSTANCE, "") val txtNamedJasmine = myFixture.configureByText("jasmine.txt", "") assertNull(JasmineConfigIconProvider().getIcon(jsonFile, 0)) assertNull(JasmineConfigIconProvider().getIcon(txtNamedJasmine, 0)) } }
5
null
5
9
9a422cf10605b59abcb8aa81b3389c9d8e13f58f
1,071
IdeaJasmine
MIT License
src/main/kotlin/com/examples/abbasdgr8/view/OrganizationsView.kt
abbasdgr8
293,219,115
false
null
package com.examples.abbasdgr8.view import com.examples.abbasdgr8.model.domain.Organization import com.examples.abbasdgr8.model.domain.Ticket import com.examples.abbasdgr8.model.domain.User import com.examples.abbasdgr8.view.ViewCommons.Companion.getFieldsWithBanner import com.examples.abbasdgr8.view.ViewCommons.Companion.getScreen import com.examples.abbasdgr8.view.ViewCommons.Companion.getSearchResults class OrganizationsView { companion object { fun getOrganizationsMenu(): String { return orgMenu } fun getOrganizationsFields(fields: List<String>): String { return getFieldsWithBanner(fields, orgFieldsBanner) } fun getSearchResults(orgs: List<Organization>): String { return getSearchResults(orgs, "Organizations") } fun getAssociationResults(org: Organization?, assocations: Pair<Set<Ticket>, Set<User>>): String { return getSearchResults(listOf(org), "Organization") + getSearchResults(assocations.first.toMutableList(), "Ticket", true) + getSearchResults(assocations.second.toMutableList(), "User", true) } private val orgMenu = getScreen("org-menu") private val orgFieldsBanner = getScreen("org-fields") } }
0
Kotlin
0
0
a979c79ee61fe014458085396cf624df7022577a
1,305
ticketing-search-app
Apache License 2.0
src/main/kotlin/icu/windea/starboundText/StarboundTextLanguage.kt
DragonKnightOfBreeze
345,884,003
false
null
package icu.windea.starboundText import com.intellij.lang.Language object StarboundTextLanguage : Language("STARBOUND_TEXT") { override fun getDisplayName() = "Starbound Text" }
0
Kotlin
0
0
598d7311ac63dd75bbb193b7a1478bd485be7255
184
Starbound-Text
MIT License
src/main/kotlin/com/mwronski/sample/payments/http/request.kt
m-wrona
149,907,527
false
null
package com.mwronski.sample.payments.http import com.mwronski.sample.payments.model.Attributes import com.mwronski.sample.payments.model.Data import com.mwronski.sample.payments.model.DataId import com.mwronski.sample.payments.model.DataType import org.hibernate.validator.constraints.Length import java.util.* import javax.validation.constraints.NotNull import javax.validation.constraints.Null /** * Request for creating new data. * Request doesn't have fields that will be set by backend during processing. * * @see com.mwronski.sample.payments.model.Data */ data class NewDataRequest( @field:NotNull(message = "Type must be set") val type: DataType, @field:Null(message = "ID must be empty") var id: DataId? = null, @field:Length(message = "OrganizationId must be set", min = 3) val organisationId: String, @field:NotNull(message = "Attributes must be set") val attributes: Attributes ) { fun toData() = Data( type = this.type, id = UUID.randomUUID().toString(), version = 0, organisationId = this.organisationId, attributes = this.attributes ) }
0
Kotlin
0
0
f3532e72b4e8f370c14f9cbb45d3b8d289652f20
1,192
sample-payment-api
MIT License
app/src/main/java/tumble/app/tumble/data/repository/preferences/DataStoreManager.kt
tumble-for-kronox
630,520,827
false
{"Kotlin": 434439}
package tumble.app.tumble.data.repository.preferences import android.content.Context import androidx.datastore.core.DataStore import androidx.datastore.preferences.core.Preferences import androidx.datastore.preferences.core.booleanPreferencesKey import androidx.datastore.preferences.core.edit import androidx.datastore.preferences.core.intPreferencesKey import androidx.datastore.preferences.core.stringPreferencesKey import androidx.datastore.preferences.preferencesDataStore import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.flow.map import tumble.app.tumble.domain.enums.Types.AppearanceType import tumble.app.tumble.domain.enums.ViewType import tumble.app.tumble.presentation.views.Settings.Notifications.NotificationOffset import javax.inject.Inject import javax.inject.Singleton import kotlin.coroutines.CoroutineContext data class CombinedData(val authSchoolId: Int? = null, val autoSignup: Boolean? = null, val viewType: ViewType? = null, val userOnBoarded: Boolean? = null, val appearance: AppearanceType? = null, val notificationOffset: NotificationOffset? = null) @Singleton class DataStoreManager @Inject constructor( @ApplicationContext private val context: Context, private val coroutineContext: CoroutineContext = Dispatchers.IO ) { private val scope = CoroutineScope(coroutineContext) private val Context.dataStore: DataStore<Preferences> by preferencesDataStore(name = "settings") private object PreferencesKeys { val AUTH_SCHOOL_ID = intPreferencesKey("auth_school_id") val USER_ON_BOARDED = booleanPreferencesKey("user_on_boarded") val NOTIFICATION_OFFSET = intPreferencesKey("notification_offset") val AUTO_SIGNUP = booleanPreferencesKey("auto_signup") val APPEARANCE = stringPreferencesKey("appearance") val VIEW_TYPE = stringPreferencesKey("view_type") } private val _authSchoolId = MutableStateFlow(-1) val authSchoolId: StateFlow<Int> = _authSchoolId private val _userOnBoarded = MutableStateFlow(false) val userOnBoarded: StateFlow<Boolean> = _userOnBoarded private val _autoSignup = MutableStateFlow(false) val autoSignup: StateFlow<Boolean> = _autoSignup private val _viewType = MutableStateFlow(ViewType.WEEK) val viewType: StateFlow<ViewType> = _viewType private val _appearance = MutableStateFlow(AppearanceType.AUTOMATIC) val appearance: StateFlow<AppearanceType> = _appearance private val _notificationOffset = MutableStateFlow(NotificationOffset.Thirty) val notificationOffset: StateFlow<NotificationOffset> = _notificationOffset init { context.dataStore.data .map { preferences -> _authSchoolId.value = preferences[PreferencesKeys.AUTH_SCHOOL_ID] ?: -1 _userOnBoarded.value = preferences[PreferencesKeys.USER_ON_BOARDED] ?: false _viewType.value = ViewType.valueOf(preferences[PreferencesKeys.VIEW_TYPE] ?: ViewType.WEEK.name) _autoSignup.value = preferences[PreferencesKeys.AUTO_SIGNUP] ?: false _appearance.value = AppearanceType.valueOf(preferences[PreferencesKeys.APPEARANCE] ?: AppearanceType.AUTOMATIC.name) _notificationOffset.value = NotificationOffset.allCases.first {it.value == (preferences[PreferencesKeys.NOTIFICATION_OFFSET]?: NotificationOffset.Thirty.value) } } .launchIn(scope) } suspend fun setAuthSchoolId(id: Int) { context.dataStore.edit { preferences -> preferences[PreferencesKeys.AUTH_SCHOOL_ID] = id } _authSchoolId.value = id } suspend fun setUserOnBoarded(userOnBoarded: Boolean) { context.dataStore.edit { preferences -> preferences[PreferencesKeys.USER_ON_BOARDED] = userOnBoarded } _userOnBoarded.value = userOnBoarded } suspend fun setNotificationOffset(offset: NotificationOffset) { context.dataStore.edit { preferences -> preferences[PreferencesKeys.NOTIFICATION_OFFSET] = offset.value } } suspend fun setAppearance(appearance: AppearanceType) { context.dataStore.edit { preferences -> preferences[PreferencesKeys.APPEARANCE] = appearance.name } } suspend fun setAutoSignup(value: Boolean) { context.dataStore.edit { preferences -> preferences[PreferencesKeys.AUTO_SIGNUP] = value } } suspend fun setBookmarksViewType(type: ViewType) { context.dataStore.edit { preferences -> preferences[PreferencesKeys.VIEW_TYPE] = type.name } } }
8
Kotlin
2
4
a560d6616e5e7ccd3ce6f386f39932b375aa77f8
4,859
Tumble-Android
The Unlicense
src/main/kotlin/lfs/ktinsim/packets/HandicapsPacket.kt
verde-lfs
588,471,008
false
null
package lfs.ktinsim.packets import lfs.ktinsim.put import lfs.ktinsim.InSim import java.nio.ByteBuffer /* struct CarHCP // Car handicaps in 2 bytes - there is an array of these in the HCP (below) { byte H_Mass; // 0 to 200 - added mass (kg) byte H_TRes; // 0 to 50 - intake restriction }; struct IS_HCP // HandiCaPs { byte Size; // 68 byte Type; // ISP_HCP byte ReqI; // 0 byte Zero; CarHCP Info[32]; // H_Mass and H_TRes for each car: XF GTI = 0 / XR GT = 1 etc }; */ data class HandicapsPacket(val carHandicaps: Array<CarHandicap>): OutgoingPacket { companion object { const val SIZE : Int = 68 val TYPE : Byte = InSim.PacketTypes.ISP_HCP.byte() } override fun getByteBuffer(): ByteBuffer { val result = initByteBuffer(SIZE) result.put(TYPE) .put(0) .put(0) for (handicap in carHandicaps) { result.put(handicap.addedMass) result.put(handicap.intakeRestriction) } return result } }
0
Kotlin
0
0
722e1418713012c136c5f5d551cf50c535fe4198
1,019
ktinsim
MIT License
sample-basic-kotlin/src/main/kotlin/org/dbtools/sample/kotlin/model/database/main/individualview/IndividualViewManager.kt
decriptor
58,690,978
true
{"INI": 2, "Markdown": 3, "Shell": 2, "Batchfile": 1, "Kotlin": 30, "Java Properties": 1, "Java": 85}
/* * IndividualViewManager.kt * * Generated on: 05/09/2016 09:21:13 * */ package org.dbtools.sample.kotlin.model.database.main.individualview import org.dbtools.sample.kotlin.model.database.DatabaseManager class IndividualViewManager : IndividualViewBaseManager { constructor(databaseManager: DatabaseManager): super(databaseManager) { } }
0
Java
0
0
08306fa6e77af27bf45537cfae5c48af0a531a50
362
dbtools-android
Apache License 2.0
domain/induction/src/main/kotlin/uk/gov/justice/digital/hmpps/educationandworkplanapi/domain/induction/dto/UpdatePreviousQualificationsDto.kt
ministryofjustice
653,598,082
false
{"Kotlin": 928275, "Mustache": 3118, "Dockerfile": 1346}
package uk.gov.justice.digital.hmpps.educationandworkplanapi.domain.induction.dto import uk.gov.justice.digital.hmpps.educationandworkplanapi.domain.induction.HighestEducationLevel import uk.gov.justice.digital.hmpps.educationandworkplanapi.domain.induction.Qualification import java.util.UUID data class UpdatePreviousQualificationsDto( val reference: UUID, val educationLevel: HighestEducationLevel?, val qualifications: List<Qualification>, val prisonId: String, )
2
Kotlin
0
2
dc972732695fb8a42a2bdb95258b6d1fb799ba40
478
hmpps-education-and-work-plan-api
MIT License
src/main/kotlin/com/easycoding/user/controller/UserController.kt
u-verma
468,735,131
false
{"Kotlin": 37915, "Dockerfile": 362}
package com.easycoding.user.controller import com.easycoding.user.domain.UserRequestDto import com.easycoding.user.persistence.entity.UserEntity import com.easycoding.user.service.UserService import org.springframework.http.ResponseEntity import org.springframework.web.bind.annotation.CrossOrigin import org.springframework.web.bind.annotation.DeleteMapping import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.PostMapping import org.springframework.web.bind.annotation.PutMapping import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RestController @CrossOrigin(origins = ["http://localhost:4200"]) @RestController @RequestMapping("/api/users") class UserController(private val userService: UserService) { @PostMapping fun createUser(@RequestBody userRequestDto: UserRequestDto): ResponseEntity<Boolean> { return ResponseEntity.ok().body(userService.saveUser(userRequestDto)) } @GetMapping fun getAllUsers(): ResponseEntity<List<UserEntity>> { return ResponseEntity.ok().body(userService.getAllUsers()) } @GetMapping("/{id}") fun getUser(@PathVariable id: String): UserEntity? { return userService.getUser(id) } @PutMapping("/{id}") fun updateUser(@PathVariable id: String, @RequestBody userRequestDto: UserRequestDto): ResponseEntity<Boolean> { return ResponseEntity.ok().body(userService.updateUser(id, userRequestDto)) } @DeleteMapping("/{id}") fun deleteUser(@PathVariable id: String) { userService.deleteUser(id) } }
0
Kotlin
0
0
d756ccedf5099ff22f12940aff4a2364b961a4d2
1,756
springboot-jooq-flyway-Integrationtest
Apache License 2.0
core/src/test/kotlin/org/cryptobiotic/rlauxe/core/TestAlphaMartComparison.kt
JohnLCaron
847,947,313
false
{"Kotlin": 587189}
package org.cryptobiotic.rlauxe.core import org.cryptobiotic.rlauxe.doublePrecision import org.cryptobiotic.rlauxe.makeStandardComparisonAssorter import org.cryptobiotic.rlauxe.util.ComparisonNoErrors import org.cryptobiotic.rlauxe.util.GenSampleFn import org.cryptobiotic.rlauxe.util.makeCvrsByExactMean import kotlin.math.max import kotlin.test.Test import kotlin.test.assertEquals class TestAlphaMartComparison { @Test fun testComparisonUpper() { val N = 10000 val cvrMean = .52 val cvrs = makeCvrsByExactMean(N, cvrMean) val compareAssorter = makeStandardComparisonAssorter(cvrMean) val sampler = ComparisonNoErrors(cvrs, compareAssorter) val theta = sampler.sampleMean() val expected = 1.0 / (3 - 2 * cvrMean) assertEquals(expected, theta, doublePrecision) val eta0 = theta val d = 100 println("N=$N cvrMean=$cvrMean theta=$theta eta0=$eta0, d=$d compareAssorter.upperBound=${compareAssorter.upperBound}") val result = doOneAlphaMartRun(sampler, N, eta0 = eta0, d = d, u = compareAssorter.upperBound) println("\n${result}") assertEquals(TestH0Status.StatRejectNull, result.status) } } fun doOneAlphaMartRun( drawSample: GenSampleFn, maxSamples: Int, eta0: Double, d: Int, u: Double, withoutReplacement: Boolean = true, showDetails: Boolean = true, ): TestH0Result { val N = drawSample.N() val t = 0.5 val upperBound = u val minsd = 1.0e-6 val c = max(eps, ((eta0 - t) / 2)) val estimFn = TruncShrinkage( N = N, withoutReplacement = withoutReplacement, upperBound = upperBound, minsd = minsd, eta0 = eta0, c = c, d = d ) val alpha = AlphaMart( estimFn = estimFn, N = N, upperBound = upperBound, withoutReplacement = withoutReplacement, ) return alpha.testH0(maxSamples, terminateOnNullReject = true, showDetails = showDetails) { drawSample.sample() } }
0
Kotlin
0
0
7a916eef31df94bb0639442594267567ae5dd5bc
2,009
rlauxe
Open LDAP Public License v1.2
source/sdk/src/test/java/com/stytch/sdk/ui/data/PasswordOptionsTest.kt
stytchauth
314,556,359
false
{"Kotlin": 1869665, "Java": 6554, "HTML": 545}
package com.stytch.sdk.ui.data import com.stytch.sdk.consumer.passwords.Passwords import org.junit.Test internal class PasswordOptionsTest { @Test fun `PasswordOptions toResetByEmailStartParameters returns the expected output`() { val options = PasswordOptions( loginExpirationMinutes = 30, resetPasswordExpirationMinutes = 20, resetPasswordTemplateId = "reset-password-template-id", ) val expected = Passwords.ResetByEmailStartParameters( email = "<EMAIL>", loginRedirectUrl = "stytchui-publicToken://deeplink", loginExpirationMinutes = options.loginExpirationMinutes?.toUInt(), resetPasswordRedirectUrl = "stytchui-publicToken://deeplink", resetPasswordExpirationMinutes = options.resetPasswordExpirationMinutes?.toUInt(), resetPasswordTemplateId = options.resetPasswordTemplateId, ) assert(options.toResetByEmailStartParameters("<EMAIL>", "publicToken") == expected) } }
4
Kotlin
2
23
82e363f5779fc552428c659f7be45c701037f431
1,036
stytch-android
MIT License
locallydynamic-android-lib/sample/installtimefeature/src/main/java/com/example/locallydynamic/installtimefeature/InstallTimeActivity.kt
poovarasanvasudevan
239,129,218
true
{"Kotlin": 319796, "Java": 302260, "Shell": 7767}
package com.example.locallydynamic.installtimefeature import androidx.appcompat.app.AppCompatActivity class InstallTimeActivity : AppCompatActivity()
0
null
0
0
9e52f801e8afdb88b245600dbfd4d6691fd22d95
151
LocallyDynamic
Apache License 2.0
app/src/test/java/com/frestoinc/sampleapp_kotlin/api/data/remote/TrendingEntityTest.kt
frestoinc
243,391,526
false
{"Kotlin": 75017}
package com.frestoinc.sampleapp_kotlin.api.data.remote import com.frestoinc.sampleapp_kotlin.models.trending_api.TrendingEntity import org.junit.Assert import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito import org.mockito.MockitoAnnotations /** * Created by frestoinc on 27,February,2020 for SampleApp_Kotlin. */ class TrendingEntityTest { private val author = "author" private val name = "name" private val avatar = "avatar" private val url = "url" private val description = "description" private val language = "language" private val languageColor = "languageColor" private val stars = 1 private val forks = 2 private val currentPeriodStars = 3 @Mock lateinit var model: TrendingEntity @Before fun setUp() { MockitoAnnotations.initMocks(this) Mockito.`when`(model.author).thenReturn(author) Mockito.`when`(model.name).thenReturn(name) Mockito.`when`(model.avatar).thenReturn(avatar) Mockito.`when`(model.url).thenReturn(url) Mockito.`when`(model.description).thenReturn(description) Mockito.`when`(model.language).thenReturn(language) Mockito.`when`(model.languageColor).thenReturn(languageColor) Mockito.`when`(model.stars).thenReturn(stars) Mockito.`when`(model.forks).thenReturn(forks) Mockito.`when`(model.currentPeriodStars).thenReturn(currentPeriodStars) } @Test fun testAuthor() { Mockito.`when`(model.author).thenReturn(author) Assert.assertEquals("author", model.author) } @Test fun testName() { Mockito.`when`(model.name).thenReturn(name) Assert.assertEquals("name", model.name) } @Test fun testAvatar() { Mockito.`when`(model.avatar).thenReturn(avatar) Assert.assertEquals("avatar", model.avatar) } @Test fun testUrl() { Mockito.`when`(model.url).thenReturn(url) Assert.assertEquals("url", model.url) } @Test fun testDescription() { Mockito.`when`(model.description).thenReturn(description) Assert.assertEquals("description", model.description) } @Test fun testLanguage() { Mockito.`when`(model.language).thenReturn(language) Assert.assertEquals("language", model.language) } @Test fun testLanguageColor() { Mockito.`when`(model.languageColor).thenReturn(languageColor) Assert.assertEquals("languageColor", model.languageColor) } @Test fun testStars() { Mockito.`when`(model.stars).thenReturn(stars) Assert.assertEquals(1, model.stars) } @Test fun testForks() { Mockito.`when`(model.forks).thenReturn(forks) Assert.assertEquals(2, model.forks) } @Test fun testCurrentPeriodStars() { Mockito.`when`(model.currentPeriodStars).thenReturn(currentPeriodStars) Assert.assertEquals(3, model.currentPeriodStars) } }
0
Kotlin
0
0
bbf107afae336e19753c14123f906d6b2f706c31
3,020
MVVM-Hilt-Retrofit-Coroutines-Room
MIT License
src/main/kotlin/solve/settings/visualization/popover/LayerSettingsPopOverNode.kt
prime-slam
542,695,410
false
null
package solve.settings.visualization.popover import javafx.scene.Node import javafx.scene.control.Label import javafx.scene.layout.VBox import javafx.scene.text.Font import solve.settings.createSettingsField import solve.utils.structures.Alignment import tornadofx.* abstract class LayerSettingsPopOverNode { protected val popOverNode: VBox = VBox() fun addSettingField(name: String, settingNode: Node, settingsNodeAlignment: Alignment = Alignment.Center) { val fieldLabel = Label(name) fieldLabel.font = Font.font(LayerSettingLabelFontSize) fieldLabel.paddingLeft = LayerSettingsLabelPaddingLeft val settingsField = createSettingsField( fieldLabel, LayerSettingsFieldLabelWidth, settingNode, LayerSettingsSettingNodeWidth, settingsNodeAlignment ) popOverNode.add(settingsField) } abstract fun getPopOverNode(): Node abstract fun removeBindings() companion object { private const val LayerSettingLabelFontSize = 16.0 private const val LayerSettingsLabelPaddingLeft = 10.0 private const val LayerSettingsFieldLabelWidth = 100.0 private const val LayerSettingsSettingNodeWidth = 160.0 } }
53
null
0
8
21412cb44115d35857ce5d1f7650d73d59000ab6
1,262
SOLVE
MIT License
libnavui-maps/src/main/java/com/mapbox/navigation/ui/maps/route/line/model/ExpressionOffsetData.kt
mapbox
87,455,763
false
null
package com.mapbox.navigation.ui.maps.route.line.model /** * @param offset the percentage of the distance traveled along the route from the origin. * @param legIndex the route leg index for this data */ internal abstract class ExpressionOffsetData( val offset: Double, val legIndex: Int, ) { abstract fun <T : ExpressionOffsetData> copyWithNewOffset(newOffset: Double): T override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ExpressionOffsetData if (offset != other.offset) return false if (legIndex != other.legIndex) return false return true } override fun hashCode(): Int { var result = offset.hashCode() result = 31 * result + legIndex return result } override fun toString(): String { return "ExpressionOffsetData(offset=$offset, legIndex=$legIndex)" } }
508
null
318
621
88163ae3d7e34948369d6945d5b78a72bdd68d7c
967
mapbox-navigation-android
Apache License 2.0
src/test/kotlin/net/navatwo/adventofcode2023/day1/Day1SolutionTest.kt
Nava2
726,034,626
false
{"Kotlin": 100705, "Python": 2640, "Shell": 28}
package net.navatwo.adventofcode2023 import net.navatwo.adventofcode2023.benchmarks.Benchmark import net.navatwo.adventofcode2023.day1.Day1Solution import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.Test class Day1SolutionTest { @Test fun `p1 sample`() { val resourceName = "day1/p1_sample.txt" val solution = Day1Solution.Part1 val input = solution.parseResource(resourceName) assertThat(Day1Solution.Part1.solve(input)).isComputed(142L) } @Test fun `p1`() { val resourceName = "day1/p1_input.txt" val solution = Day1Solution.Part1 val input = solution.parseResource(resourceName) assertThat(Day1Solution.Part1.solve(input)).isComputed(55002L) Benchmark.run( inputContent = loadText(resourceName), solution = solution, ) } @Test fun `p2 sample`() { val resourceName = "day1/p2_sample.txt" val solution = Day1Solution.Part2 val input = solution.parseResource(resourceName) assertThat(Day1Solution.Part2.solve(input)).isComputed(281) } @Test fun `p2`() { val resourceName = "day1/p1_input.txt" val solution = Day1Solution.Part2 val input = solution.parseResource(resourceName) assertThat(Day1Solution.Part2.solve(input)).isComputed(55093L) Benchmark.run( inputContent = loadText(resourceName), solution = solution, ) } }
0
Kotlin
0
0
b715ca27eb9e3080bab2e272ce75f69d5c7578bf
1,511
advent-of-code-2023
MIT License
src/test/kotlin/uno/kotlin/util.kt
kotlin-graphics
132,931,904
false
null
package uno.kotlin import glm_.i import java.awt.event.KeyEvent import java.io.File import java.nio.IntBuffer import java.util.* import kotlin.reflect.KMutableProperty0 import kotlin.reflect.KProperty /** * Created by GBarbieri on 30.03.2017. */ infix fun <T> (() -> Any).shallThrow(exClass: Class<T>) { try { this() } catch (e: Throwable) { if (exClass.isInstance(e)) return else throw Error("Exception type different") } throw Error("No exception") } val String.uri get() = url.toURI()!! val String.url get() = ClassLoader.getSystemResource(this)!! val String.stream get() = ClassLoader.getSystemResourceAsStream(this)!! val String.file get() = File(uri) val Char.isPrintable: Boolean get() = with(Character.UnicodeBlock.of(this)) { (!Character.isISOControl(this@isPrintable)) && this@isPrintable != KeyEvent.CHAR_UNDEFINED && this != null && this != Character.UnicodeBlock.SPECIALS } fun Char.parseInt() = java.lang.Character.getNumericValue(this) operator fun <K> HashSet<K>.plusAssign(element: K) { add(element) } operator fun <K> HashSet<K>.minusAssign(element: K) { remove(element) } infix operator fun Appendable.plusAssign(char: Char) { append(char) } infix operator fun Appendable.plusAssign(charSequence: CharSequence) { append(charSequence) } infix operator fun <T>StringBuilder.plusAssign(element: T) { append(element) } fun <T> treeSetOf() = TreeSet<T>() fun <K, V> SortedMap<K, V>.getOrfirst(key: K): V? = get(key) ?: first val <K, V>SortedMap<K, V>.first: V? get() = get(firstKey()) operator fun <R> KMutableProperty0<R>.setValue(host: Any?, property: KProperty<*>, value: R) = set(value) operator fun <R> KMutableProperty0<R>.getValue(host: Any?, property: KProperty<*>): R = get() operator fun <T> KMutableProperty0<T>.invoke(t: T): KMutableProperty0<T> { set(t) return this } operator fun IntBuffer.plusAssign(bool: Boolean) = plusAssign(bool.i) operator fun IntBuffer.plusAssign(i: Int) { put(i) } const val NUL = '\u0000' val isNotCI: Boolean get() = System.getenv("GITHUB_ACTIONS") != "true" && System.getenv("TRAVIS") != "true"
3
null
8
96
3ae299c509d6c1fa75acd957083a827859cd7097
2,210
vkk
Apache License 2.0
internal/src/main/kotlin/com/code42/jenkins/pipelinekt/internal/parameters/BooleanParam.kt
code42
227,466,617
false
{"Kotlin": 313768}
package com.code42.jenkins.pipelinekt.internal.parameters import com.code42.jenkins.pipelinekt.core.Parameter import com.code42.jenkins.pipelinekt.core.vars.Var import com.code42.jenkins.pipelinekt.core.writer.GroovyWriter /** * Boolean Pipeline Param */ data class BooleanParam( val defaultValue: kotlin.Boolean, val description: Var.Literal.Str, override val name: Var.Literal.Str ) : Parameter { override fun toXml(): String { return """ <hudson.model.BooleanParameterDefinition> <name>${name.value}</name> <description>${description.value}</description> <defaultValue>$defaultValue</defaultValue> </hudson.model.BooleanParameterDefinition> """.trimIndent() } override fun toGroovy(writer: GroovyWriter) { writer.writeln("booleanParam(defaultValue: $defaultValue, description: ${description.toGroovy()}, name: ${name.toGroovy()})") } }
4
Kotlin
9
55
7c37bb9c807ae97eecba1f90eac0c669f3da90da
968
pipelinekt
MIT License
src/main/kotlin/year2021/day-13.kt
ppichler94
653,105,004
false
null
package year2021 import lib.Position import lib.aoc.Day import lib.aoc.Part fun main() { Day(13, 2021, PartA13(), PartB13()).run() } open class PartA13 : Part() { data class Paper(var points: List<Position>) { var width = points.maxOf { it[0] } + 1 var height = points.maxOf { it[1] } + 1 } sealed class Command { abstract fun fold(paper: Paper) } class FoldHorizontal(val y: Int) : Command() { override fun fold(paper: Paper) { paper.points = paper.points.map { if (it[1] > y) { val newY = y - (it[1] - y) Position.at(it[0], newY) } else { it } }.distinct() paper.height = y } } class FoldVertical(val x: Int) : Command() { override fun fold(paper: Paper) { paper.points = paper.points.map { if (it[0] > x) { val newX = x - (it[0] - x) Position.at(newX, it[1]) } else { it } }.distinct() paper.width = x } } private fun Command(line: String): Command { val regex = """.*([yx])=(\d+)""".toRegex() val matches = regex.find(line)!! return when (matches.groupValues[1]) { "x" -> FoldVertical(matches.groupValues[2].toInt()) "y" -> FoldHorizontal(matches.groupValues[2].toInt()) else -> throw IllegalArgumentException("unknown fold ${matches.groupValues[1]}") } } private lateinit var commands: List<Command> protected lateinit var paper: Paper override fun parse(text: String) { val (pointsText, commandsText) = text.split("\n\n") commands = commandsText.split("\n").map(::Command) val points = pointsText.split("\n").map { it.split(",") }.map { Position.at(it[0].toInt(), it[1].toInt()) } paper = Paper(points) } override fun compute(): String { commands = commands.take(1) doFolds() return paper.points.size.toString() } protected fun doFolds() { commands.forEach { it.fold(paper) } } override val exampleAnswer: String get() = "17" override val customExampleData: String? get() = """ 6,10 0,14 9,10 0,3 10,4 4,11 6,0 6,12 4,1 0,13 10,12 3,4 3,0 8,4 1,10 2,14 8,10 9,0 fold along y=7 fold along x=5 """.trimIndent() } class PartB13 : PartA13() { override fun compute(): String { doFolds() println() for (y in 0..<paper.height) { for (x in 0..<paper.width) { print(if (Position.at(x, y) !in paper.points) " " else "#") } println() } return "" } override val exampleAnswer: String get() = "" }
0
Kotlin
0
0
1cc4a62b249cc3c6e92d2bfec8f811526da3cf16
3,145
Advent-Of-Code-Kotlin
MIT License
coroutines/data-mongodb/src/main/kotlin/org/springframework/data/mongodb/core/CoReactiveRemoveOperationExtensions.kt
spring-operator
174,079,119
false
null
package org.springframework.data.mongodb.core import com.mongodb.client.result.DeleteResult import kotlinx.coroutines.reactive.awaitSingle /** * Coroutines variant of [ReactiveRemoveOperation.TerminatingRemove.all]. * * @author Sebastien Deleuze */ suspend fun <T : Any> ReactiveRemoveOperation.TerminatingRemove<T>.allAndAwait(): DeleteResult = all().awaitSingle() /** * Coroutines variant of [ReactiveRemoveOperation.TerminatingRemove.all]. * * @author Sebastien Deleuze */ suspend fun <T : Any> ReactiveRemoveOperation.TerminatingRemove<T>.findRemoveAndAwait(): List<T> = findAndRemove().collectList().awaitSingle()
1
null
1
1
6ccefcc2c20303b4e546bdb53cf644d17dd379a3
630
spring-fu
Apache License 2.0
video-encode-decode-test/src/main/java/io/livekit/android/videoencodedecode/WhitelistEncoderFactory.kt
livekit
339,892,560
false
null
package io.livekit.android.videoencodedecode interface WhitelistEncoderFactory { var codecWhitelist: List<String>? }
9
Kotlin
69
99
5b49711143729c497d77684f892ee5fa3ef5d900
122
client-sdk-android
Apache License 2.0
styringsinfo/src/test/kotlin/db/migration/V29UppercaseEnumVerdierTest.kt
navikt
342,325,871
false
{"Kotlin": 640807, "Dockerfile": 168}
package db.migration import com.fasterxml.jackson.databind.node.ObjectNode import no.nav.helse.spre.styringsinfo.AbstractDatabaseTest.Companion.dataSource import no.nav.helse.spre.styringsinfo.teamsak.behandling.Versjon import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test import java.time.LocalDate import java.time.LocalDateTime import java.util.UUID internal class V29UppercaseEnumVerdierTest: BehandlingshendelseJsonMigreringTest( migrering = V29__uppercase_enum_verdier(), dataSource = dataSource ) { @Test fun `Legger til korrigerende rader for å rette opp i feil enum-verdier i versjon 0_0_1`() { val behandlingId1 = UUID.randomUUID() val behandling1Rad1 = leggTilRad(behandlingId1, false, behandlingsresultat = null) val behandling1Rad2 = leggTilRad(behandlingId1, true) val behandlingId2 = UUID.randomUUID() val behandling2Rad1 = leggTilRad(behandlingId2, false) val behandling2Rad2 = leggTilRad(behandlingId2, false) val behandling2Rad3 = leggTilRad(behandlingId2, true) migrer() assertKorrigert(behandling1Rad1) { gammel, ny -> assertGammelOgNyData(gammel, ny) } assertKorrigert(behandling1Rad2) { gammel, ny -> assertGammelOgNyData(gammel, ny) } assertKorrigert(behandling2Rad1) { gammel, ny -> assertGammelOgNyData(gammel, ny) } assertKorrigert(behandling2Rad2) { gammel, ny -> assertGammelOgNyData(gammel, ny) } assertKorrigert(behandling2Rad3) { gammel, ny -> assertGammelOgNyData(gammel, ny) } } @Test fun `Migrerer kun behandlingshendelser med versjon 0_0_1`() { val behandlingId = UUID.randomUUID() leggTilRad(behandlingId, false, "0.0.2") migrer() } @Test fun `Skal ikke legge til korrigerende rader for rader som allerede er korrigert`() { val behandlingId = UUID.randomUUID() val funksjonellTid = LocalDateTime.now() leggTilRad(behandlingId, false, "0.0.1", erKorrigert = true, funksjonellTid = funksjonellTid) val raden = leggTilRad(behandlingId, true, "0.0.1", erKorrigert = false, funksjonellTid = funksjonellTid) migrer() assertKorrigert(raden) { gammel, ny -> assertGammelOgNyData(gammel, ny) } } private fun assertGammelOgNyData(gammel: ObjectNode, ny: ObjectNode) { assertEquals("Automatisk", gammel.path("behandlingsmetode").asText()) assertEquals("AUTOMATISK", ny.path("behandlingsmetode").asText()) assertEquals("AvventerGodkjenning", gammel.path("behandlingstatus").asText()) assertEquals("AVVENTER_GODKJENNING", ny.path("behandlingstatus").asText()) assertEquals("Saksbehandler", gammel.path("behandlingskilde").asText()) assertEquals("SAKSBEHANDLER", ny.path("behandlingskilde").asText()) assertEquals("Omgjøring", gammel.path("behandlingtype").asText()) assertEquals("OMGJØRING", ny.path("behandlingtype").asText()) if (gammel.path("behandlingsresultat").isNull) { assertTrue(ny.path("behandlingsresultat").isNull) } else { assertEquals("Vedtatt", gammel.path("behandlingsresultat").asText()) assertEquals("VEDTATT", ny.path("behandlingsresultat").asText()) } } private fun leggTilRad(behandlingId: UUID, siste: Boolean, versjon: String = "0.0.1", erKorrigert: Boolean = false, funksjonellTid: LocalDateTime = LocalDateTime.now(), behandlingsresultat: String? = "Vedtatt") = leggTilBehandlingshendelse(behandlingId = behandlingId, siste = siste, versjon = Versjon.Companion.of(versjon), erKorrigert = erKorrigert, funksjonellTid = funksjonellTid) { val epoch = LocalDate.EPOCH.atStartOfDay() it.put("aktørId", "1234") it.put("mottattTid", "$epoch") it.put("registrertTid", "$epoch") it.put("behandlingstatus", "AvventerGodkjenning") it.put("behandlingtype", "Omgjøring") it.put("behandlingskilde", "Saksbehandler") it.putString("behandlingsmetode", "Automatisk") it.putString("relatertBehandlingId", null) it.putString("behandlingsresultat", behandlingsresultat) } private fun ObjectNode.putString(fieldName: String, value: String?): ObjectNode { return if (value == null) putNull(fieldName) else put(fieldName, value) } }
0
Kotlin
2
0
ca31dee78072369de54aa0a214b6ab3e298aa880
4,407
helse-spre
MIT License
playground/src/main/kotlin/team/duckie/quackquack/playground/theme/theme.kt
duckie-team
523,387,054
false
null
/* * Designed and developed by Duckie Team, 2022 * * Licensed under the MIT. * Please see full license: https://github.com/duckie-team/quack-quack-android/blob/master/LICENSE */ package team.duckie.quackquack.playground.theme import android.os.Build import androidx.compose.foundation.isSystemInDarkTheme import androidx.compose.material3.MaterialTheme import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme import androidx.compose.material3.dynamicLightColorScheme import androidx.compose.material3.lightColorScheme import androidx.compose.runtime.Composable import androidx.compose.ui.platform.LocalContext import team.duckie.quackquack.ui.theme.QuackTheme private val PlaygroundLightColors = lightColorScheme( primary = md_theme_light_primary, onPrimary = md_theme_light_onPrimary, primaryContainer = md_theme_light_primaryContainer, onPrimaryContainer = md_theme_light_onPrimaryContainer, secondary = md_theme_light_secondary, onSecondary = md_theme_light_onSecondary, secondaryContainer = md_theme_light_secondaryContainer, onSecondaryContainer = md_theme_light_onSecondaryContainer, tertiary = md_theme_light_tertiary, onTertiary = md_theme_light_onTertiary, tertiaryContainer = md_theme_light_tertiaryContainer, onTertiaryContainer = md_theme_light_onTertiaryContainer, error = md_theme_light_error, errorContainer = md_theme_light_errorContainer, onError = md_theme_light_onError, onErrorContainer = md_theme_light_onErrorContainer, background = md_theme_light_background, onBackground = md_theme_light_onBackground, surface = md_theme_light_surface, onSurface = md_theme_light_onSurface, surfaceVariant = md_theme_light_surfaceVariant, onSurfaceVariant = md_theme_light_onSurfaceVariant, outline = md_theme_light_outline, inverseOnSurface = md_theme_light_inverseOnSurface, inverseSurface = md_theme_light_inverseSurface, inversePrimary = md_theme_light_inversePrimary, surfaceTint = md_theme_light_surfaceTint, ) private val PlaygroundDarkColors = darkColorScheme( primary = md_theme_dark_primary, onPrimary = md_theme_dark_onPrimary, primaryContainer = md_theme_dark_primaryContainer, onPrimaryContainer = md_theme_dark_onPrimaryContainer, secondary = md_theme_dark_secondary, onSecondary = md_theme_dark_onSecondary, secondaryContainer = md_theme_dark_secondaryContainer, onSecondaryContainer = md_theme_dark_onSecondaryContainer, tertiary = md_theme_dark_tertiary, onTertiary = md_theme_dark_onTertiary, tertiaryContainer = md_theme_dark_tertiaryContainer, onTertiaryContainer = md_theme_dark_onTertiaryContainer, error = md_theme_dark_error, errorContainer = md_theme_dark_errorContainer, onError = md_theme_dark_onError, onErrorContainer = md_theme_dark_onErrorContainer, background = md_theme_dark_background, onBackground = md_theme_dark_onBackground, surface = md_theme_dark_surface, onSurface = md_theme_dark_onSurface, surfaceVariant = md_theme_dark_surfaceVariant, onSurfaceVariant = md_theme_dark_onSurfaceVariant, outline = md_theme_dark_outline, inverseOnSurface = md_theme_dark_inverseOnSurface, inverseSurface = md_theme_dark_inverseSurface, inversePrimary = md_theme_dark_inversePrimary, surfaceTint = md_theme_dark_surfaceTint, ) @Composable @Suppress("NewApi") fun PlaygroundTheme( useDarkTheme: Boolean = isSystemInDarkTheme(), useDynamicColor: Boolean = true, content: @Composable () -> Unit, ) { val context = LocalContext.current val isDynamicColor = useDynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S val colorScheme = when { useDarkTheme && isDynamicColor -> dynamicDarkColorScheme( context = context, ) useDarkTheme && !isDynamicColor -> PlaygroundDarkColors !useDarkTheme && isDynamicColor -> dynamicLightColorScheme( context = context, ) else -> PlaygroundLightColors // !useDarkTheme && !isDynamicColor } MaterialTheme( colorScheme = colorScheme, typography = PlaygroundTypography, ) { QuackTheme( content = content, ) } } /* @Composable fun PlaygroundTheme( useDarkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit, ) { val colorScheme = when (!useDarkTheme) { true -> PlaygroundLightColors else -> PlaygroundDarkColors } MaterialTheme( colorScheme = colorScheme, typography = PlaygroundTypography, content = content, ) } */
8
Kotlin
4
33
1b024100a4a51f588ade982ce564ba8e53cfbb17
4,703
quack-quack-android
MIT License
bgw-gui/src/test/kotlin/tools/aqua/bgw/util/bidirectionalmap/OperatorTest.kt
tudo-aqua
377,420,862
false
null
/* * Copyright 2021-2024 The BoardGameWork Authors * SPDX-License-Identifier: Apache-2.0 * * 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 tools.aqua.bgw.util.bidirectionalmap import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows /** Test set and get function in BidirectionalMap. */ class OperatorTest : BidirectionalMapTestBase() { /** Test set a new pair. */ @Test @DisplayName("Test set new pair") fun testSetNew() { assertEquals(2, map.size) map[4] = 5 assertEquals(3, map.size) assertTrue(map.contains(4, 5)) assertTrue(map.containsBackward(5)) assertTrue(map.containsForward(4)) } /** Test set already existing domain key. */ @Test @DisplayName("Test set already existing domain key") fun testSetAlreadyExistingDomainKey() { assertTrue(map.containsForward(0)) assertEquals(2, map.size) map[0] = 5 assertEquals(2, map.size) assertTrue(map.contains(0, 5)) assertTrue(map.containsBackward(5)) assertTrue(map.containsForward(0)) } /** Test set already existing codomain key. */ @Test @DisplayName("Test set already existing codomain key") fun testSetAlreadyExistingCodomainKey() { assertTrue(map.containsBackward(1)) assertEquals(2, map.size) map[4] = 1 assertEquals(2, map.size) assertTrue(map.contains(4, 1)) assertTrue(map.containsBackward(1)) assertTrue(map.containsForward(4)) } /** Test get a valid domain key. */ @Test @DisplayName("Test get a valid domain key") fun testGetKey() { assertEquals(1, map[0]) } /** Test get an invalid domain key. */ @Test @DisplayName("Test get an invalid domain key") fun testGetInvalidKey() { assertThrows<NoSuchElementException> { map[5] } } }
31
null
16
24
266db439e4443d10bc1ec7eb7d9032f29daf6981
2,364
bgw
Apache License 2.0
src/main/kotlin/react/bootstrap/layout/grid/row/RowAttributes.kt
h4rdc0m
300,855,749
true
{"Kotlin": 440791, "JavaScript": 1700, "CSS": 1372, "HTML": 670}
@file:Suppress("ClassName", "unused") package react.bootstrap.layout.grid.row import react.bootstrap.lib.AttributePair import react.bootstrap.lib.AttributeTriple import react.bootstrap.lib.CombinedAttributes sealed class RowAttributes : CombinedAttributes { abstract val colCount: ColCounts? abstract val itemsX: ItemsXs? abstract val itemsY: ItemsYs? sealed class ColCounts(private val value: Int) : RowAttributes() { class CNT_1 internal constructor() : ColCounts(1) class CNT_2 internal constructor() : ColCounts(2) class CNT_3 internal constructor() : ColCounts(3) class CNT_4 internal constructor() : ColCounts(4) class CNT_5 internal constructor() : ColCounts(5) class CNT_6 internal constructor() : ColCounts(6) final override val classNamePrefix: String = "ROW_COLS" final override val classNamePostfix: String = colCount.value.toString() final override val colCount: ColCounts get() = this final override val itemsX: ItemsXs? = null final override val itemsY: ItemsYs? = null infix fun xs(that: ItemsXs): ColCountItemXsPair = ColCountItemXsPair(this, that) infix fun ys(that: ItemsYs): ColCountItemYsPair = ColCountItemYsPair(this, that) companion object { val CNT_1 = CNT_1() val CNT_2 = CNT_2() val CNT_3 = CNT_3() val CNT_4 = CNT_4() val CNT_5 = CNT_5() val CNT_6 = CNT_6() } } sealed class ItemsXs : RowAttributes() { class AROUND internal constructor() : ItemsXs() class BETWEEN internal constructor() : ItemsXs() class CENTER internal constructor() : ItemsXs() class END internal constructor() : ItemsXs() class START internal constructor() : ItemsXs() final override val classNamePrefix: String = "JUSTIFY_CONTENT" final override val classNamePostfix: String = this::class.simpleName!! final override val colCount: ColCounts? = null final override val itemsX: ItemsXs get() = this final override val itemsY: ItemsYs? = null infix fun colcount(that: ColCounts): ColCountItemXsPair = ColCountItemXsPair(that, this) infix fun ys(that: ItemsYs): ItemsXsItemsYsPair = ItemsXsItemsYsPair(this, that) companion object { val AROUND = AROUND() val BETWEEN = BETWEEN() val CENTER = CENTER() val END = END() val START = START() } } sealed class ItemsYs : RowAttributes() { class BASELINE internal constructor() : ItemsYs() class CENTER internal constructor() : ItemsYs() class END internal constructor() : ItemsYs() class START internal constructor() : ItemsYs() class STRETCH internal constructor() : ItemsYs() final override val classNamePrefix: String = "ALIGN_ITEMS" final override val classNamePostfix: String = this::class.simpleName!! final override val colCount: ColCounts? = null final override val itemsX: ItemsXs? = null final override val itemsY: ItemsYs get() = this infix fun colcount(that: ColCounts): ColCountItemYsPair = ColCountItemYsPair(that, this) infix fun xs(that: ItemsXs): ItemsXsItemsYsPair = ItemsXsItemsYsPair(that, this) companion object { val BASELINE = BASELINE() val CENTER = CENTER() val END = END() val START = START() val STRETCH = STRETCH() } } data class ColCountItemXsPair internal constructor( override val first: ColCounts, override val second: ItemsXs ) : RowAttributes(), AttributePair { override val colCount: ColCounts = first override val itemsX: ItemsXs = second override val itemsY: ItemsYs? = null override val classNamePrefix: String? = null override val classNamePostfix: String? = null infix fun ys(that: ItemsYs): ColCountItemXsItemYsTriple = ColCountItemXsItemYsTriple(first, second, that) } data class ColCountItemYsPair internal constructor( override val first: ColCounts, override val second: ItemsYs ) : RowAttributes(), AttributePair { override val colCount: ColCounts = first override val itemsX: ItemsXs? = null override val itemsY: ItemsYs = second override val classNamePrefix: String? = null override val classNamePostfix: String? = null infix fun xs(that: ItemsXs): ColCountItemXsItemYsTriple = ColCountItemXsItemYsTriple(first, that, second) } data class ItemsXsItemsYsPair internal constructor( override val first: ItemsXs, override val second: ItemsYs ) : RowAttributes(), AttributePair { override val colCount: ColCounts? = null override val itemsX: ItemsXs = first override val itemsY: ItemsYs = second override val classNamePrefix: String? = null override val classNamePostfix: String? = null } data class ColCountItemXsItemYsTriple internal constructor( override val first: ColCounts, override val second: ItemsXs, override val third: ItemsYs ) : RowAttributes(), AttributeTriple { override val colCount: ColCounts = first override val itemsX: ItemsXs = second override val itemsY: ItemsYs = third override val classNamePrefix: String? = null override val classNamePostfix: String? = null } }
0
null
0
0
da38c43490d7578e2d51747ac2373d86aa34f2e4
5,633
kotlin-react-bootstrap
MIT License
rd-kt/rd-framework/src/jvmMain/kotlin/com/jetbrains/rd/framework/PlatformDependent.kt
LongJohnCoder
218,779,970
true
{"C#": 928244, "Kotlin": 823187, "C++": 395399, "CMake": 26903, "Shell": 4387, "Batchfile": 3021, "C": 946}
package com.jetbrains.rd.framework import com.jetbrains.rd.util.lifetime.Lifetime import com.jetbrains.rd.util.reactive.hasValue import com.jetbrains.rd.util.threading.SpinWait actual inline fun <T> IRdTask<T>.wait(timeoutMs: Long, pump: () -> Unit) : Boolean { return SpinWait.spinUntil(Lifetime.Eternal, timeoutMs) { result.hasValue.apply { if (!this) pump() } } } actual fun createAbstractBuffer(): AbstractBuffer { return UnsafeBuffer(ByteArray(12)) }
0
null
0
0
5d8282c3fdbcc9a70d4b695c2cb2c89d34787a66
479
rd
Apache License 2.0
android-app/src/main/java/com/github/aivanovski/testwithme/android/extensions/RectExtensions.kt
aivanovski
815,197,496
false
{"Kotlin": 149302}
package com.github.aivanovski.testwithme.android.extensions import android.graphics.Rect import com.github.aivanovski.testwithme.entity.Bounds fun Rect.toBounds(): Bounds { return Bounds( left = left, right = right, top = top, bottom = bottom ) }
0
Kotlin
0
0
786719cbda096569f75c1233df3e74c40095a6f2
288
test-with-me
Apache License 2.0
app/src/main/java/com/kieronquinn/app/taptap/ui/views/RippleView.kt
KieronQuinn
283,883,226
false
null
package com.kieronquinn.app.taptap.ui.views import android.animation.AnimatorSet import android.animation.ValueAnimator import android.animation.ValueAnimator.AnimatorUpdateListener import android.content.Context import android.graphics.Canvas import android.graphics.Paint import android.util.AttributeSet import android.view.View import android.view.animation.DecelerateInterpolator import androidx.core.content.ContextCompat import com.kieronquinn.app.taptap.R import com.kieronquinn.app.taptap.utils.extensions.px import java.util.* //Based on https://stackoverflow.com/a/52688461, modified to meet what was required class RippleView : View, AnimatorUpdateListener { private inner class Ripple internal constructor(startRadiusFraction: Float, stopRadiusFraction: Float, startAlpha: Float, stopAlpha: Float, color: Int, delay: Long, duration: Long, strokeWidth: Float, updateListener: AnimatorUpdateListener?) { var mAnimatorSet: AnimatorSet var mRadiusAnimator: ValueAnimator var mAlphaAnimator: ValueAnimator var mPaint: Paint fun draw(canvas: Canvas, centerX: Int, centerY: Int, radiusMultiplicator: Float) { mPaint.alpha = (255 * mAlphaAnimator.animatedValue as Float).toInt() canvas.drawCircle(centerX.toFloat(), centerY.toFloat(), mRadiusAnimator.animatedValue as Float * radiusMultiplicator, mPaint) } fun startAnimation() { mAnimatorSet.start() } fun stopAnimation() { mAnimatorSet.cancel() } init { mRadiusAnimator = ValueAnimator.ofFloat(startRadiusFraction, stopRadiusFraction) mRadiusAnimator.duration = duration mRadiusAnimator.addUpdateListener(updateListener) mRadiusAnimator.interpolator = DecelerateInterpolator() mAlphaAnimator = ValueAnimator.ofFloat(startAlpha, stopAlpha) mAlphaAnimator.duration = duration mAlphaAnimator.addUpdateListener(updateListener) mAlphaAnimator.interpolator = DecelerateInterpolator() mAnimatorSet = AnimatorSet() mAnimatorSet.playTogether(mRadiusAnimator, mAlphaAnimator) mAnimatorSet.startDelay = delay mPaint = Paint() mPaint.style = Paint.Style.STROKE mPaint.color = color mPaint.alpha = (255 * startAlpha).toInt() mPaint.isAntiAlias = true mPaint.strokeWidth = strokeWidth } } private var mRipples: MutableList<Ripple> = ArrayList() private val rippleColor by lazy { ContextCompat.getColor(context, R.color.ripple_circle) } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { init(context, attrs) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { init(context, attrs) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { init(context, attrs) } private var videoRadius = 0f private fun init(context: Context, attrs: AttributeSet?) { if (isInEditMode) return post { val videoWidth = 95.px val maxRadius = measuredWidth / 2 this.videoRadius = (videoWidth.toFloat() / maxRadius) } } fun startAnimation(numberRipples: Int) { visibility = VISIBLE mRipples = ArrayList() mRipples.add(Ripple(videoRadius, 1.25f, 1.0f, 0.0f, rippleColor, 0, 2000, 2.px.toFloat(), this)) for(i in 1 until numberRipples){ mRipples.add(Ripple(videoRadius, 1.25f, 1.0f, 0.0f, rippleColor, (i * 30).toLong(), 2000, 2.px.toFloat(), this)) } mRipples.forEach { it.startAnimation() } } override fun onAnimationUpdate(animation: ValueAnimator) { invalidate() } override fun onDraw(canvas: Canvas) { val centerX = width / 2 val centerY = height / 2 val radiusMultiplicator = width / 2 for (ripple in mRipples) { ripple.draw(canvas, centerX, centerY, radiusMultiplicator.toFloat()) } } companion object { const val TAG = "RippleView" } }
52
null
2
2,251
abec5a3e139786beeea75e2fb5677013d0719bf1
4,328
TapTap
Apache License 2.0
app/src/main/java/com/mrebollob/leitnerbox/presentation/leitnerbox/LeitnerBoxFragment.kt
mrebollob
155,557,246
false
null
package com.mrebollob.leitnerbox.presentation.leitnerbox import android.content.Context import android.os.Bundle import android.support.v4.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.mrebollob.leitnerbox.R import com.mrebollob.leitnerbox.domain.exception.Failure import com.mrebollob.leitnerbox.domain.extension.toast import com.mrebollob.leitnerbox.domain.model.LeitnerDay import com.mrebollob.leitnerbox.domain.model.Level import com.mrebollob.leitnerbox.presentation.leitnerbox.adapter.LevelsAdapter import kotlinx.android.synthetic.main.fragment_leitner_box.* import org.koin.android.ext.android.inject class LeitnerBoxFragment : Fragment(), LeitnerBoxView { val presenter: LeitnerBoxPresenter by inject() private var listener: LeitnerBoxFragmentListener? = null private val levelsAdapter = LevelsAdapter() private var currentDay = LeitnerDay.empty() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_leitner_box, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initUI() } override fun onResume() { super.onResume() presenter.attachView(this) } private fun initUI() { levelsListView.adapter = levelsAdapter doneButton.setOnClickListener { presenter.onDayCompletedClick(LeitnerDay(currentDay.dayNumber)) } } override fun showFirstDayTitle() { dayTextView.text = getString(R.string.leitner_view_first_day) levelsTextView.text = getString(R.string.leitner_view_first_day_info) } override fun showCurrentNumberDay(day: LeitnerDay) { this.currentDay = day dayTextView.text = getString(R.string.main_view_day_number, day.dayNumber) } override fun showLevelsToReview(levels: List<Level>) { if (levels.isEmpty()) { return } val names = levels.filter { it.active }.map { it.name }.reversed() .reduce { acc, string -> "$acc, $string" } levelsTextView.text = getString(R.string.main_view_levels_to_review, names) } override fun showLevels(levels: List<Level>) { levelsAdapter.levels = levels } override fun onDayCompleted() { listener?.onDayCompleted() } override fun handleFailure(failure: Failure) { context?.toast(getString(R.string.generic_error)) } override fun onAttach(context: Context) { super.onAttach(context) if (context is LeitnerBoxFragmentListener) { listener = context } else { throw RuntimeException("$context must implement LeitnerBoxFragmentListener") } } override fun onDetach() { super.onDetach() presenter.detachView() listener = null } interface LeitnerBoxFragmentListener { fun onDayCompleted() } companion object { @JvmStatic fun newInstance() = LeitnerBoxFragment() } }
0
Kotlin
0
2
3e3bfef678dd6e2daff7e6c67ec7dfc0b47a3f81
3,192
leitner-box
Apache License 2.0
src/com/fsilberberg/lisp/Parser.kt
333fred
56,926,391
false
null
package com.fsilberberg.lisp import java.util.* /** * Simple LISP parser that I'm making to play around with Kotlin */ fun main(x: Array<String>) = println("${parse("(Hello world (this \"(is a test)\" (of the parser )))")}") fun readExpr(): String { val expr = StringBuilder() var lastLineNewline = false while (true) { val curLine = readLine() if (curLine == "\n") { if (lastLineNewline) { break } else { lastLineNewline = true } } else { lastLineNewline = false expr.append(curLine).append("\n") } } return expr.toString() } // These regexes match non-escaped dividers. This is to be sure we don't replace // things in strings val whitespaceRegex = Regex("\\s") val nullAtom = Atom("NULL") fun parse(expr: String): SExpr { val iter = expr.iterator() return parseTokens(iter.next(), iter).first ?: nullAtom } /** * Parses a token, determining whether it is an atom or subexpression, and returning the * full com.fsilberberg.lisp.SExpr found * * @param curChar The character to start parsing on * @param iter The remaining characters to com.fsilberberg.lisp.parse * @return If an com.fsilberberg.lisp.SExpr was found, the com.fsilberberg.lisp.SExpr, and whether or not the expr was a closing paren. The only time that null * will be returned for the com.fsilberberg.lisp.SExpr is when a closing paren is found. */ fun parseTokens(curChar: Char, iter: Iterator<Char>): Pair<SExpr?, Boolean> { var finalChar = curChar while (isWhitespace(finalChar)) { if (iter.hasNext()) { finalChar = iter.next() } else { return Pair(nullAtom, false) } } return when (finalChar) { '(' -> Pair(parseList(iter), false) ')' -> Pair(null, true) '"' -> Pair(parseString(iter), false) else -> parseAtom(finalChar, iter) } } /** * Parses a subexpression from the given characters * * @param iter The characters to com.fsilberberg.lisp.parse from * @return The com.fsilberberg.lisp.SubExpr containing all parsed subexpressions */ fun parseList(iter: Iterator<Char>): SExpr { val subExprs = ArrayList<SExpr>() while (iter.hasNext()) { val (atom, closeParen) = parseTokens(iter.next(), iter) if (atom != null) { subExprs.add(atom) } if (closeParen) { break } } return SubExpr(subExprs) } /** * Parses a string from the given character iterator * * @param iter The character stream to com.fsilberberg.lisp.parse a string from * @return The atom with the parsed string inside */ fun parseString(iter: Iterator<Char>): SExpr { var escaped = false var loop = true val sb = StringBuilder() sb.append('"') while (iter.hasNext() && loop) { val nextChar = iter.next() when (nextChar) { '\\' -> { // If we haven't escaped before, this will become true. If the last char was a \, then // this will revert back to false, and we append a \. escaped = !escaped if (!escaped) { sb.append(nextChar) } } '"' -> { sb.append(nextChar) if (escaped) { escaped = false } else { loop = false } } else -> { sb.append(nextChar) escaped = false } } } return Atom(sb.toString()) } /** * Parses a given character and iterator for a single atom, returning the atom and whether that * atom ended with whitespace or a parenthesis * * @param curChar The character that starts the atom * @param iter The iterator over all remaining characters * @return The parsed atom, and true if the atom ended with a closing parenthesis */ fun parseAtom(curChar: Char, iter: Iterator<Char>): Pair<SExpr, Boolean> { val sb = StringBuilder() var encounteredCloseParen = false var nextChar = curChar var firstLoop = true do { if (!firstLoop) { nextChar = iter.next() } else { firstLoop = false } if (isWhitespace(nextChar)) { break } else if (nextChar == ')') { encounteredCloseParen = true break } else { sb.append(nextChar) } } while (iter.hasNext()) return Pair(Atom(sb.toString()), encounteredCloseParen) } fun isWhitespace(curChar: Char): Boolean { return whitespaceRegex.matches(curChar.toString()); } interface SExpr data class Atom(val expr: String) : SExpr { override fun toString(): String { return expr } fun convertAtom(): Value? { try { return NumV(expr.toDouble()) } catch (e: NumberFormatException) { if (expr.equals("true", true) || expr.equals("false", true)) { return BoolV(expr.toBoolean()) } else { if (expr.length >= 2 && expr.first() == '"' && expr.last() == '"') { return StringV(expr.substringAfter('"').substringBeforeLast('"')) } else if (expr.length >= 1 && !expr.contains(whitespaceRegex)) { return SymV(expr) } else { return null } } } } } data class SubExpr(val exprs: List<SExpr>) : SExpr { override fun toString(): String { return "( ${exprs.joinToString { it.toString() + " " }})" } }
0
Kotlin
0
0
e99bd60a88a21d6b99f16ea5713cad25c2e65f25
5,706
kotlin_lisp
MIT License
serialization/serialization-annotation/src/main/kotlin/androidx/serialization/EnumValue.kt
syntaxxxxx
334,969,342
true
{"Java": 41841144, "Kotlin": 22501867, "Python": 226099, "Shell": 105753, "C++": 23223, "ANTLR": 19795, "HTML": 10802, "TypeScript": 6933, "JavaScript": 1343, "CMake": 995}
/* * Copyright 2019 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.serialization import kotlin.annotation.AnnotationRetention.BINARY import kotlin.annotation.AnnotationTarget.FIELD /** * Tags a serializable enum value with its serialized ID. * * A serializable enum must have this annotation on all its values. One value of the enum must be * selected as the default value to use if the enum value is unrecognized or missing. Set the ID * of this value to [DEFAULT] or zero. * * ```kotlin * enum class MyEnum { * @EnumValue(EnumValue.DEFAULT) * DEFAULT, * * @EnumValue(1) * MY_VALUE * } * ``` * * @property id Integer ID of the enum value. * * Any integer is a valid enum value ID, but `0` has special meaning as the default value. * Additionally, negative values are not recommended as their proto representation is always 10 * bytes long. * * Enum value IDs must be unique within an enum class, but may be freely reused between enum * classes. * * To reserve enum value IDs for future use or to prevent unintentional reuse of removed enum * value IDs, apply the [Reserved] annotation to the enum class. */ @Retention(BINARY) @Target(FIELD) public annotation class EnumValue( @get:JvmName("value") val id: Int ) { public companion object { /** * The ID of a default enum value. * * One value in every enum must be default to be used if a parser encounters an * unrecognized or missing enum field. */ public const val DEFAULT: Int = 0 } }
0
null
0
1
e4ce477393fc1026f45fe67b73d8400f19e83975
2,121
androidx
Apache License 2.0
src/test/kotlin/io/poyarzun/concoursedsl/resources/CfResourceTest.kt
Logiraptor
151,898,063
false
null
package io.poyarzun.concoursedsl.resources import io.poyarzun.concoursedsl.domain.job import io.poyarzun.concoursedsl.domain.pipeline import io.poyarzun.concoursedsl.dsl.generateYML import org.junit.Test import kotlin.test.assertEquals class CfResourceTest { @Test fun completeYaml() { val actualYaml = generateYML(pipeline { val resource = cfResource("resource-deploy-web-app") { source("https://api.run.pivotal.io", "ORG", "SPACE") { username = "EMAIL" password = "<PASSWORD>" skipCertCheck = false clientId = "client-id" clientSecret = "<KEY>" verbose = true } } resources(resource) jobs { +job("job-deploy-app") { plan { +put(resource) { params("build-output/manifest.yml") { path = "/build/lib/my-springboot-app.jar" currentAppName = "turquoise-app" vars { this["alpha"] = "apple" this["beta"] = "banana" } varsFiles("mu.properties", "nu.properties") dockerPassword = "<PASSWORD>" dockerUserName = "simon" showAppLog = true noStart = false environmentVariables { this["key"] = "value" this["key2"] = "value2" } } } } } } }) val expectedYaml = """ --- jobs: - name: "job-deploy-app" plan: - put: "resource-deploy-web-app" params: manifest: "build-output/manifest.yml" path: "/build/lib/my-springboot-app.jar" current_app_name: "turquoise-app" environment_variables: key: "value" key2: "value2" vars: alpha: "apple" beta: "banana" vars_files: - "mu.properties" - "nu.properties" docker_user_name: "simon" docker_password: "<PASSWORD>" show_app_log: true no_start: false groups: [] resources: - name: "resource-deploy-web-app" type: "cf" source: api: "https://api.run.pivotal.io" organization: "ORG" space: "SPACE" username: "EMAIL" password: "<PASSWORD>" client_id: "client-id" client_secret: "<KEY>" skip_cert_check: false verbose: true resource_types: [] """.trimIndent() assertEquals(expectedYaml, actualYaml) } @Test fun testDocumentYaml() { // recreates the sample from this page // https://github.com/concourse/cf-resource val actualYaml = generateYML(pipeline { val resource = cfResource("resource-deploy-web-app") { source("https://api.run.pivotal.io", "ORG", "SPACE") { username = "EMAIL" password = "<PASSWORD>" skipCertCheck = false } } resources(resource) jobs { +job("job-deploy-app") { plan { +put(resource) { params("build-output/manifest.yml") { environmentVariables { this["key"] = "value" this["key2"] = "value2" } } } } } } }) val expectedYaml = """ --- jobs: - name: "job-deploy-app" plan: - put: "resource-deploy-web-app" params: manifest: "build-output/manifest.yml" environment_variables: key: "value" key2: "value2" groups: [] resources: - name: "resource-deploy-web-app" type: "cf" source: api: "https://api.run.pivotal.io" organization: "ORG" space: "SPACE" username: "EMAIL" password: "<PASSWORD>" skip_cert_check: false resource_types: [] """ .trimIndent() assertEquals(expectedYaml, actualYaml) } }
8
Kotlin
1
5
570ec6d8bf74ce600dd2d477fa68da41eae170d8
5,268
concourse-dsl
MIT License
ok-general-multiplatform/src/jsTest/kotlin/ru/otus/otuskotlin/general/multiplatform/IsSortedTest.kt
otuskotlin
323,812,728
false
{"Gradle Kotlin DSL": 7, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "INI": 1, "Kotlin": 52, "Java": 1}
package ru.otus.otuskotlin.general.multiplatform import kotlin.test.Test import kotlin.test.assertFalse import kotlin.test.assertTrue internal class IsSortedTest { @Test fun isSortedFalseTest() { val array = arrayOf(1,5,3,7) assertFalse(sorted(array)) } @Test fun isSortedTrueTest() { val array = arrayOf(1,2,3,4) assertTrue(sorted(array)) } }
0
Kotlin
1
2
a369b4e2ba74fb6dcc303d3ea2f564e2fd16a353
403
202012-otuskotlin-general
MIT License
APP/Fitness/app/src/main/java/com/lilei/fitness/utils/TimeFormatUtil.kt
fjh226151
609,465,738
true
{"Markdown": 1, "Text": 1, "Ignore List": 1, "Java Properties": 1, "Gradle": 3, "Shell": 1, "Batchfile": 1, "INI": 1, "Proguard": 1, "Java": 46, "XML": 45, "Kotlin": 7}
package com.lilei.fitness.utils import java.text.SimpleDateFormat import java.util.* class TimeFormatUtil { companion object { @JvmStatic fun getTimeString(timeStamp: Long): String? { if (timeStamp == 0L) return "" val inputTime = Calendar.getInstance() inputTime.timeInMillis = timeStamp * 1000 val currenTimeZone = inputTime.time val calendar = Calendar.getInstance() // calendar.set(Calendar.HOUR_OF_DAY, 23); // calendar.set(Calendar.MINUTE, 59); calendar[Calendar.HOUR_OF_DAY] = 0 calendar[Calendar.MINUTE] = 0 calendar[Calendar.SECOND] = 0 calendar[Calendar.MILLISECOND] = 0 var sdf = SimpleDateFormat("yyyy/MM/dd") if (calendar.before(inputTime)) { // 今天 sdf = SimpleDateFormat("HH:mm") return sdf.format(currenTimeZone) } calendar.add(Calendar.DAY_OF_MONTH, -1) if (calendar.before(inputTime)) { // 昨天 sdf = SimpleDateFormat("昨天 HH:mm") return sdf.format(currenTimeZone) } calendar.add(Calendar.YEAR, -1) if (calendar.before(inputTime)) { //今年 sdf = SimpleDateFormat("MM月dd日") return sdf.format(currenTimeZone) } return sdf.format(currenTimeZone) } @JvmStatic fun getTimeMsgString(timeStamp: Long): String? { if (timeStamp == 0L) return "" val inputTime = Calendar.getInstance() inputTime.timeInMillis = timeStamp * 1000 val currenTimeZone = inputTime.time val calendar = Calendar.getInstance() // calendar.set(Calendar.HOUR_OF_DAY, 23); // calendar.set(Calendar.MINUTE, 59); calendar[Calendar.HOUR_OF_DAY] = 0 calendar[Calendar.MINUTE] = 0 calendar[Calendar.SECOND] = 0 calendar[Calendar.MILLISECOND] = 0 var sdf = SimpleDateFormat("yyyy/MM/dd HH:mm") if (calendar.before(inputTime)) { // 今天 sdf = SimpleDateFormat("HH:mm") return sdf.format(currenTimeZone) } calendar.add(Calendar.DAY_OF_MONTH, -1) if (calendar.before(inputTime)) { // 昨天 sdf = SimpleDateFormat("昨天 HH:mm") return sdf.format(currenTimeZone) } calendar.add(Calendar.YEAR, -1) if (calendar.before(inputTime)) { //今年 sdf = SimpleDateFormat("MM月dd日 HH:mm") return sdf.format(currenTimeZone) } return sdf.format(currenTimeZone) } @JvmStatic fun getHomeDate(): String { val calendar = Calendar.getInstance() Calendar.DAY_OF_WEEK_IN_MONTH return "${getWeekDayStr(calendar.get(Calendar.DAY_OF_WEEK))} ${ SimpleDateFormat("MM月dd日").format( calendar.time ) }" } fun getCurrentTimeHMS(): String { return SimpleDateFormat("HH:mm:ss").format(Date()) } fun getCurrentTimeYear(time: Long): String { return SimpleDateFormat("yyyy").format(Date(time)) } fun getCurrentTimeYear(): String { return SimpleDateFormat("yyyy").format(Date()) } fun getCurrentTimeMonth(): String { return SimpleDateFormat("MM").format(Date()) } fun getCurrentTimeMonthDay(data: Long): String { return SimpleDateFormat("MM月dd日").format(data) } fun getCurrentTimeMonth(date: Date): String { return SimpleDateFormat("MM").format(date) } fun getCurrentTimeDay(): String { return SimpleDateFormat("dd").format(Date()) } fun getCurrentTimeDay(date: Date): String { return SimpleDateFormat("dd").format(date) } fun getCurrentTimeHour(long: Long): String { return SimpleDateFormat("HH").format(Date(long)) } fun getCurrentTimeMinute(long: Long): String { return SimpleDateFormat("mm").format(Date(long)) } fun getCurrentTimeHour(): String { return SimpleDateFormat("HH").format(Date()) } fun getCurrentTimeMinute(): String { return SimpleDateFormat("mm").format(Date()) } fun getCurrentTimeHM(): String { return SimpleDateFormat("HH:mm").format(Date()) } fun getCurrentTimeYearHM(): String { return SimpleDateFormat("yyyy-MM-dd HH:mm").format(Date()) } fun getCurrentTimeYearHMChina(): String { return SimpleDateFormat("yyyy年MM月dd日 HH:mm").format(Date()) } fun getCurrentTimeYearHMChina(long: Long): String { return SimpleDateFormat("yyyy年MM月dd日 HH:mm").format(Date(long)) } fun getCurrentTimeHM(long: Long): String { return SimpleDateFormat("HH:mm").format(Date(long)) } fun getCurrentTimeYM(long: Long): String { return SimpleDateFormat("yyyy.MM").format(Date(long)) } fun getCurrentTimeYMChina(long: Long): String { return SimpleDateFormat("yyyy年MM月").format(Date(long)) } fun getCurrentTimeYMD(long: Long): String { return SimpleDateFormat("yyyy.MM.dd").format(Date(long)) } //距离本周日还剩几天 fun getCurrentTimeToSun(long: Long): Int { val calendar = Calendar.getInstance() calendar.time = Date(long) Calendar.DAY_OF_WEEK_IN_MONTH val week = calendar.get(Calendar.DAY_OF_WEEK) - 1 return if (week == 0) { //周日 0 } else { 7 - week } } fun getCurrentTimeMDW(long: Long): String { val calendar = Calendar.getInstance() calendar.time = Date(long) Calendar.DAY_OF_WEEK_IN_MONTH val week = getWeekDayStr(calendar.get(Calendar.DAY_OF_WEEK)) return "${SimpleDateFormat("MM月dd").format(calendar.time)} $week" } fun getCurrentTimeYMDWChina(long: Long): String { val calendar = Calendar.getInstance() calendar.time = Date(long) Calendar.DAY_OF_WEEK_IN_MONTH val week = getWeekDayStr(calendar.get(Calendar.DAY_OF_WEEK)) return "${SimpleDateFormat("yyyy年MM月dd日").format(calendar.time)} $week" } fun getCurrentTimeYMDChina(long: Long): String { return SimpleDateFormat("yyyy年MM月dd日").format(Date(long)) } fun getTodayStartTime(): Long { var calendar = Calendar.getInstance() calendar.apply { set(Calendar.HOUR_OF_DAY, 0) set(Calendar.MINUTE, 0) set(Calendar.SECOND, 0) set(Calendar.MILLISECOND, 0) } return calendar.timeInMillis } fun getCurrentTimeUpWeekMD(long: Long): String { return SimpleDateFormat("MM.dd").format(Date(long)) } fun string2Time(time: String, format: String): Long { return SimpleDateFormat(format).parse(time).time } fun Time2String(time: Long, format: String): String { return SimpleDateFormat(format).format(time) } /** * 上个月 */ fun getUpMonthLong(long: Long): Long { var date = Date(long) var calendar = Calendar.getInstance() calendar.time = date // 设置为当前时间 calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) - 1); // 设置为上一个月 return calendar.time.time } /** * 下个月 */ fun getNextMonthLong(long: Long): Long { var date = Date(long) var calendar = Calendar.getInstance() calendar.time = date // 设置为当前时间 calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + 1) // 设置为下一个月 return calendar.time.time } fun getMondayLong(long: Long): Long { var date = Date(long) var calendar = Calendar.getInstance() calendar.time = date // 设置为当前时间 calendar.firstDayOfWeek = Calendar.MONDAY val day = calendar.get(Calendar.DAY_OF_WEEK) calendar.add(Calendar.DATE, calendar.firstDayOfWeek - day) return calendar.time.time } fun getSundayLong(long: Long): Long { var date = Date(long) var calendar = Calendar.getInstance() calendar.time = date // 设置为当前时间 calendar.firstDayOfWeek = Calendar.MONDAY val day = calendar.get(Calendar.DAY_OF_WEEK) calendar.add(Calendar.DATE, calendar.firstDayOfWeek - day + 6) return calendar.time.time } /** * 上周 */ fun getUpWeekLong(long: Long): Long { var date = Date(getMondayLong(long)) var calendar = Calendar.getInstance() calendar.time = date // 设置为当前时间 calendar.firstDayOfWeek = Calendar.MONDAY calendar.add(Calendar.DATE, -7) // 设置为上周 return calendar.time.time } /** * 下周 */ fun getNextWeekLong(long: Long): Long { var date = Date(long) var calendar = Calendar.getInstance() calendar.time = date // 设置为当前时间 calendar.set(Calendar.WEEK_OF_MONTH, calendar.get(Calendar.WEEK_OF_MONTH) + 1) // 设置为下周 return calendar.time.time } fun getFileName(): String { return SimpleDateFormat("yyyyMMdd").format(Date()) } fun getTimeWeekChina(long: Long): String { val calendar = Calendar.getInstance() calendar.time = Date(long) Calendar.DAY_OF_WEEK_IN_MONTH val week = getWeekDayStr(calendar.get(Calendar.DAY_OF_WEEK)) return "$week" } /** * 时间转化为星期 * * @param indexOfWeek 星期的第几天 */ fun getWeekDayStr(indexOfWeek: Int): String? { var weekDayStr = "" when (indexOfWeek) { 1 -> weekDayStr = "周日" 2 -> weekDayStr = "周一" 3 -> weekDayStr = "周二" 4 -> weekDayStr = "周三" 5 -> weekDayStr = "周四" 6 -> weekDayStr = "周五" 7 -> weekDayStr = "周六" } return weekDayStr } fun timeStringToLong(time: String, format: String = "yyyy-MM-dd HH:mm"): Long { return SimpleDateFormat(format).parse(time).time } fun timeToLineYMD(long: Long): String { return SimpleDateFormat("yyyy-MM-dd").format(Date(long)) } fun timeChinaToLine(time: String): String { return time.replace("年", "-").replace("月", "-").replace("日", "") } fun timeToChinaYMD(time: String, oldValue: String): String { var t = time.split(oldValue) return "${t[0]}年${t[1]}月${t[2]}日" } } }
0
Java
0
0
14321ecb29cd9425565ef9e6fc33f165dccb809b
11,475
fitness_Android
Apache License 2.0
buildSrc/src/main/kotlin/versions.kt
d7z-team
492,530,094
false
{"Java": 35172, "Kotlin": 29855}
import org.gradle.api.Project import org.gradle.api.logging.Logging import java.io.File import java.util.Properties /** * 版本实体 */ interface VersionContext { /** * 根据名称获取版本号 */ operator fun get(key: String): String } private val logger = Logging.getLogger("buildSrc.versions") private val versions = HashMap<File, VersionContext>() private val contextVersion = Properties().apply { val filter: (Map.Entry<Any, Any>) -> Boolean = { it.key.toString().toLowerCase().contains("version") } putAll(System.getProperties().filter(filter)) // 规范化环境变量 putAll( System.getenv().filter(filter) .map { it.key.toLowerCase().replace("_", ".") to it.value } ) // 规范化环境变量 } internal class InternalVersionContext(private val path: File) : VersionContext { private val properties = Properties() init { val gradlePropFile = File(path, "gradle.properties") val versionPropFile = File(path, "version.properties") if (gradlePropFile.isFile) { properties.load(gradlePropFile.inputStream()) } if (versionPropFile.isFile) { properties.load(versionPropFile.inputStream()) } } override fun get(key: String): String { val property = contextVersion.getProperty(key) if (property != null && property.isNotBlank()) { logger.warn( "Found dependency \"{}\" with dynamic version constraints.Current version is \"{}\".", key, property ) return property } return contextVersion.getOrElse(key, { properties.getOrElse(key, { logger.warn("Unable to find a valid version of $key.") "" }) }).toString() } } fun Project.contextVersions(header: String = ""): VersionContext { return versions(this.rootProject, header) } fun versions(project: Project, header: String = ""): VersionContext { val data = versions.getOrPut(project.projectDir, { InternalVersionContext(project.projectDir) }) if (header.isBlank()) { return data } else { return HeaderVersionContext(data, header) } } class HeaderVersionContext(private val child: VersionContext, private val header: String) : VersionContext { override fun get(key: String) = child.get("$header.$key") }
1
null
1
1
f82a9a32e08345df0691ddd08ff0d511d79182a7
2,391
certificate-system
MIT License
feature/rsa/src/main/java/zaitsev/a/d/mirea/rsa/RSA.kt
Anton-Zaitsev
816,037,410
false
{"Gradle Kotlin DSL": 12, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 11, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "Kotlin": 256, "TOML": 1, "CMake": 2, "C++": 8, "Proguard": 11, "XML": 36, "INI": 4, "Java": 3}
package zaitsev.a.d.mirea.rsa interface RSA { fun encrypt(text: String, publicKeyUser: String): String? fun decrypt(encryptedText: String, myPrivateKey: String): String? fun generateKeyPair(): KeyPair }
0
Java
0
0
08623c8850b0b301c7af9c7961d6436988f6d1a3
215
AI-News
MIT License
app/src/test/kotlin/io/github/joaoevangelista/convertx/op/MassConversionsTest.kt
theevangelista
74,320,911
false
{"Kotlin": 40464, "Java": 6269}
package io.github.joaoevangelista.convertx.op import io.github.joaoevangelista.convertx.op.Mass.GRAMS import io.github.joaoevangelista.convertx.op.Mass.KILOGRAM import org.junit.Test import javax.measure.unit.NonSI import javax.measure.unit.SI /** * @author <NAME> */ class MassConversionsTest { @Test fun shouldConvertKilogramToTon() { val measure = Conversions.ofMass(1000.0, Mass.KILOGRAM, Mass.TON) assert(measure.unit == NonSI.METRIC_TON) assert(measure.value == 1.0, { "${measure.value} is not equal to 1.0" }) } @Test fun shouldConvertGramToKilogram() { val measure = Conversions.ofMass(1000.0, GRAMS, KILOGRAM) assert(measure.unit == SI.KILOGRAM) assert(measure.value == 1.0, { "${measure.value} is not equal to 1.0" }) } }
0
Kotlin
1
1
ab94f4cb1bbc822b054518071e4c07cf05f71732
775
Convertx
Apache License 2.0
backend/src/test/kotlin/io/github/gelassen/manufactory_knowledge_management/HttpControllersTest.kt
Gelassen
751,944,452
false
{"Kotlin": 45429, "Mustache": 1314, "Dockerfile": 316}
package io.github.gelassen.manufactory_knowledge_management import com.ninjasquad.springmockk.MockkBean import io.github.gelassen.manufactory_knowledge_management.model.Breakdown import io.github.gelassen.manufactory_knowledge_management.model.Machine import io.mockk.every import org.junit.jupiter.api.Test import org.springframework.beans.factory.annotation.Autowired import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest import org.springframework.http.MediaType import org.springframework.test.web.servlet.MockMvc import org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get import org.springframework.test.web.servlet.result.MockMvcResultMatchers import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status @WebMvcTest class HttpControllersTest(@Autowired val mockMvc: MockMvc) { @MockkBean lateinit var machinesRepository: MachinesRepository @MockkBean lateinit var breakdownsRepository: CustomBreakdownsRepository @Test fun `on GET request machines?barcode=valid_barcode receives valid response`() { val stubApiResponses = stubApiResponses() every { machinesRepository.findMachineByBarcode(any()) } returns stubApiResponses.first() mockMvc.perform(get("/api/v1/machine?barcode=Sodick LQ1W").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isOk) .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.jsonPath("\$.data.name").value(stubApiResponses.first().name)) .andExpect(MockMvcResultMatchers.jsonPath("\$.data.breakdowns[0].failure").value(stubApiResponses.first().breakdowns.first().failure)) } @Test fun `on GET request machines?barcode=not_valid_barcode receives NOT_FOUND response`() { var notValidBarcode = "Sodick which does not exist" val stubApiResponses = stubApiResponses() every { machinesRepository.findMachineByBarcode("Sodick LQ1W") } returns stubApiResponses.first() every { machinesRepository.findMachineByBarcode(notValidBarcode) } returns null mockMvc.perform(get("/api/v1/machine?barcode=$notValidBarcode").accept(MediaType.APPLICATION_JSON)) .andExpect(status().isNotFound) .andExpect(MockMvcResultMatchers.content().contentType(MediaType.APPLICATION_JSON)) .andExpect(MockMvcResultMatchers.jsonPath("\$.message").value("Machine with '$notValidBarcode' barcode does not exist. Did you send the right barcode?")) } private fun stubApiResponses(): List<Machine> { var sodick = Machine( name = "<NAME>", manufacturer = "Sodick", barcode = "Sodick LQ1W" ) sodick.breakdowns.add( Breakdown( failure = "Ошибка короткого замыкания circuit shortage", solution = " - вероятно, станок определяет короткое замыкание через падение напряжения в цепи\n" + " - возможно, какая-то грязь коротит станок, и обычная полная чистка должна помочь решить проблему\n" + " - станок полностью не чистили, но произвели замену части комплектующих (шлейфы?)\n" + " - это решило проблему circuit shortage, но проблема медленной подачи проволки осталась\n" + " - система ЧПУ была откатана до последней стабильной работы, при покупке станка или внесения изменения в ОС ЧПУ командой снимаются бекапы и хранятся на сервере организации\n" + " - после восстановление системы из бекапов полноценная работа была восстановлена", dateTime = System.currentTimeMillis(), machine = sodick ) ) var fanuc = Machine( name = "Fanuc 2000", manufacturer = "Fanuc", barcode = "Fanuc 2000" ) return listOf(sodick, fanuc) } }
9
Kotlin
0
0
a6947d1e8371e22b4a07f854808379f75ad09a1c
3,991
manufactory-knowledge-management-system
MIT License
core/src/test/kotlin/at.hschroedl.fluentast/ast/expression/AssignmentTest.kt
hschne
103,569,412
false
null
package at.hschroedl.fluentast.ast.expression import at.hschroedl.fluentast.assignment import at.hschroedl.fluentast.exception.FluentArgumentException import at.hschroedl.fluentast.test.dummyExpression import at.hschroedl.fluentast.test.dummyLiteral import at.hschroedl.fluentast.test.toInlineString import org.eclipse.jdt.core.dom.Assignment import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.ValueSource import kotlin.test.assertFailsWith internal class AssignmentTest { @ParameterizedTest(name = "Create assignment with {arguments}") @ValueSource(strings = arrayOf("=", "+=", "-=", "/=", "&=", "|=", "^=", "%=", "<<=", ">>=", ">>>=")) internal fun assignment_withDefaultAssignment_returnsAssignment(operator: String) { val expression = assignment(dummyExpression("a"), operator, dummyLiteral(1)).build() as Assignment assertEquals("a${operator}1", expression.toInlineString()) } @Test internal fun assignment_invalidOperator_returnsAssignment() { assertFailsWith(FluentArgumentException::class) { assignment(dummyExpression("a"), "test", dummyLiteral(1)).build() as Assignment } } }
0
Kotlin
0
0
49510f0cadf3083b58de6011215b76c1b720d72f
1,328
Fluentast
Apache License 2.0
android/app/src/main/java/io/realm/conference/data/dao/EventDataDao.kt
realm
101,996,167
false
null
package io.realm.conference.data.dao import android.arch.lifecycle.LiveData import io.realm.Realm import io.realm.RealmResults import io.realm.conference.data.entity.EventData import io.realm.conference.data.extensions.asLiveData import io.realm.conference.data.extensions.where class EventDataDao(val db: Realm) { fun getEventData() : EventData? { return where().findFirst() } fun getEventDataAsync() : LiveData<EventData> { return where().findFirstAsync().asLiveData() } fun findAll() : RealmResults<EventData> { return where().findAll() } private fun where() = db.where<EventData>() }
2
Swift
10
62
ba85e58d5a3feadd5e03e7c8312b9d2bd1304d96
646
EventKit
Apache License 2.0
app/src/main/java/com/yassineabou/clock/ui/theme/Color.kt
yassineAbou
603,165,906
false
{"Kotlin": 166506}
package com.yassineabou.clock.ui.theme import androidx.compose.ui.graphics.Color val md_theme_light_primary = Color(0xFF1949F0) val md_theme_light_onPrimary = Color(0xFFFFFFFF) val md_theme_light_primaryContainer = Color(0xFFDEE1FF) val md_theme_light_onPrimaryContainer = Color(0xFF001258) val md_theme_light_secondary = Color(0xFF3550D4) val md_theme_light_onSecondary = Color(0xFFFFFFFF) val md_theme_light_secondaryContainer = Color(0xFFDEE0FF) val md_theme_light_onSecondaryContainer = Color(0xFF00105A) val md_theme_light_tertiary = Color(0xFF4156B9) val md_theme_light_onTertiary = Color(0xFFFFFFFF) val md_theme_light_tertiaryContainer = Color(0xFFDEE1FF) val md_theme_light_onTertiaryContainer = Color(0xFF001158) val md_theme_light_error = Color(0xFFBA1A1A) val md_theme_light_errorContainer = Color(0xFFFFDAD6) val md_theme_light_onError = Color(0xFFFFFFFF) val md_theme_light_onErrorContainer = Color(0xFF410002) val md_theme_light_background = Color(0xFFF8FDFF) val md_theme_light_onBackground = Color(0xFF001F25) val md_theme_light_surface = Color(0xFFF8FDFF) val md_theme_light_onSurface = Color(0xFF001F25) val md_theme_light_surfaceVariant = Color(0xFFE3E1EC) val md_theme_light_onSurfaceVariant = Color(0xFF45464F) val md_theme_light_outline = Color(0xFF767680) val md_theme_light_inverseOnSurface = Color(0xFFD6F6FF) val md_theme_light_inverseSurface = Color(0xFF00363F) val md_theme_light_inversePrimary = Color(0xFFB9C3FF) val md_theme_light_shadow = Color(0xFF000000) val md_theme_light_surfaceTint = Color(0xFF1949F0) val md_theme_light_outlineVariant = Color(0xFFC6C5D0) val md_theme_light_scrim = Color(0xFF000000) val md_theme_dark_primary = Color(0xFFB9C3FF) val md_theme_dark_onPrimary = Color(0xFF00228B) val md_theme_dark_primaryContainer = Color(0xFF0033C2) val md_theme_dark_onPrimaryContainer = Color(0xFFDEE1FF) val md_theme_dark_secondary = Color(0xFFBAC3FF) val md_theme_dark_onSecondary = Color(0xFF001F8F) val md_theme_dark_secondaryContainer = Color(0xFF1334BC) val md_theme_dark_onSecondaryContainer = Color(0xFFDEE0FF) val md_theme_dark_tertiary = Color(0xFFB9C3FF) val md_theme_dark_onTertiary = Color(0xFF032289) val md_theme_dark_tertiaryContainer = Color(0xFF263DA0) val md_theme_dark_onTertiaryContainer = Color(0xFFDEE1FF) val md_theme_dark_error = Color(0xFFFFB4AB) val md_theme_dark_errorContainer = Color(0xFF93000A) val md_theme_dark_onError = Color(0xFF690005) val md_theme_dark_onErrorContainer = Color(0xFFFFDAD6) val md_theme_dark_background = Color(0xFF001F25) val md_theme_dark_onBackground = Color(0xFFA6EEFF) val md_theme_dark_surface = Color(0xFF001F25) val md_theme_dark_onSurface = Color(0xFFA6EEFF) val md_theme_dark_surfaceVariant = Color(0xFF45464F) val md_theme_dark_onSurfaceVariant = Color(0xFFC6C5D0) val md_theme_dark_outline = Color(0xFF90909A) val md_theme_dark_inverseOnSurface = Color(0xFF001F25) val md_theme_dark_inverseSurface = Color(0xFFA6EEFF) val md_theme_dark_inversePrimary = Color(0xFF1949F0) val md_theme_dark_shadow = Color(0xFF000000) val md_theme_dark_surfaceTint = Color(0xFFB9C3FF) val md_theme_dark_outlineVariant = Color(0xFF45464F) val md_theme_dark_scrim = Color(0xFF000000) val Blue = Color(0xFF2E57FC) val Blue100 = Color(0xFFE6EDFD) val Black100 = Color(0xFF0F2D37) val Red100 = Color(0xFFed4a65) const val PrimaryLightAlpha = .25f
1
Kotlin
1
4
7eb70533931fd4f3d2e827e6b072d6cae0a1a210
3,333
Clock
Apache License 2.0
src/main/java/metifikys/MainController.kt
Metifikys
103,301,877
false
null
package metifikys import javafx.collections.FXCollections import javafx.collections.ObservableList import javafx.fxml.FXML import javafx.scene.Scene import javafx.scene.control.Button import javafx.scene.control.ComboBox import javafx.scene.control.ListView import javafx.scene.control.TextField import javafx.scene.input.KeyCode import javafx.scene.input.KeyCodeCombination import javafx.scene.input.KeyCombination import javafx.stage.Stage import metifikys.list.ListProcessor import metifikys.list.controller.ListsController import metifikys.list.controller.comands.FileCommand import metifikys.state.StateController import org.apache.commons.lang3.tuple.MutablePair import java.io.File import java.nio.file.Path import java.util.ArrayList import java.util.prefs.Preferences class MainController { private var listsController: ListsController? = null @FXML private lateinit var leftList: ListView<MutablePair<String, Path>> @FXML private lateinit var leftText: TextField @FXML private lateinit var leftDrivers: ComboBox<String> @FXML private lateinit var rightList: ListView<MutablePair<String, Path>> @FXML private lateinit var rightText: TextField @FXML private lateinit var rightDrivers: ComboBox<String> @FXML private lateinit var copyButton: Button @FXML private lateinit var cutButton: Button @FXML private lateinit var deleteButton: Button @FXML private lateinit var mkFolderButton: Button @FXML fun initialize() { // Preferences prefs = Preferences.userRoot().node("metifikys.FileManager"); // prefs.put("left", "left"); // System.out.println(prefs.get("left", "")); val names = ArrayList<String>() for (path in File.listRoots()) names.add(path.toString()) val strings = FXCollections.observableArrayList(names) leftDrivers.setItems(strings) rightDrivers.setItems(strings) // todo from config file leftDrivers.selectionModel.select(0) rightDrivers.selectionModel.select(0) listsController = ListsController.of( ListProcessor.of(leftList, leftText, leftDrivers), ListProcessor.of(rightList, rightText, rightDrivers) ) StateController.addElement(listsController!!) println("initialized") // todo from config file setOnClickCommandInButton(copyButton, FileCommand.COPY) setOnClickCommandInButton(cutButton, FileCommand.CUT) setOnClickCommandInButton(deleteButton, FileCommand.DELETE) setOnClickCommandInButton(mkFolderButton, FileCommand.CREATE_FOLDER) } private fun setOnClickCommandInButton(button: Button, command: FileCommand) { button.setOnMouseClicked { event -> listsController!!.processCommand(command) } } fun setScene(scene: Scene) { scene.setOnKeyPressed { event -> // todo from config file when (event.code) { KeyCode.F5 -> listsController!!.processCommand(FileCommand.COPY) KeyCode.F6 -> listsController!!.processCommand(FileCommand.CUT) KeyCode.F7 -> listsController!!.processCommand(FileCommand.CREATE_FOLDER) KeyCode.F8 -> listsController!!.processCommand(FileCommand.DELETE) } } val leftComb = KeyCodeCombination(KeyCode.F1, KeyCombination.ALT_DOWN) val rightComb = KeyCodeCombination(KeyCode.F2, KeyCombination.ALT_DOWN) scene.setOnKeyReleased { event -> if (leftComb.match(event)) { listsController!!.focusOnComboBoxLeft() } else if (rightComb.match(event)) { listsController!!.focusOnComboBoxRight() } else { when (event.code) { KeyCode.TAB -> listsController!!.changeFocus() } } } } }
1
Kotlin
0
0
3d42729ad6710a070490e29d7fd195721239b425
3,965
FileManager
Apache License 2.0
app/src/main/java/themulti0/eatthatsit/services/benedictformula/BenedictBmrFormulaFactory.kt
TheMulti0
211,525,832
false
null
package themulti0.eatthatsit.services.benedictformula import themulti0.eatthatsit.services.benedictformula.bmr.* import themulti0.eatthatsit.services.benedictformula.models.BenedictFormulaType object BenedictBmrFormulaFactory { fun create(type: BenedictFormulaType): IBenedictBmrFormula { return when (type) { BenedictFormulaType.Average -> AverageBenedictFormula() BenedictFormulaType.HarrisBenedict -> HarrisBenedictFormula() BenedictFormulaType.MiffinStJeor -> MiffinStJeorBenedictFormula() BenedictFormulaType.RozaShizgal -> RozaShizgalBenedictFormula() } } }
0
Kotlin
0
0
06c97700521a929811b867ac915f44d33509bc3f
637
EatThatsIt
Apache License 2.0
app/src/main/java/com/fahad/kotlin_auth_with_googles/FirebaseSignInWithGoogleApp.kt
fahad0samara
740,627,457
false
{"Kotlin": 49303}
package com.fahad.kotlin_auth_with_googles import android.app.Application import dagger.hilt.android.HiltAndroidApp @HiltAndroidApp class FirebaseSignInWithGoogleApp : Application()
0
Kotlin
0
1
a8dff6e462b8d838d94e46c9d332841416ee1c47
184
kotlin_auth_with_google_and_navgigtion
MIT License
app/src/main/java/com/cloudbib/client/MyApplication.kt
shigeo-nakamura
601,298,792
false
null
package com.cloudbib.client import android.app.Application class MyApplication : Application() { companion object { lateinit var instance: MyApplication private set } override fun onCreate() { super.onCreate() instance = this } }
0
Kotlin
0
0
7a82871df8604cfe14339c4761d186a746e9db92
286
cloud-bib-app
Apache License 2.0
test-utils/src/main/java/com/kinandcarta/create/proxytoggle/testutils/LaunchIntent.kt
theappbusiness
275,194,675
false
null
package com.kinandcarta.create.proxytoggle.testutils import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.IntentFilter import io.mockk.every import org.robolectric.Shadows private const val PACKAGE_NAME = "com.kinandcarta.create.proxytoggle" private const val MAIN_ACTIVITY_NAME = "MainActivity" fun addMainActivityToRobolectric(context: Context) { every { context.packageName } returns PACKAGE_NAME val packageManager = Shadows.shadowOf(context.packageManager) packageManager.apply { addActivityIfNotPresent(ComponentName(context, MAIN_ACTIVITY_NAME)) addIntentFilterForActivity( ComponentName(context, MAIN_ACTIVITY_NAME), IntentFilter(Intent.ACTION_MAIN).apply { addCategory(Intent.CATEGORY_LAUNCHER) } ) } } fun expectedLaunchIntent(context: Context): Intent { return Intent().apply { action = Intent.ACTION_MAIN addCategory(Intent.CATEGORY_LAUNCHER) setPackage(PACKAGE_NAME) component = ComponentName(context, MAIN_ACTIVITY_NAME) flags = Intent.FLAG_ACTIVITY_NEW_TASK } }
3
Kotlin
51
292
89f35a026a82bc7e2535fa532cec8244056cca61
1,189
android-proxy-toggle
MIT License
app/src/main/java/com/exceptos/tukio/Data/ModelClasses/ModelsEtExtFunctions.kt
DamiTesfaye
209,073,194
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "JSON": 2, "Proguard": 1, "Kotlin": 60, "XML": 200, "Java": 1}
package com.exceptos.tukio.Data.ModelClasses import android.content.Context import android.content.Intent import android.widget.Toast import androidx.annotation.DrawableRes import androidx.recyclerview.widget.RecyclerView import com.google.firebase.firestore.DocumentSnapshot import com.exceptos.tukio.Utils.AppUtils /** * Created by Big-Nosed Developer on the Edge of Infinity. */ data class EventsModel(var eventType: String?, var eventTitle: String, var eventDesc: String, var eventLocation: String, var eventDate: String, var eventTags: List<String>, var eventRegLink: String?, var userUID: String, var eventTicketLink: String?, var eventDressCode: String?, var eventImageLink: String, var eventGuests: Map<String, Any>?, var eventImageLinkThumb: String?, var eventPostTime: String?, var amountPaid: Long?, var eventMilis: Long? ) { constructor() : this("", "", "", "", "", arrayListOf<String>(), "", "", "", "", "" , HashMap<String, Any>(), "", "", 0, 0) } data class ChipModel(var chipText: String, @DrawableRes var imageResource: Int) data class NewUpdateModel(var updateType: String, var updateValue: Any) data class FullEventsModel(var eventsModel: EventsModel, var eventID: String ) { constructor() : this(EventsModel("","", "", "", "", arrayListOf<String>(), "", "", "", "", "" , HashMap<String, Any>(), "", "", 0, 0), "") } data class UpdatesModel(var updateTitle: String, var updateDesc: String){ constructor(): this ("", "") } data class FullUpdateModel(var updatesModel: UpdatesModel, var eventName: String?){ constructor(): this (UpdatesModel("", ""), "") } data class GoingModel(var userUID: String){ constructor(): this("") } data class FullGoingModel(var goingModel: GoingModel, var goingDocument: String){ constructor(): this(GoingModel(""), "") } data class CommentModel(val posterUID: String, var commentMessage: String, val currentTimePosted: Long){ constructor(): this("", "", 0L) } data class GuestModel(var guestName: String, var guestBio: String) data class UserModel(var userName: String, var userEmail: String, var userImage: String?, var userThumbLink: String?, var userBio: String, var tags: List<String>?){ constructor() : this("", "", "", "", "", arrayListOf<String>()) } fun UpdatesModel.toHashMap(): HashMap<String, Any>{ val hashMap = HashMap<String, Any>() val updateTitle = this.updateTitle val updateDesc = this.updateDesc hashMap["updateTitle"] = updateTitle hashMap["updateDesc"] = updateDesc return hashMap } fun NewUpdateModel.toHashMap(): HashMap<String, Any>{ val hashMap = HashMap<String, Any>() val updateType = this.updateType val updateValue = this.updateValue hashMap["updateType"] = this.updateType hashMap["updateValue"] = this.updateValue return hashMap } fun CommentModel.toHashMap(): HashMap<String, Any>{ val hashMap = HashMap<String, Any>() hashMap["commentMessage"] = this.commentMessage hashMap["posterUID"] = this.posterUID hashMap["currentTimePosted"] = this.currentTimePosted return hashMap } fun DocumentSnapshot.breakDownToCommentModel(): CommentModel{ val posterUID = this["posterUID"].toString() val commentMessage = this["commentMessage"].toString() val currentTimePosted = this["currentTimePosted"] as Long return CommentModel(posterUID = posterUID, commentMessage = commentMessage, currentTimePosted = currentTimePosted) } fun DocumentSnapshot.breakDownToUpdatesModel(): UpdatesModel{ val updateTitle = this["updateTitle"].toString() val updateDesc = this["updateDesc"].toString() return UpdatesModel(updateTitle, updateDesc) } fun DocumentSnapshot.breakDocumentIntoEvntsModel(): EventsModel { val eventType = this["eventType"].toString() val eventTitle = this["eventTitle"].toString() val eventDesc = this["eventDesc"].toString() val eventLocation = this["eventLocation"].toString() val eventDate = this["eventDate"].toString() val eventTags = this["eventTags"] as List<String> val eventRegLink = this["eventRegLink"].toString() val userUID = this["userUID"].toString() val eventTicketLink = this["eventTicketLink"].toString() val eventDressCode = this["eventDressCode"].toString() val eventImageLink = this["eventImageLink"].toString() val listOfGuests = this["eventGuests"] as HashMap<String, Any>? val eventImageLinkThumb = this["eventImageLinkThumb"].toString() val eventPostTime = this["eventPostTime"].toString() val amountPaid = this["amountPaid"] as Long? val eventMilis = this["eventMilis"] as Long? return EventsModel(eventType, eventTitle, eventDesc, eventLocation, eventDate, eventTags, eventRegLink, userUID, eventTicketLink, eventDressCode, eventImageLink, listOfGuests, eventImageLinkThumb, eventPostTime, amountPaid, eventMilis) } fun DocumentSnapshot.breakDownToUserModel(): UserModel{ val userName = this["userName"].toString() val userEmail = this["userEmail"].toString() val userPicLink = this["userImage"].toString() val userThumbLink = this["userThumbLink"].toString() val userBio = this["userBio"].toString() val tags = this["tags"] as List<String>? return UserModel(userName, userEmail, userPicLink,userThumbLink, userBio, tags) } fun RecyclerView.initRecyclerView(layoutManagerType: String, context: Context){ if (layoutManagerType == AppUtils.STAGGERED_LAYOUT_MANAGER){ this.layoutManager = AppUtils.getRecycleLayout(AppUtils.STAGGERED_LAYOUT_MANAGER, context) this.setHasFixedSize(true) }else if (layoutManagerType == AppUtils.LINEAR_LAYOUT_MANAGER){ this.layoutManager = AppUtils.getRecycleLayout(AppUtils.LINEAR_LAYOUT_MANAGER, context) this.setHasFixedSize(true) } } fun MutableList<FullEventsModel>.compareAccordingToMoneyPaid(): MutableList<FullEventsModel>{ val firstModel = this[0] val secondModel = this[1] if (firstModel.eventsModel.amountPaid!! < secondModel.eventsModel.amountPaid!!){ val list = mutableListOf<FullEventsModel>() list.add(0, secondModel) list.add(1, firstModel) return list }else{ return this } } fun MutableList<FullEventsModel>.addPromotedEventsIntoNormalEvents(promotedEventsList: List<FullEventsModel>){ if(promotedEventsList.size > 1 && size > 4){ val indexOfFirstPromotedEvent = 1 val indexOfSecondPromotedEvent = 5 if(!contains(promotedEventsList[0]) && !contains(promotedEventsList[1])) { add(indexOfFirstPromotedEvent, promotedEventsList[0]) add(indexOfSecondPromotedEvent, promotedEventsList[1]) } }else{ val indexOfFirstPromotedEvent = 1 if (!contains(promotedEventsList[0])){ add(indexOfFirstPromotedEvent, promotedEventsList[0]) } } } fun List<String>.compareLists(otherList: List<String>): Int{ var sameItems = 0 for (value in this){ if (otherList.contains(value)){ sameItems++ } } return sameItems } fun FullEventsModel.passIntoIntent(context: Context, activity: Class<*>, startedFrom: String, userName: String, eventLocation: String): Intent{ val intent = Intent(context, activity) intent.putExtra("documentID", this.eventID) intent.putExtra("posterUID", this.eventsModel.userUID) intent.putExtra("startedFrom", startedFrom) intent.putExtra("eventTitle", this.eventsModel.eventTitle) intent.putExtra("eventDesc", this.eventsModel.eventDesc) intent.putExtra("eventLocation", eventLocation) intent.putExtra("eventTicketLink", this.eventsModel.eventTicketLink) intent.putExtra("eventRegLink", this.eventsModel.eventRegLink) intent.putExtra("eventTicketLink", this.eventsModel.eventTicketLink) intent.putExtra("eventDate", this.eventsModel.eventDate) intent.putExtra("eventDressCode", this.eventsModel.eventDressCode) intent.putExtra("eventImageThumb", this.eventsModel.eventImageLinkThumb) intent.putExtra("eventImageLink", this.eventsModel.eventImageLink) intent.putExtra("eventType", this.eventsModel.eventType) intent.putExtra("userName", userName) intent.putExtra("eventMilis", this.eventsModel.eventMilis) return intent } fun EventsModel.toHashMap(): HashMap<String, Any?>{ val hashMap = HashMap<String, Any?>() hashMap["eventType"] = this.eventType hashMap["eventTitle"] = this.eventTitle hashMap["eventDesc"] = this.eventDesc hashMap["eventLocation"] = this.eventLocation hashMap["eventDate"] = this.eventDate hashMap["userUID"] = this.userUID hashMap["eventTags"] = this.eventTags hashMap["eventRegLink"] = this.eventRegLink hashMap["eventTicketLink"] = this.eventTicketLink hashMap["eventDressCode"] = this.eventDressCode hashMap["eventImageLink"] = this.eventImageLink hashMap["eventGuests"] = this.eventGuests hashMap["eventImageLinkThumb"] = this.eventImageLinkThumb hashMap["eventPostTime"] = this.eventPostTime hashMap["amountPaid"] = this.amountPaid hashMap["eventMilis"] = this.eventMilis return hashMap } fun Context.indicate(message: String){ Toast.makeText(this, message, Toast.LENGTH_SHORT) .show() }
0
null
0
0
5ed3ddef719b2814121b80f0a029707e1898100b
9,814
Tukio2.0
MIT License
app/src/main/java/com/qingmei2/sample/ui/main/MainViewModel.kt
msdgwzhy6
157,537,516
true
{"Kotlin": 112168}
package com.qingmei2.sample.ui.main import com.qingmei2.sample.base.BaseViewModel class MainViewModel : BaseViewModel()
0
Kotlin
0
1
ac829cbef19a105ce34589cda89c6c397386b60d
121
MVVM-Rhine
Apache License 2.0
app/src/main/java/com/example/testapp/dev/ui/navigation/MyFragmentNavigator.kt
matpag
175,480,427
false
null
package com.example.testapp.dev.ui.navigation import android.content.Context import android.os.Bundle import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import androidx.navigation.Navigator import androidx.navigation.fragment.FragmentNavigator /** * Temporary work-around to let navigation component consider our fragment factory * https://issuetracker.google.com/issues/119054429#comment4 */ @Navigator.Name("fragment") class MyFragmentNavigator( context: Context, fragmentManager: FragmentManager, fragmentContainer: Int ) : FragmentNavigator(context, fragmentManager, fragmentContainer) { override fun instantiateFragment(context: Context, fragmentManager: FragmentManager, className: String, args: Bundle?): Fragment { val clazz = Class.forName(className) return fragmentManager.fragmentFactory.instantiate(clazz.classLoader!!, className, args) } }
0
Kotlin
0
0
a5ea7c9d0b7839eaa52da10dd1845a47eda1e8a7
963
dagger-test-fragmentfactory
Apache License 2.0
src/main/kotlin/generator/builders/dsl/OkGenDslBuilder.kt
OKGenTool
766,121,849
false
{"Kotlin": 122205}
package generator.builders.dsl import com.squareup.kotlinpoet.* import datamodel.* import generator.builders.routing.routes.PATHSFILE import generator.capitalize import generator.decapitalize import generator.model.Packages import generator.model.Parameter import generator.model.Visibility import generator.writeFile import io.ktor.server.routing.* import org.slf4j.LoggerFactory private val logger = LoggerFactory.getLogger("OkGenDslBuilder.kt") private const val INNERCLASS = "OKGenRoute" private const val OUTERCLASS = "OkGenDsl" private const val APIOPERATIONS = "ApiOperations" private const val KTORROUTE = "ktorRoute" fun buildOkGenDsl(dslOperations: List<DSLOperation>, componentNames: List<String>) { logger.info("Generating $OUTERCLASS file") val logger = PropertySpec .builder("logger", ClassName("org.slf4j", "Logger")) .initializer( "%T.getLogger(%T::class.java.simpleName)", ClassName("org.slf4j", "LoggerFactory"), ClassName(Packages.DSL, "OkGenDsl") ).addModifiers(KModifier.PRIVATE) .build() val route = Parameter( KTORROUTE, Route::class.java.asTypeName(), Visibility.PRIVATE ) val fileSpec = FileSpec.builder(Packages.DSL, OUTERCLASS) .addProperty(logger) .addType( //Build outer class TypeSpec.classBuilder(OUTERCLASS) .getConstructor(listOf(route)) .addProperty( PropertySpec.builder( "route", ClassName( Packages.DSL, "$OUTERCLASS.$INNERCLASS" ) ) .initializer("$INNERCLASS()") .build() ) .addProperty( PropertySpec.builder( APIOPERATIONS.decapitalize(), ClassName( Packages.DSL, APIOPERATIONS ) ) .initializer("$APIOPERATIONS()") .addModifiers(KModifier.PRIVATE) .build() ) //Build inner Class .addType( getInnerClass(dslOperations) ) .build() ) .addImports(componentNames) writeFile(fileSpec.build()) } private fun getInnerClass(dslOperations: List<DSLOperation>): TypeSpec = TypeSpec.classBuilder(INNERCLASS).apply { addModifiers(KModifier.INNER) getOperationFunctions(dslOperations).forEach { addFunction(it) } }.build() private fun getOperationFunctions(dslOperations: List<DSLOperation>): List<FunSpec> { val functions = mutableListOf<FunSpec>() dslOperations.map { if (it.name in notImplemented) return@map //TODO implement these operations //Define suspend function for operation parameter val suspFunc = LambdaTypeName.get( receiver = ClassName(Packages.DSLOPERATIONS, it.name.capitalize()), returnType = UNIT ).copy(suspending = true) val codeBlock = CodeBlock.builder() .add("${APIOPERATIONS.decapitalize()}.addOperation(\"${it.name}\")\n") .add("$KTORROUTE.${it.method.value}<$PATHSFILE.${it.name.capitalize()}>{\n") .getRequestCode(it) .add("}") functions.add( FunSpec.builder(it.name) .addParameter("function", suspFunc) .addCode(codeBlock.build()) .build() ) } return functions } private fun CodeBlock.Builder.getRequestCode(operation: DSLOperation): CodeBlock.Builder { //For Requests with query parameters if (!operation.parameters.isNullOrEmpty()) { var parameters = "" operation.parameters.map { when (it.`in`) { In.PATH -> { this.add("\tval ${it.name} = call.parameters[\"${it.name}\"]${getConvertion(it.type)}\n") } else -> { if (it.type == DataType.ARRAY) this.add("\tval ${it.name} = call.request.rawQueryParameters[\"${it.name}\"]?.split(\",\")\n") else this.add("\tval ${it.name} = call.request.rawQueryParameters[\"${it.name}\"]\n") } } parameters += "${it.name}," } this.add("\tfunction(${operation.name.capitalize()}($parameters call))") } else { //For requests with body val body = operation.requestBody var className: String = "" when (body) { is BodyObj -> className = body.dataType.kotlinType.simpleName is BodyRef -> className = SchemaProps.getRefSimpleName(body.schemaRef) is BodyCollRef -> className = body.className is BodyCollPojo -> className = body.dataType.kotlinType.simpleName } this.add("\tvar body:${className.capitalize()}? = null\n") .add("\ttry {\n") .add("\t\tbody = call.receive<${className.capitalize()}>()\n") .add("\t}catch (ex: Exception){\n") .add("\t\tlogger.error(ex.message)\n") .add("\t}\n") .add("\tfunction(${operation.name.capitalize()}(body, call))") } return this } fun getConvertion(type: DataType): String = when (type) { DataType.INTEGER -> "?.toIntOrNull()" DataType.LONG -> "?.toLongOrNull()" DataType.FLOAT -> "?.toFloatOrNull()" DataType.DOUBLE -> "?.toDoubleOrNull()" DataType.BYTE -> "?.toByteOrNull()" DataType.BOOLEAN -> "?.toBoolean()" DataType.NUMBER -> "?.toDoubleOrNull()" DataType.ARRAY -> "?.split(\",\")" else -> { "" } } private fun FileSpec.Builder.addImports(componentNames: List<String>): FileSpec.Builder { this.addImport("io.ktor.server.resources", "post") .addImport("io.ktor.server.resources", "put") .addImport("io.ktor.server.resources", "get") .addImport("io.ktor.server.resources", "delete") .addImport("io.ktor.server.application", "call") .addImport("io.ktor.server.request", "receive") .addImport(Packages.ROUTES, PATHSFILE) componentNames.forEach { this.addImport(Packages.MODEL, it) } return this } //TODO implement these operations val notImplemented = setOf( "postPetPetIdUploadImage", "getInventory", "placeOrder", "createUser", "createUsersWithListInput", "logoutUser", "updateUser", "uploadFile" )
25
Kotlin
0
2
a50ca78edfb22cb5e88a5251a62611f4f9fbaad9
6,912
okgentool
Apache License 2.0
src/test/kotlin/com/yo1000/spree/beans/factory/config/JndiPropertyPlaceholderConfigureTest.kt
yo1000
110,262,228
false
{"Shell": 7058, "Kotlin": 4474}
package com.yo1000.spree.beans.factory.config import org.jetbrains.spek.api.Spek import org.jetbrains.spek.api.dsl.given import org.jetbrains.spek.api.dsl.it import org.jetbrains.spek.data_driven.data import org.jetbrains.spek.data_driven.on import org.springframework.mock.jndi.SimpleNamingContextBuilder import kotlin.test.assertEquals /** * * @author yo1000 */ class JndiPropertyPlaceholderConfigureTest : Spek({ given("the JNDI Resolver") { val contextBuilder = SimpleNamingContextBuilder() contextBuilder.bind("java:comp/env/Name1", "Value1") contextBuilder.bind("java:comp/Name2", "Value2") contextBuilder.bind("java:Name3", "Value3") contextBuilder.bind("Name4", "Value4") contextBuilder.activate() val data = arrayOf( data("Name1", "Value1"), data("Name2", "Value2"), data("Name3", "Value3"), data("Name4", "Value4"), data("Name0", "") ) on("resolvePlaceholder by '%s'", *data) { jndiName, expected -> val driver = object : JndiPropertyPlaceholderConfigure() { fun doResolvePlaceholder(jndiName: String): String? { return resolvePlaceholder(jndiName) } } it("should resolve to '$expected'") { assertEquals(driver.doResolvePlaceholder(jndiName) ?: "", expected) } } } })
0
Shell
0
0
05c1d75efc106b39a463332fe42f530dcfb536d6
1,470
spree
MIT License
app/src/main/java/com/example/nsc_events/MainActivity.kt
SeattleColleges
656,909,888
false
{"Kotlin": 180213}
package com.example.nsc_events import android.content.Context import android.content.SharedPreferences import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.tooling.preview.Preview import com.example.nsc_events.screen.ScreenMain import com.example.nsc_events.ui.theme.Nsc_eventsTheme class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { pref = getSharedPreferences("nscHidden", Context.MODE_PRIVATE) super.onCreate(savedInstanceState) setContent { Nsc_eventsTheme { // A surface container using the 'background' color from the theme Surface( modifier = Modifier.fillMaxSize(), color = MaterialTheme.colorScheme.background ) { ScreenMain() } } } } companion object { private lateinit var pref: SharedPreferences fun getPref(): SharedPreferences { return pref } } } @Preview(showBackground = true, showSystemUi = true) @Composable fun GreetingPreview() { Nsc_eventsTheme { ScreenMain() } }
3
Kotlin
3
4
32fae5f4eef3ff0671858ba164197ad40f689388
1,529
nsc-events-android
MIT License
compiler/testData/diagnostics/testsSpec/s-16.30_when-expression/p-3/pos/1.9.kt
petukhovv
105,522,774
true
{"Kotlin": 28221473, "Java": 7536538, "JavaScript": 153376, "HTML": 64401, "Lex": 18248, "ANTLR": 9797, "IDL": 8755, "Shell": 6769, "CSS": 4679, "Batchfile": 4437, "Groovy": 4358}
// !DIAGNOSTICS: -UNUSED_EXPRESSION /* KOTLIN SPEC TEST (POSITIVE) SECTION 16.30: When expression PARAGRAPH: 3 SENTENCE 1: When expression without bound value (the form where the expression enclosed in parantheses is absent) evaluates one of the many different expressions based on corresponding conditions present in the same when entry. NUMBER: 9 DESCRIPTION: 'When' with elvis operator expression in the control structure body. */ fun case_1(value: Int, value1: String?, value2: String?, value3: String?) { when { value == 1 -> value1 ?: true value == 2 -> value1 ?: value2 ?: true value == 3 -> value1 ?: value2 ?: value3 ?: true value == 4 -> value1!! <!USELESS_ELVIS!>?: true<!> value == 5 -> { value2 ?: value3 ?: true } } }
1
Kotlin
1
0
45c8f0c24b6655580acbdc4e967bbe0cd5763ac0
809
kotlin
Apache License 2.0
Tawaf/app/src/main/java/me/mxcsyounes/tawaf/models/Line2D.kt
Younes-Charfaoui
143,928,035
false
null
package me.mxcsyounes.tawaf.models; class Line2D { val a: Float val b: Float val c: Float constructor(a: Float, b: Float, c: Float) { this.a = a this.b = b this.c = c } constructor(pointOne: Point2D, pointTwo: Point2D) { this.a = pointTwo.y - pointOne.y; this.b = pointOne.x - pointTwo.x this.c = -(a * pointOne.x + b * pointOne.y) } fun distanceToPoint(point: Point2D): Double { val nominator = a * point.x + b * point.y + c val denominator = Math.sqrt((a * a + b * b).toDouble()); return nominator / denominator } fun getCoefficientOfGuid() = a / b }
0
Kotlin
1
2
765ea87de470aabe9733cc942a976c52bf276be3
671
Tawafi
MIT License
src/test/kotlin/me/peckb/aoc/_2018/calendar/day09/Day09Test.kt
peckb1
433,943,215
false
null
package me.peckb.aoc._2018.calendar.day09 import javax.inject.Inject import me.peckb.aoc._2018.DaggerTestDayComponent import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test internal class Day09Test { @Inject lateinit var day09: Day09 @BeforeEach fun setup() { DaggerTestDayComponent.create().inject(this) } @Test fun testDay09PartOne() { assertEquals(398048, day09.partOne(DAY_09)) } @Test fun testDay09PartTwo() { assertEquals(3180373421, day09.partTwo(DAY_09)) } companion object { private const val DAY_09: String = "advent-of-code-input/2018/day09.input" } }
0
Kotlin
1
4
62165673b98381031d964a962ed0328474d20870
685
advent-of-code
MIT License
RpcApp/app/src/androidTest/java/com/car_rpc/app/server_info/ServerInfoTest.kt
adiprerepa
198,348,521
false
{"Java": 79849, "Kotlin": 8268, "C++": 5749, "C": 3828, "Shell": 1975}
package com.car_rpc.app.server_info
15
Java
1
2
b171f5c1bfd50fe148571ad91029a70181797d90
37
Car-Rpc
MIT License
examples/android/src/main/kotlin/com/algolia/instantsearch/examples/android/showcase/androidview/filter/rating/RatingTextView.kt
algolia
55,971,521
false
null
package com.algolia.instantsearch.examples.showcase.view.filter.rating import android.widget.TextView import com.algolia.instantsearch.core.Callback import com.algolia.instantsearch.core.number.range.NumberRangeView import com.algolia.instantsearch.core.number.range.Range class RatingTextView(private val textView: TextView) : NumberRangeView<Float> { override var onRangeChanged: Callback<Range<Float>>? = null override fun setBounds(bounds: Range<Float>?) = Unit override fun setRange(range: Range<Float>?) { textView.text = "${range?.min ?: 0}" } }
5
null
30
156
eaf37a61303a8b9c5688a596e8aeab29dfbba398
582
instantsearch-android
Apache License 2.0