path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
src/main/kotlin/com/soquiz/plugins/routing/routes/QuestionRoutes.kt
waminiyi
859,267,402
false
{"Kotlin": 38025, "Dockerfile": 827}
package com.soquiz.plugins.routing.routes import com.soquiz.database.mapping.toQuestionWithDetails import com.soquiz.database.repositories.QuestionRepository import com.soquiz.models.Difficulty import com.soquiz.models.Language import com.soquiz.models.QuestionUpdate import com.soquiz.models.QuestionWithDetails import com.soquiz.utils.isAdminCall import com.soquiz.utils.isEditorCall import io.ktor.http.* import io.ktor.serialization.* import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.auth.jwt.* import io.ktor.server.request.* import io.ktor.server.response.* import io.ktor.server.routing.* fun Application.registerQuestionRoutes() { val repository = QuestionRepository() routing { route("/api/v1/quiz") { get { get { val limit = call.request.queryParameters["limit"]?.toIntOrNull() ?: 5 val language = call.request.queryParameters["language"]?.let { Language.valueOf(it) } ?: Language.en val category = call.request.queryParameters["category"] val topic = call.request.queryParameters["topic"] val difficulty = call.request.queryParameters["difficulty"]?.let { Difficulty.valueOf(it) } try { val questions = repository.getQuestions( limit = limit, language = language, category = category, topic = topic, difficulty = difficulty ) call.respond(HttpStatusCode.OK, questions) } catch (e: Exception) { call.respond(HttpStatusCode.BadRequest, "Invalid parameters: ${e.message}") } } } get("/{id}") { val questionId = call.parameters["id"] if (questionId == null) { call.respond(HttpStatusCode.BadRequest, "Missing question ID") return@get } val question = repository.getQuestionById(questionId) if (question == null) { call.respond(HttpStatusCode.NotFound, "Question not found") } else { call.respond(question) } } authenticate("auth-jwt") { post { if (!call.isAdminCall() && !call.isEditorCall()) { call.respond(HttpStatusCode.Forbidden, "You do not have permission to perform this action.") return@post } try { val post = call.receive<QuestionWithDetails>() repository.addQuestion(post) call.respond(HttpStatusCode.Created) } catch (ex: IllegalStateException) { call.respond(HttpStatusCode.BadRequest) } catch (ex: JsonConvertException) { call.respond(HttpStatusCode.BadRequest) } } patch("/{id}") { if (!call.isAdminCall() && !call.isEditorCall()) { call.respond(HttpStatusCode.Forbidden, "You do not have permission to perform this action.") return@patch } val questionId = call.parameters["id"] ?: return@patch call.respond( HttpStatusCode.BadRequest, "Missing question ID" ) try { val updateRequest = call.receive<QuestionUpdate>() val updatedQuestion = repository.updateQuestion(questionId, updateRequest) call.respond(HttpStatusCode.OK, updatedQuestion.toQuestionWithDetails()) } catch (ex: IllegalStateException) { call.respond(HttpStatusCode.BadRequest) } catch (ex: JsonConvertException) { call.respond(HttpStatusCode.BadRequest) } } } delete("{topicId}") { if (!call.isAdminCall() && !call.isEditorCall()) { call.respond(HttpStatusCode.Forbidden, "You do not have permission to perform this action.") return@delete } val questionId = call.parameters["id"] if (questionId == null) { call.respond(HttpStatusCode.BadRequest, "Missing question ID") return@delete } val result = repository.removeQuestion(questionId) if (result) { call.respond(HttpStatusCode.OK, "Question deleted successfully") } else { call.respond(HttpStatusCode.NotFound, "Question not found") } } } } }
0
Kotlin
0
0
c1c02fea3cc7883cab6270a1aee9d2b01f9e43ba
5,177
soquiz_api
PostgreSQL License
measurements/src/main/java/be/appwise/measurements/units/UnitArea.kt
appwise-labs
349,150,482
false
null
package be.appwise.measurements.units import android.icu.util.MeasureUnit import be.appwise.measurements.converters.UnitConverter import be.appwise.measurements.converters.UnitConverterLinear import be.appwise.measurements.isAtLeastO class UnitArea(symbol: String, converter: UnitConverter, measureUnit: MeasureUnit? = null) : Dimension(symbol, converter, measureUnit) { private constructor(symbol: String, coefficient: Double) : this(symbol, UnitConverterLinear(coefficient)) private constructor(symbol: String, coefficient: Double, measureUnit: MeasureUnit?) : this(symbol, UnitConverterLinear(coefficient), measureUnit) private object Symbol { const val squareMegameters = "Mm²" const val squareKilometers = "km²" const val squareMeters = "m²" const val squareCentimeters = "cm²" const val squareMillimeters = "mm²" const val squareMicrometers = "µm²" const val squareNanometers = "nm²" const val squareInches = "in²" const val squareFeet = "ft²" const val squareYards = "yd²" const val squareMiles = "mi²" const val acres = "ac" const val ares = "a" const val hectares = "ha" } private object Coefficient { const val squareMegameters = 1e12 const val squareKilometers = 1e6 const val squareMeters = 1.0 const val squareCentimeters = 1e-4 const val squareMillimeters = 1e-6 const val squareMicrometers = 1e-12 const val squareNanometers = 1e-18 const val squareInches = 0.00064516 const val squareFeet = 0.092903 const val squareYards = 0.836127 const val squareMiles = 2.59e+6 const val acres = 4046.86 const val ares = 100.0 const val hectares = 10000.0 } private object Unit { val squareMegameters = null val squareKilometers = if (isAtLeastO) MeasureUnit.SQUARE_KILOMETER else null val squareMeters = if (isAtLeastO) MeasureUnit.SQUARE_METER else null val squareCentimeters = if (isAtLeastO) MeasureUnit.SQUARE_CENTIMETER else null val squareMillimeters = null val squareMicrometers = null val squareNanometers = null val squareInches = if (isAtLeastO) MeasureUnit.SQUARE_INCH else null val squareFeet = if (isAtLeastO) MeasureUnit.SQUARE_FOOT else null val squareYards = if (isAtLeastO) MeasureUnit.SQUARE_YARD else null val squareMiles = if (isAtLeastO) MeasureUnit.SQUARE_MILE else null val acres = if (isAtLeastO) MeasureUnit.ACRE else null val ares = null val hectares = if (isAtLeastO) MeasureUnit.HECTARE else null } companion object { val squareMegameters = UnitArea(Symbol.squareMegameters, Coefficient.squareMegameters, Unit.squareMegameters) val squareKilometers = UnitArea(Symbol.squareKilometers, Coefficient.squareKilometers, Unit.squareKilometers) val squareMeters = UnitArea(Symbol.squareMeters, Coefficient.squareMeters, Unit.squareMeters) val squareCentimeters = UnitArea(Symbol.squareCentimeters, Coefficient.squareCentimeters, Unit.squareCentimeters) val squareMillimeters = UnitArea(Symbol.squareMillimeters, Coefficient.squareMillimeters, Unit.squareMillimeters) val squareMicrometers = UnitArea(Symbol.squareMicrometers, Coefficient.squareMicrometers, Unit.squareMicrometers) val squareNanometers = UnitArea(Symbol.squareNanometers, Coefficient.squareNanometers, Unit.squareNanometers) val squareInches = UnitArea(Symbol.squareInches, Coefficient.squareInches, Unit.squareInches) val squareFeet = UnitArea(Symbol.squareFeet, Coefficient.squareFeet, Unit.squareFeet) val squareYards = UnitArea(Symbol.squareYards, Coefficient.squareYards, Unit.squareYards) val squareMiles = UnitArea(Symbol.squareMiles, Coefficient.squareMiles, Unit.squareMiles) val acres = UnitArea(Symbol.acres, Coefficient.acres, Unit.acres) val ares = UnitArea(Symbol.ares, Coefficient.ares, Unit.ares) val hectares = UnitArea(Symbol.hectares, Coefficient.hectares, Unit.hectares) } override fun baseUnit() = squareMeters }
19
Kotlin
4
5
2eed1771160637082553336aa7673d076c518264
4,225
AndroidCore
MIT License
core/src/main/java/com/kylecorry/andromeda/core/specifications/Specification.kt
kylecorry31
394,273,851
false
null
package com.kylecorry.andromeda.core.specifications abstract class Specification<T> { abstract fun isSatisfiedBy(value: T): Boolean fun and(other: Specification<T>): Specification<T> { return AndSpecification(this, other) } fun or(other: Specification<T>): Specification<T> { return OrSpecification(this, other) } fun not(): Specification<T> { return NotSpecification(this) } }
29
Kotlin
0
8
4ddd86ebe72ffec5c6f9800e61eb54b29d9dd5ed
435
andromeda
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/TrashClock.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Outline.TrashClock: ImageVector get() { if (_trashClock != null) { return _trashClock!! } _trashClock = Builder(name = "TrashClock", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveToRelative(9.0f, 22.0f) horizontalLineToRelative(-0.866f) curveToRelative(-1.554f, 0.0f, -2.837f, -1.166f, -2.986f, -2.713f) lineToRelative(-1.277f, -13.287f) horizontalLineToRelative(14.236f) lineToRelative(-0.086f, 0.905f) curveToRelative(-0.053f, 0.55f, 0.351f, 1.038f, 0.9f, 1.09f) curveToRelative(0.032f, 0.004f, 0.064f, 0.005f, 0.096f, 0.005f) curveToRelative(0.51f, 0.0f, 0.945f, -0.388f, 0.994f, -0.905f) lineToRelative(0.104f, -1.095f) horizontalLineToRelative(0.886f) curveToRelative(0.553f, 0.0f, 1.0f, -0.447f, 1.0f, -1.0f) reflectiveCurveToRelative(-0.447f, -1.0f, -1.0f, -1.0f) horizontalLineToRelative(-4.101f) curveToRelative(-0.465f, -2.279f, -2.485f, -4.0f, -4.899f, -4.0f) horizontalLineToRelative(-2.0f) curveToRelative(-2.414f, 0.0f, -4.435f, 1.721f, -4.899f, 4.0f) lineTo(1.0f, 4.0f) curveToRelative(-0.553f, 0.0f, -1.0f, 0.447f, -1.0f, 1.0f) reflectiveCurveToRelative(0.447f, 1.0f, 1.0f, 1.0f) horizontalLineToRelative(0.861f) lineToRelative(1.296f, 13.479f) curveToRelative(0.247f, 2.578f, 2.387f, 4.521f, 4.977f, 4.521f) horizontalLineToRelative(0.866f) curveToRelative(0.553f, 0.0f, 1.0f, -0.447f, 1.0f, -1.0f) reflectiveCurveToRelative(-0.447f, -1.0f, -1.0f, -1.0f) close() moveTo(10.0f, 2.0f) horizontalLineToRelative(2.0f) curveToRelative(1.304f, 0.0f, 2.415f, 0.836f, 2.828f, 2.0f) horizontalLineToRelative(-7.656f) curveToRelative(0.413f, -1.164f, 1.524f, -2.0f, 2.828f, -2.0f) close() moveTo(17.0f, 10.0f) curveToRelative(-3.859f, 0.0f, -7.0f, 3.141f, -7.0f, 7.0f) reflectiveCurveToRelative(3.141f, 7.0f, 7.0f, 7.0f) reflectiveCurveToRelative(7.0f, -3.141f, 7.0f, -7.0f) reflectiveCurveToRelative(-3.141f, -7.0f, -7.0f, -7.0f) close() moveTo(17.0f, 22.0f) curveToRelative(-2.757f, 0.0f, -5.0f, -2.243f, -5.0f, -5.0f) reflectiveCurveToRelative(2.243f, -5.0f, 5.0f, -5.0f) reflectiveCurveToRelative(5.0f, 2.243f, 5.0f, 5.0f) reflectiveCurveToRelative(-2.243f, 5.0f, -5.0f, 5.0f) close() moveTo(18.707f, 17.293f) curveToRelative(0.391f, 0.391f, 0.391f, 1.023f, 0.0f, 1.414f) curveToRelative(-0.195f, 0.195f, -0.451f, 0.293f, -0.707f, 0.293f) reflectiveCurveToRelative(-0.512f, -0.098f, -0.707f, -0.293f) lineToRelative(-1.0f, -1.0f) curveToRelative(-0.188f, -0.188f, -0.293f, -0.441f, -0.293f, -0.707f) verticalLineToRelative(-2.0f) curveToRelative(0.0f, -0.553f, 0.447f, -1.0f, 1.0f, -1.0f) reflectiveCurveToRelative(1.0f, 0.447f, 1.0f, 1.0f) verticalLineToRelative(1.586f) lineToRelative(0.707f, 0.707f) close() } } .build() return _trashClock!! } private var _trashClock: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
4,581
icons
MIT License
src/me/anno/utils/structures/arrays/IntArrayList.kt
won21kr
351,713,352
true
{"Kotlin": 1983578, "Java": 301507, "C": 75596, "GLSL": 9436}
package me.anno.utils.structures.arrays class IntArrayList(val capacity: Int){ private val buffers = ArrayList<IntArray>() var size = 0 operator fun get(index: Int) = buffers[index / capacity][index % capacity] operator fun plusAssign(value: Int){ val index = size % capacity if(index == 0) buffers.add(IntArray(capacity)) buffers.last()[index] = value size++ } }
0
null
0
0
b85295f59ddfa9fc613a384d439fd1b30b06a5a4
416
RemsStudio
Apache License 2.0
mybatis-flex-kotlin-ksp/src/test/kotlin/KTest.kt
KAMO030
678,726,164
false
{"Kotlin": 229069, "Smarty": 4372, "Java": 95}
import org.junit.jupiter.api.Test class KTest { @Test fun test() { } }
0
Kotlin
4
25
5e4539da55d0d7d3ed9f5f4c401fd33b86f49457
84
MyBatis-Flex-Kotlin
Apache License 2.0
keel-echo/src/main/kotlin/com/netflix/spinnaker/keel/echo/EchoService.kt
robumberger
114,662,961
true
{"Kotlin": 276511, "Shell": 2094}
/* * Copyright 2017 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.spinnaker.keel.echo import com.fasterxml.jackson.annotation.JsonInclude import com.netflix.spinnaker.keel.policy.NotificationSeverity import retrofit.client.Response import retrofit.http.Body import retrofit.http.POST interface EchoService { // @Headers("Content-type: application/json") @POST("/notifications") fun create(@Body notification: Notification): Response @JsonInclude(JsonInclude.Include.NON_NULL) data class Notification( val notificationType: Type, val to: Collection<String>, val cc: Collection<String> = listOf(), val templateGroup: String, val severity: NotificationSeverity, val source: Source, val additionalContext: Map<String, Any?> = mapOf() ) { data class Source(val application: String) enum class Type { SLACK, HIPCHAT, EMAIL, SMS, PAGER_DUTY } } }
0
Kotlin
0
0
5381ff45dde711ccaab904c61085c2d4bf2ad87c
1,479
keel
Apache License 2.0
app/src/main/java/chat/rocket/android/authentication/login/presentation/LoginPresenter.kt
mortada-codes
139,255,922
true
{"Kotlin": 780066, "Shell": 2737}
package chat.rocket.android.authentication.login.presentation import chat.rocket.android.authentication.domain.model.LoginDeepLinkInfo import chat.rocket.android.authentication.presentation.AuthenticationNavigator import chat.rocket.android.core.lifecycle.CancelStrategy import chat.rocket.android.helper.OauthHelper import chat.rocket.android.infrastructure.LocalRepository import chat.rocket.android.server.domain.GetAccountsInteractor import chat.rocket.android.server.domain.GetConnectingServerInteractor import chat.rocket.android.server.domain.GetSettingsInteractor import chat.rocket.android.server.domain.PublicSettings import chat.rocket.android.server.domain.SaveAccountInteractor import chat.rocket.android.server.domain.SaveCurrentServerInteractor import chat.rocket.android.server.domain.TokenRepository import chat.rocket.android.server.domain.casLoginUrl import chat.rocket.android.server.domain.favicon import chat.rocket.android.server.domain.gitlabUrl import chat.rocket.android.server.domain.isCasAuthenticationEnabled import chat.rocket.android.server.domain.isFacebookAuthenticationEnabled import chat.rocket.android.server.domain.isGithubAuthenticationEnabled import chat.rocket.android.server.domain.isGitlabAuthenticationEnabled import chat.rocket.android.server.domain.isGoogleAuthenticationEnabled import chat.rocket.android.server.domain.isLdapAuthenticationEnabled import chat.rocket.android.server.domain.isLinkedinAuthenticationEnabled import chat.rocket.android.server.domain.isLoginFormEnabled import chat.rocket.android.server.domain.isMeteorAuthenticationEnabled import chat.rocket.android.server.domain.isPasswordResetEnabled import chat.rocket.android.server.domain.isRegistrationEnabledForNewUsers import chat.rocket.android.server.domain.isTwitterAuthenticationEnabled import chat.rocket.android.server.domain.model.Account import chat.rocket.android.server.domain.wideTile import chat.rocket.android.server.infraestructure.RocketChatClientFactory import chat.rocket.android.util.extension.launchUI import chat.rocket.android.util.extensions.avatarUrl import chat.rocket.android.util.extensions.casUrl import chat.rocket.android.util.extensions.encodeToBase64 import chat.rocket.android.util.extensions.generateRandomString import chat.rocket.android.util.extensions.isEmail import chat.rocket.android.util.extensions.parseColor import chat.rocket.android.util.extensions.registerPushToken import chat.rocket.android.util.extensions.samlUrl import chat.rocket.android.util.extensions.serverLogoUrl import chat.rocket.android.util.retryIO import chat.rocket.common.RocketChatAuthException import chat.rocket.common.RocketChatException import chat.rocket.common.RocketChatTwoFactorException import chat.rocket.common.model.Email import chat.rocket.common.model.Token import chat.rocket.common.model.User import chat.rocket.common.util.ifNull import chat.rocket.core.RocketChatClient import chat.rocket.core.internal.rest.login import chat.rocket.core.internal.rest.loginWithCas import chat.rocket.core.internal.rest.loginWithEmail import chat.rocket.core.internal.rest.loginWithLdap import chat.rocket.core.internal.rest.loginWithOauth import chat.rocket.core.internal.rest.loginWithSaml import chat.rocket.core.internal.rest.me import chat.rocket.core.internal.rest.settingsOauth import kotlinx.coroutines.experimental.delay import timber.log.Timber import java.util.concurrent.TimeUnit import javax.inject.Inject private const val TYPE_LOGIN_USER_EMAIL = 0 private const val TYPE_LOGIN_CAS = 1 private const val TYPE_LOGIN_SAML = 2 private const val TYPE_LOGIN_OAUTH = 3 private const val TYPE_LOGIN_DEEP_LINK = 4 private const val SERVICE_NAME_FACEBOOK = "facebook" private const val SERVICE_NAME_GITHUB = "github" private const val SERVICE_NAME_GOOGLE = "google" private const val SERVICE_NAME_LINKEDIN = "linkedin" private const val SERVICE_NAME_GILAB = "gitlab" class LoginPresenter @Inject constructor( private val view: LoginView, private val strategy: CancelStrategy, private val navigator: AuthenticationNavigator, private val tokenRepository: TokenRepository, private val localRepository: LocalRepository, private val getAccountsInteractor: GetAccountsInteractor, private val settingsInteractor: GetSettingsInteractor, serverInteractor: GetConnectingServerInteractor, private val saveCurrentServer: SaveCurrentServerInteractor, private val saveAccountInteractor: SaveAccountInteractor, private val factory: RocketChatClientFactory ) { // TODO - we should validate the current server when opening the app, and have a nonnull get() private var currentServer = serverInteractor.get()!! private lateinit var client: RocketChatClient private lateinit var settings: PublicSettings private lateinit var usernameOrEmail: String private lateinit var password: String private lateinit var credentialToken: String private lateinit var credentialSecret: String private lateinit var deepLinkUserId: String private lateinit var deepLinkToken: String fun setupView() { setupConnectionInfo(currentServer) setupLoginView() setupUserRegistrationView() setupForgotPasswordView() setupCasView() setupOauthServicesView() } fun authenticateWithUserAndPassword(usernameOrEmail: String, password: String) { when { usernameOrEmail.isBlank() -> { view.alertWrongUsernameOrEmail() } password.isEmpty() -> { view.alertWrongPassword() } else -> { this.usernameOrEmail = usernameOrEmail this.password = password doAuthentication(TYPE_LOGIN_USER_EMAIL) } } } fun authenticateWithCas(casToken: String) { credentialToken = casToken doAuthentication(TYPE_LOGIN_CAS) } fun authenticateWithSaml(samlToken: String) { credentialToken = samlToken doAuthentication(TYPE_LOGIN_SAML) } fun authenticateWithOauth(oauthToken: String, oauthSecret: String) { credentialToken = oauthToken credentialSecret = oauthSecret doAuthentication(TYPE_LOGIN_OAUTH) } fun authenticateWithDeepLink(deepLinkInfo: LoginDeepLinkInfo) { val serverUrl = deepLinkInfo.url setupConnectionInfo(serverUrl) deepLinkUserId = deepLinkInfo.userId deepLinkToken = deepLinkInfo.token tokenRepository.save(serverUrl, Token(deepLinkUserId, deepLinkToken)) doAuthentication(TYPE_LOGIN_DEEP_LINK) } private fun setupConnectionInfo(serverUrl: String) { currentServer = serverUrl client = factory.create(serverUrl) settings = settingsInteractor.get(serverUrl) } fun signup() = navigator.toSignUp() fun forgotPassword() = navigator.toForgotPassword() private fun setupLoginView() { if (settings.isLoginFormEnabled()) { view.showFormView() view.setupLoginButtonListener() view.setupGlobalListener() } else { view.hideFormView() } } private fun setupCasView() { if (settings.isCasAuthenticationEnabled()) { val casToken = generateRandomString(17) view.setupCasButtonListener( settings.casLoginUrl().casUrl(currentServer, casToken), casToken ) view.showCasButton() } } private fun setupUserRegistrationView() { if (settings.isRegistrationEnabledForNewUsers() && settings.isLoginFormEnabled()) { view.setupSignUpView() view.showSignUpView() } } private fun setupForgotPasswordView() { if (settings.isPasswordResetEnabled()) { view.setupForgotPasswordView() view.showForgotPasswordView() } } private fun setupOauthServicesView() { launchUI(strategy) { try { val services = retryIO("settingsOauth()") { client.settingsOauth().services } if (services.isNotEmpty()) { val state = "{\"loginStyle\":\"popup\",\"credentialToken\":\"${generateRandomString(40)}\",\"isCordova\":true}".encodeToBase64() var totalSocialAccountsEnabled = 0 if (settings.isFacebookAuthenticationEnabled()) { val clientId = getOauthClientId(services, SERVICE_NAME_FACEBOOK) if (clientId != null) { view.setupFacebookButtonListener( OauthHelper.getFacebookOauthUrl( clientId, currentServer, state ), state ) view.enableLoginByFacebook() totalSocialAccountsEnabled++ } } if (settings.isGithubAuthenticationEnabled()) { val clientId = getOauthClientId(services, SERVICE_NAME_GITHUB) if (clientId != null) { view.setupGithubButtonListener( OauthHelper.getGithubOauthUrl( clientId, state ), state ) view.enableLoginByGithub() totalSocialAccountsEnabled++ } } if (settings.isGoogleAuthenticationEnabled()) { val clientId = getOauthClientId(services, SERVICE_NAME_GOOGLE) if (clientId != null) { view.setupGoogleButtonListener( OauthHelper.getGoogleOauthUrl( clientId, currentServer, state ), state ) view.enableLoginByGoogle() totalSocialAccountsEnabled++ } } if (settings.isLinkedinAuthenticationEnabled()) { val clientId = getOauthClientId(services, SERVICE_NAME_LINKEDIN) if (clientId != null) { view.setupLinkedinButtonListener( OauthHelper.getLinkedinOauthUrl( clientId, currentServer, state ), state ) view.enableLoginByLinkedin() totalSocialAccountsEnabled++ } } if (settings.isMeteorAuthenticationEnabled()) { //TODO: Remove until we have this implemented // view.enableLoginByMeteor() // totalSocialAccountsEnabled++ } if (settings.isTwitterAuthenticationEnabled()) { //TODO: Remove until Twitter provides support to OAuth2 // view.enableLoginByTwitter() // totalSocialAccountsEnabled++ } if (settings.isGitlabAuthenticationEnabled()) { val clientId = getOauthClientId(services, SERVICE_NAME_GILAB) if (clientId != null) { val gitlabOauthUrl = if (settings.gitlabUrl() != null) { OauthHelper.getGitlabOauthUrl( host = settings.gitlabUrl(), clientId = clientId, serverUrl = currentServer, state = state ) } else { OauthHelper.getGitlabOauthUrl( clientId = clientId, serverUrl = currentServer, state = state ) } view.setupGitlabButtonListener(gitlabOauthUrl, state) view.enableLoginByGitlab() totalSocialAccountsEnabled++ } } getCustomOauthServices(services).let { for (service in it) { val serviceName = getCustomOauthServiceName(service) val customOauthUrl = OauthHelper.getCustomOauthUrl( getCustomOauthHost(service), getCustomOauthAuthorizePath(service), getCustomOauthClientId(service), currentServer, serviceName, state, getCustomOauthScope(service) ) view.addCustomOauthServiceButton( customOauthUrl, state, serviceName, getServiceNameColor(service), getServiceButtonColor(service) ) totalSocialAccountsEnabled++ } } getSamlServices(services).let { val samlToken = generateRandomString(17) for (service in it) { view.addSamlServiceButton( currentServer.samlUrl(getSamlProvider(service), samlToken), samlToken, getSamlServiceName(service), getServiceNameColor(service), getServiceButtonColor(service) ) totalSocialAccountsEnabled++ } } if (totalSocialAccountsEnabled > 0) { view.enableOauthView() if (totalSocialAccountsEnabled > 3) { view.setupFabListener() } } else { view.disableOauthView() } } else { view.disableOauthView() } } catch (exception: RocketChatException) { Timber.e(exception) view.disableOauthView() } } } private fun doAuthentication(loginType: Int) { launchUI(strategy) { view.disableUserInput() view.showLoading() try { val token = retryIO("login") { when (loginType) { TYPE_LOGIN_USER_EMAIL -> { when { settings.isLdapAuthenticationEnabled() -> client.loginWithLdap(usernameOrEmail, password) usernameOrEmail.isEmail() -> client.loginWithEmail(usernameOrEmail, password) else -> client.login(usernameOrEmail, password) } } TYPE_LOGIN_CAS -> { delay(3, TimeUnit.SECONDS) client.loginWithCas(credentialToken) } TYPE_LOGIN_SAML -> { delay(3, TimeUnit.SECONDS) client.loginWithSaml(credentialToken) } TYPE_LOGIN_OAUTH -> { client.loginWithOauth(credentialToken, credentialSecret) } TYPE_LOGIN_DEEP_LINK -> { val myself = client.me() // Just checking if the credentials worked. if (myself.id == deepLinkUserId) { Token(deepLinkUserId, deepLinkToken) } else { throw RocketChatAuthException("Invalid Authentication Deep Link Credentials...") } } else -> { throw IllegalStateException("Expected TYPE_LOGIN_USER_EMAIL, TYPE_LOGIN_CAS,TYPE_LOGIN_SAML, TYPE_LOGIN_OAUTH or TYPE_LOGIN_DEEP_LINK") } } } val myself = retryIO("me()") { client.me() } if (myself.username != null) { val user = User( id = myself.id, roles = myself.roles, status = myself.status, name = myself.name, emails = myself.emails?.map { Email(it.address ?: "", it.verified) }, username = myself.username, utcOffset = myself.utcOffset ) localRepository.saveCurrentUser(url = currentServer, user = user) saveCurrentServer.save(currentServer) saveAccount(myself.username!!) saveToken(token) registerPushToken() if (loginType == TYPE_LOGIN_USER_EMAIL) { view.saveSmartLockCredentials(usernameOrEmail, password) } navigator.toChatList() } else if (loginType == TYPE_LOGIN_OAUTH) { navigator.toRegisterUsername(token.userId, token.authToken) } } catch (exception: RocketChatException) { when (exception) { is RocketChatTwoFactorException -> { navigator.toTwoFA(usernameOrEmail, password) } else -> { exception.message?.let { view.showMessage(it) }.ifNull { view.showGenericErrorMessage() } } } } finally { view.hideLoading() view.enableUserInput() } } } private fun getOauthClientId(listMap: List<Map<String, Any>>, serviceName: String): String? { return listMap.find { map -> map.containsValue(serviceName) }?.let { it["clientId"] ?: it["appId"] }.toString() } private fun getSamlServices(listMap: List<Map<String, Any>>): List<Map<String, Any>> { return listMap.filter { map -> map["service"] == "saml" } } private fun getSamlServiceName(service: Map<String, Any>): String { return service["buttonLabelText"].toString() } private fun getSamlProvider(service: Map<String, Any>): String { return (service["clientConfig"] as Map<*, *>)["provider"].toString() } private fun getCustomOauthServices(listMap: List<Map<String, Any>>): List<Map<String, Any>> { return listMap.filter { map -> map["custom"] == true } } private fun getCustomOauthHost(service: Map<String, Any>): String { return service["serverURL"].toString() } private fun getCustomOauthAuthorizePath(service: Map<String, Any>): String { return service["authorizePath"].toString() } private fun getCustomOauthClientId(service: Map<String, Any>): String { return service["clientId"].toString() } private fun getCustomOauthServiceName(service: Map<String, Any>): String { return service["service"].toString() } private fun getCustomOauthScope(service: Map<String, Any>): String { return service["scope"].toString() } private fun getServiceButtonColor(service: Map<String, Any>): Int { return service["buttonColor"].toString().parseColor() } private fun getServiceNameColor(service: Map<String, Any>): Int { return service["buttonLabelColor"].toString().parseColor() } private suspend fun saveAccount(username: String) { val icon = settings.favicon()?.let { currentServer.serverLogoUrl(it) } val logo = settings.wideTile()?.let { currentServer.serverLogoUrl(it) } val thumb = currentServer.avatarUrl(username) val account = Account(currentServer, icon, logo, username, thumb) saveAccountInteractor.save(account) } private fun saveToken(token: Token) { tokenRepository.save(currentServer, token) } private suspend fun registerPushToken() { localRepository.get(LocalRepository.KEY_PUSH_TOKEN)?.let { client.registerPushToken(it, getAccountsInteractor.get(), factory) } // TODO: When the push token is null, at some point we should receive it with // onTokenRefresh() on FirebaseTokenService, we need to confirm it. } }
0
Kotlin
0
1
e6b014150523f5f5ee1390ca34893472a02bbfef
21,981
Rocket.Chat.Android
MIT License
app/src/main/java/chat/rocket/android/authentication/login/presentation/LoginPresenter.kt
mortada-codes
139,255,922
true
{"Kotlin": 780066, "Shell": 2737}
package chat.rocket.android.authentication.login.presentation import chat.rocket.android.authentication.domain.model.LoginDeepLinkInfo import chat.rocket.android.authentication.presentation.AuthenticationNavigator import chat.rocket.android.core.lifecycle.CancelStrategy import chat.rocket.android.helper.OauthHelper import chat.rocket.android.infrastructure.LocalRepository import chat.rocket.android.server.domain.GetAccountsInteractor import chat.rocket.android.server.domain.GetConnectingServerInteractor import chat.rocket.android.server.domain.GetSettingsInteractor import chat.rocket.android.server.domain.PublicSettings import chat.rocket.android.server.domain.SaveAccountInteractor import chat.rocket.android.server.domain.SaveCurrentServerInteractor import chat.rocket.android.server.domain.TokenRepository import chat.rocket.android.server.domain.casLoginUrl import chat.rocket.android.server.domain.favicon import chat.rocket.android.server.domain.gitlabUrl import chat.rocket.android.server.domain.isCasAuthenticationEnabled import chat.rocket.android.server.domain.isFacebookAuthenticationEnabled import chat.rocket.android.server.domain.isGithubAuthenticationEnabled import chat.rocket.android.server.domain.isGitlabAuthenticationEnabled import chat.rocket.android.server.domain.isGoogleAuthenticationEnabled import chat.rocket.android.server.domain.isLdapAuthenticationEnabled import chat.rocket.android.server.domain.isLinkedinAuthenticationEnabled import chat.rocket.android.server.domain.isLoginFormEnabled import chat.rocket.android.server.domain.isMeteorAuthenticationEnabled import chat.rocket.android.server.domain.isPasswordResetEnabled import chat.rocket.android.server.domain.isRegistrationEnabledForNewUsers import chat.rocket.android.server.domain.isTwitterAuthenticationEnabled import chat.rocket.android.server.domain.model.Account import chat.rocket.android.server.domain.wideTile import chat.rocket.android.server.infraestructure.RocketChatClientFactory import chat.rocket.android.util.extension.launchUI import chat.rocket.android.util.extensions.avatarUrl import chat.rocket.android.util.extensions.casUrl import chat.rocket.android.util.extensions.encodeToBase64 import chat.rocket.android.util.extensions.generateRandomString import chat.rocket.android.util.extensions.isEmail import chat.rocket.android.util.extensions.parseColor import chat.rocket.android.util.extensions.registerPushToken import chat.rocket.android.util.extensions.samlUrl import chat.rocket.android.util.extensions.serverLogoUrl import chat.rocket.android.util.retryIO import chat.rocket.common.RocketChatAuthException import chat.rocket.common.RocketChatException import chat.rocket.common.RocketChatTwoFactorException import chat.rocket.common.model.Email import chat.rocket.common.model.Token import chat.rocket.common.model.User import chat.rocket.common.util.ifNull import chat.rocket.core.RocketChatClient import chat.rocket.core.internal.rest.login import chat.rocket.core.internal.rest.loginWithCas import chat.rocket.core.internal.rest.loginWithEmail import chat.rocket.core.internal.rest.loginWithLdap import chat.rocket.core.internal.rest.loginWithOauth import chat.rocket.core.internal.rest.loginWithSaml import chat.rocket.core.internal.rest.me import chat.rocket.core.internal.rest.settingsOauth import kotlinx.coroutines.experimental.delay import timber.log.Timber import java.util.concurrent.TimeUnit import javax.inject.Inject private const val TYPE_LOGIN_USER_EMAIL = 0 private const val TYPE_LOGIN_CAS = 1 private const val TYPE_LOGIN_SAML = 2 private const val TYPE_LOGIN_OAUTH = 3 private const val TYPE_LOGIN_DEEP_LINK = 4 private const val SERVICE_NAME_FACEBOOK = "facebook" private const val SERVICE_NAME_GITHUB = "github" private const val SERVICE_NAME_GOOGLE = "google" private const val SERVICE_NAME_LINKEDIN = "linkedin" private const val SERVICE_NAME_GILAB = "gitlab" class LoginPresenter @Inject constructor( private val view: LoginView, private val strategy: CancelStrategy, private val navigator: AuthenticationNavigator, private val tokenRepository: TokenRepository, private val localRepository: LocalRepository, private val getAccountsInteractor: GetAccountsInteractor, private val settingsInteractor: GetSettingsInteractor, serverInteractor: GetConnectingServerInteractor, private val saveCurrentServer: SaveCurrentServerInteractor, private val saveAccountInteractor: SaveAccountInteractor, private val factory: RocketChatClientFactory ) { // TODO - we should validate the current server when opening the app, and have a nonnull get() private var currentServer = serverInteractor.get()!! private lateinit var client: RocketChatClient private lateinit var settings: PublicSettings private lateinit var usernameOrEmail: String private lateinit var password: String private lateinit var credentialToken: String private lateinit var credentialSecret: String private lateinit var deepLinkUserId: String private lateinit var deepLinkToken: String fun setupView() { setupConnectionInfo(currentServer) setupLoginView() setupUserRegistrationView() setupForgotPasswordView() setupCasView() setupOauthServicesView() } fun authenticateWithUserAndPassword(usernameOrEmail: String, password: String) { when { usernameOrEmail.isBlank() -> { view.alertWrongUsernameOrEmail() } password.isEmpty() -> { view.alertWrongPassword() } else -> { this.usernameOrEmail = usernameOrEmail this.password = <PASSWORD> doAuthentication(TYPE_LOGIN_USER_EMAIL) } } } fun authenticateWithCas(casToken: String) { credentialToken = casToken doAuthentication(TYPE_LOGIN_CAS) } fun authenticateWithSaml(samlToken: String) { credentialToken = samlToken doAuthentication(TYPE_LOGIN_SAML) } fun authenticateWithOauth(oauthToken: String, oauthSecret: String) { credentialToken = oauthToken credentialSecret = oauthSecret doAuthentication(TYPE_LOGIN_OAUTH) } fun authenticateWithDeepLink(deepLinkInfo: LoginDeepLinkInfo) { val serverUrl = deepLinkInfo.url setupConnectionInfo(serverUrl) deepLinkUserId = deepLinkInfo.userId deepLinkToken = deepLinkInfo.token tokenRepository.save(serverUrl, Token(deepLinkUserId, deepLinkToken)) doAuthentication(TYPE_LOGIN_DEEP_LINK) } private fun setupConnectionInfo(serverUrl: String) { currentServer = serverUrl client = factory.create(serverUrl) settings = settingsInteractor.get(serverUrl) } fun signup() = navigator.toSignUp() fun forgotPassword() = navigator.toForgotPassword() private fun setupLoginView() { if (settings.isLoginFormEnabled()) { view.showFormView() view.setupLoginButtonListener() view.setupGlobalListener() } else { view.hideFormView() } } private fun setupCasView() { if (settings.isCasAuthenticationEnabled()) { val casToken = generateRandomString(17) view.setupCasButtonListener( settings.casLoginUrl().casUrl(currentServer, casToken), casToken ) view.showCasButton() } } private fun setupUserRegistrationView() { if (settings.isRegistrationEnabledForNewUsers() && settings.isLoginFormEnabled()) { view.setupSignUpView() view.showSignUpView() } } private fun setupForgotPasswordView() { if (settings.isPasswordResetEnabled()) { view.setupForgotPasswordView() view.showForgotPasswordView() } } private fun setupOauthServicesView() { launchUI(strategy) { try { val services = retryIO("settingsOauth()") { client.settingsOauth().services } if (services.isNotEmpty()) { val state = "{\"loginStyle\":\"popup\",\"credentialToken\":\"${generateRandomString(40)}\",\"isCordova\":true}".encodeToBase64() var totalSocialAccountsEnabled = 0 if (settings.isFacebookAuthenticationEnabled()) { val clientId = getOauthClientId(services, SERVICE_NAME_FACEBOOK) if (clientId != null) { view.setupFacebookButtonListener( OauthHelper.getFacebookOauthUrl( clientId, currentServer, state ), state ) view.enableLoginByFacebook() totalSocialAccountsEnabled++ } } if (settings.isGithubAuthenticationEnabled()) { val clientId = getOauthClientId(services, SERVICE_NAME_GITHUB) if (clientId != null) { view.setupGithubButtonListener( OauthHelper.getGithubOauthUrl( clientId, state ), state ) view.enableLoginByGithub() totalSocialAccountsEnabled++ } } if (settings.isGoogleAuthenticationEnabled()) { val clientId = getOauthClientId(services, SERVICE_NAME_GOOGLE) if (clientId != null) { view.setupGoogleButtonListener( OauthHelper.getGoogleOauthUrl( clientId, currentServer, state ), state ) view.enableLoginByGoogle() totalSocialAccountsEnabled++ } } if (settings.isLinkedinAuthenticationEnabled()) { val clientId = getOauthClientId(services, SERVICE_NAME_LINKEDIN) if (clientId != null) { view.setupLinkedinButtonListener( OauthHelper.getLinkedinOauthUrl( clientId, currentServer, state ), state ) view.enableLoginByLinkedin() totalSocialAccountsEnabled++ } } if (settings.isMeteorAuthenticationEnabled()) { //TODO: Remove until we have this implemented // view.enableLoginByMeteor() // totalSocialAccountsEnabled++ } if (settings.isTwitterAuthenticationEnabled()) { //TODO: Remove until Twitter provides support to OAuth2 // view.enableLoginByTwitter() // totalSocialAccountsEnabled++ } if (settings.isGitlabAuthenticationEnabled()) { val clientId = getOauthClientId(services, SERVICE_NAME_GILAB) if (clientId != null) { val gitlabOauthUrl = if (settings.gitlabUrl() != null) { OauthHelper.getGitlabOauthUrl( host = settings.gitlabUrl(), clientId = clientId, serverUrl = currentServer, state = state ) } else { OauthHelper.getGitlabOauthUrl( clientId = clientId, serverUrl = currentServer, state = state ) } view.setupGitlabButtonListener(gitlabOauthUrl, state) view.enableLoginByGitlab() totalSocialAccountsEnabled++ } } getCustomOauthServices(services).let { for (service in it) { val serviceName = getCustomOauthServiceName(service) val customOauthUrl = OauthHelper.getCustomOauthUrl( getCustomOauthHost(service), getCustomOauthAuthorizePath(service), getCustomOauthClientId(service), currentServer, serviceName, state, getCustomOauthScope(service) ) view.addCustomOauthServiceButton( customOauthUrl, state, serviceName, getServiceNameColor(service), getServiceButtonColor(service) ) totalSocialAccountsEnabled++ } } getSamlServices(services).let { val samlToken = generateRandomString(17) for (service in it) { view.addSamlServiceButton( currentServer.samlUrl(getSamlProvider(service), samlToken), samlToken, getSamlServiceName(service), getServiceNameColor(service), getServiceButtonColor(service) ) totalSocialAccountsEnabled++ } } if (totalSocialAccountsEnabled > 0) { view.enableOauthView() if (totalSocialAccountsEnabled > 3) { view.setupFabListener() } } else { view.disableOauthView() } } else { view.disableOauthView() } } catch (exception: RocketChatException) { Timber.e(exception) view.disableOauthView() } } } private fun doAuthentication(loginType: Int) { launchUI(strategy) { view.disableUserInput() view.showLoading() try { val token = retryIO("login") { when (loginType) { TYPE_LOGIN_USER_EMAIL -> { when { settings.isLdapAuthenticationEnabled() -> client.loginWithLdap(usernameOrEmail, password) usernameOrEmail.isEmail() -> client.loginWithEmail(usernameOrEmail, password) else -> client.login(usernameOrEmail, password) } } TYPE_LOGIN_CAS -> { delay(3, TimeUnit.SECONDS) client.loginWithCas(credentialToken) } TYPE_LOGIN_SAML -> { delay(3, TimeUnit.SECONDS) client.loginWithSaml(credentialToken) } TYPE_LOGIN_OAUTH -> { client.loginWithOauth(credentialToken, credentialSecret) } TYPE_LOGIN_DEEP_LINK -> { val myself = client.me() // Just checking if the credentials worked. if (myself.id == deepLinkUserId) { Token(deepLinkUserId, deepLinkToken) } else { throw RocketChatAuthException("Invalid Authentication Deep Link Credentials...") } } else -> { throw IllegalStateException("Expected TYPE_LOGIN_USER_EMAIL, TYPE_LOGIN_CAS,TYPE_LOGIN_SAML, TYPE_LOGIN_OAUTH or TYPE_LOGIN_DEEP_LINK") } } } val myself = retryIO("me()") { client.me() } if (myself.username != null) { val user = User( id = myself.id, roles = myself.roles, status = myself.status, name = myself.name, emails = myself.emails?.map { Email(it.address ?: "", it.verified) }, username = myself.username, utcOffset = myself.utcOffset ) localRepository.saveCurrentUser(url = currentServer, user = user) saveCurrentServer.save(currentServer) saveAccount(myself.username!!) saveToken(token) registerPushToken() if (loginType == TYPE_LOGIN_USER_EMAIL) { view.saveSmartLockCredentials(usernameOrEmail, password) } navigator.toChatList() } else if (loginType == TYPE_LOGIN_OAUTH) { navigator.toRegisterUsername(token.userId, token.authToken) } } catch (exception: RocketChatException) { when (exception) { is RocketChatTwoFactorException -> { navigator.toTwoFA(usernameOrEmail, password) } else -> { exception.message?.let { view.showMessage(it) }.ifNull { view.showGenericErrorMessage() } } } } finally { view.hideLoading() view.enableUserInput() } } } private fun getOauthClientId(listMap: List<Map<String, Any>>, serviceName: String): String? { return listMap.find { map -> map.containsValue(serviceName) }?.let { it["clientId"] ?: it["appId"] }.toString() } private fun getSamlServices(listMap: List<Map<String, Any>>): List<Map<String, Any>> { return listMap.filter { map -> map["service"] == "saml" } } private fun getSamlServiceName(service: Map<String, Any>): String { return service["buttonLabelText"].toString() } private fun getSamlProvider(service: Map<String, Any>): String { return (service["clientConfig"] as Map<*, *>)["provider"].toString() } private fun getCustomOauthServices(listMap: List<Map<String, Any>>): List<Map<String, Any>> { return listMap.filter { map -> map["custom"] == true } } private fun getCustomOauthHost(service: Map<String, Any>): String { return service["serverURL"].toString() } private fun getCustomOauthAuthorizePath(service: Map<String, Any>): String { return service["authorizePath"].toString() } private fun getCustomOauthClientId(service: Map<String, Any>): String { return service["clientId"].toString() } private fun getCustomOauthServiceName(service: Map<String, Any>): String { return service["service"].toString() } private fun getCustomOauthScope(service: Map<String, Any>): String { return service["scope"].toString() } private fun getServiceButtonColor(service: Map<String, Any>): Int { return service["buttonColor"].toString().parseColor() } private fun getServiceNameColor(service: Map<String, Any>): Int { return service["buttonLabelColor"].toString().parseColor() } private suspend fun saveAccount(username: String) { val icon = settings.favicon()?.let { currentServer.serverLogoUrl(it) } val logo = settings.wideTile()?.let { currentServer.serverLogoUrl(it) } val thumb = currentServer.avatarUrl(username) val account = Account(currentServer, icon, logo, username, thumb) saveAccountInteractor.save(account) } private fun saveToken(token: Token) { tokenRepository.save(currentServer, token) } private suspend fun registerPushToken() { localRepository.get(LocalRepository.KEY_PUSH_TOKEN)?.let { client.registerPushToken(it, getAccountsInteractor.get(), factory) } // TODO: When the push token is null, at some point we should receive it with // onTokenRefresh() on FirebaseTokenService, we need to confirm it. } }
0
Kotlin
0
1
e6b014150523f5f5ee1390ca34893472a02bbfef
21,983
Rocket.Chat.Android
MIT License
app/src/main/java/com/enginebai/moviehunt/utils/Formatter.kt
enginebai
32,935,880
false
null
package com.enginebai.moviehunt.utils import java.text.DateFormat import java.text.SimpleDateFormat import java.time.Instant import java.time.format.DateTimeFormatter import java.util.* import kotlin.math.ln import kotlin.math.pow fun Int.format(): String { // source: https://stackoverflow.com/questions/9769554/how-to-convert-number-into-k-thousands-m-million-and-b-billion-suffix-in-jsp?lq=1 if (this < 1000) return toString() val exp = ln(this.toDouble()).div(ln(1000.0)).toInt() return String.format("%.2f %c", this.div(1000.0.pow(exp)), "kMGTPE"[exp - 1]) } fun Int.formatHourMinutes(): String { val hours = this.div(60) val minutes = this % 60 return String.format("%d:%02d", hours, minutes) } object DateTimeFormatter { private const val API_DATE_FORMAT = "yyyy-MM-dd" const val DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss" fun String.toCalendarOrNull(format: String = API_DATE_FORMAT): Calendar? { val dateFormat = SimpleDateFormat(format, Locale.getDefault()) val date = try { dateFormat.parse(this) } catch (e: Exception) { null } return date?.let { Calendar.getInstance().apply { time = it } } } fun Calendar.format(format: String = API_DATE_FORMAT): String? { val dateFormat = SimpleDateFormat(format, Locale.getDefault()) return dateFormat.format(this.time) } }
4
Kotlin
79
657
a08608e4b23dbf7d1aebfe4dbd3f7811f267abc8
1,409
MovieHunt
MIT License
src/main/kotlin/io/runescript/plugin/ide/codeInsight/intention/RsNumberConversionIntention.kt
waleedyaseen
642,509,853
false
{"Kotlin": 389293, "Java": 258593, "Lex": 11778, "HTML": 1047}
package io.runescript.plugin.ide.codeInsight.intention import com.intellij.codeInsight.intention.numeric.AbstractNumberConversionIntention import com.intellij.codeInsight.intention.numeric.NumberConverter import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import com.intellij.psi.util.elementType import io.runescript.plugin.lang.psi.RsElementGenerator import io.runescript.plugin.lang.psi.RsElementTypes import io.runescript.plugin.lang.psi.RsFile import java.util.* class RsNumberConversionIntention : AbstractNumberConversionIntention() { override fun extract(element: PsiElement): NumberConversionContext? { if (element.elementType == RsElementTypes.INTEGER) { var rawValue = element.text var negated = false if (rawValue[0] == '-' || rawValue[0] == '+') { negated = rawValue[0] == '-' rawValue = rawValue.substring(1) } var radix = 10 if (rawValue.startsWith("0x")) { radix = 16 rawValue = rawValue.substring(2) } var number = rawValue.toUIntOrNull(radix)?.toInt() ?: return null if (negated) number *= -1 return NumberConversionContext(element, number, element.text, false) } return null } override fun getConverters(file: PsiFile): List<NumberConverter> { return if (file is RsFile) CONVERTERS else Collections.emptyList() } override fun replace(sourceElement: PsiElement, replacement: String) { sourceElement.replace(RsElementGenerator.createIntegerLiteral(sourceElement.project, replacement)) } companion object { private val INTEGER_TO_HEX = object : NumberConverter { override fun getConvertedText(text: String, number: Number): String? { return if (text.startsWith("0x") || text.startsWith("0X")) { null } else { "0x${Integer.toHexString(number.toInt())}" } } override fun toString(): String { return "hex" } } private val INTEGER_TO_DECIMAL = object : NumberConverter { override fun getConvertedText(text: String, number: Number): String? { return if (text.startsWith("0x") || text.startsWith("0X")) { number.toString() } else { null } } override fun toString(): String { return "decimal" } } private val CONVERTERS = listOf(INTEGER_TO_DECIMAL, INTEGER_TO_HEX) } }
8
Kotlin
2
3
02196142c95e7e5923e425fff5535b5299f8ce64
2,704
intellij-runescript
MIT License
app/src/main/java/com/xluo/nops/adapter/PenListAdapter.kt
VocientLuo
794,170,414
false
{"Kotlin": 469730, "Java": 118636}
package com.xluo.nops.adapter import android.content.Context import android.graphics.Color import android.view.LayoutInflater import android.view.ViewGroup import com.xluo.lib_base.adapter.BaseSingleRVAdapter import com.xluo.nops.R import com.xluo.nops.databinding.PopPaintListItemBinding import com.xluo.pen.PenManager import com.xluo.pen.bean.PaintBean /** * Create by AjjAndroid * Time:2022/3/8 */ class PenListAdapter(context: Context, data: List<PaintBean>) : BaseSingleRVAdapter<PaintBean, PopPaintListItemBinding>(context, data) { var onClick: ((PaintBean) -> Unit)? = null private var selectedPenId = -1 fun updateSelectedPen(id: Int) { if (selectedPenId != id) { selectedPenId = id notifyDataSetChanged() } } override fun getViewBinding( viewType: Int, from: LayoutInflater, parent: ViewGroup? ): PopPaintListItemBinding { return PopPaintListItemBinding.inflate(from, parent, false) } override fun bindView( binding: PopPaintListItemBinding, entity: PaintBean, position: Int ) { binding.tvPaintName.text = "${entity.name}" if (entity.id == selectedPenId) { binding.tvPaintName.setTextColor(Color.parseColor("#ffffff")) binding.imagePaintType.setBackgroundResource(R.drawable.draw_huabi_item_bg_sel) } else { binding.tvPaintName.setTextColor(Color.parseColor("#999999")) binding.imagePaintType.setBackgroundResource(R.drawable.draw_huabi_item_bg) } // 这里不要用缓存pen对象,很麻烦。 val pen = PenManager.getPen(entity, false) binding.imagePaintType.bindPen(pen) binding.layoutPaint.setOnClickListener { onClick?.invoke(entity) selectedPenId = entity.id notifyDataSetChanged() } } }
0
Kotlin
0
0
2ffabe9101cf772ee51a76a48b4287e18e64a5ed
1,884
NoPS
Apache License 2.0
src/main/kotlin/com/xrpn/immutable/FKMap.kt
xrpn
364,037,871
false
null
package com.xrpn.immutable import com.xrpn.imapi.* import com.xrpn.immutable.FKSet.Companion.emptyIMKSet import com.xrpn.immutable.FRBTree.Companion.nul import com.xrpn.immutable.TKVEntry.Companion.ofIntKey import com.xrpn.immutable.TKVEntry.Companion.ofk import kotlin.reflect.KClass // // W W I P P P // W W I P P // W W W I P P P // W W W W I P // W W I P // sealed class FKMap<out K, out V: Any>: IMMap<K, V>, Map <@UnsafeVariance K, V> where K: Any, K: Comparable<@UnsafeVariance K> { // imcollection override val seal: IMSC = IMSC.IMMAP override fun fcontains(item: TKVEntry<@UnsafeVariance K, @UnsafeVariance V>): Boolean = when (this) { is FKMapEmpty -> false is FKMapNotEmpty -> body.fcontains(item) } override fun fdropAll(items: IMCollection<TKVEntry<@UnsafeVariance K, @UnsafeVariance V>>): FKMap<K, V> { TODO("Not yet implemented") } override fun fdropItem(item: TKVEntry<@UnsafeVariance K, @UnsafeVariance V>): IMMap<K, V> = fdropkv(item.getk(), item.getv()) override fun ffilter(isMatch: (TKVEntry<K, V>) -> Boolean): FKMap<K, V> { TODO("Not yet implemented") } override fun ffilterNot(isMatch: (TKVEntry<K, V>) -> Boolean): FKMap<K, V> { TODO("Not yet implemented") } override fun ffindAny(isMatch: (TKVEntry<K, V>) -> Boolean): TKVEntry<K, V>? = when (this) { is FKMapEmpty -> null is FKMapNotEmpty -> body.ffindAny(isMatch) } override fun fisStrict(): Boolean = when (this) { is FKMapEmpty -> true is FKMapNotEmpty -> body.fisStrict() } override fun fcount(isMatch: (TKVEntry<K, V>) -> Boolean): Int = when (this) { is FKMapEmpty -> 0 is FKMapNotEmpty -> body.fcount(isMatch) } override fun fsize(): Int = size // imkeyed override fun asIMBTree(): IMBTree<K,V> = when (this) { is FKMapEmpty -> FRBTree.emptyIMBTree() is FKMapNotEmpty -> body } override fun fcontainsValue(value: @UnsafeVariance V): Boolean = when (this) { is FKMapEmpty -> false is FKMapNotEmpty -> body.fcontainsValue(value) } override fun fcountValue(isMatch: (V) -> Boolean): Int = when (this) { is FKMapEmpty -> 0 is FKMapNotEmpty -> body.ffold(0) {acc, tkv -> if(isMatch(tkv.getv())) acc + 1 else acc } } override fun ffilterKey(isMatch: (K) -> Boolean): FKMap<K, V> { TODO("Not yet implemented") } override fun ffilterKeyNot(isMatch: (K) -> Boolean): FKMap<K, V> { TODO("Not yet implemented") } override fun ffilterValue(isMatch: (V) -> Boolean): IMMap<K, V> { TODO("Not yet implemented") } override fun ffilterValueNot(isMatch: (V) -> Boolean): IMMap<K, V> { TODO("Not yet implemented") } override fun ffindAnyValue(isMatch: (V) -> Boolean): V? { TODO("Not yet implemented") } // extras override operator fun contains(k: @UnsafeVariance K): Boolean = fcontainsKey(k) override operator fun set(k: @UnsafeVariance K, v: @UnsafeVariance V): FKMap<K, V> = fputkv(k, v) // filtering override fun fcontainsKey(key: @UnsafeVariance K): Boolean = when (this) { is FKMapEmpty -> false is FKMapNotEmpty -> body.ffindValueOfKey(key) != null } override fun fcountKey(isMatch: (K) -> Boolean): Int = when (this) { is FKMapEmpty -> 0 is FKMapNotEmpty -> body.fcountKey(isMatch) } override fun fdrop(key: @UnsafeVariance K): FKMap<K,V> = when (this) { is FKMapEmpty -> this is FKMapNotEmpty -> body.ffindKey(key)?.let { ofFKMapBody(body.fdropItem(it.froot()!!)) } ?: this } override fun fdropKeys(keys: IMSet<@UnsafeVariance K>): FKMap<K, V> = when (this) { is FKMapEmpty -> this is FKMapNotEmpty -> ofFKMapBody(keys.ffold(this.toFRBTree()){t, k -> t.ffindKey(k)?.let {tt -> t.fdropItem(tt.froot()!!) } ?: t} ) } override fun fdropkv(key: @UnsafeVariance K, value: @UnsafeVariance V): FKMap<K,V> = when (this) { is FKMapEmpty -> this is FKMapNotEmpty -> ofFKMapBody(body.fdropItem(TKVEntry.ofkv(key, value))) } override fun fget(key: @UnsafeVariance K): V? = when (this) { is FKMapEmpty -> null is FKMapNotEmpty -> body.ffindValueOfKey(key) } override fun fpick(): TKVEntry<K, V>? = when (this) { is FKMapEmpty -> null is FKMapNotEmpty -> body.froot() } override fun fAND(items: IMKeyedValue<@UnsafeVariance K, @UnsafeVariance V>): FKMap<K, V> { TODO("Not yet implemented") } override fun fNOT(items: IMKeyedValue<@UnsafeVariance K, @UnsafeVariance V>): FKMap<K, V> = of(this.asIMBTree().fdropAlt(items.asIMBTree())) override fun fOR(items: IMKeyedValue<@UnsafeVariance K, @UnsafeVariance V>): FKMap<K, V> { TODO("Not yet implemented") } override fun fXOR(items: IMKeyedValue<@UnsafeVariance K, @UnsafeVariance V>): FKMap<K, V> { TODO("Not yet implemented") } // grouping override fun fentries(): IMSet<TKVEntry<K,V>> = (@Suppress("UNCHECKED_CAST") (entries as IMSet<TKVEntry<K, V>>)) override fun fkeys(): IMSet<K> = (@Suppress("UNCHECKED_CAST") (keys as IMSet<K>)) override fun <R : Comparable<R>> maxBy(f: (V) -> R): TKVEntry<K, V>? { TODO("Not yet implemented") } override fun <R : Comparable<R>> minBy(f: (V) -> R): TKVEntry<K, V>? { TODO("Not yet implemented") } override fun fpartition(isMatch: (TKVEntry<K, V>) -> Boolean): Pair<IMMap<K, V>, IMMap<K, V>> { TODO("Not yet implemented") } override fun fpopAndRemainder(): Pair<TKVEntry<K, V>?, IMMap<K, V>> { TODO("Not yet implemented") } override fun fvalues(): FList<V> = values as FList<V> // transforming override fun <C, D : Any> fflatMap(f: (TKVEntry<K, V>) -> IMMap<C, D>): IMMap<C, D> where C: Any, C : Comparable<C> { TODO("Not yet implemented") } override fun <J> fmapKeys(f: (TKVEntry<K, V>) -> J): FKMap<J, V> where J: Any, J : Comparable<J> { TODO("Not yet implemented") } override fun <W : Any> fmapValues(f: (TKVEntry<K, V>) -> W): FKMap<K, W> { TODO("Not yet implemented") } override fun <C> ffold(z: C, f: (acc: C, TKVEntry<K, V>) -> C): C { TODO("Not yet implemented") } override fun <C, D : Any> fmap(f: (TKVEntry<K, V>) -> TKVEntry<C, D>): FKMap<C, D> where C: Any, C : Comparable<C> { TODO("Not yet implemented") } override fun freduce(f: (acc: V, V) -> @UnsafeVariance V): V? { TODO("Not yet implemented") } // altering override fun fputkv(key: @UnsafeVariance K, value: @UnsafeVariance V): FKMap<K,V> = when (this) { is FKMapEmpty -> ofFKMapNotEmpty(FRBTree.of(TKVEntry.ofkv(key, value)) as FRBTNode<K, V>) is FKMapNotEmpty -> ofFKMapNotEmpty(body.finsert(TKVEntry.ofkv(key, value)) as FRBTNode) } override fun fputPair(p: Pair<@UnsafeVariance K, @UnsafeVariance V>): FKMap<K,V> = when (this) { is FKMapEmpty -> ofFKMapNotEmpty(FRBTree.of(TKVEntry.ofp(p)) as FRBTNode<K, V>) is FKMapNotEmpty -> ofFKMapNotEmpty(body.finsert(TKVEntry.ofp(p)) as FRBTNode) } override fun fputList(l: FList<TKVEntry<@UnsafeVariance K, @UnsafeVariance V>>): FKMap<K,V> = if (l.fempty()) this else when (this) { is FKMapEmpty -> ofFKMapNotEmpty(FRBTree.of(l as IMList<TKVEntry<K,V>>) as FRBTNode<K, V>) is FKMapNotEmpty -> ofFKMapNotEmpty(body.finserts(l) as FRBTNode<K, V>) } override fun fputTree(t: IMBTree<@UnsafeVariance K, @UnsafeVariance V>): FKMap<K,V> = when (this) { is FKMapEmpty -> t.toIMMap() as FKMap<K,V> is FKMapNotEmpty -> if (t.fempty()) this else ofFKMapNotEmpty(body.finsertt(t) as FRBTNode<K, V>) } override fun fputMap(m: IMMap<@UnsafeVariance K, @UnsafeVariance V>): FKMap<K,V> = when (this) { is FKMapEmpty -> when(m) { is FKMap<K,V> -> m else -> throw RuntimeException("unknown map: ${m::class}") } is FKMapNotEmpty -> fputTree(m.toIMBTree()) } // utility override fun equal(rhs: IMMap<@UnsafeVariance K, @UnsafeVariance V>): Boolean = this.equals(rhs) override fun fforEach (f: (V) -> Unit) = when(this) { is FKMapEmpty -> Unit is FKMapNotEmpty -> body.fforEach { tkv -> f(tkv.getv()) } } override fun toIMBTree(): IMBTree<K, V> = when(this) { is FKMapEmpty -> nul() is FKMapNotEmpty -> body } override fun copy(): FKMap<K, V> = when (this) { is FKMapEmpty -> emptyIMMap() is FKMapNotEmpty -> body.ffold(nul<K, V>()) { acc, tkv -> acc.finsert(tkv) }.toIMMap() } override fun copyToMutableMap(): MutableMap<@UnsafeVariance K, @UnsafeVariance V> = when (this) { is FKMapEmpty -> mutableMapOf() is FKMapNotEmpty -> body.ffold(mutableMapOf()) { acc, tkv -> acc[tkv.getk()] = tkv.getv(); acc } } // // ========= implementation // internal fun toFRBTree(): FRBTree<K, V> = when (this) { is FKMapEmpty -> nul() is FKMapNotEmpty -> body } // private companion object: IMMapCompanion { override fun <K, V: Any> emptyIMMap(): FKMap<K, V> where K: Any, K: Comparable<K> = FKMapEmpty.empty() override fun <K, V : Any> of(vararg items: Pair<K, V>): FKMap<K, V> where K: Any, K : Comparable<K> = of(items.iterator()) override fun <K, V : Any> of(items: Iterator<Pair<K, V>>): FKMap<K, V> where K: Any, K : Comparable<K> { var acc: FRBTree<K, V> = nul() items.forEach { acc = acc.finsert(TKVEntry.ofp(it)) } return ofFKMapBody(acc) } override fun <K, V : Any> of(items: IMList<Pair<K, V>>): FKMap<K, V> where K: Any, K : Comparable<K> = if (items.fempty()) FKMapEmpty.empty() else ofFKMapBody(FRBTree.of(items.fmap { TKVEntry.ofp(it) })) override fun <K, V : Any> of(items: IMBTree<K, V>): FKMap<K, V> where K: Any, K : Comparable<K> = when (items) { is FRBTree -> ofFKMapBody(items) is FBSTree -> items.toIMMap() as FKMap<K, V> else -> throw RuntimeException("unknown tree type ${items::class}") } override fun <K, V : Any> Collection<V>.toIMMap(keyMaker: (V) -> K): FKMap<K, V> where K: Any, K : Comparable<K> { var acc: FRBTree<K, V> = nul() this.forEach { acc = acc.finsert(TKVEntry.ofkv(keyMaker(it), it)) } return ofFKMapBody(acc) } fun <K: Comparable<K>, V: Any> of(_body: FList<TKVEntry<K,V>>): FKMap<K, V> = if (_body is FLNil) emptyIMMap() else ofFKMapNotEmpty(FRBTree.of(_body) as FRBTNode) } } internal class FKMapEmpty<K, V: Any> private constructor ( val body: FRBTree<K, V> ): FKMap<K, V>() where K: Any, K: Comparable<@UnsafeVariance K> { // placate the compiler fun donotuse() = print(body) // ========== Any override fun equals(other: Any?): Boolean = when { singletonEmpty === other -> true other == null -> false other is IMMap<*, *> -> false other is Map<*,*> -> other.isEmpty() else -> false } val hash: Int by lazy { this::class.simpleName.hashCode() } override fun hashCode(): Int = hash val show: String by lazy { FKMap::class.simpleName + "(*->*)" } override fun toString(): String = show // ========== FKMap companion object { private val singletonEmpty = FKMapEmpty(FRBTNil) internal fun <K, V: Any> empty(): FKMap<K, V> where K: Any, K: Comparable<@UnsafeVariance K> = singletonEmpty } // ========== Map override fun isEmpty(): Boolean = true override val size: Int = 0 override val entries: Set<Map.Entry<K, V>> = /* TODO fix the key type, it should be TKVEntry<K,V> */ emptyIMKSet<Int, TKVEntry<K,V>>(IntKeyType) override val keys: Set<K> = /* TODO fix the key type, it should be K */ emptyIMKSet<Int, K>(IntKeyType) override val values: Collection<V> = FList.emptyIMList() override fun containsKey(key: K): Boolean = false override fun containsValue(value: V): Boolean = false override operator fun get(key: K): V? = null } internal class FKMapNotEmpty<out K, out V: Any> private constructor ( val body: FRBTNode<@UnsafeVariance K, @UnsafeVariance V> ): FKMap<K, V>() where K: Any, K: Comparable<@UnsafeVariance K> { // ========== Any override fun equals(other: Any?): Boolean = when { this === other -> true other == null -> false other is IMMap<*, *> -> when { other.fempty() -> false fpick()!!.strictlyNot(other.fpick()!!.untype()) -> false else -> @Suppress("UNCHECKED_CAST") IMMapEqual2(this, other as IMMap<K, V>) } other is Map<*, *> -> if (other.isEmpty()) false else { val nnSample = (@Suppress("UNCHECKED_CAST") (other.entries.first() as Map.Entry<Any, Any>)) when { this.fpick()!!.getkKc() != nnSample.key::class -> false this.fpick()!!.getvKc() != nnSample.value::class -> false else -> other.equals(this) } } else -> false } val hash: Int by lazy { // hash of a FRBTree depends on the content AND on the shape of the tree; // for map hash, the shape of the tree is irrelevant, whence the following (127 * (this.body.inorder().hashCode() + 11)) / 109 } override fun hashCode(): Int = hash val show: String by lazy { val spacerOpen = "(" val spacerClose = ")," val cn: String = FKMap::class.simpleName!! "$cn(${body.inorder().ffoldLeft("") { acc, tkv -> acc + spacerOpen + tkv.getk().toString() + "->" + tkv.getv().toString() + spacerClose }.dropLast(1)})" } override fun toString(): String = show // ========== Map override fun isEmpty(): Boolean = false override val size: Int by lazy { body.size } override val entries: Set<Map.Entry<K, V>> by lazy { val (item: TKVEntry<K, V>?, remainder: FRBTree<K, V>) = body.fpopAndRemainder() item as TKVEntry<K, V> val res: IMSet<TKVEntry<K, V>> = when(item.getk()) { is String -> remainder .ffold(@Suppress("UNCHECKED_CAST") (FKSet.ofs(item) as IMSetNotEmpty<TKVEntry<K, V>>)) { acc, tkv -> acc.faddItem(tkv) as IMSetNotEmpty<TKVEntry<K, V>> } else -> remainder // will use hashCode() as key, beware of collisions .ffold(@Suppress("UNCHECKED_CAST") (FKSet.ofi(item) as IMSetNotEmpty<TKVEntry<K, V>>)) { acc, tkv -> acc.faddItem(tkv) as IMSetNotEmpty<TKVEntry<K, V>> } } @Suppress("UNCHECKED_CAST") (res as Set<Map.Entry<K, V>>) } override val keys: Set<K> by lazy { val item: TKVEntry<K, V>? = body.froot() fun assemblekk(): FKSet<@UnsafeVariance K, @UnsafeVariance K> { val (ei: TKVEntry<K, V>?, remainder: FRBTree<K, V>) = body.fpopAndRemainder() val seed: FRBTree<K, K> = FRBTree.of(ofk(ei!!.getk())) return remainder.ffold(seed) { acc, tkv -> acc.finsert(ofk(tkv.getk())) }.toIMRSet(seed.frestrictedKey())!! } if (null == item) TODO() else { val res: IMSet<K> = when (item) { is RTKVEntry -> when (item.getrk()) { is DeratedCustomKeyType -> throw RuntimeException("internal error") else -> assemblekk() } else -> when (item.getk()) { is String, is Int -> assemblekk() else -> { val (ei: TKVEntry<K, V>?, remainder: FRBTree<K, V>) = body.fpopAndRemainder() val seed: FRBTree<Int, K> = FRBTree.of(ofIntKey(ei!!.getk())) remainder.ffold(seed) { acc, tkv -> acc.finsert(ofIntKey(tkv.getk())) }.toIMRSet(seed.frestrictedKey())!! } } } @Suppress("UNCHECKED_CAST") (res as Set<K>) } } override val values: Collection<V> by lazy { body.fmapvToList { it } as FList<V> } override fun containsKey(key: @UnsafeVariance K): Boolean = body.fcontainsKey(key) override fun containsValue(value: @UnsafeVariance V): Boolean = body.fcontainsValue(value) override operator fun get(key: @UnsafeVariance K): V? = body.ffindValueOfKey(key) companion object { internal fun <K, V: Any> of(b: FRBTNode<K, V>): FKMap<K, V> where K: Any, K: Comparable<K> = FKMapNotEmpty(b) } override fun fisStrictlyLike(sample: KeyedTypeSample<KClass<Any>?, KClass<Any>>): Boolean? { TODO("Not yet implemented") } } fun <K, V : Any> Pair<K,V>.toMap(): FKMap<K, V> where K: Any, K: Comparable<K> = ofFKMapNotEmpty(FRBTree.of(TKVEntry.ofp(this)) as FRBTNode) fun <K, V : Any> V.toMap(keyMaker: (V) -> K): FKMap<K, V> where K: Any, K: Comparable<K> = ofFKMapNotEmpty(FRBTree.of(TKVEntry.ofkv(keyMaker(this), this)) as FRBTNode) internal fun <K, V: Any> ofFKMapBody(b: FRBTree<K, V>): FKMap<K, V> where K: Any, K: Comparable<K> = when(b) { is FRBTNode -> FKMapNotEmpty.of(b) else -> FKMapEmpty.empty() } internal fun <K, V: Any> ofFKMapNotEmpty(b: FRBTNode<K, V>): FKMap<K, V> where K: Any, K: Comparable<K> = FKMapNotEmpty.of(b)
0
Kotlin
1
3
09da19a3b49d41ae0679b853b4efe4605ba319f6
17,549
immutable-kotlin
Apache License 2.0
src/main/kotlin/com/marconcini/kdlparser/objects/KDLValue.kt
Gryzor
695,637,336
false
{"Kotlin": 79997, "Java": 61971}
package com.marconcini.kdlparser.objects import com.marconcini.kdlparser.print.PrintConfig import com.marconcini.kdlparser.print.PrintUtil import java.io.IOException import java.io.StringWriter import java.io.Writer import java.math.BigDecimal import java.math.BigInteger abstract class KDLValue<T>(private val type: String?) : KDLObject { abstract fun getValue(): T abstract fun getAsString(): KDLString abstract fun getAsNumber(): KDLNumber? abstract fun getAsNumberOrElse(defaultValue: Number): Number abstract fun getAsBoolean(): KDLBoolean? abstract fun getAsBooleanOrElse(defaultValue: Boolean): Boolean abstract fun writeKDLValue(writer: Writer, printConfig: PrintConfig) abstract fun toKDLValue(): String fun getType() = type open fun isString(): Boolean = false open fun isNumber(): Boolean = false open fun isBoolean(): Boolean = false open fun isNull(): Boolean = false override fun writeKDL(writer: Writer, printConfig: PrintConfig) { type?.let { writer.write("(") PrintUtil.writeStringQuotedAppropriately(writer, it, true, printConfig) writer.write(")") } writeKDLValue(writer, printConfig) } override fun toKDL(): String { val writer = StringWriter() type?.let { writer.write("(") try { PrintUtil.writeStringQuotedAppropriately( writer, it, true, PrintConfig.PRETTY_DEFAULT ) } catch (e: IOException) { throw RuntimeException( String.format( "Failed to convert KDL value to KDL: '%s'", this ), e ) } writer.write(")") } writer.write(toKDLValue()) return writer.toString() } companion object { @JvmStatic fun from(o: Any?): KDLValue<*> = from(o, null) @JvmStatic fun from(o: Any?, type: String?): KDLValue<*> { if (o == null) return KDLNull(type) if (o is Boolean) { return KDLBoolean(o, type) } if (o is BigInteger) { return KDLNumber(BigDecimal(o as BigInteger?), 10, type) } if (o is BigDecimal) { return KDLNumber(o, 10, type) } if (o is Number) { return KDLNumber(BigDecimal(o.toString()), 10, type) } if (o is String) { return KDLString(o, type) } if (o is KDLValue<*>) return o throw RuntimeException(String.format("No KDLValue for object '%s'", o)) } } }
0
Kotlin
0
0
fcc9e73eaebad2d95a06a18074be890b1a5a8253
2,835
KDLkt
MIT License
core/src/com/thedeadpixelsociety/ld34/scripts/WallScript.kt
deadpixelsociety
47,857,871
false
null
package com.thedeadpixelsociety.ld34.scripts import com.badlogic.ashley.core.Engine import com.badlogic.ashley.core.Entity import com.badlogic.gdx.math.Vector2 import com.thedeadpixelsociety.ld34.Events import com.thedeadpixelsociety.ld34.TimeKeeper import com.thedeadpixelsociety.ld34.components.Box2DComponent import com.thedeadpixelsociety.ld34.components.TransformComponent import com.thedeadpixelsociety.ld34.systems.TagSystem class WallScript() : Script { companion object { const val HIT_DELAY = .5f } private var hit = false private var lastHit = 0f private val proj = Vector2() override fun act(engine: Engine, entity: Entity) { val box2d = entity.getComponent(Box2DComponent::class.java) if (box2d != null && box2d.collision) { val player = engine.getSystem(TagSystem::class.java)["player"] if (!hit && player != null && box2d.collided == player && (TimeKeeper.totalTime - lastHit) > HIT_DELAY) { hit = true lastHit = TimeKeeper.totalTime Events.wall(entity, player) } } // Box2d says we're longer colliding, but we don't want to end the 'hit' until we're at least a certain // distance apart to eliminate repeat events if (hit && box2d.collision == false) { val player = engine.getSystem(TagSystem::class.java)["player"] if (player != null) { val transform = entity.getComponent(TransformComponent::class.java) val playerTransform = player.getComponent(TransformComponent::class.java) val a = playerTransform.position val b = box2d.lastNormal val dot = a.dot(b) proj.set(dot * b.x, dot * b.y) if (proj.x != 0f) { proj.sub(transform.position.x, 0f) } else if (proj.y != 0f) { proj.sub(0f, transform.position.y) } val dist = proj.len() if (dist > 17.5f) { hit = false } } } } }
0
Kotlin
1
12
198f23d667b6e1b4829481bd9f54aa5e26bde051
2,162
roto-ld34
MIT License
7_kyu/A_Rule_of_Divisibility_by_7.kt
UlrichBerntien
439,630,417
false
{"Go": 293606, "Rust": 191729, "Python": 184557, "Lua": 137612, "Assembly": 89144, "C": 76738, "Julia": 35473, "Kotlin": 33204, "R": 27633, "C#": 20860, "Shell": 14326, "Forth": 3750, "PLpgSQL": 2117, "C++": 122}
package divseven fun seven(n:Long):LongArray { var counter = 0L var m = n while( m > 99 ) { m = (m/10) - 2*(m%10) ++counter } return longArrayOf(m, counter) }
0
Go
0
0
034d7f2bdcebc503b02877f2241e4dd143188b43
195
Codewars-Katas
MIT License
k8s-plugin-igor/src/main/kotlin/com/amazon/spinnaker/igor/k8s/service/GitHubService.kt
nimakaviani
287,605,692
false
null
// Copyright 2022 Amazon.com, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.amazon.spinnaker.igor.k8s.service import com.amazon.spinnaker.igor.k8s.model.GitHubCommitResponse import com.amazon.spinnaker.igor.k8s.model.GitHubTagResponse import retrofit.http.GET import retrofit.http.Path interface GitHubService { @GET("/repos/{projectKey}/{repositorySlug}/tags") fun getTags( @Path("projectKey") projectKey: String, @Path("repositorySlug") repositorySlug: String ): List<GitHubTagResponse> @GET("/repos/{projectKey}/{repositorySlug}/commits/{commitId}") fun getCommit( @Path("projectKey") projectKey: String, @Path("repositorySlug") repositorySlug: String, @Path("commitId") commitId: String ): GitHubCommitResponse }
7
Kotlin
9
13
2a8bb2191ec71548fc318cdfde79b209707ede91
1,314
managed-delivery-k8s-plugin
Apache License 2.0
app/src/main/kotlin/ru/annin/truckmonitor/domain/value/NavigationMenuItem.kt
VTUZ-12IE1bzud
89,852,740
false
null
package ru.annin.truckmonitor.domain.value /** * Пункты меню. * * @author <NAME>. */ enum class NavigationMenuItem { HOME, HISTORY, USER_INFO, ABOUT, LOG_OUT }
0
Kotlin
0
0
ae30f652737892b23030f885a1a60b62e2080306
169
TruckMonitor-Android
Apache License 2.0
app/src/main/java/com/eneskayiklik/word_diary/feature/quiz/component/session_components/WritingSession.kt
Enes-Kayiklik
651,794,521
false
null
package com.eneskayiklik.word_diary.feature.quiz.component.session_components import androidx.compose.animation.animateColorAsState import androidx.compose.animation.core.tween import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Divider import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.text.TextRange import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.TextFieldValue import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp import com.eneskayiklik.word_diary.core.database.entity.WordEntity import com.eneskayiklik.word_diary.core.ui.theme.GreenYellow import com.eneskayiklik.word_diary.core.ui.theme.SuccessGreen import com.eneskayiklik.word_diary.util.extensions.takeHint @OptIn(ExperimentalComposeUiApi::class) @Composable fun WritingSession( activeWord: WordEntity, onWordCorrect: (word: WordEntity, timeSpent: Long) -> Unit, onHintTaken: (WordEntity) -> Unit, modifier: Modifier = Modifier ) { var initialTime by rememberSaveable { mutableStateOf(System.currentTimeMillis()) } val focusRequester = remember { FocusRequester() } val keyboardController = LocalSoftwareKeyboardController.current var textInputValue by remember { mutableStateOf(TextFieldValue()) } val isInputValid by remember(key1 = activeWord) { derivedStateOf { textInputValue.text.trim().contains(activeWord.word, true) } } var hintTaken by remember { mutableStateOf(false) } val inputColorAnim by animateColorAsState( targetValue = when { isInputValid -> SuccessGreen hintTaken -> GreenYellow else -> MaterialTheme.colorScheme.background }, animationSpec = tween(durationMillis = 300), finishedListener = { if (hintTaken) hintTaken = false if (isInputValid) onWordCorrect(activeWord, System.currentTimeMillis() - initialTime) } ) LaunchedEffect(key1 = isInputValid) { try { focusRequester.requestFocus() keyboardController?.show() } catch (e: Exception) { e.printStackTrace() } } LaunchedEffect(key1 = activeWord) { textInputValue = TextFieldValue() initialTime = System.currentTimeMillis() } Column( modifier = modifier, horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(8.dp, Alignment.CenterVertically) ) { Text( text = activeWord.meaning, style = MaterialTheme.typography.headlineMedium, modifier = Modifier.padding(bottom = 4.dp) ) Divider(modifier = Modifier.fillMaxWidth()) BasicTextField( modifier = Modifier .fillMaxWidth() .focusRequester(focusRequester), value = textInputValue, onValueChange = { if (isInputValid.not()) textInputValue = it }, textStyle = MaterialTheme.typography.headlineMedium.copy( color = MaterialTheme.colorScheme.onSurface, textAlign = TextAlign.Center ), keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text), singleLine = true, cursorBrush = SolidColor(MaterialTheme.colorScheme.primary), decorationBox = { innerTextField -> Box( modifier = Modifier .fillMaxWidth() .clip(MaterialTheme.shapes.small) .background(inputColorAnim) .padding(vertical = 4.dp), contentAlignment = Alignment.Center ) { innerTextField() } } ) TextButton(onClick = { if (isInputValid.not()) { val newValue = textInputValue.text.takeHint(activeWord.word) textInputValue = textInputValue.copy( text = newValue, selection = TextRange(newValue.length) ) hintTaken = true onHintTaken(activeWord) } }) { Text(text = "Hint") } } }
0
Kotlin
0
3
c40d2b7fe1ce9b8926b660dcbbaa088fbca05f11
5,558
WordDiary
MIT License
native/native.tests/tests/org/jetbrains/kotlin/konan/blackboxtest/support/runner/AbstractLocalProcessRunner.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors. * Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file. */ package org.jetbrains.kotlin.konan.blackboxtest.support.runner import org.jetbrains.kotlin.konan.blackboxtest.support.TestExecutable internal abstract class AbstractLocalProcessRunner<R> : AbstractRunner<R>() { protected abstract val visibleProcessName: String protected abstract val executable: TestExecutable protected abstract val programArgs: List<String> protected open fun customizeProcess(process: Process) = Unit final override fun buildRun() = AbstractRun { val startTimeMillis = System.currentTimeMillis() val process = ProcessBuilder(programArgs).directory(executable.executableFile.parentFile).start() customizeProcess(process) val exitCode = process.waitFor() val finishTimeMillis = System.currentTimeMillis() val stdOut = process.inputStream.bufferedReader().readText() val stdErr = process.errorStream.bufferedReader().readText() RunResult(exitCode, finishTimeMillis - startTimeMillis, stdOut, stdErr) } abstract override fun buildResultHandler(runResult: RunResult): ResultHandler // Narrow returned type. abstract inner class ResultHandler(runResult: RunResult) : AbstractRunner<R>.ResultHandler(runResult) { override fun handle(): R { verifyExpectation(0, runResult.exitCode) { "$visibleProcessName exited with non-zero code." } return doHandle() } protected abstract fun doHandle(): R } }
125
Kotlin
4813
39,375
83d2d2cfcfc3d9903c902ca348f331f89bed1076
1,678
kotlin
Apache License 2.0
src/main/java/me/arial/spawner/Main.kt
AxieFeat
784,539,859
false
{"Kotlin": 62774}
package me.arial.spawner import me.arial.spawner.particle.LoadParticles import org.bukkit.configuration.file.FileConfiguration import org.bukkit.configuration.file.YamlConfiguration import org.bukkit.plugin.java.JavaPlugin import java.io.File class Main : JavaPlugin() { companion object { var instance: Main? = null } override fun onEnable() { instance = this saveDefaultConfig() val particlesFile = File(dataFolder, "particles.yml") if (!particlesFile.exists()) saveResource("particles.yml", false) val config: FileConfiguration = YamlConfiguration.loadConfiguration(particlesFile) LoadParticles.loadEffect(config) server.pluginManager.registerEvents(EventListener(), this) } override fun onDisable() { } }
0
Kotlin
0
0
a84fa454022cbeaaf7d0b318b705f4071768997a
808
FunSpawner
MIT License
app/src/main/java/loodos/droid/bitcointicker/api/models/GenericResponse.kt
BatuhanGunes
360,654,341
false
null
package loodos.droid.bitcointicker.api.models data class GenericResponse( val code: Int, val message: String )
0
Kotlin
1
0
40507e84762ef9a69c12de52d183119780401109
119
BitcoinTicker
Apache License 2.0
PPWRemote6/java/com/example/yamamoto2002/ppwremote6/RemoteCommand.kt
yamamoto2002
39,676,340
false
{"C#": 5012231, "C++": 2828025, "C": 1112991, "Mathematica": 137805, "HLSL": 70194, "TeX": 44058, "Cuda": 42378, "Kotlin": 41458, "Shell": 32693, "MATLAB": 10267, "Python": 5479, "Batchfile": 4075, "Assembly": 3075, "HTML": 2472, "Objective-C": 552, "PowerShell": 204, "Makefile": 167}
package com.example.yamamoto2002.ppwremote6 import android.util.Log import java.io.IOException import java.io.InputStream import java.lang.System.arraycopy import java.nio.ByteBuffer import java.nio.ByteOrder import java.nio.charset.StandardCharsets /** @param trackIdx Track idx. Used on Play Pause and Seek. */ class RemoteCommand(var cmd : CommandType, var trackIdx : Int = 0) { enum class CommandType(val fourcc:Int) { PlaylistData(0x534c4c50), Exit(0x54495845), Pause(0x53554150), Stop(0x504f5453), PlayPositionUpdate(0x55504c50), Greetings(0x52575050), PlaylistWant(0x574c4c50), Play(0x59414c50), Seek(0x4b454553), SelectTrack(0x544c4553), } /// STATE_STOPPED STATE_PLAYING STATE_PAUSED var state : Int = 0 /// Play position on track. Used on Play Pause and Seek. var positionMillisec: Int = 0 /// used by Seek send var trackMillisec : Int = 0 class PlayListItem { var durationMillsec: Int = 0 var sampleRate : Int = 0 var bitDepth : Int = 0 var albumName: String = "" var artistName: String = "" var titleName: String = "" var albumCoverArt: ByteArray = ByteArray(0) } /// PlaylistData var playlist: MutableList<PlayListItem> = mutableListOf() companion object { const val VERSION: Long = 102 const val STATE_STOPPED : Int = 0 const val STATE_PLAYING : Int = 1 const val STATE_PAUSED : Int = 2 private const val TOO_LARGE : Long = 100 * 1000 * 1000 private const val TOO_MANY_TRACKS : Long = 10000 fun intToByteArray(v: Int): ByteArray { val b = ByteBuffer.allocate(4) b.order(ByteOrder.LITTLE_ENDIAN) b.putInt(v) return b.array() } fun longToByteArray(v: Long): ByteArray { val b = ByteBuffer.allocate(8) b.order(ByteOrder.LITTLE_ENDIAN) b.putLong(v) return b.array() } private fun byteArrayToInt(v :ByteArray) : Int { return ByteBuffer.wrap(v,0,4).order(java.nio.ByteOrder.LITTLE_ENDIAN).int } private fun byteArrayToLong(v :ByteArray) : Long { return ByteBuffer.wrap(v,0,8).order(java.nio.ByteOrder.LITTLE_ENDIAN).long } // ブロックして所望サイズのデータを受信する。 private fun readBlocking(ins : InputStream, bytes : Int) : ByteArray { val r = ByteArray(bytes) var offs = 0 while (offs < bytes) { if (0 == ins.available()) { Thread.sleep(10) //Log.i("RemoteCommand", "Sleep...") continue } val wantBytes = bytes - offs val readBytes = ins.read(r, offs, wantBytes) if (readBytes == -1) { throw IOException("readBlocking failed") } offs += readBytes } return r } private fun readInt(ins : InputStream) : Int { val buff = readBlocking(ins, 4) return byteArrayToInt(buff) } private fun readLong(ins : InputStream) : Long { val buff = readBlocking(ins, 8) return byteArrayToLong(buff) } private fun readByteArray(ins : InputStream) : ByteArray { val bytes = readInt(ins) if (bytes < 0 || TOO_LARGE < bytes) { throw IOException("String too large") } if (bytes == 0) { return ByteArray(0) } return readBlocking(ins, bytes) } private fun readUtf8(ins : InputStream) : String { val buff = readByteArray(ins) if (buff.isEmpty()) { return "" } return String(buff, StandardCharsets.UTF_8) } fun fromStream(ins : InputStream) : RemoteCommand { val cmd = RemoteCommand(CommandType.Exit) val fourcc = readInt(ins) val bytes = readLong(ins) if (bytes < 0 || TOO_LARGE < bytes) { return cmd } when (fourcc) { CommandType.PlaylistData.fourcc -> { /* * Number of payload bytes (int64) * * playbackState (int32) * * Number of tracks (int32) * if (0 < number of tracks) { * selected track (int32) * * Track0 duration millisec (int32) * Track0 sampleRate (int32) * Track0 bit depth (int32) * Track0 albumName bytes (int32) * Track0 albumName (utf8 string) * Track0 artistName bytes (int32) * Track0 artistName (utf8 string) * Track0 titleName bytes (int32) * Track0 titleName (utf8 string) * Track0 albumCoverArt bytes (int32) * Track0 albumCoverArt (binary) * * Track1 * ... * } */ cmd.state = readInt(ins) if (cmd.state < 0 || STATE_PAUSED < cmd.state) { Log.e("RemoteCommand", "nTracks is out of range ${cmd.state}") return cmd } val nTracks = readInt(ins) if (nTracks < 0 || TOO_MANY_TRACKS < nTracks) { Log.e("RemoteCommand", "nTracks is out of range $nTracks") return cmd } if (nTracks == 0) { cmd.cmd = RemoteCommand.CommandType.PlaylistData return cmd } cmd.trackIdx = readInt(ins) if (cmd.trackIdx < 0 || nTracks <= cmd.trackIdx) { Log.i("RemoteCommand", "trackIdx is out of range ${cmd.trackIdx} fixed to 0") cmd.trackIdx = 0 } for (i in 0 until nTracks) { //Log.i("RemoteCommand", "Reading track $i of $nTracks") val p = RemoteCommand.PlayListItem() p.durationMillsec = readInt(ins) p.sampleRate = readInt(ins) p.bitDepth = readInt(ins) p.albumName = readUtf8(ins) p.artistName = readUtf8(ins) p.titleName = readUtf8(ins) p.albumCoverArt = readByteArray(ins) //Log.i("RemoteCommand", "p.albumCoverArt $i size = ${p.albumCoverArt.size}") cmd.playlist.add(p) } cmd.cmd = CommandType.PlaylistData } CommandType.Pause.fourcc -> { if (bytes != 4L) { Log.e("RemoteCommand", "Pause bytes not equal to 4 $bytes") return cmd } cmd.trackIdx = readInt(ins) if (cmd.trackIdx < 0) { Log.e("RemoteCommand", "trackIdx is negative ${cmd.trackIdx}") return cmd } cmd.cmd = CommandType.Pause } CommandType.PlayPositionUpdate.fourcc -> { if (bytes != 12L) { Log.e("RemoteCommand", "PlayPositionUpdate bytes not equal to 12 $bytes") return cmd } cmd.state = readInt(ins) if (cmd.state < 0 || 2 < cmd.state) { Log.e("RemoteCommand", "state is invalid ${cmd.state}") return cmd } cmd.trackIdx = readInt(ins) if (cmd.trackIdx < 0) { Log.e("RemoteCommand", "trackIdx is negative ${cmd.trackIdx}") return cmd } cmd.positionMillisec = readInt(ins) if (cmd.positionMillisec < 0) { Log.e("RemoteCommand", "positionMs is negative ${cmd.positionMillisec}") return cmd } cmd.cmd = CommandType.PlayPositionUpdate } CommandType.Exit.fourcc -> { if (bytes != 0L) { Log.e("RemoteCommand", "Exit bytes not equal to 0 $bytes") return cmd } } CommandType.Stop.fourcc -> { if (bytes != 0L) { Log.e("RemoteCommand", "Stop bytes not equal to 0 $bytes") return cmd } cmd.cmd = CommandType.Stop } else -> { Log.i("RemoteCommand", "Unknown fourcc $fourcc") } } return cmd } } private fun countByteArrayListTotalBytes(a : List<ByteArray>) : Int { var bytes = 0 a.onEach { bytes += it.size } return bytes } private fun byteArrayListToByteArray(a : List<ByteArray>) : ByteArray { val bytes = countByteArrayListTotalBytes(a) val r = ByteArray(bytes) var offs = 0 a.onEach { arraycopy(it,0,r,offs,it.size) offs += it.size } return r } fun toByteArray() : ByteArray { val r = mutableListOf<ByteArray>() when (cmd) { CommandType.Greetings -> { /* "Greetings" size = 8 (4bytes) version = 100 (8bytes) */ r.add(longToByteArray(VERSION)) } CommandType.PlaylistWant -> { // no payload } CommandType.Exit -> { // no payload } CommandType.Pause -> { // no payload } CommandType.Play -> { /* "PLAY" trackIdx (4bytes) */ r.add(intToByteArray(trackIdx)) } CommandType.Seek -> { /* total 8bytes positionMillisec (4bytes) trackMillisec (4bytes) */ r.add(intToByteArray(positionMillisec)) r.add(intToByteArray(trackMillisec)) } else -> { throw NotImplementedError("RemoteCommand.toByteArray") } } // calc payload size val payloadBytes = countByteArrayListTotalBytes(r) // insert header and payload bytes in the front r.add(0, longToByteArray(payloadBytes.toLong())) r.add(0, intToByteArray(cmd.fourcc)) return byteArrayListToByteArray(r) } }
37
C#
1
0
331a9fc531269e5dfdc78548e583f793a7687dc0
11,495
bitspersampleconv2
MIT License
meistercharts-commons/src/jvmMain/kotlin/it/neckar/logging/LevelJvm.kt
Neckar-IT
599,079,962
false
{"Kotlin": 5819931, "HTML": 87784, "JavaScript": 1378, "CSS": 1114}
package it.neckar.logging /** * Alias for our expected Level defined in commons to existing slf4j Level class */ actual typealias Level = org.slf4j.event.Level
3
Kotlin
3
5
ed849503e845b9d603598e8d379f6525a7a92ee2
163
meistercharts
Apache License 2.0
presentation/src/commonMain/kotlin/ireader/presentation/ui/component/list/scrollbars/LazyColumnScrollbar.kt
kazemcodes
540,829,865
true
{"Kotlin": 2179459}
package ireader.presentation.ui.component.list.scrollbars import androidx.compose.foundation.lazy.LazyListState import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.Shape import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import ireader.domain.models.prefs.PreferenceValues @Composable expect fun LazyColumnScrollbar( listState: LazyListState, rightSide: Boolean = true, thickness: Dp = 6.dp, padding: Dp = 8.dp, thumbMinHeight: Float = 0.1f, thumbColor: Color, thumbSelectedColor: Color, indicatorContent: (@Composable (index: Int, isThumbSelected: Boolean) -> Unit)?, thumbShape: Shape , enable: Boolean, selectionMode: PreferenceValues.ScrollbarSelectionMode, content: @Composable () -> Unit, ) @Composable fun ILazyColumnScrollbar( listState: LazyListState, rightSide: Boolean = true, thickness: Dp = 6.dp, padding: Dp = 8.dp, thumbMinHeight: Float = 0.1f, thumbColor: Color = MaterialTheme.colorScheme.primaryContainer, thumbSelectedColor: Color = MaterialTheme.colorScheme.primary, indicatorContent: (@Composable (index: Int, isThumbSelected: Boolean) -> Unit)? = null, thumbShape: Shape = CircleShape, enable: Boolean = true, selectionMode: PreferenceValues.ScrollbarSelectionMode = PreferenceValues.ScrollbarSelectionMode.Thumb, content: @Composable () -> Unit, ) = LazyColumnScrollbar(listState, rightSide, thickness, padding, thumbMinHeight, thumbColor, thumbSelectedColor, indicatorContent, thumbShape, enable, selectionMode, content)
0
Kotlin
0
6
b6b2414fa002cec2aa0d199871fcfb4c2e190a8f
1,827
IReader
Apache License 2.0
app/src/main/java/com/vineelsai/dm/MainActivity.kt
VSPlayStore
559,578,184
false
{"Kotlin": 3283}
package com.vineelsai.dm import android.content.Intent import android.net.Uri import android.os.Bundle import android.widget.Button import android.widget.EditText import androidx.appcompat.app.AppCompatActivity import com.hbb20.CountryCodePicker class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val sentBtn = findViewById<Button>(R.id.send) val countryCodePicker = findViewById<CountryCodePicker>(R.id.countryCodePicker) val number = findViewById<EditText>(R.id.number) val message = findViewById<EditText>(R.id.message) sentBtn.setOnClickListener { val countryCode = countryCodePicker.selectedCountryCode if (number.text.trim().length == 10) { val intent = Intent(Intent.ACTION_VIEW) intent.data = Uri.parse("https://api.whatsapp.com/send?phone=${countryCode + number.text}&text=${message.text}") startActivity(intent) } else { number.error = "Enter a valid mobile number" } } } }
0
Kotlin
0
0
f8064bfd58865de6bdedd7886fbf1864fc20bf19
1,211
Direct-Message
MIT License
kotlin-reference-server/src/main/kotlin/org/stellar/reference/model/Customer.kt
rkharevych
673,720,892
true
{"YAML": 61, "Gradle Kotlin DSL": 10, "Markdown": 19, "Shell": 6, "Git Attributes": 1, "Dockerfile": 3, "Batchfile": 1, "Text": 3, "Ignore List": 1, "Makefile": 1, "Kotlin": 173, "INI": 3, "Java": 405, "Smarty": 1, "JSON": 18, "XML": 14, "Java Properties": 2, "TOML": 6, "HCL": 13, "Python": 1, "Dotenv": 2, "SQL": 8}
package org.stellar.reference.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class Customer( val id: String? = null, @SerialName("stellar_account") val stellarAccount: String? = null, val memo: String? = null, val memoType: String? = null, @SerialName("first_name") val firstName: String? = null, @SerialName("last_name") val lastName: String? = null, @SerialName("email_address") val emailAddress: String? = null, @SerialName("bank_account_number") val bankAccountNumber: String? = null, @SerialName("bank_account_type") val bankAccountType: String? = null, @SerialName("bank_routing_number") val bankRoutingNumber: String? = null, @SerialName("clabe_number") val clabeNumber: String? = null, ) enum class Status { NEEDS_INFO, ACCEPTED, PROCESSING, ERROR, }
1
Java
0
0
6442a92a84627af1993a007990918134b589982b
852
java-stellar-anchor-sdk
Apache License 2.0
feature_discovery/src/main/kotlin/com/leovp/feature_discovery/data/DiscoveryModule.kt
yhz61010
665,842,314
false
{"Kotlin": 236627}
@file:Suppress("unused") package com.leovp.feature_discovery.data import com.leovp.feature_discovery.data.repository.DiscoveryRepositoryImpl import com.leovp.feature_discovery.domain.repository.DiscoveryRepository import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent import javax.inject.Qualifier import javax.inject.Singleton /** * Author: Michael Leo * Date: 2023/9/13 10:49 */ @Qualifier @Retention(AnnotationRetention.BINARY) annotation class DiscoveryRepositoryImplement @Module @InstallIn(SingletonComponent::class) abstract class DiscoveryModule { @Singleton @DiscoveryRepositoryImplement @Binds abstract fun bindRepository(repository: DiscoveryRepositoryImpl): DiscoveryRepository }
0
Kotlin
0
0
c7c9e50984fc39ba1baf50378e4dde5b71c7205c
780
AndroidShowcase
MIT License
imx-core-sdk-kotlin-jvm/src/test/kotlin/com/immutable/sdk/extensions/ECKeyPairExtensionsTest.kt
immutable
467,767,205
false
{"Kotlin": 668106, "Java": 131024, "Mustache": 29745, "Solidity": 10068}
package com.immutable.sdk.extensions import junit.framework.TestCase.assertEquals import org.junit.Test import org.web3j.crypto.ECKeyPair import java.math.BigInteger class ECKeyPairExtensionsTest { @Test fun testGetUncompressedPublicKey() { val priKey = BigInteger("64921332213866445295402452406359669616940831814648692629855451985861889755924") val pubKey = BigInteger( "9901532862291060574053445876038647650509149806815782609589844942518406773458626646324" + "507388973112731900700287178564981928810919490275135830477941243800767" ) val keyPair = ECKeyPair(priKey, pubKey) assertEquals( "0x04bd0daf39994ee40477d9ab5a29956d52f0869a329aede770bdd913a560d1086175d" + "0d39dc1150be883d0e80517801583dd6cbffea87c47f52a58dece873e6cbf", keyPair.getUncompressedPublicKey() ) } }
2
Kotlin
2
5
4a823d30db92356c325140874f5ba708547585ca
901
imx-core-sdk-kotlin-jvm
Apache License 2.0
src/main/kotlin/id/walt/idp/siwe/siwfManager.kt
walt-id
472,421,655
false
{"Kotlin": 129734, "Vue": 29550, "JavaScript": 4711, "Dockerfile": 1131}
package id.walt.idp.siwe import id.walt.idp.config.IDPConfig import id.walt.idp.oidc.OIDCSession import io.ktor.client.* import io.ktor.client.call.* import io.ktor.client.engine.cio.* import io.ktor.client.plugins.contentnegotiation.* import io.ktor.client.plugins.logging.* import io.ktor.client.request.* import io.ktor.serialization.kotlinx.json.* import io.ktor.util.* import kotlinx.coroutines.runBlocking import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonEncoder import java.net.URLEncoder import java.nio.charset.StandardCharsets object siwfManager { val client = HttpClient(CIO.create{requestTimeout = 0}) { install(ContentNegotiation) { json(Json { ignoreUnknownKeys = true }) } install(Logging) { logger = Logger.SIMPLE level = LogLevel.ALL } expectSuccess = false } fun verifySignature(session: OIDCSession, message: String, signature: String): Boolean{ val nonce= getNonce(message) if (session.siweSession?.nonce != nonce) { return false; } if (SiweManager.nonceBlacklists.contains(nonce)) { return false } SiweManager.nonceBlacklists.add(nonce) return runBlocking { val result = client.post("${IDPConfig.config.jsProjectExternalUrl}/flow/signature/verification?signature=${URLEncoder.encode(signature, StandardCharsets.UTF_8.toString())}&message=${URLEncoder.encode(message, StandardCharsets.UTF_8.toString())}") { }.body<Boolean>() return@runBlocking result } } fun getAddress(message:String): String{ val address= message.split(" .").get(0).split(":").last().trim() return address } fun getNonce(message: String): String{ val nonce= message.split(".").last().split(":").last().trim() return nonce } }
0
Kotlin
6
21
e6c1c7694ca8da80e2510b0fbef3fd8a04a31d19
1,843
waltid-idpkit
Apache License 2.0
app/src/main/java/com/uzias/starwarsshop/util/ErrorPredicate.kt
uziassantosferreira
108,789,405
false
null
package com.uzias.starwarsshop.util interface ErrorPredicate { fun evaluate(error: Throwable): Boolean }
0
Kotlin
1
38
dec2d949a69e870bf37a76c4f22d86c93c12c143
109
Star-Wars-Shop
Apache License 2.0
kondor-core/src/test/kotlin/com/ubertob/kondor/json/JsonRenderTest.kt
uberto
343,412,601
false
{"Kotlin": 298299, "Java": 46239, "Shell": 910}
package com.ubertob.kondor.json import com.ubertob.kondor.json.JsonStyle.Companion.compact import com.ubertob.kondor.json.JsonStyle.Companion.compactWithNulls import com.ubertob.kondor.json.JsonStyle.Companion.pretty import com.ubertob.kondor.json.JsonStyle.Companion.prettyWithNulls import com.ubertob.kondor.json.jsonnode.* import org.junit.jupiter.api.Test import strikt.api.expectThat import strikt.assertions.isEqualTo import kotlin.random.Random class JsonRenderTest { @Test fun `render null`() { val jsonString = JsonNodeNull(NodePathRoot).render() expectThat(jsonString).isEqualTo("null") } @Test fun `render Boolean`() { val value = true val jsonString = JsonNodeBoolean(value, NodePathRoot).render() expectThat(jsonString).isEqualTo("true") } @Test fun `render exp Num`() { val value = Double.MIN_VALUE val jsonString = JsonNodeNumber(value, NodePathRoot).render() expectThat(jsonString).isEqualTo("4.9E-324") } @Test fun `render integer Num`() { val value = Int.MAX_VALUE val jsonString = JsonNodeNumber(value, NodePathRoot).render() expectThat(jsonString).isEqualTo("2147483647") } @Test fun `render Nan Num`() { val value = Double.NaN val jsonString = JsonNodeNumber(value, NodePathRoot).render() expectThat(jsonString).isEqualTo("NaN") } @Test fun `render directly non numeric values`() { expectThat(JDouble.toJson(Double.NaN)).isEqualTo(""""NaN"""") expectThat(JDouble.toJson(Double.NEGATIVE_INFINITY)).isEqualTo(""""-Infinity"""") expectThat(JDouble.toJson(Double.POSITIVE_INFINITY)).isEqualTo(""""Infinity"""") } @Test fun `render String field honoring Json escaping rules`() { val value = "abc {} \\ , : [] \" \n \t \r 123" val jsonString = JsonNodeString(value, NodePathRoot).render() expectThat(jsonString).isEqualTo(""""abc {} \\ , : [] \" \n \t \r 123"""") } @Test fun `render array`() { val jsonString = JsonNodeArray( listOf(JsonNodeString("abc", NodePathRoot), JsonNodeString("def", NodePathRoot)), NodePathRoot ).render() expectThat(jsonString).isEqualTo("""["abc","def"]""") } @Test fun `render array with nulls`() { val jsonString = JsonNodeArray( listOf( JsonNodeString("abc", NodePathRoot), JsonNodeNull(NodePathRoot), JsonNodeString("def", NodePathRoot) ), NodePathRoot ).render() expectThat(jsonString).isEqualTo("""["abc","def"]""") } @Test fun `pretty render array`() { val nodeArray = JsonNodeArray( listOf( JsonNodeString("abc", NodePathRoot), JsonNodeNull(NodePathRoot), JsonNodeString("def", NodePathRoot) ), NodePathRoot ) val jsonString = pretty.render(nodeArray) expectThat(jsonString).isEqualTo( """[ | "abc", | "def" |]""".trimMargin() ) val jsonStringNN = prettyWithNulls.render(nodeArray) expectThat(jsonStringNN).isEqualTo( """[ | "abc", | null, | "def" |]""".trimMargin() ) } @Test fun `render object from node`() { val jsonString = JsonNodeObject( mapOf( "id" to JsonNodeNumber(123, NodePathRoot), "name" to JsonNodeString("Ann", NodePathRoot) ), NodePathRoot ).render() val expected = """{"id":123,"name":"Ann"}""" expectThat(jsonString).isEqualTo(expected) } @Test fun `render object with nulls`() { val nullOnlyObj =OptionalAddress(null, null, null) expectThat(JOptionalAddress.toJson(nullOnlyObj, compact)) .isEqualTo("""{}""") val streetOnlyObj =OptionalAddress(null, "42 Adams Road", null) expectThat(JOptionalAddress.toJson(streetOnlyObj, compact)) .isEqualTo("""{"street":"42 Adams Road"}""") val nameAndstreetObj =OptionalAddress("Marvin", "42 Adams Road", null) expectThat(JOptionalAddress.toJson(nameAndstreetObj, compact)) .isEqualTo("""{"name":"Marvin","street":"42 Adams Road"}""") } @Test fun `render object with nulls from node`() { val jsonString = JsonNodeObject( mapOf( "firstNullable" to JsonNodeNull(NodePathRoot), "id" to JsonNodeNumber(123, NodePathRoot), "name" to JsonNodeString("Ann", NodePathRoot), "lastNullable" to JsonNodeNull(NodePathRoot) ), NodePathRoot ).render() val expected = """{"id":123,"name":"Ann"}""" expectThat(jsonString).isEqualTo(expected) } @Test fun `custom pretty render object`() { repeat(5) { val indent = Random.nextInt(8) fun customNewLine(app: CharWriter, offset: Int): CharWriter = app.apply { app.write('\n') repeat(offset * indent) { app.write(' ') } } val style = pretty.copy(appendNewline = ::customNewLine ) val jsonString = JsonNodeObject( mapOf( "id" to JsonNodeNumber(123, NodePathRoot), "name" to JsonNodeString("Ann", NodePathRoot) ), NodePathRoot ).render(style) val internal = " ".repeat(indent) val expected = """{ |$internal"id": 123, |$internal"name": "Ann" |}""".trimMargin() expectThat(jsonString).isEqualTo(expected) } } @Test fun `render object with null explicit`() { val path = NodePathRoot val nodeObject = JsonNodeObject( mapOf( "id" to JsonNodeNumber(123, path), "name" to JsonNodeString("Ann", path), "somethingelse" to JsonNodeNull(path) ), NodePathRoot ) val jsonString = prettyWithNulls.render(nodeObject) val expected = """{ | "id": 123, | "name": "Ann", | "somethingelse": null |}""".trimMargin() expectThat(jsonString).isEqualTo(expected) val jsonStringNN = pretty.render(nodeObject) val expectedNN = """{ | "id": 123, | "name": "Ann" |}""".trimMargin() expectThat(jsonStringNN).isEqualTo(expectedNN) } @Test fun `compact render object`() { val jsonString = JsonNodeObject( mapOf( "id" to JsonNodeNumber(123, NodePathRoot), "name" to JsonNodeString("Ann", NodePathRoot), "nullable" to JsonNodeNull(NodePathRoot) ), NodePathRoot ).render(compact) expectThat(jsonString).isEqualTo("""{"id":123,"name":"Ann"}""") } @Test fun `compact render object with null explicit`() { val jsonString = JsonNodeObject( mapOf( "id" to JsonNodeNumber(123, NodePathRoot), "name" to JsonNodeString("Ann", NodePathRoot), "nullable" to JsonNodeNull(NodePathRoot), "arrayNullable" to JsonNodeArray( listOf( JsonNodeString("Bob", NodePathRoot), JsonNodeNull(NodePathRoot) ), NodePathRoot ), "objectNullable" to JsonNodeObject( mapOf( "one" to JsonNodeString("two", NodePathRoot), "three" to JsonNodeNull(NodePathRoot) ), NodePathRoot ) ), NodePathRoot ).render(compactWithNulls) expectThat(jsonString).isEqualTo("""{"id":123,"name":"Ann","nullable":null,"arrayNullable":["Bob",null],"objectNullable":{"one":"two","three":null}}""") } @Test fun `using converter with different default style`() { val addr = OptionalAddress("Jack", null, "London") val jsonPretty = JOptionalAddress.toJson(addr) expectThat(jsonPretty).isEqualTo( """{ | "city": "London", | "name": "Jack", | "street": null |}""".trimMargin() ) } }
0
Kotlin
10
66
a43e01ddca5a493cd10824a485b3a7e81554afbf
8,838
kondor-json
Apache License 2.0
Functional Programming/Manipulating Lists/Exercise 6/src/Task.kt
marchdz
633,862,396
false
null
// ManipulatingLists/Task6.kt package manipulatingListsExercise6 import atomictest.eq fun <T> List<List<T>>.flatten(): List<T> = flatMap { TODO() } fun main() { val listOfLists = listOf(listOf(1, 2, 3), listOf(4, 5, 6)) listOfLists.flatten() eq listOf(1, 2, 3, 4, 5, 6) }
0
Kotlin
0
0
1efabf8721c4efbb0891b7b9469efc9e7b36f189
280
atomic-kotlin-exercises
MIT License
app/src/main/java/com/chrynan/launcher/exception/NotDefaultLauncherException.kt
chRyNaN
161,240,007
false
null
package com.chrynan.launcher.exception class NotDefaultLauncherException(errorMessage: String? = null) : RuntimeException(errorMessage)
0
Kotlin
0
0
c226fc3997b0e76bcb237e2d09ee47ceed5bad2e
136
Launcher
Apache License 2.0
app/src/main/java/com/example/winner/tebakgambar2.kt
laser123495
591,175,591
false
{"Kotlin": 105375}
package com.example.winner import android.app.Dialog import android.content.Intent import android.graphics.Color import android.graphics.drawable.ColorDrawable import android.media.MediaPlayer import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.os.Handler import android.widget.Button import android.widget.Toast import com.example.winner.databinding.ActivityFinishBinding import com.example.winner.databinding.ActivityTebakgambar2Binding import com.example.winner.databinding.ActivityTebakgambarBinding import kotlinx.android.synthetic.main.activity_perhitungan1.* import kotlinx.android.synthetic.main.activity_tebakgambar1.* import kotlinx.android.synthetic.main.activity_tebakgambar1.tb1help import kotlinx.android.synthetic.main.activity_tebakgambar2.* class tebakgambar2 : AppCompatActivity() { private lateinit var binding: ActivityTebakgambar2Binding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityTebakgambar2Binding.inflate(layoutInflater) setContentView(binding.root) var mediaPlayer = MediaPlayer.create(this,R.raw.kucing) mediaPlayer.start() kucing.animate().apply { duration = 700 rotationYBy(360f) }.start() Handler().postDelayed({ var mediaPlayer2 = MediaPlayer.create(this,R.raw.roar) mediaPlayer2.start() kucing3.animate().apply { duration = 700 rotationYBy(360f) }.start() },1000) Handler().postDelayed({ var mediaPlayer2 = MediaPlayer.create(this,R.raw.roar) mediaPlayer2.start() kucing2.animate().apply { duration = 700 rotationYBy(360f) }.start() },500) binding.tb2help.setOnClickListener { tb2help.animate().apply { duration = 2000 rotationYBy(720f) }.start() var mediaPlayer = MediaPlayer.create(this,R.raw.click) mediaPlayer.start() Toast.makeText(applicationContext,"coba pilih yang paling kiri..gambar kucing *meow...*", Toast.LENGTH_SHORT).show() } binding.kucing.setOnClickListener { var mediaPlayer = MediaPlayer.create(this,R.raw.kucing) mediaPlayer.start() Toast.makeText(applicationContext," yee benar, kamu hebat!!",Toast.LENGTH_SHORT).show() kucing.animate().apply { duration = 500 rotationYBy(360f) }.start() Handler().postDelayed({val intent = Intent(this,tebakgambar3::class.java) startActivity(intent) },600) } binding.kucing2.setOnClickListener { var mediaPlayer = MediaPlayer.create(this,R.raw.roar) mediaPlayer.start() Toast.makeText(applicationContext," yah salah, itu harimau *roarr!!*",Toast.LENGTH_SHORT).show() kucing2.animate().apply { duration = 500 rotationYBy(360f) }.start() } binding.kucing3.setOnClickListener { var mediaPlayer = MediaPlayer.create(this,R.raw.roar) mediaPlayer.start() Toast.makeText(applicationContext," yah salah, itu singa *roarr!!*",Toast.LENGTH_SHORT).show() kucing3.animate().apply { duration = 500 rotationYBy(360f) }.start() } binding.back.setOnClickListener { var mediaPlayer = MediaPlayer.create(this,R.raw.click) mediaPlayer.start() val dilaogBinding = layoutInflater.inflate(R.layout.activity_quit,null) val myDialog = Dialog(this) myDialog.setContentView(dilaogBinding) myDialog.setCancelable(true) myDialog.window?.setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT)) myDialog.show() val yesbtn = dilaogBinding.findViewById<Button>(R.id.alert_yes) yesbtn.setOnClickListener{ var mediaPlayer = MediaPlayer.create(this,R.raw.click) mediaPlayer.start() val intent = Intent(this,tebakgambar::class.java) startActivity(intent) } val nobtn = dilaogBinding.findViewById<Button>(R.id.alert_no) nobtn.setOnClickListener{ var mediaPlayer = MediaPlayer.create(this,R.raw.click) mediaPlayer.start() myDialog.dismiss() } } } }
0
Kotlin
0
0
4ca08dd0f2268aca296da39b9a685d181170b62a
4,653
winner_app
Apache License 2.0
src/main/java/me/han/muffin/client/module/modules/other/StreamerModeModule.kt
SmallFishDD
425,272,585
false
{"Kotlin": 1725682, "Java": 943392, "GLSL": 15937}
package me.han.muffin.client.module.modules.other import me.han.muffin.client.core.Globals import me.han.muffin.client.event.EventStageable import me.han.muffin.client.event.events.client.UpdateEvent import me.han.muffin.client.event.events.render.TextEvent import me.han.muffin.client.module.Module import me.han.muffin.client.utils.client.ChatUtils import me.han.muffin.client.value.Value import org.apache.commons.lang3.StringUtils import team.stiff.pomelo.impl.annotated.handler.annotation.Listener internal object StreamerModeModule: Module("StreamerMode", Category.OTHERS, "Change your name and your skins.") { private val resetName = Value(false, "ResetName") val allPlayersValue = Value(false, "AllPlayers") val skinProtectValue = Value(true, "SkinProtect") val hideCA = Value(true, "HideCA") var fakeName = "Handsome" init { addSettings(resetName, allPlayersValue, skinProtectValue, hideCA) } @Listener private fun onPlayerUpdate(event: UpdateEvent) { if (event.stage != EventStageable.EventStage.PRE) return if (resetName.value) { fakeName = "Handsome" resetName.value = false } } @Listener private fun onText(event: TextEvent) { if (fullNullCheck() || event.text.contains(ChatUtils.PREFIX)) return event.text = StringUtils.replace(event.text, Globals.mc.player.name, fakeName) if (allPlayersValue.value) { for (playerInfo in Globals.mc.player.connection.playerInfoMap) { event.text = StringUtils.replace(event.text, playerInfo.gameProfile.name, "Protected User") } } } }
1
Kotlin
2
2
13235eada9edd9ccca039dea4d3a59cc7a930830
1,670
muffin-0.10.4-src-leaked
MIT License
app/src/main/java/com/myapp/medled/adapters/recycler_view/DoctorsRecyclerViewAdapter.kt
F-Y-E-F
307,081,321
false
null
package com.myapp.medled.adapters.recycler_view import android.annotation.SuppressLint import android.text.format.DateFormat import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.myapp.medled.R import com.myapp.medled.adapters.recycler_view.view_holders.DoctorsRecyclerViewHolder import com.myapp.medled.models.User import com.myapp.medled.screens.doctor.AllDoctorsInterface import java.util.* import kotlin.collections.ArrayList class DoctorsRecyclerViewAdapter(private val listOfDoctors:ArrayList<User>, private val listener:AllDoctorsInterface) : RecyclerView.Adapter<DoctorsRecyclerViewHolder>() { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): DoctorsRecyclerViewHolder { return DoctorsRecyclerViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.doctor_card,parent,false)) } override fun getItemCount(): Int { return listOfDoctors.size } @SuppressLint("SetTextI18n") override fun onBindViewHolder(holder: DoctorsRecyclerViewHolder, position: Int) { val doctor = listOfDoctors[holder.adapterPosition] //------------| get start and end time as string |---------------- val c = Calendar.getInstance() c.timeInMillis = doctor.startTime!! val startTime = DateFormat.format("HH:mm",c).toString() c.timeInMillis = doctor.endTime!! val endTime = DateFormat.format("HH:mm",c).toString() //================================================================= //setup doctor's data holder.doctorName.text = doctor.name holder.doctorWorkTime.text = "$startTime-$endTime" holder.doctorStarCount.text = doctor.starCount.toString() holder.doctorType.text = doctor.medicineBranch holder.doctorAvatar.setImageResource(doctor.avatar) holder.allBox.setOnClickListener { listener.chooseDoctor(doctor) } } }
0
Kotlin
0
1
e13b29a1be0cda44071d6326fff65025464dc0fd
1,983
medled-compiled-version
The Unlicense
baseLib/src/main/java/me/ycdev/android/lib/common/internalapi/android/os/UserHandleIA.kt
yongce
12,662,755
false
null
package me.ycdev.android.lib.common.internalapi.android.os import android.annotation.SuppressLint import android.os.UserHandle import androidx.annotation.RestrictTo import timber.log.Timber import java.lang.reflect.InvocationTargetException import java.lang.reflect.Method @SuppressLint("PrivateApi") object UserHandleIA { private const val TAG = "UserHandleIA" private var sMtd_myUserId: Method? = null init { try { sMtd_myUserId = UserHandle::class.java.getMethod("myUserId") } catch (e: NoSuchMethodException) { Timber.tag(TAG).w(e, "method not found") } } fun myUserId(): Int { if (sMtd_myUserId != null) { try { return sMtd_myUserId!!.invoke(null) as Int } catch (e: IllegalAccessException) { Timber.tag(TAG).w(e, "Failed to invoke #myUserId()") } catch (e: InvocationTargetException) { Timber.tag(TAG).w(e, "Failed to invoke #myUserId() ag") } } return 0 } /** * Just for unit test. */ @RestrictTo(RestrictTo.Scope.TESTS) internal fun checkReflectMyUserId(): Boolean { return sMtd_myUserId != null } }
0
Kotlin
6
19
5ffb4444b1e285a5f31138bbb98a39f869342c15
1,240
AndroidLib
Apache License 2.0
app/src/main/java/com/business/the_movie_app/remote/MovieApiMethodImpl.kt
sterlingking1990
656,014,950
false
null
package com.business.the_movie_app.remote import com.business.the_movie_app.model.response.Movie import io.reactivex.Single import javax.inject.Inject class MovieApiMethodImpl @Inject constructor(private val movieApi: MovieApi) : MovieApiMethod { override fun getMovies(apiKey:String): Single<List<Movie>> { return movieApi.getPopularMovies(apiKey) .map { response -> response.results } } }
0
Kotlin
0
0
3bc93a50405a9b15e9e53be0a3b11bd5ef3b9e95
420
the-movie-app
MIT License
app/src/main/java/com/business/the_movie_app/remote/MovieApiMethodImpl.kt
sterlingking1990
656,014,950
false
null
package com.business.the_movie_app.remote import com.business.the_movie_app.model.response.Movie import io.reactivex.Single import javax.inject.Inject class MovieApiMethodImpl @Inject constructor(private val movieApi: MovieApi) : MovieApiMethod { override fun getMovies(apiKey:String): Single<List<Movie>> { return movieApi.getPopularMovies(apiKey) .map { response -> response.results } } }
0
Kotlin
0
0
3bc93a50405a9b15e9e53be0a3b11bd5ef3b9e95
420
the-movie-app
MIT License
app/src/test/java/com/softcube/re_reddit/application/base/BaseUseCaseTest.kt
wgarcia4190
374,144,617
false
null
package com.softcube.re_reddit.application.base import com.softcube.re_reddit.data.remote.model.ApiError import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.flow /** * com.softcube.re_reddit.application.base * * Created by <NAME> on 6/5/21 * Copyright © 2021 <NAME>. All rights reserved. */ abstract class BaseUseCaseTest<in P, out T>() { var result: NetworkResult = NetworkResult.SUCCESS fun execute(params: P): T { when (result) { NetworkResult.SUCCESS -> return getValue(params) NetworkResult.ERROR -> throw ApiError(null, "Something went wrong") } } abstract fun getValue(params: P): T }
0
Kotlin
0
1
9a8a1aac6c3c7daf7717cdc381acde328dbd4749
631
re-reddit-android
MIT License
domene/src/main/kotlin/no/nav/tiltakspenger/domene/behandling/Søknadsbehandling.kt
navikt
487,246,438
false
{"Kotlin": 916954, "Shell": 1309, "Dockerfile": 495, "HTML": 45}
package no.nav.tiltakspenger.domene.behandling import no.nav.tiltakspenger.domene.saksopplysning.Saksopplysning import no.nav.tiltakspenger.domene.saksopplysning.lagVurdering import no.nav.tiltakspenger.domene.vilkår.Utfall import no.nav.tiltakspenger.felles.BehandlingId import no.nav.tiltakspenger.felles.Periode import no.nav.tiltakspenger.felles.SakId sealed interface Søknadsbehandling : Behandling { val søknader: List<Søknad> fun søknad(): Søknad { return søknader.siste() } data class Opprettet( override val id: BehandlingId, override val sakId: SakId, override val søknader: List<Søknad>, override val vurderingsperiode: Periode, override val saksopplysninger: List<Saksopplysning>, override val tiltak: List<Tiltak>, override val saksbehandler: String?, ) : Søknadsbehandling { companion object { fun fromDb( id: BehandlingId, sakId: SakId, søknader: List<Søknad>, vurderingsperiode: Periode, saksopplysninger: List<Saksopplysning>, tiltak: List<Tiltak>, saksbehandler: String?, ): Opprettet { return Opprettet( id = id, sakId = sakId, søknader = søknader, vurderingsperiode = vurderingsperiode, saksopplysninger = saksopplysninger, tiltak = tiltak, saksbehandler = saksbehandler, ) } fun leggTilSøknad(behandling: Søknadsbehandling, søknad: Søknad): Opprettet { val fakta = if (søknad.vurderingsperiode() != behandling.vurderingsperiode) { lagFaktaInit(søknad) + lagFaktaAvSøknad(søknad) } else { lagFaktaAvSøknad(søknad).fold(behandling.saksopplysninger) { acc, saksopplysning -> acc.oppdaterSaksopplysninger(saksopplysning) } } return Opprettet( id = behandling.id, sakId = behandling.sakId, søknader = behandling.søknader + søknad, vurderingsperiode = søknad.vurderingsperiode(), saksopplysninger = fakta, tiltak = behandling.tiltak, saksbehandler = behandling.saksbehandler, ) } fun opprettBehandling(sakId: SakId, søknad: Søknad): Opprettet { return Opprettet( id = BehandlingId.random(), sakId = sakId, søknader = listOf(søknad), vurderingsperiode = søknad.vurderingsperiode(), saksopplysninger = lagFaktaInit(søknad) + lagFaktaAvSøknad(søknad), tiltak = emptyList(), saksbehandler = null, ) } } override fun erÅpen() = true fun vilkårsvurder(): BehandlingVilkårsvurdert { // Først lager vi Vurderinger // todo Her kan vi vurdere å lage bare en map og ta som en forutsetning at det er en saksopplysning for hvert vilkår val vurderinger = saksopplysninger().flatMap { it.lagVurdering(vurderingsperiode) } // Etter at vi har laget vurderinger, sjekker vi utfallet if (vurderinger.any { it.utfall == Utfall.KREVER_MANUELL_VURDERING }) { return BehandlingVilkårsvurdert.Manuell( id = id, sakId = sakId, søknader = søknader, vurderingsperiode = vurderingsperiode, saksopplysninger = saksopplysninger, tiltak = tiltak, vilkårsvurderinger = vurderinger, saksbehandler = saksbehandler, ) } if (vurderinger.any { it.utfall == Utfall.KREVER_MANUELL_VURDERING }) { return BehandlingVilkårsvurdert.Manuell( id = id, sakId = sakId, søknader = søknader, vurderingsperiode = vurderingsperiode, saksopplysninger = saksopplysninger, tiltak = tiltak, vilkårsvurderinger = vurderinger, saksbehandler = saksbehandler, ) } if (vurderinger.all { it.utfall == Utfall.OPPFYLT }) { return BehandlingVilkårsvurdert.Innvilget( id = id, sakId = sakId, søknader = søknader, vurderingsperiode = vurderingsperiode, saksopplysninger = saksopplysninger, tiltak = tiltak, vilkårsvurderinger = vurderinger, saksbehandler = saksbehandler, ) } if (vurderinger.all { it.utfall == Utfall.IKKE_OPPFYLT }) { return BehandlingVilkårsvurdert.Avslag( id = id, sakId = sakId, søknader = søknader, vurderingsperiode = vurderingsperiode, saksopplysninger = saksopplysninger, tiltak = tiltak, vilkårsvurderinger = vurderinger, saksbehandler = saksbehandler, ) } return BehandlingVilkårsvurdert.Avslag( id = id, sakId = sakId, søknader = søknader, vurderingsperiode = vurderingsperiode, saksopplysninger = saksopplysninger, tiltak = tiltak, vilkårsvurderinger = vurderinger, saksbehandler = saksbehandler, ) } override fun leggTilSøknad(søknad: Søknad): BehandlingVilkårsvurdert { return Opprettet( id = id, sakId = sakId, søknader = søknader + søknad, vurderingsperiode = vurderingsperiode, saksopplysninger = lagFaktaAvSøknad(søknad).fold(saksopplysninger) { acc, saksopplysning -> acc.oppdaterSaksopplysninger(saksopplysning) }, tiltak = tiltak, saksbehandler = saksbehandler, ).vilkårsvurder() } override fun leggTilSaksopplysning(saksopplysning: Saksopplysning): LeggTilSaksopplysningRespons { val oppdatertSaksopplysningListe = saksopplysninger.oppdaterSaksopplysninger(saksopplysning) return if (oppdatertSaksopplysningListe == this.saksopplysninger) { LeggTilSaksopplysningRespons( behandling = this, erEndret = false, ) } else { LeggTilSaksopplysningRespons( behandling = this.copy(saksopplysninger = oppdatertSaksopplysningListe).vilkårsvurder(), erEndret = true, ) } } override fun oppdaterTiltak(tiltak: List<Tiltak>): Søknadsbehandling = this.copy( tiltak = tiltak, ) override fun startBehandling(saksbehandler: String): Søknadsbehandling = this.copy( saksbehandler = saksbehandler, ) override fun avbrytBehandling(): Søknadsbehandling = this.copy( saksbehandler = null, ) } }
2
Kotlin
0
2
5f464f9a99de224789f79dda35ea949978bd04e8
7,781
tiltakspenger-vedtak
MIT License
brav/app/src/main/java/com/thadocizn/brav/views/PaymentActivity.kt
labs14-brav
196,241,971
false
{"Kotlin": 52438}
package com.thadocizn.brav.views import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.stripe.android.ApiResultCallback import com.stripe.android.Stripe import com.stripe.android.model.Card import com.stripe.android.model.Token import com.stripe.android.view.CardMultilineWidget import com.thadocizn.brav.R import com.thadocizn.brav.models.StripeToken import com.thadocizn.brav.services.RetroInstance import com.thadocizn.brav.utils.SharedPreference import kotlinx.android.synthetic.main.activity_payment.* import kotlinx.coroutines.* import org.jetbrains.anko.intentFor import org.jetbrains.anko.longToast import org.jetbrains.anko.newTask class PaymentActivity : CoroutineScopeActivity() { private lateinit var cardInputWidget: CardMultilineWidget private lateinit var idToken: String var caseId: Int? = 0 var invoiceId: Int = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_payment) caseId = intent.getIntExtra("caseId", 0) invoiceId = intent.getIntExtra("invoiceId", 0) val sharedPreference = SharedPreference(this) idToken = sharedPreference.getToken("token").toString() btnSubmit.setOnClickListener { val card = getCard() if (card != null) { getstripeToken(card) } } } private fun getCard(): Card? { cardInputWidget = findViewById(R.id.card_input_widget) return cardInputWidget.card } private fun getstripeToken(card: Card): Unit { val stripe = Stripe(this, "pk_test_jvHFK1rRq0u4Bj2BejCL7ngi") stripe.createToken(card, object : ApiResultCallback<Token> { override fun onSuccess(result: Token) { //TODO("not implemented") //To change body of created functions use File | Settings | File Templates. //create a method to send token to backend to complete payment val response = result.id sendToken(response) } override fun onError(e: Exception) { // TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }) } private fun sendToken(token:String):Job = launch { val service = RetroInstance().service(idToken) val call = service.sendTokenAsync(1, StripeToken(token)) call.await() if (call.isCompleted) { getPaymentMade() } applicationContext.startActivity(intentFor<CaseActivity>().newTask()) } private fun getPaymentMade():Job = launch { val service = RetroInstance().service(idToken) val call = service.invoicePaid(1) call.await() applicationContext.longToast("Payment Sent") } }
0
Kotlin
1
0
7c2adfbe4fc365d58bf724e9c2d84e211b2d43b4
2,955
Android
MIT License
cassandra-data-service/src/main/kotlin/com/example/DataInitializer.kt
xmlking
104,446,236
false
null
package com.example import com.example.domain.GuestBookEntry import com.example.repository.GuestBookRepository import org.springframework.context.event.ContextRefreshedEvent import org.springframework.context.event.EventListener import org.springframework.stereotype.Component import reactor.core.publisher.Flux @Component class DataInitializer(val repository: GuestBookRepository) { @EventListener(ContextRefreshedEvent::class) fun init() { initGuestBookEntrys(); initUsers(); } private fun initGuestBookEntrys() { if(repository.count().block() == 0L) { val entries = Flux.just( GuestBookEntry("Sumo", "comment0"), GuestBookEntry("<NAME>", "comment1"), GuestBookEntry("<NAME>", "comment2"), GuestBookEntry("<NAME>", "comment3"), GuestBookEntry("<NAME>", "comment4"), GuestBookEntry("<NAME>", "comment5") ) repository.insert(entries).blockLast() println("created test data: ${repository.count().block()}") } } private fun initUsers() { } }
0
Kotlin
17
40
8ab1b2a2f98fae739562c733360fb4e69687879d
1,151
microservices-observability
MIT License
app/src/main/java/ca/kieve/yomiyou/ui/theme/Color.kt
kieve
442,198,320
false
null
package ca.kieve.yomiyou.ui.theme import androidx.compose.ui.graphics.Color val DarkGray = Color(0xFF020202) val Blue700 = Color(0xFF1976D2) val Blue500 = Color(0xFF2196F3) val Blue200 = Color(0xFF90CAF9)
0
Kotlin
0
3
f65b454c0e21602744f875fee51554eaafd89bca
207
yomiyou
Apache License 2.0
app/src/main/java/ca/kieve/yomiyou/ui/theme/Color.kt
kieve
442,198,320
false
null
package ca.kieve.yomiyou.ui.theme import androidx.compose.ui.graphics.Color val DarkGray = Color(0xFF020202) val Blue700 = Color(0xFF1976D2) val Blue500 = Color(0xFF2196F3) val Blue200 = Color(0xFF90CAF9)
0
Kotlin
0
3
f65b454c0e21602744f875fee51554eaafd89bca
207
yomiyou
Apache License 2.0
plugin-dotnet-agent/src/test/kotlin/jetbrains/buildServer/dotnet/test/utils/TestUtils.kt
JetBrains
49,584,664
false
{"Kotlin": 2711266, "C#": 319161, "Java": 95520, "Dockerfile": 831, "CSS": 123}
package jetbrains.buildServer.dotnet.test.utils import jetbrains.buildServer.TempFiles class TestUtils { companion object { val myTempFiles = TempFiles() @Suppress("UNCHECKED_CAST") fun <T> uninitialized(value: T?): T = value as T } }
3
Kotlin
25
94
c7f12409b67420d5655780ce6e50638ce4ca1f8d
269
teamcity-dotnet-plugin
Apache License 2.0
mastodon/src/commonMain/kotlin/fediapi/mastodon/model/Error.kt
wingio
739,512,706
false
{"Kotlin": 162782}
package fediapi.mastodon.model import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable /** * Represents an error message. * * @param error The error message. * @param errorDescription A longer description of the error, mainly provided with the OAuth API. */ @Serializable public data class Error( val error: String, @SerialName("error_description") val errorDescription: String? = null )
0
Kotlin
0
1
60720c72c90cd503e9b4cff88bcef1ac71c578b6
429
fediapi
MIT License
app/src/main/java/com/example/weatherapp/feature_settings/domain/use_case/SaveSettings.kt
VladShurakov
712,506,582
false
{"Kotlin": 89164}
package com.example.weatherapp.feature_settings.domain.use_case import com.example.weatherapp.feature_settings.domain.model.SettingsBundle import com.example.weatherapp.feature_settings.domain.repository.SettingsRepository /* * Save settings in sharedPreferences */ class SaveSettings( private val repository: SettingsRepository ) { operator fun invoke(settingsBundle: SettingsBundle){ repository.saveSettings(settingsBundle) } }
3
Kotlin
0
2
cf88fa650b18e7e11ed7294f1d073e1162b60016
455
WeatherApp
Apache License 2.0
content-types/content-types-core-services/src/main/kotlin/org/orkg/contenttypes/domain/actions/papers/PaperResearchFieldCreator.kt
TIBHannover
197,416,205
false
{"Kotlin": 4657129, "Cypher": 219284, "Python": 4881, "Shell": 2767, "Groovy": 1936, "HTML": 240}
package org.orkg.contenttypes.domain.actions.papers import org.orkg.contenttypes.domain.actions.CreatePaperCommand import org.orkg.contenttypes.domain.actions.CreatePaperState import org.orkg.contenttypes.domain.actions.StatementCollectionPropertyCreator import org.orkg.graph.domain.Predicates import org.orkg.graph.input.LiteralUseCases import org.orkg.graph.input.StatementUseCases class PaperResearchFieldCreator( private val statementCollectionPropertyCreator: StatementCollectionPropertyCreator ) : CreatePaperAction { constructor( literalService: LiteralUseCases, statementService: StatementUseCases ) : this(StatementCollectionPropertyCreator(literalService, statementService)) override operator fun invoke(command: CreatePaperCommand, state: CreatePaperState): CreatePaperState = state.apply { statementCollectionPropertyCreator.create( contributorId = command.contributorId, subjectId = state.paperId!!, predicateId = Predicates.hasResearchField, objects = command.researchFields ) } }
0
Kotlin
0
4
d54b4998b1f620f03e0afbece9cd3f26abdbf055
1,135
orkg-backend
MIT License
base/gen/src/main/java/com/spirytusz/booster/processor/gen/functions/write/strategy/base/KtTypeWriteCodeGenerator.kt
spirytusz
392,160,927
false
null
package com.spirytusz.booster.processor.gen.functions.write.strategy.base import com.spirytusz.booster.processor.base.data.type.KtType import com.squareup.kotlinpoet.CodeBlock interface KtTypeWriteCodeGenerator { fun generate( fieldName: String, ktType: KtType, codegenHook: (CodeBlock.Builder, String) -> Unit ): CodeBlock }
1
Kotlin
4
27
e2ede7bcece69832ae0267d1a34c4c6f2fdaac09
360
GsonBooster
MIT License
src/main/kotlin/com/skillw/uisystem/internal/manager/UIConfig.kt
q210520993
757,874,891
false
{"Kotlin": 21497, "JavaScript": 5002}
package com.skillw.uisystem.internal.manager import com.daxton.unrealcore.application.UnrealCoreAPI import com.skillw.pouvoir.Pouvoir import com.skillw.pouvoir.api.manager.ConfigManager import com.skillw.pouvoir.internal.core.script.javascript.JSGlobal import com.skillw.pouvoir.util.static import com.skillw.uisystem.UISystem import org.spigotmc.AsyncCatcher import taboolib.common.platform.function.getDataFolder import java.io.File object UIConfig : ConfigManager(UISystem) { override val priority: Int = 0 override fun onLoad() { AsyncCatcher.enabled = false createIfNotExists("scripts", "example.js") Pouvoir.scriptEngineManager.globalVariables.let { it["UISystem"] = UISystem::class.java.static() it["UnrealCoreAPI"] = UnrealCoreAPI::class.java } } private val scripts = File(getDataFolder(), "scripts") override fun onEnable() { onReload() } override fun subReload() { Pouvoir.scriptManager.addScriptDir(scripts) } var isDebug = false val debug: Boolean get() = this["config"].getBoolean("options.debug") || isDebug val resources: String? get() = this["config"].getString("resources.name") val resourcesEnable: Boolean get() = this["config"].getBoolean("resources.enable") val resourcesPassword: String? get() = this["config"].getString("resources.password") val disableHud: List<String> get() = this["config"].getStringList("disableHud") @JvmStatic fun debug(debug: () -> Unit) { if (this.debug) { debug.invoke() } } }
0
Kotlin
0
0
44f9aefe12c6f26d54ecbffd0d13b79968811a19
1,644
UISystem
MIT License
crystal-map-api/src/main/java/com/schwarz/crystalapi/query/Query.kt
SchwarzIT
92,849,438
false
{"Kotlin": 267497, "Java": 22478}
package com.schwarz.crystalapi.query @Retention(AnnotationRetention.BINARY) annotation class Query(val fields: Array<String>)
1
Kotlin
3
14
6737df3ffdde97826152d8239f403a01fa6db7af
127
crystal-map
MIT License
app/src/main/java/com/renatojobal/orix/ui/HomeScreen.kt
renatojobal
391,631,511
false
null
package com.renatojobal.orix.ui import androidx.compose.foundation.ExperimentalFoundationApi import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.GridCells import androidx.compose.foundation.lazy.LazyVerticalGrid import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Text import androidx.compose.ui.Alignment import androidx.compose.ui.draw.clip import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.renatojobal.orix.R import com.renatojobal.orix.CardItemModel import com.renatojobal.orix.ui.theme.* @ExperimentalFoundationApi @Composable fun HomeScreen(onSelectedRoom: () -> Unit) { Box( modifier = Modifier .background(White) .fillMaxSize() ) { Column { // App bar AppBarSection() // Salute GreetingSection(name = "Renato") // Rooms RoomsSection( cardItemModels = listOf( CardItemModel( emoji = "\uD83D\uDECB", title = "Living Room", devices = 5, color = PieOrange ), CardItemModel( emoji = "\uD83C\uDF73", title = "Kitchen", devices = 4, color = PieYellow ), CardItemModel( emoji = "\uD83D\uDDA8", title = "Office", devices = 10, color = PiePurple ), CardItemModel( emoji = "\uD83D\uDECC", title = "Bedroom", devices = 6, color = PieBlue ), CardItemModel( emoji = "\uD83D\uDEC0", title = "Bathroom", devices = 7, color = PieRed ), CardItemModel( emoji = "\uD83C\uDF7D", title = "Dining Room", devices = 4, color = PieGreen ) ), onSelectedRoom = onSelectedRoom ) } } } @Composable fun AppBarSection() { Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Icon( painter = painterResource(id = R.drawable.ic_menu), tint = MaterialTheme.colors.onSurface, contentDescription = "menu", modifier = Modifier.size(40.dp, 40.dp) ) Icon( painter = painterResource(id = R.drawable.ic_group), tint = MaterialTheme.colors.onSurface, contentDescription = "group", modifier = Modifier.size(40.dp, 40.dp) ) } } @Composable fun GreetingSection(name: String) { Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .padding(20.dp) ) { Column( verticalArrangement = Arrangement.Center ) { Text( text = "Hi $name \uD83D\uDC4B", style = MaterialTheme.typography.h4, fontWeight = FontWeight.Bold ) Text( text = "Welcome to Orix Home.", style = MaterialTheme.typography.subtitle1, modifier = Modifier.padding(0.dp, 10.dp) ) } } } @ExperimentalFoundationApi @Composable fun RoomsSection( cardItemModels: List<CardItemModel>, onSelectedRoom: () -> Unit ) { Column { Row( horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, modifier = Modifier .fillMaxWidth() .padding(16.dp) ) { Row { Text( text = "Your", style = MaterialTheme.typography.h4 ) Text( text = " Rooms", style = MaterialTheme.typography.h4, fontWeight = FontWeight.Bold ) } Box( contentAlignment = Alignment.Center, modifier = Modifier .padding(start = 15.dp, top = 15.dp, bottom = 15.dp) .clip(RoundedCornerShape(20.dp)) .background( IceGreen ) .padding(15.dp) ) { Row { Text( text = "Add ", color = JavaGreen ) Icon( painter = painterResource(id = R.drawable.ic_add_box), tint = JavaGreen, contentDescription = "add" ) } } } // Rooms grid LazyVerticalGrid( cells = GridCells.Fixed(2), contentPadding = PaddingValues(start = 7.5.dp, end = 7.5.dp, bottom = 20.dp), modifier = Modifier.fillMaxHeight() ) { items(cardItemModels.size) { Box( modifier = Modifier .fillMaxSize() .clickable(onClick = onSelectedRoom) ) { CardItem( color = cardItemModels[it].color, emoji = cardItemModels[it].emoji, title = cardItemModels[it].title, subtitle = "${cardItemModels[it].devices} devices" ) } } } } } @ExperimentalFoundationApi @Preview("Default home preview") @Composable fun DefaultPreview() { OrixTheme { HomeScreen { val navController = null } } }
0
Kotlin
0
1
5f3895f6f208585b4a8701d7793f3f7dfb2a2622
7,008
Orix
MIT License
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/BluetoothDisabled.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.regular 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.Regular.BluetoothDisabled: ImageVector get() { if (_bluetoothDisabled != null) { return _bluetoothDisabled!! } _bluetoothDisabled = fluentIcon(name = "Regular.BluetoothDisabled") { fluentPath { moveTo(3.28f, 2.22f) arcToRelative(0.75f, 0.75f, 0.0f, true, false, -1.06f, 1.06f) lineTo(10.0f, 11.06f) verticalLineToRelative(1.37f) lineToRelative(-2.08f, 1.74f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 0.96f, 1.15f) lineToRelative(1.12f, -0.94f) verticalLineToRelative(5.87f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 1.3f, 0.5f) lineToRelative(4.03f, -4.36f) lineToRelative(5.39f, 5.39f) arcToRelative(0.75f, 0.75f, 0.0f, false, false, 1.06f, -1.06f) lineTo(3.28f, 2.22f) close() moveTo(11.5f, 12.56f) lineToRelative(2.77f, 2.77f) lineToRelative(-2.77f, 3.0f) lineTo(11.5f, 12.56f) close() moveTo(15.95f, 9.43f) lineToRelative(-1.82f, 1.52f) lineToRelative(-1.07f, -1.07f) lineToRelative(1.32f, -1.1f) lineToRelative(-2.88f, -3.1f) verticalLineToRelative(2.64f) lineTo(10.0f, 6.82f) lineTo(10.0f, 3.75f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 1.3f, -0.5f) lineToRelative(4.72f, 5.1f) curveToRelative(0.29f, 0.31f, 0.26f, 0.8f, -0.07f, 1.08f) close() } } return _bluetoothDisabled!! } private var _bluetoothDisabled: ImageVector? = null
0
Kotlin
0
24
336c85b59b6a6ad97a522a25a0042cd8e0750474
2,078
compose-fluent-ui
Apache License 2.0
CoffeeProtectionandAnalysisSystem/app/src/main/java/com/example/coffeeprotectionandanalysissystem/view/detail/DetailArtikelActivity.kt
C241-PS120
797,800,217
false
{"Kotlin": 65335}
package com.example.coffeeprotectionandanalysissystem.view.detail import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.bumptech.glide.Glide import com.example.coffeeprotectionandanalysissystem.R import com.example.coffeeprotectionandanalysissystem.databinding.ActivityDetailArtikelBinding import java.text.SimpleDateFormat import java.util.Locale class DetailArtikelActivity : AppCompatActivity() { private lateinit var binding: ActivityDetailArtikelBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) // Initialize view binding binding = ActivityDetailArtikelBinding.inflate(layoutInflater) setContentView(binding.root) // Set up the toolbar setSupportActionBar(binding.topbar) supportActionBar?.setDisplayHomeAsUpEnabled(true) supportActionBar?.setDisplayShowHomeEnabled(true) // Get data from Intent val title = intent.getStringExtra("title") val imageUrl = intent.getStringExtra("imageUrl") val content = intent.getStringExtra("content") val author = intent.getStringExtra("author") val createdAt = intent.getStringExtra("createdAt") // Set data to views binding.rvTitle.text = title binding.rvContent.text = content binding.rvAuthor.text = author binding.rvDate.text = formatDate(createdAt) Glide.with(this) .load(imageUrl) .into(binding.rvArticle) // Apply window insets using view binding ViewCompat.setOnApplyWindowInsetsListener(binding.root) { v, insets -> val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars()) v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom) insets } } override fun onBackPressed() { super.onBackPressed() finish() overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_right) } override fun onSupportNavigateUp(): Boolean { onBackPressed() return true } // Method to format the date string private fun formatDate(dateString: String?): String { return if (dateString.isNullOrEmpty()) { "" } else { try { val inputFormat = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.getDefault()) val outputFormat = SimpleDateFormat("dd MMMM yyyy", Locale.getDefault()) val date = inputFormat.parse(dateString) if (date != null) { outputFormat.format(date) } else { "" } } catch (e: Exception) { dateString // Return the original string if parsing fails } } } }
0
Kotlin
0
0
1f8acf8af157ece656ed9dd170e3ffbd3db11513
2,960
bangkit-mobile-dev
Apache License 2.0
src/main/kotlin/at/cpickl/gadsu/appointment/gcal/sync/controller.kt
christophpickl
56,092,216
false
null
package at.cpickl.gadsu.appointment.gcal.sync import at.cpickl.gadsu.appointment.Appointment import at.cpickl.gadsu.appointment.AppointmentService import at.cpickl.gadsu.appointment.gcal.CalendarNameInvalidException import at.cpickl.gadsu.appointment.gcal.GCalService import at.cpickl.gadsu.client.ClientService import at.cpickl.gadsu.client.ClientState import at.cpickl.gadsu.global.QuitEvent import at.cpickl.gadsu.preferences.PreferencesData import at.cpickl.gadsu.service.LOG import at.cpickl.gadsu.service.Logged import at.cpickl.gadsu.view.AsyncDialogSettings import at.cpickl.gadsu.view.AsyncWorker import at.cpickl.gadsu.view.MainFrame import at.cpickl.gadsu.view.components.DialogType import at.cpickl.gadsu.view.components.Dialogs import com.google.common.eventbus.EventBus import com.google.common.eventbus.Subscribe import com.google.inject.Provider import javax.inject.Inject interface GCalController { } @Logged open class GCalControllerImpl @Inject constructor( private val gcal: GCalService, private val dialogs: Dialogs, private val syncService: SyncService, private val clientService: ClientService, private val mainFrame: MainFrame, private val async: AsyncWorker, private val appointmentService: AppointmentService, private val preferences: Provider<PreferencesData>, bus: EventBus ) : GCalController { companion object { private val DIALOG_TITLE = "GCal Sync" } private val log = LOG(javaClass) private val window: SyncReportWindow by lazy { SyncReportSwingWindow(mainFrame, bus) } @Subscribe open fun onRequestGCalSyncEvent(event: RequestGCalSyncEvent) { // MINOR add possibility to interrupt background process by clicking on window close button async.doInBackground<SyncReport?>( settings = AsyncDialogSettings("GCal Sync", "Verbindung zu Google Server wird aufgebaut ..."), backgroundTask = { doTheSync() }, doneTask = { report: SyncReport? -> if (report == null) { // prematurely aborted, do nothing } else if (report.isEmpty()) { dialogs.show( title = DIALOG_TITLE, message = "Es wurden keinerlei beachtenswerte Termine gefunden." ) } else { window.initReport(report, clientService.findAll(ClientState.ACTIVE), preferences.get().isGmailAndGapiConfigured) window.start() } }, exceptionTask = { e -> log.error("GCal synchronisation failed!", e) dialogs.showGCalError() } ) } @Subscribe open fun onRequestImportSyncEvent(event: RequestImportSyncEvent) { val appointmentsToImport = window.readImportAppointments().filter { it.enabled } val appointmentsToDelete = window.readDeleteAppointments() val appointmentsToUpdate = window.readUpdateAppointments() if (appointmentsToImport.isEmpty() && appointmentsToDelete.isEmpty() && appointmentsToUpdate.isEmpty()) { dialogs.show(DIALOG_TITLE, "Scherzkeks ;) Es gibt nix zum Importieren.") return } async.doInBackground<Unit>( settings = AsyncDialogSettings(DIALOG_TITLE, "Importiere Termine ..."), backgroundTask = { doTheImport(appointmentsToImport, appointmentsToDelete, appointmentsToUpdate) }, doneTask = { window.closeWindow() // MINOR gcal sync feedback: could show details on what exactly had happened (just a regular JTextArea and fill with some plain text, nothing fancy) dialogs.show(DIALOG_TITLE, "Der Kalenderabgleich war erfolgreich.") }, exceptionTask = { e -> log.error("GCal import failed!", e) dialogs.showGCalError() window.closeWindow() } ) } @Subscribe open fun onQuitEvent(event: QuitEvent) { window.destroy() } private fun doTheSync(): SyncReport? { val isOnline: Boolean try { isOnline = gcal.isOnline // this isOnline request got some heavy I/O } catch(e: CalendarNameInvalidException) { dialogs.show(DIALOG_TITLE, "Ungültigen Kalendarname eingegeben: ${e.calendarName}!\n\n" + "Verfügbare Kalender:\n${e.availableCalendars}", type = DialogType.ERROR) return null } if (!isOnline) { dialogs.show( title = DIALOG_TITLE, message = "Du bist nicht mit Google Calender verbunden. Siehe Einstellungen. Neustarten!", type = DialogType.WARN ) return null } return syncService.syncAndSuggest() } private fun doTheImport(appointmentsToImport: List<ImportAppointment>, appointmentsToDelete: List<Appointment>, appointmentsToUpdate: List<Appointment>) { log.debug("IMPORT ================================ START") appointmentsToUpdate.forEach { appointmentService.insertOrUpdate(it) } appointmentsToDelete.forEach { appointmentService.delete(it) } syncService.import(appointmentsToImport) log.debug("IMPORT ================================ END") } private fun Dialogs.showGCalError() { dialogs.show(DIALOG_TITLE, "Beim Synchronisieren mit Google Calender ist ein Fehler aufgetreten.", type = DialogType.ERROR) } }
43
Kotlin
1
2
f6a84c42e1985bc53d566730ed0552b3ae71d94b
5,874
gadsu
Apache License 2.0
src/ors_client/api/src/main/kotlin/org/astu/reviewed_objects_client/reviewed_objects_api/models/GetReviewPlanDTO.kt
sesuineg
776,441,411
false
{"Kotlin": 125595, "C#": 24410, "JavaScript": 475}
/** * ors_server * * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: 1.0 * * * Please note: * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * Do not edit this file manually. */ @file:Suppress( "ArrayInDataClass", "EnumEntryName", "RemoveRedundantQualifierName", "UnusedImport" ) package org.astu.reviewed_objects_client.reviewed_objects_api.models import org.astu.reviewed_objects_client.reviewed_objects_api.models.GetReviewObjectDTO import com.squareup.moshi.Json /** * * * @param id * @param name * @param reviewedObject */ data class GetReviewPlanDTO ( @Json(name = "id") var id: kotlin.Int? = null, @Json(name = "name") var name: kotlin.String? = null, @Json(name = "reviewedObject") var reviewedObject: GetReviewObjectDTO? = null )
0
Kotlin
0
0
e45e4854a027fc6bd418a7b42f47b3ccebb0f2d4
949
object-review-system
MIT License
src/main/kotlin/shader/FragmentShader.kt
Heknon
368,843,099
false
null
package shader import org.lwjgl.opengl.GL20 class FragmentShader( shaderCode: String, programId: Int ) : Shader( shaderCode, GL20.GL_FRAGMENT_SHADER, programId )
0
Kotlin
0
0
ef898d4dd6fbc1fc7a0f38ad990871a274d1c02d
183
Minecraft-Final-CS
MIT License
vuesaxicons/src/commonMain/kotlin/moe/tlaster/icons/vuesax/vuesaxicons/bold/Arrangecircle.kt
Tlaster
560,394,734
false
{"Kotlin": 25133302}
package moe.tlaster.icons.vuesax.vuesaxicons.bold import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import moe.tlaster.icons.vuesax.vuesaxicons.BoldGroup public val BoldGroup.Arrangecircle: ImageVector get() { if (_arrangecircle != null) { return _arrangecircle!! } _arrangecircle = Builder(name = "Arrangecircle", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f).apply { path(fill = SolidColor(Color(0xFF292D32)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 2.0f) curveTo(6.48f, 2.0f, 2.0f, 6.48f, 2.0f, 12.0f) curveTo(2.0f, 17.52f, 6.48f, 22.0f, 12.0f, 22.0f) curveTo(17.52f, 22.0f, 22.0f, 17.52f, 22.0f, 12.0f) curveTo(22.0f, 6.48f, 17.52f, 2.0f, 12.0f, 2.0f) close() moveTo(10.93f, 17.15f) curveTo(10.93f, 17.25f, 10.91f, 17.34f, 10.87f, 17.44f) curveTo(10.79f, 17.62f, 10.65f, 17.77f, 10.46f, 17.85f) curveTo(10.37f, 17.89f, 10.27f, 17.91f, 10.17f, 17.91f) curveTo(10.07f, 17.91f, 9.98f, 17.89f, 9.88f, 17.85f) curveTo(9.79f, 17.81f, 9.71f, 17.76f, 9.64f, 17.69f) lineTo(6.6f, 14.65f) curveTo(6.31f, 14.36f, 6.31f, 13.88f, 6.6f, 13.59f) curveTo(6.89f, 13.3f, 7.37f, 13.3f, 7.66f, 13.59f) lineTo(9.42f, 15.35f) verticalLineTo(6.85f) curveTo(9.42f, 6.44f, 9.76f, 6.1f, 10.17f, 6.1f) curveTo(10.58f, 6.1f, 10.92f, 6.44f, 10.92f, 6.85f) verticalLineTo(17.15f) horizontalLineTo(10.93f) close() moveTo(17.39f, 10.42f) curveTo(17.24f, 10.57f, 17.05f, 10.64f, 16.86f, 10.64f) curveTo(16.67f, 10.64f, 16.48f, 10.57f, 16.33f, 10.42f) lineTo(14.57f, 8.66f) verticalLineTo(17.16f) curveTo(14.57f, 17.57f, 14.23f, 17.91f, 13.82f, 17.91f) curveTo(13.41f, 17.91f, 13.07f, 17.57f, 13.07f, 17.16f) verticalLineTo(6.85f) curveTo(13.07f, 6.75f, 13.09f, 6.66f, 13.13f, 6.56f) curveTo(13.21f, 6.38f, 13.35f, 6.23f, 13.54f, 6.15f) curveTo(13.72f, 6.07f, 13.93f, 6.07f, 14.11f, 6.15f) curveTo(14.2f, 6.19f, 14.28f, 6.24f, 14.35f, 6.31f) lineTo(17.39f, 9.35f) curveTo(17.68f, 9.65f, 17.68f, 10.12f, 17.39f, 10.42f) close() } } .build() return _arrangecircle!! } private var _arrangecircle: ImageVector? = null
0
Kotlin
0
2
b8a8231e6637c2008f675ae76a3423b82ee53950
3,317
VuesaxIcons
MIT License
mvi_rhine/src/main/java/com/github/qingmei2/mvi/di/Scopes.kt
qingmei2
167,174,767
false
null
package com.github.qingmei2.mvi.di import javax.inject.Scope @Scope @MustBeDocumented @Retention(AnnotationRetention.RUNTIME) annotation class ActivityScope @Scope @MustBeDocumented @Retention(AnnotationRetention.RUNTIME) annotation class FragmentScope
4
Kotlin
25
170
6fce8ebc0b123bec8684f90f9b11fa606d469c42
255
MVI-Architecture
Apache License 2.0
projects/unpaid-work-and-delius/src/main/kotlin/uk/gov/justice/digital/hmpps/controller/user/UserService.kt
ministryofjustice
500,855,647
false
{"Kotlin": 4403685, "HTML": 72513, "D2": 44286, "Ruby": 26979, "Shell": 23475, "SCSS": 6630, "HCL": 2712, "Dockerfile": 2552, "JavaScript": 1428, "Python": 268}
package uk.gov.justice.digital.hmpps.controller.user import org.springframework.stereotype.Service import uk.gov.justice.digital.hmpps.service.UserAccessService @Service class UserService(private val userAccessService: UserAccessService) { fun userAccessFor(username: String, crn: String) = userAccessService.caseAccessFor(username, crn) }
4
Kotlin
0
2
35dce3c0cb146117ab52162a8a14d97394d05101
347
hmpps-probation-integration-services
MIT License
bytebank/src/main/kotlin/br/com/alura/bytebank/teste/testaExpressao.kt
FernandoLink
670,308,529
false
null
package br.com.alura.bytebank.teste public fun testeExpressao() { val entrada: String = "1.0" val valorRecebido: Double? = try { entrada.toDouble() } catch (e: NumberFormatException) { println("Problema na conversão") e.printStackTrace() null } val valorComTaxa: Double? = if (valorRecebido != null) { valorRecebido + 0.1 } else { null } // exemplo com when val valorComTaxa2: Double? = when { valorRecebido != null -> { valorRecebido + 0.1 } else -> { null } } if (valorComTaxa != null) { println("valor recebido: $valorComTaxa") } else { println("valor inválido") } }
0
Kotlin
0
0
872d9192a741afaa438894698ec0b5e31088434b
747
kotlin
MIT License
pumps/ethereum/src/main/kotlin/fund/cyber/PumpApplication.kt
GoodforGod
129,151,733
true
{"Kotlin": 332422, "Shell": 139}
package fund.cyber import fund.cyber.pump.common.ChainPump import fund.cyber.search.configuration.CHAIN import fund.cyber.search.configuration.env import fund.cyber.search.model.chains.EthereumFamilyChain import org.springframework.boot.SpringApplication import org.springframework.boot.autoconfigure.SpringBootApplication import org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration import org.springframework.context.annotation.Bean @SpringBootApplication(exclude = [KafkaAutoConfiguration::class]) class EthereumPumpApplication { @Bean fun chain(): EthereumFamilyChain { val chainAsString = env(CHAIN, "") return EthereumFamilyChain.valueOf(chainAsString) } companion object { @JvmStatic fun main(args: Array<String>) { val application = SpringApplication(EthereumPumpApplication::class.java) application.setRegisterShutdownHook(false) val applicationContext = application.run(*args) val pump = applicationContext.getBean(ChainPump::class.java) pump.startPump() } } }
0
Kotlin
0
1
dcf7f09463cd76674326caf87509e048882b4176
1,111
cyber-search
MIT License
src/main/kotlin/com/terraformation/backend/species/api/SpeciesLookupController.kt
terraware
323,722,525
false
{"Kotlin": 3741923, "HTML": 88820, "Python": 46278, "FreeMarker": 16407, "PLpgSQL": 3305, "Makefile": 746, "Dockerfile": 674}
package com.terraformation.backend.species.api import com.fasterxml.jackson.annotation.JsonInclude import com.terraformation.backend.api.ApiResponse404 import com.terraformation.backend.api.CustomerEndpoint import com.terraformation.backend.api.SuccessResponsePayload import com.terraformation.backend.db.default_schema.ConservationCategory import com.terraformation.backend.db.default_schema.SpeciesProblemType import com.terraformation.backend.db.default_schema.tables.pojos.SpeciesProblemsRow import com.terraformation.backend.species.db.GbifStore import com.terraformation.backend.species.model.GbifTaxonModel import com.terraformation.backend.species.model.GbifVernacularNameModel import io.swagger.v3.oas.annotations.ExternalDocumentation import io.swagger.v3.oas.annotations.Operation import io.swagger.v3.oas.annotations.media.ArraySchema import io.swagger.v3.oas.annotations.media.Schema import io.swagger.v3.oas.annotations.responses.ApiResponse import jakarta.ws.rs.BadRequestException import org.springframework.web.bind.annotation.GetMapping import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestParam import org.springframework.web.bind.annotation.RestController @CustomerEndpoint @RestController @RequestMapping("/api/v1/species/lookup") class SpeciesLookupController(private val gbifStore: GbifStore) { @GetMapping("/names") @Operation( description = "Gets a list of known scientific names whose words begin with particular letters.") fun listSpeciesNames( @RequestParam @Schema( description = "Space-delimited list of word prefixes to search for. Non-alphabetic characters " + "are ignored, and matches are case-insensitive. The order of prefixes is " + "significant; \"ag sc\" will match \"Aglaonema schottianum\" but won't match " + "\"Scabiosa agrestis\".", example = "ag sc", minLength = 2, maxLength = 100) search: String, @RequestParam("maxResults", defaultValue = "10") @Schema(description = "Maximum number of results to return.", minimum = "1", maximum = "50") maxResults: Int, ): SpeciesLookupNamesResponsePayload { if (search.trim().length !in 2..100) { throw BadRequestException("Search term must be between 2 and 100 characters") } val cappedMaxResults = maxResults.coerceIn(1, 50) val prefixes = search.split(' ') val names = gbifStore.findNamesByWordPrefixes(prefixes, maxResults = cappedMaxResults + 1).mapNotNull { it.name } val partial = names.size > cappedMaxResults return SpeciesLookupNamesResponsePayload(names.take(cappedMaxResults), partial) } @ApiResponse(responseCode = "200") @ApiResponse404("The scientific name was not found in the server's taxonomic database.") @GetMapping("/details") @Operation(summary = "Gets more information about a species with a particular scientific name.") fun getSpeciesDetails( @RequestParam @Schema(description = "Exact scientific name to look up. This name is case-sensitive.") scientificName: String, @RequestParam @Schema( description = "If specified, only return common names in this language or whose language is " + "unknown. Names with unknown languages are always included. This is a " + "two-letter ISO 639-1 language code.", example = "en") language: String? = null, ): SpeciesLookupDetailsResponsePayload { val model = gbifStore.fetchOneByScientificName(scientificName, language) val problem = gbifStore.checkScientificName(scientificName) return SpeciesLookupDetailsResponsePayload(model, problem) } } data class SpeciesLookupNamesResponsePayload( val names: List<String>, @Schema( description = "True if there were more matching names than could be included in the response.") val partial: Boolean ) : SuccessResponsePayload @JsonInclude(JsonInclude.Include.NON_NULL) data class SpeciesLookupCommonNamePayload( val name: String, @Schema( description = "ISO 639-1 two-letter language code indicating the name's language. Some common " + "names in the server's taxonomic database are not tagged with languages; this " + "value will not be present for those names.") val language: String?, ) { constructor(model: GbifVernacularNameModel) : this(model.name, model.language) } @JsonInclude(JsonInclude.Include.NON_NULL) data class SpeciesLookupDetailsResponsePayload( val scientificName: String, @ArraySchema( arraySchema = Schema(description = "List of known common names for the species, if any.")) val commonNames: List<SpeciesLookupCommonNamePayload>?, @Schema( description = "IUCN Red List conservation category code.", externalDocs = ExternalDocumentation(url = "https://en.wikipedia.org/wiki/IUCN_Red_List#Categories")) val conservationCategory: ConservationCategory?, val familyName: String, @Schema( description = "If this is not the accepted name for the species, the type of problem the name has. " + "Currently, this will always be \"Name Is Synonym\".") val problemType: SpeciesProblemType?, @Schema( description = "If this is not the accepted name for the species, the name to suggest as an " + "alternative.") val suggestedScientificName: String?, ) { constructor( model: GbifTaxonModel, problem: SpeciesProblemsRow?, ) : this( model.scientificName, model.vernacularNames.map { SpeciesLookupCommonNamePayload(it) }.ifEmpty { null }, model.conservationCategory, model.familyName, problem?.typeId, problem?.suggestedValue) }
3
Kotlin
1
9
4b567755b38c1021a76d677f22d865c45d4099b1
5,953
terraware-server
Apache License 2.0
app/src/main/java/com/peruapps/christopher_elias/ui/fragments/profile/ProfileModule.kt
ChristopherME
189,524,605
false
null
package com.peruapps.christopher_elias.ui.fragments.profile import androidx.lifecycle.ViewModel import com.peruapps.christopher_elias.di.ViewModelKey import dagger.Binds import dagger.Module import dagger.android.ContributesAndroidInjector import dagger.multibindings.IntoMap /** * Created by <NAME> on 30-may-2019 * <EMAIL> * Lima, Perú * Copyright (c) 2019 All rights reserved. */ @Module internal abstract class ProfileModule{ @ContributesAndroidInjector internal abstract fun profileFragment() : Profile @Binds @IntoMap @ViewModelKey(ProfileViewModel::class) abstract fun bindProfileViewModel(viewModel: ProfileViewModel) : ViewModel }
0
Kotlin
0
0
785b1e3938a69936b0c0732f82cb6b40fbfc8d0b
675
senior-test
Apache License 2.0
examples/src/main/kotlin/examples/tweens/FadingInASprite.kt
hiperbou
77,711,558
false
{"Kotlin": 456816, "HTML": 335}
package examples.tweens import Phaser.* class FadingInASprite: State() { //var game = Phaser.Game(800, 600, Phaser.AUTO, "phaser-example", object{ var preload= preload; var create= create }) override fun preload() { game.load.image("space", "assets/misc/starfield.png", 138, 15) game.load.image("logo", "assets/sprites/phaser2.png") } override fun create() { game.add.tileSprite(0, 0, 800, 600, "space") var sprite = game.add.sprite(game.world.centerX, game.world.centerY, "logo") sprite.anchor.setTo(0.5, 0.5) sprite.alpha = 0.0 game.add.tween(sprite).to( object{ var alpha= 1 }, 2000, Phaser.Easing.Linear::None, true, 0, 1000, true) } }
2
Kotlin
11
55
18d247ecf44c32f5aca0560dce7727c10dfe196a
711
kotlin-phaser
MIT License
app/src/main/java/com/chalkbox/propertyfinder/application/components/MainActivityComponent.kt
RiversideOtters
250,147,724
false
null
package com.chalkbox.propertyfinder.application.components import com.chalkbox.propertyfinder.MainActivity import com.chalkbox.propertyfinder.application.scopes.MainActivityScope import dagger.Component @MainActivityScope @Component( dependencies = [ BaseComponent::class ] ) interface MainActivityComponent { fun inject(arg: MainActivity) }
0
Kotlin
0
0
92c3be6363c19a68493fd91546e1bd373bc5ae82
363
PropertyFinder-Android
MIT License
baselibrary/src/main/java/com/sscl/baselibrary/widget/AutoSwipeRefreshLayout.kt
JackiePenghe
576,202,469
false
null
package com.sscl.baselibrary.widget import android.content.* import android.util.AttributeSet import android.view.* import java.lang.Exception import java.lang.reflect.Field import java.lang.reflect.Method import kotlin.jvm.JvmOverloads import androidx.swiperefreshlayout.widget.SwipeRefreshLayout /** * 可以自动触发下拉刷新的控件 * * @author jackie */ class AutoSwipeRefreshLayout @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : SwipeRefreshLayout(context, attrs) { /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 公开方法 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ /** * 自动刷新 */ fun autoRefresh() { try { val mCircleView: Field = SwipeRefreshLayout::class.java.getDeclaredField("mCircleView") mCircleView.isAccessible = true (mCircleView.get(this) as View?)?.visibility = VISIBLE val setRefreshing: Method = SwipeRefreshLayout::class.java.getDeclaredMethod( "setRefreshing", Boolean::class.javaPrimitiveType, Boolean::class.javaPrimitiveType ) setRefreshing.isAccessible = true setRefreshing.invoke(this, true, true) } catch (e: Exception) { e.printStackTrace() } } }
0
Kotlin
0
0
0fb258b891552e8eb1f6f5d8132ad923c399773d
1,368
baselibrary-for-kotlin
Apache License 2.0
app/src/main/java/dev/yunzai/milibrary/activities/SignUpActivity.kt
yunjaena
373,853,053
false
null
package dev.yunzai.milibrary.activities import android.os.Bundle import android.view.inputmethod.EditorInfo import dev.yunzai.milibrary.R import dev.yunzai.milibrary.base.activity.ViewBindingActivity import dev.yunzai.milibrary.base.hideKeyBoard import dev.yunzai.milibrary.base.showAlertDialog import dev.yunzai.milibrary.databinding.ActivitySignupBinding import dev.yunzai.milibrary.util.getEmojiFilter import dev.yunzai.milibrary.util.setOnSingleClickListener import dev.yunzai.milibrary.viewmodels.SignUpViewModel import org.koin.androidx.viewmodel.ext.android.viewModel class SignUpActivity : ViewBindingActivity<ActivitySignupBinding>() { override val layoutId: Int = R.layout.activity_signup private val signUpViewModel: SignUpViewModel by viewModel() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) init() } private fun init() { initView() initObserver() } private fun initView() { binding.userIdEditText.filters = arrayOf(getEmojiFilter()) binding.passwordEditText.filters = arrayOf(getEmojiFilter()) binding.passwordCheckEditText.filters = arrayOf(getEmojiFilter()) binding.signUp.setOnSingleClickListener { signUp() } binding.passwordCheckEditText.setOnEditorActionListener { v, actionId, event -> when (actionId) { EditorInfo.IME_ACTION_DONE -> { hideKeyBoard() signUp() } } return@setOnEditorActionListener true } useDefaultLoading(signUpViewModel) } private fun initObserver() { with(signUpViewModel) { errorMessage.observe(this@SignUpActivity) { if (it == null) return@observe showAlertDialog(getString(R.string.alert), getString(it), getString(R.string.ok)) { dialog -> dialog.dismiss() } } errorMessageFromServerEvent.observe(this@SignUpActivity) { if (it == null) return@observe showAlertDialog(getString(R.string.alert), it, getString(R.string.ok)) { dialog -> dialog.dismiss() } } signUpSuccessEvent.observe(this@SignUpActivity) { showAlertDialog( getString(R.string.alert), getString(R.string.sign_up_success), getString(R.string.ok) ) { dialog -> dialog.dismiss() finish() } } } } private fun signUp() { val id = binding.userIdEditText.text.toString().trim() val password = binding.passwordEditText.text.toString().trim() val passwordCheck = binding.passwordCheckEditText.text.toString().trim() signUpViewModel.signUp(id, password, passwordCheck) } }
0
Kotlin
0
2
4c6774ff46c20eb53465ef64366a2ee0c90d2930
2,993
MiliBrary_AOS
Apache License 2.0
app/src/main/java/co/utils/CrashUtils.kt
CANDY-HOUSE
280,844,064
false
{"Kotlin": 675713, "Shell": 406}
package co.utils import android.annotation.SuppressLint import android.content.Context import android.content.pm.PackageManager import android.os.Build import android.provider.Settings import android.util.Log import org.json.JSONException import org.json.JSONObject import java.io.* import java.text.SimpleDateFormat import java.util.* class CrashUtils : Thread.UncaughtExceptionHandler { private var crashListener: CrashListener? = null private var isJumpError = true private var context: Context? = null private var errorInfo: ErrorBean? = null private var isDebug = false fun init(context: Context?): CrashUtils { this.context = context errorInfo = ErrorBean() Thread.setDefaultUncaughtExceptionHandler(this) return this } fun setDebug(debug: Boolean): CrashUtils { isDebug = debug return this } fun setCrashListener(crashListener: CrashListener?) { this.crashListener = crashListener } fun setJumpError(isJumpError: Boolean): CrashUtils { this.isJumpError = isJumpError return this } override fun uncaughtException(thread: Thread, ex: Throwable) { if (crashListener != null) { crashListener!!.CrashInfo(ex) } else { Log.e("CrashHandler", "No crash listening set") } errorInfo = Covers(ex) writeToFile(context, errorInfo!!.throwString(ex)) } fun writeToFile(context: Context?, msg: String?) { try { val fatherFile = File(context!!.filesDir, "crash") if (!fatherFile.exists()) { fatherFile.mkdirs() } val name = "crash" + SimpleDateFormat("yyyyMMddHHmmss").format(Date()) val file = File(fatherFile, name) val printWriter = PrintWriter(FileOutputStream(file.absoluteFile)) printWriter.write(msg) printWriter.flush() printWriter.close() } catch (e: FileNotFoundException) { e.printStackTrace() } } private fun Covers(t: Throwable): ErrorBean? { errorInfo!!.date = Date().toString() errorInfo!!.cause = t.cause errorInfo!!.localizedMessage = t.localizedMessage errorInfo!!.message = t.message val resultList: MutableList<ErrorBean.StackTraceBean> = ArrayList(t.stackTrace.size) for (s in t.stackTrace) { val st = ErrorBean.StackTraceBean() st.className = s.className st.fileName = s.fileName st.lineNumber = s.lineNumber st.methodName = s.methodName st.isNativeMethod = s.isNativeMethod resultList.add(st) } errorInfo!!.stackTrace = resultList errorInfo!!.type = t.cause try { val pm = context!!.packageManager val pi = pm.getPackageInfo(context!!.packageName, 0) errorInfo!!.brand = Build.BRAND errorInfo!!.model = Build.MODEL errorInfo!!.sdk_version_name = Build.VERSION.RELEASE errorInfo!!.sdk_version_code = Build.VERSION.SDK_INT.toString() + "" errorInfo!!.app_version_name = pi.versionName + "" errorInfo!!.app_version_code = pi.versionCode.toString() + "" errorInfo!!.android_id = getAndroidID(context) errorInfo!!.package_name = context!!.packageName errorInfo!!.app_name = pi.applicationInfo.loadLabel(pm).toString() errorInfo!!.isDebug = isDebug.toString() + "" } catch (e: PackageManager.NameNotFoundException) { e.printStackTrace() } return errorInfo } @SuppressLint("ApplySharedPref") fun saveError(str: String?) { val sharedPreferences = context!!.getSharedPreferences("data", Context.MODE_PRIVATE) val editor = sharedPreferences.edit() editor.putString("error", str) editor.commit() } fun readError(): String? { val sharedPreferences = context!!.getSharedPreferences("data", Context.MODE_PRIVATE) return sharedPreferences.getString("error", "None") } interface CrashListener { fun CrashInfo(ex: Throwable?) } class ErrorBean { var brand = Build.BRAND var model = Build.MODEL var app_name: String? = null var package_name: String? = null var app_version_name: String? = null var app_version_code: String? = null var sdk_version_name: String? = null var sdk_version_code: String? = null var android_id: String? = null var mobile: String? = null var isDebug: String? = null var type: Throwable? = null var cause: Any? = null var localizedMessage: String? = null var message: String? = null var stackTrace: List<StackTraceBean>? = null var date: String? = null fun isNullString(o: Any?): String { return o?.toString() ?: "nullObject " } fun toNewString(): String { val jsonObject = JSONObject() try { jsonObject.put("app_name", isNullString(app_name)) jsonObject.put("app_version_name", isNullString(app_version_name)) jsonObject.put("sdk_version_name", isNullString(sdk_version_name)) jsonObject.put("package_name", isNullString(package_name)) jsonObject.put("brand", isNullString(brand)) jsonObject.put("model", isNullString(model)) jsonObject.put("app_version_code", isNullString(app_version_code)) jsonObject.put("sdk_version_code", isNullString(sdk_version_code)) jsonObject.put("android_id", isNullString(android_id)) jsonObject.put("type", isNullString(type)) jsonObject.put("message", isNullString(message)) jsonObject.put("data", SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())) jsonObject.put("cause", isNullString(cause)) } catch (e: JSONException) { e.printStackTrace() } return jsonObject.toString() } fun throwString(t: Throwable): String { val stringBuilder = StringBuilder() stringBuilder.append(toNewString()) stringBuilder.append("\n") stringBuilder.append("------------------------throwable-------------------\n") for (s in t.stackTrace) { val st = StackTraceBean() st.className = s.className st.fileName = s.fileName st.lineNumber = s.lineNumber st.methodName = s.methodName st.isNativeMethod = s.isNativeMethod stringBuilder.append( """ $s """.trimIndent() ) } return stringBuilder.toString() } override fun toString(): String { return "{" + "\"app_name\":" + isNull(app_name) + "," + "\"app_version_name\":" + isNull(app_version_name) + "," + "\"sdk_version_name\":" + isNull(sdk_version_name) + "," + "\"errorFile\":" + isNull(stackTrace!![0].fileName) + "," + "\"errorLineNum\":" + isNull(stackTrace!![0].lineNumber) + "," + "\"errorMethod\":" + isNull(stackTrace!![0].methodName) + "," + "\"package_name\":" + isNull(package_name) + "," + "\"brand\":" + isNull(brand) + "," + "\"model\":" + isNull(model) + "," + "\"app_version_code\":" + isNull(app_version_code) + "," + "\"sdk_version_code\":" + isNull(sdk_version_code) + "," + "\"android_id\":" + isNull(android_id) + "," + "\"mobile\":" + isNull(mobile) + "," + "\"isDebug\":" + isNull(isDebug) + "," + "\"type\":" + isNull(type) + "," + "\"date\":" + System.currentTimeMillis() + "," + "\"cause\":" + isNull(cause) + "," + "\"localizedMessage\":" + localizedMessage + "," + "\"message\":" + message + "," + "\"stackTrace\":" + stackTrace.toString() + "}" } fun isNull(o: Any?): String { return if (o == null) "\"\" " else "\"" + o + "\"" } class StackTraceBean : Serializable { /** * className : com.pandarupees.app.frame.ui.activity.Test * fileName : Test.java * lineNumber : 12 * methodName : test * nativeMethod : false */ var className: String? = null var fileName: String? = null var lineNumber = 0 var methodName: String? = null var isNativeMethod = false override fun toString(): String { return "{" + "\"className\":" + isNull(className) + "," + "\"fileName\":" + isNull(fileName) + "," + "\"lineNumber\":" + isNull(lineNumber) + "," + "\"methodName\":" + isNull(methodName) + "," + "\"nativeMethod\":" + isNull(isNativeMethod) + "}" } fun isNull(o: Any?): String { return if (o == null) "\"\" " else "\"" + o + "\"" } } } companion object { private var INSTANCE: CrashUtils? = null val instance: CrashUtils get() { if (INSTANCE == null) { INSTANCE = CrashUtils() } return INSTANCE!! } @SuppressLint("HardwareIds") fun getAndroidID(context: Context?): String { val id = Settings.Secure.getString( context!!.contentResolver, Settings.Secure.ANDROID_ID ) return if ("9774d56d682e549c" == id) "" else id ?: "" } } }
14
Kotlin
11
24
e1cf834bc30b619751566542034079ee45239ba5
10,246
SesameSDK_Android_with_DemoApp
MIT License
presentation/src/test/java/com/tayfuncesur/presentation/viewmodel/ProjectsViewModelTest.kt
TayfunCesur
184,639,163
false
null
package com.tayfuncesur.presentation.viewmodel import android.arch.core.executor.testing.InstantTaskExecutorRule import com.nhaarman.mockito_kotlin.* import com.tayfuncesur.domain.bookmark.GetBookmarkedProjects import com.tayfuncesur.domain.getProjects.GetProjects import com.tayfuncesur.domain.model.Project import com.tayfuncesur.presentation.ProjectsViewModel import com.tayfuncesur.presentation.mapper.ProjectViewMapper import io.reactivex.observers.DisposableObserver import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 import org.mockito.Captor import com.tayfuncesur.presentation.MockData import com.tayfuncesur.presentation.state.Resource import java.util.* @RunWith(JUnit4::class) class ProjectsViewModelTest { @get:Rule var instantTaskExecutorRule = InstantTaskExecutorRule() private var getProjects = mock<GetProjects>() private var getBookmarkedProjects = mock<GetBookmarkedProjects>() private val mapper = mock<ProjectViewMapper>() private lateinit var projectsViewModel: ProjectsViewModel @Captor val captor = argumentCaptor<DisposableObserver<List<Project>>>() @Captor val captorString = argumentCaptor<DisposableObserver<List<String>>>() @Before fun setup() { projectsViewModel = ProjectsViewModel(getProjects, getBookmarkedProjects, mapper) } @Test fun shouldLoadProjectsExecutes() { projectsViewModel.loadProjects() verify(getProjects, times(2)).execute(any(), eq(null)) } @Test fun shouldLoadProjectsReturnesData() { val projectList = MockData.generateRandomProjectList(2) val projectViewList = MockData.generateRandomProjectViewList(2) whenever(mapper.mapToView(projectList[0])).thenReturn(projectViewList[0]) whenever(mapper.mapToView(projectList[1])).thenReturn(projectViewList[1]) projectsViewModel.loadProjects() verify(getProjects, times(2)).execute(captor.capture(), eq(null)) captor.firstValue.onNext(projectList) assert(projectsViewModel.getRemoteProjectsLiveData().value is Resource.Success<*>) } @Test fun shouldLoadBookmarkedProjectsExecutes() { projectsViewModel.loadBookmarkedProjects() verify(getProjects, times(1)).execute(any(), eq(null)) } @Test fun shouldLoadBookmarkedProjectsReturnesData() { projectsViewModel.loadBookmarkedProjects() verify(getBookmarkedProjects, times(1)).execute(captorString.capture(), eq(null)) captorString.firstValue.onNext(listOf(UUID.randomUUID().toString())) assert(projectsViewModel.getBookmarkedProjectsLiveData().value is Resource.Success<*>) } }
0
Kotlin
10
65
8aa6705cf42651422ec677c5e48c9cab12e54b9f
2,752
GithubProjectBrowser
Apache License 2.0
src/test/java/org/jitsi/rtp/rtcp/RtcpSdesPacketTest.kt
bbaldino
173,043,170
true
{"Kotlin": 349802}
/* * Copyright @ 2018 - present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.rtp.rtcp import io.kotlintest.IsolationMode import io.kotlintest.matchers.collections.shouldContain import io.kotlintest.shouldBe import io.kotlintest.specs.ShouldSpec import org.jitsi.rtp.extensions.clone import org.jitsi.rtp.extensions.compareToFromBeginning import org.jitsi.rtp.extensions.toHex import java.nio.ByteBuffer internal class RtcpSdesPacketTest : ShouldSpec() { override fun isolationMode(): IsolationMode? = IsolationMode.InstancePerLeaf init { "Creating an RTCP SDES packet" { "from a buffer" { val sdesPacketBuf = ByteBuffer.wrap(byteArrayOf( 0x81.toByte(), 0xCA.toByte(), 0x00.toByte(), 0x06.toByte(), // ssrc 3828749302 0xE4.toByte(), 0x36.toByte(), 0x13.toByte(), 0xF6.toByte(), // cname, length 16 0x01.toByte(), 0x10.toByte(), 0x52.toByte(), 0x2B.toByte(), 0x2F.toByte(), 0x7A.toByte(), 0x76.toByte(), 0x38.toByte(), 0x4A.toByte(), 0x54.toByte(), 0x4C.toByte(), 0x32.toByte(), 0x59.toByte(), 0x51.toByte(), 0x51.toByte(), 0x6C.toByte(), 0x47.toByte(), 0x78.toByte(), 0x00.toByte(), 0x00.toByte() )) val origBuf = sdesPacketBuf.clone() val pkt = RtcpSdesPacket(sdesPacketBuf) should("parse the fields correctly") { pkt.chunks.size shouldBe 1 } should("have left the buffer's position in the right place") { sdesPacketBuf.position() shouldBe 0 } "and then serializing it" { val output = pkt.getBuffer() should("write the fields correctly") { origBuf.compareToFromBeginning(output) shouldBe 0 } } "and then adding another chunk" { val newChunk = SdesChunk(12345L, mutableListOf( CnameSdesItem("otheruser@domain.com") )) pkt.chunks.add(newChunk) "and then serializing it" { val out = pkt.getBuffer() should("write the correct data") { // We already know parsing works, so start by parsing the new // buffer and make sure that succeeds, then we can test the fields // in the parsed packet val newPacket = RtcpSdesPacket(out) newPacket.chunks.size shouldBe 2 newPacket.chunks shouldContain newChunk } } } } } } }
0
Kotlin
0
0
b8226d21296d773b792eaff18add487c27d35b1c
3,470
jitsi-rtp-1
Apache License 2.0
ktor-network/androidNative/src/io/ktor/network/util/SocketUtils.androidNative.kt
ktorio
40,136,600
false
{"Kotlin": 6007831, "C": 453568, "Python": 948, "JavaScript": 775, "HTML": 336, "Mustache": 77, "Handlebars": 9}
/* * Copyright 2014-2024 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.network.util import io.ktor.network.interop.* import kotlinx.cinterop.* import platform.posix.* @OptIn(ExperimentalForeignApi::class) internal actual fun ktor_inet_ntop( family: Int, src: CPointer<*>?, dst: CPointer<ByteVar>?, size: UInt ): CPointer<ByteVar>? = inet_ntop(family, src, dst, size.convert()) internal actual fun <T> unpack_sockaddr_un( sockaddr: sockaddr, block: (family: UShort, path: String) -> T ): T { error("Address ${sockaddr.sa_family} is not supported on Android Native") } @OptIn(ExperimentalForeignApi::class) internal actual fun pack_sockaddr_un( family: UShort, path: String, block: (address: CPointer<sockaddr>, size: UInt) -> Unit ) { error("Address $family is not supported on Android Native") }
156
Kotlin
1051
12,926
f90f2edf11caca28a61dbe9973faae64c17a2842
917
ktor
Apache License 2.0
app/src/main/java/com/gwj/sem4_anime_app/data/model/FavouriteAnime.kt
GWJian
730,619,677
false
{"Kotlin": 141201}
package com.gwj.sem4_anime_app.data.model import android.util.Log import com.gwj.sem4_anime_app.data.model.data.Images import com.gwj.sem4_anime_app.data.model.data.Jpg import com.gwj.sem4_anime_app.data.model.data.Webp data class FavouriteAnime( val id: String = "", val mal_id: Int?, val title: String, val episodes: Int?, val type: String, val images: Images, ) { fun toHashMap():HashMap<String, Any?> { return hashMapOf( "id" to id, "mal_id" to mal_id, "title" to title, "episodes" to episodes, "type" to type, "images" to images ) } companion object { fun fromHashMap(hash: Map<String, Any?>): FavouriteAnime { return FavouriteAnime( id = hash["id"].toString(), mal_id = hash["mal_id"].toString().toIntOrNull(), title = hash["title"].toString(), episodes = hash["episodes"].toString().toIntOrNull(), type = hash["type"].toString(), images = Images.fromHashMap(hash["images"] as Map<*, *>) ) } } }
0
Kotlin
0
0
bc0e0d52caadcacf33c0b01e6dd3acc6f9f546d7
1,171
sem4_anime_app
MIT License
commons/src/main/java/net/xpece/android/app/XpFragment.kt
cypherdare
94,902,452
true
{"Java": 709225, "Kotlin": 187437, "IDL": 719, "Batchfile": 44}
@file:JvmName("XpFragment") package net.xpece.android.app import android.support.v4.app.DialogFragment import android.support.v4.app.Fragment import android.support.v4.app.FragmentManager import android.support.v4.app.FragmentTransaction /** * Created by Eugen on 29.10.2016. */ fun Fragment.invalidateOptionsMenu() = activity?.apply { supportInvalidateOptionsMenu() } fun android.app.Fragment.invalidateOptionsMenu() = activity?.apply { invalidateOptionsMenu() } /** * Hack to force update the LoaderManager's host to avoid a memory leak in retained/detached fragments. * Call this in Fragment.onAttach() * * https://code.google.com/p/android/issues/detail?id=227136 * * Remove when the bug is fixed in support-v4. */ fun Fragment.updateLoaderManagerHostController() { updateLoaderManagerHostController() } fun DialogFragment.showAllowingStateLoss(fragmentManager: FragmentManager, tag: String) { try { show(fragmentManager, tag) } catch (ex :IllegalStateException) { // } } fun DialogFragment.showAllowingStateLoss(fragmentTransaction: FragmentTransaction, tag: String) { try { show(fragmentTransaction, tag) } catch (ex :IllegalStateException) { // } } fun android.app.DialogFragment.showAllowingStateLoss(fragmentManager: android.app.FragmentManager, tag: String) { try { show(fragmentManager, tag) } catch (ex :IllegalStateException) { // } } fun android.app.DialogFragment.showAllowingStateLoss(fragmentTransaction: android.app.FragmentTransaction, tag: String) { try { show(fragmentTransaction, tag) } catch (ex :IllegalStateException) { // } }
0
Java
0
0
278a3fde7a662635450c5296b372a91b5f33db60
1,685
android-commons
Apache License 2.0
library/src/main/java/io/dotlottie/loader/models/DotLottieConfig.kt
dotlottie
301,698,570
false
null
package io.dotlottie.loader.models import io.dotlottie.loader.DotLottieCache import io.dotlottie.loader.DotLottieCacheStrategy import io.dotlottie.loader.DotLottieConverter /** * Model for loader configuration options * must initialize default values for all as * it will be used as the default global config */ public data class DotLottieConfig( val cacheStrategy: DotLottieCacheStrategy? = null, val cacheManager: DotLottieCache? = null, val converter: DotLottieConverter? = null )
0
Kotlin
1
4
7c3ad2dd37cc60ea1a437d538c946747061311d3
502
dotlottieloader-android
The Unlicense
app/src/main/java/com/example/themoviedb/data/room/AppDatabase.kt
arenas782
550,447,044
false
{"Kotlin": 92444}
package com.example.themoviedb.data.room import androidx.room.Database import androidx.room.RoomDatabase import com.example.themoviedb.data.model.response.tvshows.TVShow import com.example.themoviedb.data.model.RemoteKeys @Database(entities = [TVShow::class, RemoteKeys::class], version = 5) abstract class AppDatabase : RoomDatabase() { abstract fun tvShowDAO(): TVShowDAO abstract fun remoteKeysDao() : RemoteKeysDao companion object { const val DATABASE_NAME : String = "tv_shows_db" } }
0
Kotlin
0
0
05aad8942a280eb917b74d0304a22100cf385b29
517
the_movie_dbv_compose
MIT License
kotlin-react-core/src/jsMain/kotlin/react/internal/isolatedPromise.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
package react.internal import js.coroutines.internal.IsolatedCoroutineScope import js.coroutines.promise import js.promise.Promise import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineStart internal fun <T> isolatedPromise( block: suspend CoroutineScope.() -> T, ): Promise<T> = IsolatedCoroutineScope() .promise( start = CoroutineStart.UNDISPATCHED, block = block, )
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
441
kotlin-wrappers
Apache License 2.0
src/test/kotlin/org/neo4j/graphql/AugmentationTests.kt
claymccoy
291,179,346
true
{"Kotlin": 177994, "Python": 1290}
package org.neo4j.graphql import org.junit.jupiter.api.TestFactory import org.neo4j.graphql.utils.GraphQLSchemaTestSuite class AugmentationTests { @TestFactory fun `augmentation-tests`() = GraphQLSchemaTestSuite("augmentation-tests.adoc").run() }
0
null
0
0
9187d2218b91201a106e0614ed6895152536f5fc
258
neo4j-graphql-java
Apache License 2.0
app/src/main/java/com/github/skytoph/taski/di/habit/WorkManagerModule.kt
skytoph
708,362,840
false
{"Kotlin": 602263}
package com.github.skytoph.taski.di.habit import android.content.Context import androidx.work.WorkManager import com.github.skytoph.taski.core.adapter.GeneralTypeAdapterFactory import com.github.skytoph.taski.core.alarm.HabitUriConverter import com.github.skytoph.taski.core.alarm.ReminderScheduler import com.github.skytoph.taski.core.alarm.WorkScheduler import com.google.gson.Gson import com.google.gson.GsonBuilder import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object WorkManagerModule { @Provides @Singleton fun scheduler( workManager: WorkManager, gson: Gson, uriConverter: HabitUriConverter ): ReminderScheduler = WorkScheduler(workManager, uriConverter, gson) @Provides @Singleton fun workManager(@ApplicationContext context: Context): WorkManager = WorkManager.getInstance(context) @Provides fun gson(): Gson = GsonBuilder().registerTypeAdapterFactory(GeneralTypeAdapterFactory()).create() @Provides fun uriConverter(): HabitUriConverter = HabitUriConverter.Base() }
0
Kotlin
0
1
6639c40403f384c2125b6370499fcd6a0120a72b
1,250
HabitMate
The Unlicense
Skyflow/src/main/kotlin/Skyflow/Margin.kt
skyflowapi
396,648,989
false
{"Kotlin": 674976, "Shell": 585}
package Skyflow class Margin(val left: Int = 10, val top: Int = 10, val right: Int = 10, val bottom: Int = 10) {}
12
Kotlin
2
7
0ffcbf43c2767d6324f29952e8ce94d354aa57d8
114
skyflow-android
MIT License
examples/src/main/java/com/mapbox/navigation/examples/utils/RouteDrawingUtil.kt
jackgregory
337,518,939
true
{"Kotlin": 1912845, "Java": 124339, "Python": 10396, "Makefile": 5455, "JavaScript": 2362, "Shell": 1686}
package com.mapbox.navigation.examples.utils import android.annotation.SuppressLint import android.graphics.Color import android.widget.Toast import com.mapbox.api.directions.v5.DirectionsCriteria import com.mapbox.api.matching.v5.MapboxMapMatching import com.mapbox.api.matching.v5.models.MapMatchingResponse import com.mapbox.geojson.Feature import com.mapbox.geojson.FeatureCollection import com.mapbox.geojson.LineString import com.mapbox.geojson.Point import com.mapbox.mapboxsdk.maps.MapView import com.mapbox.mapboxsdk.maps.MapboxMap import com.mapbox.mapboxsdk.style.layers.CircleLayer import com.mapbox.mapboxsdk.style.layers.LineLayer import com.mapbox.mapboxsdk.style.layers.Property.LINE_JOIN_ROUND import com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleColor import com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleOpacity import com.mapbox.mapboxsdk.style.layers.PropertyFactory.circleRadius import com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineColor import com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineJoin import com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineOpacity import com.mapbox.mapboxsdk.style.layers.PropertyFactory.lineWidth import com.mapbox.mapboxsdk.style.sources.GeoJsonSource import com.mapbox.navigation.core.directions.session.RoutesRequestCallback import retrofit2.Call import retrofit2.Callback import retrofit2.Response import timber.log.Timber /** * A utility for drawing a line on a map and using map matching to get a route. * When enable() is called the utility will listen for long click events on the map and for each point * a dot will be placed on the map with a line between representing the collective points received. * * Calling fetchRoute() will attempt to fetch a map matched route matching the points that * have been configured. When a route is received draw it on the map and be sure to set the route * on your [MapboxNavivation] instance. * * Suggested usage: * Instantiate this class after the Map Style is loaded and ready. * * Call enable() to activate the long press listener which will collect the points used for creating * a route. * * Call disable() to deactivate the long press listener. * * When finished establishing points for the route you want to create call fetchRoute(). If a route * was received successfully it will be passed to the [RoutesRequestCallback] else a toast will appear * with some error information, also the error information will be logged. * * When a route is received call clear() this utility's line. * * Another useful function is removeLastPoint() which will remove the last point added. This could * be useful as a sort of "undo" if you make a mistake in where you press on the map. You may need * to temporarily add a button to your layout in order to make use of this function. * */ class RouteDrawingUtil(private val mapView: MapView) { private val touchPoints = mutableListOf<Point>() companion object { const val LINE_LAYER_SOURCE_ID = "DRAW_UTIL_LINE_LAYER_SOURCE_ID" const val LINE_LAYER_ID = "DRAW_UTIL_LINE_LAYER_ID" const val LINE_END_LAYER_ID = "DRAW_UTIL_LINE_END_LAYER_ID" const val LINE_END_SOURCE_ID = "DRAW_UTIL_LINE_END_SOURCE_ID" private const val LINE_COLOR = "#ffcc00" private const val LINE_WIDTH = 5f private const val LINE_OPACITY = 1f } init { mapView.getMapAsync { map -> map.getStyle { style -> val drawingLayerSource = style.getSourceAs<GeoJsonSource>( LINE_LAYER_SOURCE_ID ) if (drawingLayerSource == null) { style.addSource(GeoJsonSource(LINE_LAYER_SOURCE_ID)) } val lineEndSource = style.getSourceAs<GeoJsonSource>( LINE_END_SOURCE_ID ) if (lineEndSource == null) { style.addSource(GeoJsonSource(LINE_END_SOURCE_ID)) } val drawingLayer = style.getLayerAs<LineLayer>(LINE_LAYER_ID) if (drawingLayer == null) { style.addLayer( LineLayer( LINE_LAYER_ID, LINE_LAYER_SOURCE_ID ).withProperties( lineWidth(LINE_WIDTH), lineJoin(LINE_JOIN_ROUND), lineOpacity(LINE_OPACITY), lineColor(Color.parseColor(LINE_COLOR)) ) ) } val lineEndLayer = style.getLayerAs<CircleLayer>(LINE_END_LAYER_ID) if (lineEndLayer == null) { style.addLayer( CircleLayer( LINE_END_LAYER_ID, LINE_END_SOURCE_ID ).withProperties( circleRadius(5f), circleOpacity(1f), circleColor(Color.BLACK) ) ) } } } } @SuppressLint("ClickableViewAccessibility") fun enable() { mapView.getMapAsync { map -> map.addOnMapLongClickListener(mapLongClickListener) } } @SuppressLint("ClickableViewAccessibility") fun disable() { mapView.getMapAsync { map -> map.removeOnMapLongClickListener(mapLongClickListener) } } fun clear() { touchPoints.clear() mapView.getMapAsync { map -> map.getStyle { style -> style.getSourceAs<GeoJsonSource>(LINE_LAYER_SOURCE_ID) ?.setGeoJson(LineString.fromLngLats(listOf())) style.getSourceAs<GeoJsonSource>(LINE_END_SOURCE_ID) ?.setGeoJson(FeatureCollection.fromFeatures(listOf())) } } } private val mapLongClickListener = MapboxMap.OnMapLongClickListener { latLng -> touchPoints.add(Point.fromLngLat(latLng.longitude, latLng.latitude)) mapView.getMapAsync { map -> map.getStyle { style -> when (touchPoints.size) { 0 -> { } 1 -> { style.getSourceAs<GeoJsonSource>(LINE_END_SOURCE_ID) ?.setGeoJson(touchPoints.first()) } else -> { style.getSourceAs<GeoJsonSource>(LINE_LAYER_SOURCE_ID) ?.setGeoJson(LineString.fromLngLats(touchPoints)) style.getSourceAs<GeoJsonSource>(LINE_END_SOURCE_ID) ?.setGeoJson(getFeatureCollection(touchPoints)) } } } } true } private fun getFeatureCollection(points: List<Point>): FeatureCollection { return points.map { Feature.fromGeometry(it) }.run { FeatureCollection.fromFeatures(this) } } fun removeLastPoint() { if (touchPoints.isNotEmpty()) { touchPoints.removeLast() mapView.getMapAsync { map -> map.getStyle { style -> style.getSourceAs<GeoJsonSource>(LINE_LAYER_SOURCE_ID) ?.setGeoJson(LineString.fromLngLats(touchPoints)) style.getSourceAs<GeoJsonSource>(LINE_END_SOURCE_ID) ?.setGeoJson(getFeatureCollection(touchPoints)) } } } } fun fetchRoute(routeReadyCallback: RoutesRequestCallback) { if (touchPoints.size < 2) { return } val mapMatching = MapboxMapMatching.builder() .accessToken(Utils.getMapboxAccessToken(mapView.context)) .coordinates(touchPoints) .waypointIndices(0, touchPoints.size - 1) .steps(true) .bannerInstructions(false) .voiceInstructions(false) .profile(DirectionsCriteria.PROFILE_DRIVING) .build() mapMatching.enqueueCall( object : Callback<MapMatchingResponse> { override fun onFailure(call: Call<MapMatchingResponse>, t: Throwable) { Timber.e("MapMatching request failure %s", t.toString()) } override fun onResponse( call: Call<MapMatchingResponse>, response: Response<MapMatchingResponse> ) { val route = response.body()?.matchings()?.get(0)?.toDirectionRoute() if (route == null) { Timber.e( "Failed to get a route with " + "message ${response.code()} ${response.message()}" ) Toast.makeText( mapView.context, "Failed to get a route with " + "message ${response.code()} ${response.message()}", Toast.LENGTH_SHORT ).show() clear() enable() } else { routeReadyCallback.onRoutesReady(listOf(route)) } } } ) } }
0
null
0
0
81a06b641ddbdb4bc05c35663618b56615da6312
9,570
mapbox-navigation-android
Apache License 2.0
desktop/src/jvmMain/kotlin/presentation/window/translation/TranslationScreenState.kt
kisa002
584,385,916
false
{"Kotlin": 223546, "Ruby": 1722, "Swift": 860}
package presentation.window.translation sealed class TranslationScreenState { object Home : TranslationScreenState() object Translate : TranslationScreenState() object Recent : TranslationScreenState() object Saved : TranslationScreenState() data class Error(val errorEvent: TranslationScreenErrorEvent) : TranslationScreenState() }
1
Kotlin
2
51
fbe00ebee9ae05c5e10986b7dedabc4609c0085e
353
Transer
MIT License
keventbus/src/main/java/com/library/keventbus/SubscriberInfoIndex.kt
wkxjc
350,606,522
false
null
package com.library.keventbus interface SubscriberInfoIndex { val methodsByClass: Map<Class<*>, MutableList<SubscriberMethodInfo>> }
0
Kotlin
0
1
b953e60b8cf95f83adbc13aebb8a5a60f606a0ba
137
KEventBus
Apache License 2.0
SKIE/compiler/kotlin-plugin/src/kgp_common/kotlin/co/touchlab/skie/sir/element/SirDeclaration.kt
touchlab
685,579,240
false
{"Kotlin": 1136590, "Swift": 24501, "Shell": 183}
package co.touchlab.skie.sir.element sealed interface SirDeclaration : SirElement { val parent: SirDeclarationParent } val SirDeclaration.module: SirModule get() = parent.module val SirDeclaration.namespaceParent: SirDeclarationParent get() = if (parent is SirDeclarationNamespace) parent.namespaceParent else parent val SirDeclaration.file: SirFile? get() = parent as? SirFile ?: (parent as? SirDeclaration)?.file
6
Kotlin
4
327
00e56fd551ab19df6945a456060688888848ddf1
436
SKIE
Apache License 2.0
app/src/main/java/com/miguel/match_point/Match.kt
migueldemollet
396,967,805
false
null
package com.miguel.match_point class Match(service: Int, sets: Int, goldPoint: Boolean) { private var isTieBreak = false private var state = 0 private var side = 0 private var service = service private val sets = sets private val goldPoint = goldPoint fun point(playerWin: Player, playerLost: Player) : IntArray { playerWin.addPoint() playerLost.addPointLost() changeSide() if (isTieBreak) { side = 0 tieBreak(playerWin, playerLost) } else if (playerWin.point == 4 && playerWin.point - 1 > playerLost.point) { game(playerWin, playerLost) side = 0 changeService() } else if (playerWin.point == 4 && playerLost.point == 4) { playerWin.point = 3 playerLost.point = 3 } else if (playerWin.point == 5 && playerLost.point == 3) { game(playerWin, playerLost) side = 0 changeService() } else if (goldPoint && playerWin.point == 4 && playerLost.point == 3) { game(playerWin, playerLost) side = 0 changeService() } when(sets) { 3 -> { if (playerWin.setPoint == 2) { state = 2 } } 5 -> { if (playerWin.setPoint == 3) { state = 2 } } } return intArrayOf(state, side, service) } private fun game(playerWin: Player, playerLost: Player): Unit { playerWin.addGame() playerLost.lostGame() if (playerWin.game >= 6 && playerWin.game - 2 >= playerLost.game) { playerWin.addSet() playerLost.lostSet() } else if (playerWin.game == 6 && playerLost.game == 6) { state = 1 isTieBreak = true tieBreak(playerWin, playerLost) } } private fun tieBreak(playerWin: Player, playerLost: Player): Unit { if (playerWin.point >= 7 && playerWin.point - 2 >= playerLost.point) { playerWin.addGame() playerWin.addSet() playerLost.lostSet() isTieBreak = false state = 0 } } private fun changeSide() : Unit { side = if (side == 0) { 1 } else 0 } private fun changeService() : Unit { service = if (service == 0) { 1 } else 0 } }
0
Kotlin
0
1
2fed6750664e2e0ea3c40a7ed6a8e125ff0ea1ad
2,529
Match-Point
MIT License
app/src/main/java/com/grudus/minutnikpoprzezwieki/dto/TimeState.kt
grudus
146,987,884
false
null
package com.grudus.minutnikpoprzezwieki.dto data class TimeState(val remainingTime: String, val progress: Float) { init { require(progress in 0.0..100.0) } }
0
Kotlin
0
0
a127d02adc248bec6fdf8a5d5a67ca8143e53a9d
174
MinutnikPoprzezWieki
MIT License
Ppap/app/src/main/java/com/jeongg/ppap/data/dto/user/RefreshTokenDTO.kt
PnuPostAlarmProject
674,548,015
false
{"Kotlin": 224253}
package com.jeongg.ppap.data.dto.user import kotlinx.serialization.Serializable @Serializable data class RefreshTokenDTO( val refreshToken: String )
0
Kotlin
0
5
dd489dc5b6fdad778e7634a4a45f1760fc7ed920
155
android
MIT License
app/src/main/java/br/com/connectattoo/local/database/entitys/TagEntity.kt
connectattoo
601,818,127
false
{"Kotlin": 104943, "Shell": 88, "JavaScript": 67}
package br.com.connectattoo.local.database.entitys import androidx.room.ColumnInfo import androidx.room.Entity import androidx.room.PrimaryKey import br.com.connectattoo.data.Tag @Entity(tableName = "client_profile_tags") data class TagEntity( @PrimaryKey(autoGenerate = true) val idRoom: Long = 0, @ColumnInfo("id_api") val id: String? = "", @ColumnInfo("tag_name") val name: String? = "" ) { fun toTagResponse(): Tag = Tag( id = id, name = name ) } fun List<TagEntity>.toTag(): List<Tag> = this.map { it.toTagResponse() }
0
Kotlin
3
0
91abd4461e2d3d24e982e5815ec4ca29dd2e0e98
579
connectattoo.android
MIT License
app/src/main/java/com/soszynski/mateusz/dotmeme/activities/FoldersSettingsActivity.kt
TheLastGimbus
163,899,086
false
null
package com.soszynski.mateusz.dotmeme.activities import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.soszynski.mateusz.dotmeme.R import kotlinx.android.synthetic.main.activity_folders_settings.* class FoldersSettingsActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_folders_settings) toolbar.setNavigationOnClickListener { onBackPressed() } } }
0
Kotlin
0
3
126dcccf2f822ec3733b0737db6f381b86f6b22f
537
.meme
Apache License 2.0
app/src/main/java/com/example/earthimagesapp/domain/model/Day.kt
mateico
637,574,482
false
null
package com.example.earthimagesapp.domain.model import com.example.earthimagesapp.data.local.DayStatus data class Day( val date: String, val status: DayStatus )
1
Kotlin
0
1
03bf5b5034cf8bede35d846333e88438023910b9
171
earth_image_app
MIT License
src/main/kotlin/dev/sublab/substrate/metadata/lookup/type/def/RuntimeTypeDefVariant.kt
sublabdev
540,213,973
false
{"Kotlin": 157012}
/** * * Copyright 2023 SUBSTRATE LABORATORY LLC <<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 dev.sublab.substrate.metadata.lookup.type.def import dev.sublab.common.numerics.UInt8 /** * Variant runtime type */ data class RuntimeTypeDefVariant( val variants: List<Variant> ) { data class Variant( val name: String, val fields: List<RuntimeTypeDefField>, internal val indexUInt8: UInt8, val docs: List<String> ) { val index get() = indexUInt8.toUInt() } }
3
Kotlin
3
6
8a5469b2820c74f4a5a85576db4fdd681cfefa94
1,053
substrate-client-kotlin
Apache License 2.0
src/Day03.kt
baghaii
573,918,961
false
{"Kotlin": 11922}
fun main() { fun part1(input: List<String>): Int { var totalScore = 0 input.forEach { val firstHalf = it.substring(0, it.length / 2) val secondHalf = it.substring(it.length / 2, it.length ) val inBoth = mutableListOf<Char>() firstHalf.forEach { ch -> if (secondHalf.contains(ch) && !inBoth.contains(ch)) { inBoth.add(ch) } } val score = inBoth.map { ch -> scoreChar(ch) }.sum() totalScore += score } return totalScore } fun part2(input: List<String>): Int { var score = 0 for(i in 0 .. input.size - 3 step 3) { val elf1 = input[i] val elf2 = input[i+1] val elf3 = input[i+2] val badge = elf1.find{ch -> elf2.contains(ch) && elf3.contains(ch)}!! score += scoreChar(badge) } return score } // test if implementation meets criteria from the description, like: val testInput = readInput("Day03_test") check(part1(testInput) == 157) check(part2(testInput) == 70) val input = readInput("Day03") println(part1(input)) println(part2(input)) } fun scoreChar(ch: Char): Int { return if (ch in 'a'..'z') { ch - 'a' + 1 } else { ch - 'A' + 27 } }
0
Kotlin
0
0
8c66dae6569f4b269d1cad9bf901e0a686437469
1,401
AdventOfCode2022
Apache License 2.0
src/day02/Day02.kt
Dr4kn
575,092,295
false
{"Kotlin": 12652}
package day02 import readInput import java.lang.Exception fun main() { fun convertToValue(letter: String): Int { return when (letter) { "A", "X" -> 1 // Rock "B", "Y" -> 2 // Paper "C", "Z" -> 3 // Scissors else -> throw Exception("Not a valid Symbol") } } fun scoring(elf: Int, you: Int): Int { if (you == elf) { // draw return you + 3 } if (you == 1 && elf == 3) { // Rock defeats Scissors return you + 6 } if (you == 2 && elf == 1) { // Paper defeats Rock return you + 6 } if (you == 3 && elf == 2) { // Scissors defeats Paper return you + 6 } return you // loss } fun decideValue(elf: Int, you: Int): Int { if (you == 1) { // loss return when (elf) { 1 -> 3 2 -> 1 3 -> 2 else -> throw Exception("Not a valid number") } } if (you == 2) { // draw return when (elf) { 1 -> 1 2 -> 2 3 -> 3 else -> throw Exception("Not a valid number") } } if (you == 3) { // win return when (elf) { 1 -> 2 2 -> 3 3 -> 1 else -> throw Exception("Not a valid number") } } throw Exception("Not a valid decision") } fun part1(input: List<String>): Int { var sum = 0 input.forEach { val players = it.split(" ") sum += scoring(convertToValue(players[0]), convertToValue(players[1])) } return sum } fun part2(input: List<String>): Int { var sum = 0 input.forEach { val players = it.split(" ") val elf = convertToValue(players[0]) val you = convertToValue(players[1]) sum += scoring(elf, decideValue(elf, you)) } return sum } // test if implementation meets criteria from the description, like: val testInput = readInput("Day02_test") check(part1(testInput) == 15) check(part2(testInput) == 12) val input = readInput("Day02") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
6de396cb4eeb27ff0dd9a98b56e68a13c2c90cd5
2,376
advent-of-code-2022
Apache License 2.0
src/main/kotlin/no/nav/pensjon/opptjening/omsorgsopptjening/bestem/pensjonsopptjening/person/external/pdl/PdlResponse.kt
navikt
593,529,397
false
{"Kotlin": 589332, "Dockerfile": 97}
package no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.person.external.pdl import com.fasterxml.jackson.annotation.JsonFormat import com.fasterxml.jackson.annotation.JsonIgnoreProperties import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.omsorgsopptjening.model.Familierelasjon import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.omsorgsopptjening.model.Familierelasjoner import no.nav.pensjon.opptjening.omsorgsopptjening.bestem.pensjonsopptjening.omsorgsopptjening.model.Person import java.time.LocalDate import java.time.LocalDateTime internal data class PdlResponse( val data: PdlData, private val errors: List<PdlError>? = null ) { val error: PdlError? = errors?.firstOrNull() } internal data class PdlData( val hentPerson: HentPersonQueryResponse? ) @JsonIgnoreProperties(ignoreUnknown = true) internal data class HentPersonQueryResponse( val folkeregisteridentifikator: List<Folkeregisteridentifikator>, val foedsel: List<Foedsel>, val doedsfall: List<Doedsfall?>, val forelderBarnRelasjon: List<ForelderBarnRelasjon>, ) { private fun gjeldendeIdent(): PdlFnr { return folkeregisteridentifikator .firstOrNull { it.status == Folkeregisteridentifikator.Status.I_BRUK } ?.let { PdlFnr(it.identifikasjonsnummer, gjeldende = true) } ?: throw PdlMottatDataException("Fnr i bruk finnes ikke") } private fun bestemDoedsdato(doedsfall: List<Doedsfall?>): LocalDate? { return doedsfall.firstOrNull()?.doedsdato } private fun foedselsdato(): LocalDate { return when (foedsel.size) { 0 -> { throw PdlMottatDataException("Fødselsår finnes ikke i respons fra pdl") } 1 -> { LocalDate.parse(foedsel.first().foedselsdato) } else -> { LocalDate.parse(foedsel.avklarFoedsel()?.foedselsdato) ?: throw PdlMottatDataException("Fødselsår finnes ikke i respons fra pdl") } } } private fun familierelasjoner(): Familierelasjoner { return forelderBarnRelasjon.map { Familierelasjon( ident = it.relatertPersonsIdent, relasjon = when (it.relatertPersonsRolle) { ForelderBarnRelasjon.Rolle.BARN -> Familierelasjon.Relasjon.BARN ForelderBarnRelasjon.Rolle.FAR -> Familierelasjon.Relasjon.FAR ForelderBarnRelasjon.Rolle.MOR -> Familierelasjon.Relasjon.MOR ForelderBarnRelasjon.Rolle.MEDMOR -> Familierelasjon.Relasjon.MEDMOR } ) }.let { Familierelasjoner(it) } } fun toDomain(): Person { return Person( fnr = gjeldendeIdent().fnr, fødselsdato = foedselsdato(), dødsdato = bestemDoedsdato(doedsfall), familierelasjoner = familierelasjoner(), ) } } @JsonIgnoreProperties(ignoreUnknown = true) internal data class Folkeregisteridentifikator( val identifikasjonsnummer: String, val status: Status, val type: Type, val metadata: Metadata, val folkeregistermetadata: Folkeregistermetadata? = null, ) { enum class Status { I_BRUK, OPPHOERT } enum class Type { FNR, DNR } } @JsonIgnoreProperties(ignoreUnknown = true) internal data class Foedsel( val foedselsaar: Int, val foedselsdato: String, val metadata: Metadata, val folkeregistermetadata: Folkeregistermetadata? = null, ) @JsonIgnoreProperties(ignoreUnknown = true) internal data class ForelderBarnRelasjon( val relatertPersonsIdent: String, val relatertPersonsRolle: Rolle, val minRolleForPerson: Rolle, val metadata: Metadata, val folkeregistermetadata: Folkeregistermetadata? = null, ) { enum class Rolle { FAR, MOR, MEDMOR, BARN } } @JsonIgnoreProperties(ignoreUnknown = true) internal data class Doedsfall( @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd") val doedsdato: LocalDate ) @JsonIgnoreProperties(ignoreUnknown = true) internal data class Metadata( val historisk: Boolean, val master: String, val endringer: List<Endring> = emptyList() ) @JsonIgnoreProperties(ignoreUnknown = true) internal data class Folkeregistermetadata( val ajourholdstidspunkt: LocalDateTime? = null ) @JsonIgnoreProperties(ignoreUnknown = true) internal data class Endring( val registrert: LocalDateTime )
1
Kotlin
1
0
3e2c545126479f2bd50907ec47ada6d4a9ead3a1
4,592
omsorgsopptjening-bestem-pensjonsopptjening
MIT License
app/src/main/java/com/whalescale/binit/view/main/screens/drop_locations/DropOffLocationsScreen.kt
Ninise
605,546,083
false
{"Kotlin": 257021}
package com.whalescale.binit.view.main.screens.drop_locations import android.widget.Toast import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.runtime.Composable import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalSoftwareKeyboardController import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.TextStyle import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.hilt.navigation.compose.hiltViewModel import com.whalescale.binit.R import com.whalescale.binit.ui.theme.* import com.whalescale.binit.utils.Const import com.whalescale.binit.view.custom_views.DefaultButton import com.whalescale.binit.view.main.MainViewModel @Composable fun DropOffLocationsScreen() { val viewModel = hiltViewModel<MainViewModel>() DropOffLocationsScreenContent(makeSuggestion = { name, type, desc, location -> viewModel.makeSuggestion(name, type, desc, location, null) }) } @OptIn(ExperimentalComposeUiApi::class) @Composable fun DropOffLocationsScreenContent(makeSuggestion: (String, String, String, String) -> Unit) { val text = remember { mutableStateOf("") } val scrollState = rememberScrollState() val context = LocalContext.current val keyboardController = LocalSoftwareKeyboardController.current Column( modifier = Modifier .fillMaxSize() .background(color = Color.White) .padding(horizontal = 20.dp) .verticalScroll(scrollState), horizontalAlignment = Alignment.CenterHorizontally ) { Text( text = stringResource(R.string.title_drop_location_screen), color = IconsDark, fontFamily = Inter, fontWeight = FontWeight.Bold, fontSize = 18.sp, modifier = Modifier.padding(top = 15.dp) ) Image( painter = painterResource(id = R.drawable.ic_location_screen_image), contentDescription = "Drop-ff placeholder", modifier = Modifier .height(170.dp) .fillMaxWidth() .padding(horizontal = 40.dp) .padding(top = 30.dp) .padding(end = 50.dp) ) Text( text = stringResource(R.string.sub_title_drop_locations_screen), color = IconsDark, fontFamily = Inter, fontWeight = FontWeight.Medium, fontSize = 16.sp, modifier = Modifier .padding(top = 30.dp) .align(alignment = Alignment.Start) ) Text( text = stringResource(R.string.sub_schedule_screen), color = IconsDark, fontFamily = Inter, fontWeight = FontWeight.Normal, fontSize = 14.sp, modifier = Modifier .padding(top = 1.dp) .align(alignment = Alignment.Start) ) TextField( value = text.value, onValueChange = { value -> text.value = value }, modifier = Modifier .fillMaxWidth() .wrapContentHeight() .padding(vertical = 16.dp), maxLines = 5, minLines = 5, placeholder = { Text(stringResource(R.string.message), style = TextStyle(color = HintText, fontSize = 16.sp, fontFamily = Inter, fontWeight = FontWeight.Normal)) }, textStyle = TextStyle(color = BodyText, fontSize = 16.sp, fontFamily = Inter, fontWeight = FontWeight.Normal), singleLine = false, shape = RoundedCornerShape(6.dp), // The TextFiled has rounded corners top left and right by default colors = TextFieldDefaults.textFieldColors( textColor = BodyText, cursorColor = cursorText, backgroundColor = SearchBackGray, focusedIndicatorColor = Color.Transparent, unfocusedIndicatorColor = Color.Transparent, disabledIndicatorColor = Color.Transparent ) ) DefaultButton(text = stringResource(id = R.string.send), pressed = { makeSuggestion(Const.S_LOCATION_NAME, Const.S_SUGGESTION, text.value, Const.S_ANDROID) text.value = "" Toast.makeText(context, "Message has sent, thank you! :)", Toast.LENGTH_SHORT).show() keyboardController?.hide() }) } } @Preview @Composable fun DropOffLocationsScreen_Preview() { DropOffLocationsScreenContent(makeSuggestion = { _, _, _, _ -> }) }
0
Kotlin
0
0
57bfe5d533c7576e83126220d7f43ecf27404d4f
5,370
BinitAndroid
Apache License 2.0
compiler/testData/ir/irText/classes/inlineClassSyntheticMethods.kt
mcpiroman
375,462,779
true
{"Kotlin": 73023707, "Java": 6608057, "Swift": 4256908, "C": 2635707, "C++": 2546276, "Objective-C": 636652, "JavaScript": 211357, "Objective-C++": 165224, "Groovy": 103363, "Python": 44364, "Shell": 31842, "TypeScript": 22854, "Lex": 18369, "Batchfile": 11692, "CSS": 11368, "HTML": 6971, "Ruby": 6839, "EJS": 5241, "Dockerfile": 4685, "CMake": 4448, "Pascal": 1698, "FreeMarker": 1393, "LLVM": 395, "Scala": 80}
// !LANGUAGE: +InlineClasses // MUTE_SIGNATURE_COMPARISON_K2: JVM_IR // ^ KT-57429 class C<T>(val t: T) { override fun hashCode(): Int = t as Int } inline class IC<TT>(val c: C<TT>) { fun foo(): Int = c.hashCode() } fun box(): String { val ic = IC<Int>(C(42)) if (ic.foo() != 42) return "FAIL" return "OK" }
0
Kotlin
0
1
973adb6a38df87d16ee089eee7faafa1983fd76a
332
kotlin
Apache License 2.0
library/src/main/java/com/inconceptlabs/designsystem/components/emptyitem/EmptyItemTokens.kt
inconcept
766,961,605
false
{"Kotlin": 81700}
package com.inconceptlabs.designsystem.components.emptyitem import androidx.compose.foundation.layout.PaddingValues import androidx.compose.runtime.Composable import androidx.compose.runtime.compositionLocalOf import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.TextStyle import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import com.inconceptlabs.designsystem.theme.AppTheme import com.inconceptlabs.designsystem.theme.attributes.Size val LocalEmptyItemTokens = compositionLocalOf { EmptyItemTokens.Default } data class EmptyItemTokens( val paddingValues: PaddingValues = PaddingValues( horizontal = 24.dp, vertical = 36.dp ), val cornerRadius: Dp = 20.dp, val dashWidth: Dp = 5.dp, val dashGap: Dp = dashWidth, val iconSize: Dp = 56.dp, val iconTint: @Composable () -> Color = { AppTheme.colorScheme.BG6 }, val buttonSize: Size = Size.M, val titleStyle: @Composable () -> TextStyle = { AppTheme.typography.S2 }, val titleColor: @Composable () -> Color = { AppTheme.colorScheme.T8 }, val descriptionStyle: @Composable () -> TextStyle = { AppTheme.typography.P5 }, val descriptionColor: @Composable () -> Color = { AppTheme.colorScheme.T8 }, ) { companion object { internal val Default = EmptyItemTokens() } }
0
Kotlin
0
6
a22053277401b9762391cc64a34e05c0bd67a28d
1,340
android-design-system
MIT License
src/main/kotlin/it/andbin/colortools/controller/model/ColorsBrowserForm.kt
andbin
272,759,577
false
null
/* * Copyright (C) 2020 <NAME> ("andbin") * * This file is part of the "Kotlin+SpringBoot Color Tools" project * and is released under the MIT License. See one of the license files * included in the root of the project for the full text of the license. */ package it.andbin.colortools.controller.model import it.andbin.colortools.model.ColorNameMatchMode import it.andbin.colortools.model.ColorSortMode open class ColorsBrowserForm { var nameFilter: String = "" set(value) { field = value.trim() } var nameMatchMode: ColorNameMatchMode = ColorNameMatchMode.PARTIAL var sortMode: ColorSortMode = ColorSortMode.NAME_ASCENDING }
0
Kotlin
0
0
31a6c1a59b75bd1f45de712a4cbba1632b1ce104
655
kotlin-springboot-color-tools
MIT License