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/adapter/Adapter.kt
byBackfish
510,866,399
false
{"Kotlin": 65429, "Java": 1232}
package adapter import net.minecraftforge.fml.common.FMLModContainer import net.minecraftforge.fml.common.ILanguageAdapter import net.minecraftforge.fml.common.ModContainer import net.minecraftforge.fml.relauncher.Side import org.apache.logging.log4j.LogManager import java.lang.reflect.Field import java.lang.reflect.Method @Suppress("UNUSED") class Adapter : ILanguageAdapter { private val logger = LogManager.getLogger("ILanguageAdapter/Kotlin") override fun setProxy(target: Field, proxyTarget: Class<*>, proxy: Any) { val instanceField = findInstanceFieldOrThrow(proxyTarget) val modObject = findModObjectOrThrow(instanceField) target.set(modObject, proxy) } override fun getNewInstance( container: FMLModContainer?, objectClass: Class<*>, classLoader: ClassLoader, factoryMarkedAnnotation: Method? ): Any? { val instanceField = findInstanceFieldOrThrow(objectClass) val modObject = findModObjectOrThrow(instanceField) return modObject } override fun supportsStatics() = false override fun setInternalProxies(mod: ModContainer?, side: Side?, loader: ClassLoader?) = Unit private fun findInstanceFieldOrThrow(targetClass: Class<*>): Field { val instanceField: Field = try { targetClass.getField("INSTANCE") } catch (exception: NoSuchFieldException) { throw noInstanceFieldException(exception) } catch (exception: SecurityException) { throw instanceSecurityException(exception) } return instanceField } private fun findModObjectOrThrow(instanceField: Field): Any { val modObject = try { instanceField.get(null) } catch (exception: IllegalArgumentException) { throw unexpectedInitializerSignatureException(exception) } catch (exception: IllegalAccessException) { throw wrongVisibilityOnInitializerException(exception) } return modObject } private fun noInstanceFieldException(exception: Exception) = KotlinAdapterException("Couldn't find INSTANCE singleton on Kotlin @Mod container", exception) private fun instanceSecurityException(exception: Exception) = KotlinAdapterException("Security violation accessing INSTANCE singleton on Kotlin @Mod container", exception) private fun unexpectedInitializerSignatureException(exception: Exception) = KotlinAdapterException("Kotlin @Mod object has an unexpected initializer signature, somehow?", exception) private fun wrongVisibilityOnInitializerException(exception: Exception) = KotlinAdapterException("Initializer on Kotlin @Mod object isn't `public`", exception) private class KotlinAdapterException(message: String, exception: Exception) : RuntimeException("Kotlin adapter error - do not report to Forge! " + message, exception) }
0
Kotlin
0
0
d82639e486fc5d892890038f0c41b15a8854ce7b
2,934
AvoMod-Recode
MIT License
app/src/main/java/org/wikipedia/views/SwipeRefreshLayoutWithScroll.kt
greatfire
460,298,221
false
null
package org.wikipedia.views import android.content.Context import android.util.AttributeSet import android.view.View import androidx.swiperefreshlayout.widget.SwipeRefreshLayout class SwipeRefreshLayoutWithScroll constructor(context: Context, attrs: AttributeSet?) : SwipeRefreshLayout(context, attrs) { var scrollableChild: View? = null override fun canChildScrollUp(): Boolean { return if (scrollableChild == null) { false } else scrollableChild!!.scrollY > 0 } }
2
null
4
38
8c8de602274b0132fc5d22b394a2c47fcd0bf2eb
510
apps-android-wikipedia-envoy
Apache License 2.0
solar/src/main/java/com/chiksmedina/solar/boldduotone/essentionalui/CloseCircle.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.boldduotone.essentionalui 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 com.chiksmedina.solar.boldduotone.EssentionalUiGroup val EssentionalUiGroup.CloseCircle: ImageVector get() { if (_closeCircle != null) { return _closeCircle!! } _closeCircle = Builder( name = "CloseCircle", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0xFF000000)), stroke = null, fillAlpha = 0.5f, strokeAlpha = 0.5f, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(22.0f, 12.0f) curveTo(22.0f, 17.5228f, 17.5228f, 22.0f, 12.0f, 22.0f) curveTo(6.4771f, 22.0f, 2.0f, 17.5228f, 2.0f, 12.0f) curveTo(2.0f, 6.4771f, 6.4771f, 2.0f, 12.0f, 2.0f) curveTo(17.5228f, 2.0f, 22.0f, 6.4771f, 22.0f, 12.0f) close() } path( fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(8.9697f, 8.9697f) curveTo(9.2626f, 8.6768f, 9.7374f, 8.6768f, 10.0303f, 8.9697f) lineTo(12.0f, 10.9394f) lineTo(13.9697f, 8.9697f) curveTo(14.2626f, 8.6768f, 14.7374f, 8.6768f, 15.0303f, 8.9697f) curveTo(15.3232f, 9.2626f, 15.3232f, 9.7375f, 15.0303f, 10.0304f) lineTo(13.0607f, 12.0f) lineTo(15.0303f, 13.9696f) curveTo(15.3232f, 14.2625f, 15.3232f, 14.7374f, 15.0303f, 15.0303f) curveTo(14.7374f, 15.3232f, 14.2625f, 15.3232f, 13.9696f, 15.0303f) lineTo(12.0f, 13.0607f) lineTo(10.0304f, 15.0303f) curveTo(9.7375f, 15.3232f, 9.2626f, 15.3232f, 8.9697f, 15.0303f) curveTo(8.6768f, 14.7374f, 8.6768f, 14.2626f, 8.9697f, 13.9697f) lineTo(10.9394f, 12.0f) lineTo(8.9697f, 10.0303f) curveTo(8.6768f, 9.7374f, 8.6768f, 9.2626f, 8.9697f, 8.9697f) close() } } .build() return _closeCircle!! } private var _closeCircle: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
2,998
SolarIconSetAndroid
MIT License
core/src/main/java/com/amplifyframework/predictions/options/FaceLivenessSessionOptions.kt
aws-amplify
177,009,933
false
{"Java": 5271440, "Kotlin": 3557401, "Shell": 28043, "Groovy": 11755, "Python": 3681, "Ruby": 1874}
/* * Copyright 2023 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amplifyframework.predictions.options import com.amplifyframework.annotations.InternalAmplifyApi @InternalAmplifyApi open class FaceLivenessSessionOptions protected constructor() { companion object { /** * Use the default options. * @return Default options. */ @JvmStatic fun defaults() = FaceLivenessSessionOptions() /** * Get a builder to construct an instance of this object. * @return a builder to construct an instance of this object. */ @JvmStatic fun builder(): Builder<*> = CoreBuilder() } override fun hashCode() = javaClass.hashCode() override fun equals(other: Any?): Boolean { return if (this === other) { true } else !(other == null || javaClass != other.javaClass) } override fun toString(): String { return "FaceLivenessSessionOptions()" } abstract class Builder<T : Builder<T>> { /** * Return the type of builder this is so that chaining can work correctly without implicit casting. * @return the type of builder this is */ abstract fun getThis(): T /** * Build an instance of FaceLivenessSessionOptions (or one of its subclasses). * @return an instance of FaceLivenessSessionOptions (or one of its subclasses) */ open fun build() = FaceLivenessSessionOptions() } class CoreBuilder : Builder<CoreBuilder>() { override fun getThis() = this } }
103
Java
115
245
c1030d45909bb6e2ace4dc195047f9c2a8630fe2
2,138
amplify-android
Apache License 2.0
backend/src/main/kotlin/es/guillermoorellana/keynotedex/backend/external/frontmatter/GithubFrontMatterScrapper.kt
wiyarmir
116,376,394
false
null
package es.guillermoorellana.keynotedex.backend.external.frontmatter import es.guillermoorellana.keynotedex.backend.external.GithubHttpClient import es.guillermoorellana.keynotedex.backend.frontmatter.FrontMatterParser class GithubFrontMatterScrapper( private val githubHttpClient: GithubHttpClient, private val frontMatterParser: FrontMatterParser ) { suspend fun fetch(repo: String, path: String): List<Conference> = githubHttpClient.getDirectoryFiles(repo, path) .map { frontMatterParser.parse(Conference.serializer(), it) } }
6
Kotlin
3
51
ec6d7e50d5c7285e6d26f06caaca03a279af38c6
564
keynotedex
Apache License 2.0
light/src/main/kotlin/net/kotlinx/domain/batchTask/BatchTaskRuntime.kt
mypojo
565,799,715
false
{"Kotlin": 1495826, "Jupyter Notebook": 13540, "Java": 9531}
package net.kotlinx.domain.batchTask import net.kotlinx.json.gson.GsonData /** 배치 작업 */ interface BatchTaskRuntime { /** * @return 한번의 실행에 다수의 로직이 리턴될 수 있음 * */ suspend fun executeLogic(option: GsonData, input: List<String>): Map<String, List<GsonData>> }
0
Kotlin
0
1
1b361a5ae8aae718f0e81768452e6803c0990e71
279
kx_kotlin_support
MIT License
android/libraries/rib-compiler-app/src/main/kotlin/com/uber/rib/compiler/TypeProcessorPipeline.kt
uber
105,686,726
false
{"Kotlin": 593831, "Java": 468239, "Swift": 422552, "JavaScript": 14648, "Shell": 4069, "Ruby": 2152, "Objective-C": 814}
/* * Copyright (C) 2017. Uber Technologies * * 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.uber.rib.compiler import java.util.ArrayList import javax.annotation.processing.RoundEnvironment import javax.lang.model.element.Element import javax.lang.model.element.TypeElement /** Base ProcessorPipeline that parses the annotated elements as type element. */ abstract class TypeProcessorPipeline( processContext: ProcessContext ) : ProcessorPipeline(processContext) { /** * Process the annotations. * * @param annotations * @param roundEnv * @throws Throwable */ @Throws(Throwable::class) override fun processAnnotations(annotations: Set<TypeElement>, roundEnv: RoundEnvironment) { val annotatedElements: Collection<Element> = roundEnv.getElementsAnnotatedWith(annotationType) val annotatedTypes: MutableList<TypeElement> = ArrayList(annotatedElements.size) for (e in annotatedElements) { annotatedTypes.add(e as TypeElement) } processTypeElements(annotatedTypes) } /** * Process the list of [TypeElement]. * * @param annotatedClasses the type element list. * @throws Throwable */ @Throws(Throwable::class) protected abstract fun processTypeElements(annotatedClasses: List<TypeElement>) }
124
Kotlin
905
7,754
08b95b6d0ee16c1b5e02a769d8b40f0310add73a
1,790
RIBs
Apache License 2.0
core/src/test/kotlin/com/oneeyedmen/minutest/executing.kt
npryce
153,911,934
true
{"Kotlin": 84691}
package com.oneeyedmen.minutest import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.DynamicContainer import org.junit.jupiter.api.DynamicNode import org.junit.jupiter.api.DynamicTest import java.util.stream.Stream import kotlin.streams.asSequence fun executeTest(tests: Stream<out DynamicNode>) { tests.asSequence().forEach { dynamicNode -> when (dynamicNode) { is DynamicTest -> dynamicNode.executable.execute() is DynamicContainer -> executeTest(dynamicNode.children) } } } fun assertLogged(log: List<String>, vararg expected: String) { assertEquals(expected.toList(), log) } fun assertNothingLogged(log: List<String>) { assertEquals(emptyList<String>(), log) }
0
Kotlin
0
2
741acdd0349a6e169eb687a5ab4054aedc7eceab
755
minutest
Apache License 2.0
test/tasks/Request7ChannelsKtTest.kt
Elm0xz
351,789,151
true
{"Kotlin": 34574}
package tasks import contributors.MockGithubService import contributors.concurrentProgressResults import contributors.testRequestData import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.runBlockingTest import org.junit.Assert import org.junit.Test class Request7ChannelsKtTest { @Test fun testChannels() = runBlockingTest { val virtualStartTime = currentTime var index = 0 loadContributorsChannels(MockGithubService, testRequestData) { users, _ -> val expected = concurrentProgressResults[index++] val totalVirtualTime = currentTime - virtualStartTime // TODO: uncomment this assertion Assert.assertEquals("Expected intermediate result after virtual ${expected.timeFromStart} ms:", expected.timeFromStart, totalVirtualTime) Assert.assertEquals("Wrong intermediate result after $totalVirtualTime:", expected.users, users) } } }
0
Kotlin
0
0
f6bb1fc7da2419b1babfea9b8d7ed0f71d179462
982
intro-coroutines
Apache License 2.0
src/jvmMain/kotlin/com/bkahlert/kommons/tracing/rendering/Style.kt
bkahlert
323,048,013
false
null
package com.bkahlert.kommons.tracing.rendering import com.bkahlert.kommons.text.ANSI.FilteringFormatter import com.bkahlert.kommons.text.ANSI.Formatter import com.bkahlert.kommons.text.ANSI.Formatter.Companion.ToCharSequence import com.bkahlert.kommons.text.LineSeparators import com.bkahlert.kommons.text.takeUnlessEmpty /** * A style is a simple generalization attempt * to improve separation of concern. * * This component assumes that what needs to be styled consists of * a start and end element and 0 or more content elements. */ public interface Style { public val onlineLinePrefix: String public val onlineLineSeparator: String public val indent: Int public val layout: ColumnsLayout /** * Styles the introducing first element. * * The optional [contentFormatter] will to the headline, [decorationFormatter] will be applied to all * "decoration" added. */ public fun start( element: CharSequence, contentFormatter: FilteringFormatter<CharSequence>, decorationFormatter: Formatter<CharSequence> = ToCharSequence, ): CharSequence? /** * Styles a content element. * * The optional [decorationFormatter] will be applied to all * "decoration" added. */ public fun content( element: CharSequence, decorationFormatter: Formatter<CharSequence> = ToCharSequence, ): CharSequence? /** * Styles an element to be inserted in its parent which * is necessary for nested layouts. * * The optional [decorationFormatter] will be applied to all * "decoration" added. */ public fun parent( element: CharSequence, decorationFormatter: Formatter<CharSequence> = ToCharSequence, ): CharSequence? = content(element, decorationFormatter) /** * Styles the finalizing last element. * * The optional [decorationFormatter] will be applied to all * "decoration" added. */ public fun end( element: ReturnValue, resultValueFormatter: (ReturnValue) -> ReturnValue?, decorationFormatter: Formatter<CharSequence> = ToCharSequence, ): CharSequence? public fun buildString(block: StringBuilder.() -> Unit): CharSequence? = StringBuilder().apply(block).takeUnlessEmpty() public fun StringBuilder.append(vararg text: CharSequence?): StringBuilder = apply { text.forEach { if (it != null) append(it) } } public fun StringBuilder.appendLine(vararg text: CharSequence?): StringBuilder = apply { append(*text, LineSeparators.DEFAULT) } }
7
Kotlin
0
9
35e2ac1c4246decdf7e7a1160bfdd5c9e28fd066
2,606
kommons
MIT License
app/src/main/java/com/example/vonage/voicesampleapp/activities/fragments/DialerFragment.kt
Vonage-Community
638,584,040
false
null
package com.example.vonage.voicesampleapp.activities.fragments import android.media.AudioManager import android.media.ToneGenerator import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.DialogFragment import com.example.vonage.voicesampleapp.App import com.example.vonage.voicesampleapp.R import com.example.vonage.voicesampleapp.databinding.FragmentDialerBinding import com.example.vonage.voicesampleapp.utils.Constants import com.example.vonage.voicesampleapp.utils.DialerType // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER private const val ARG_TYPE = "dialer_type" /** * A [Fragment] subclass to render a Dialer. * Use the [DialerFragment.newInstance] factory method to * create an instance of this fragment. */ class DialerFragment : DialogFragment() { private val clientManager = App.coreContext.clientManager private var type: DialerType = DialerType.PHONE_NUMBER private lateinit var binding: FragmentDialerBinding private val toneGenerator = ToneGenerator(AudioManager.STREAM_DTMF, DTMF_VOLUME) private var dialedNumber : String get() { return binding.dialedNumberTextView.text.toString() } set(value) { binding.dialedNumberTextView.text = value } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { type = DialerType.valueOf(it.getString(ARG_TYPE)!!) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { // Inflate the layout for this fragment binding = FragmentDialerBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) setBindings() } private fun setBindings() = binding.run { buttonDismiss.setOnClickListener{ dismiss() } buttonCall.visibility = if(type == DialerType.PHONE_NUMBER) View.VISIBLE else View.GONE buttonCall.setOnClickListener { makeCall() } listOf(button1, button2, button3, button4, button5, button6, button7, button8, button9, buttonStar, button0, buttonPound) .forEach { button -> button.setOnClickListener { appendDigit(button.text.toString()) if(type == DialerType.DTMF) sendDtmf(button.text.toString()) } } button0.setOnLongClickListener { appendDigit("+"); true } buttonBackspace.apply { setOnClickListener{ backspace() } setOnLongClickListener{ clearNumber(); true } } } private fun appendDigit(digit: String){ dialedNumber += digit } private fun backspace(){ dialedNumber = dialedNumber.dropLast(1) } private fun clearNumber(){ dialedNumber = "" } private fun makeCall(){ val callContext = dialedNumber.takeUnless { it.isEmpty() }?.let { mapOf( Constants.CONTEXT_KEY_RECIPIENT to it, Constants.CONTEXT_KEY_TYPE to Constants.PSTN_TYPE ) } clientManager.startOutboundCall(callContext) } private fun sendDtmf(digit: String){ val toneType = when(digit){ getString(R.string.dialer_btn_zero) -> ToneGenerator.TONE_DTMF_0 getString(R.string.dialer_btn_one) -> ToneGenerator.TONE_DTMF_1 getString(R.string.dialer_btn_two) -> ToneGenerator.TONE_DTMF_2 getString(R.string.dialer_btn_three) -> ToneGenerator.TONE_DTMF_3 getString(R.string.dialer_btn_four) -> ToneGenerator.TONE_DTMF_4 getString(R.string.dialer_btn_five) -> ToneGenerator.TONE_DTMF_5 getString(R.string.dialer_btn_six) -> ToneGenerator.TONE_DTMF_6 getString(R.string.dialer_btn_seven) -> ToneGenerator.TONE_DTMF_7 getString(R.string.dialer_btn_eight) -> ToneGenerator.TONE_DTMF_8 getString(R.string.dialer_btn_nine) -> ToneGenerator.TONE_DTMF_9 getString(R.string.dialer_btn_pound) -> ToneGenerator.TONE_DTMF_P getString(R.string.dialer_btn_star) -> ToneGenerator.TONE_DTMF_S else -> null } ?: return toneGenerator.startTone(toneType, DTMF_DURATION) App.coreContext.activeCall?.let { clientManager.sendDtmf(it, digit) } } companion object { private const val DTMF_VOLUME = 100 private const val DTMF_DURATION = 100 /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * * @param type Dialer Type. * @return A new instance of fragment DialerFragment. */ @JvmStatic fun newInstance(type: DialerType) = DialerFragment().apply { arguments = Bundle().apply { putString(ARG_TYPE, type.name) } } } }
0
Kotlin
0
0
9a55dbbc02ccc57fc57447beededdb517c92eb03
5,247
sample-clientsdk-android_kotlin-voip_app
MIT License
src/main/kotlin/users/security/ConfigureSecurity.kt
krikotnenko
689,073,512
false
{"Kotlin": 169460}
package users.security import io.ktor.http.* import io.ktor.server.application.* import io.ktor.server.auth.* import io.ktor.server.auth.jwt.* import io.ktor.server.sessions.* import users.constants.USER_SESSION import users.routes.utils.UserSession fun Application.configureSecurity() { JwtConfig.initialize("digital-adapter") install(Authentication) { jwt { verifier(JwtConfig.instance.verifier) validate { credential -> if (credential.payload.getClaim("login").asString() != "") { JWTPrincipal(credential.payload) } else { null } } challenge { _, _ -> } } } install(Sessions) { cookie<UserSession>(USER_SESSION) { cookie.path = "/" cookie.extensions["SameSite"] = "lax" cookie.maxAgeInSeconds = 86400 cookie.httpOnly = false cookie.encoding = CookieEncoding.BASE64_ENCODING } } }
0
Kotlin
0
0
332b375155a77cd07b97cd6d6199d6cdad27d6a5
1,044
digital-adapter
MIT License
soapui-streams-direct/src/main/kotlin/eu/k5/soapui/streams/direct/model/test/TestStepPropertiesDirect.kt
denninger-eu
244,302,123
false
null
package eu.k5.soapui.streams.direct.model.test import com.eviware.soapui.impl.wsdl.teststeps.WsdlPropertiesTestStep import com.eviware.soapui.impl.wsdl.teststeps.WsdlTestStepWithProperties import com.eviware.soapui.impl.wsdl.teststeps.addProperty import com.eviware.soapui.model.support.DefaultTestStepProperty import eu.k5.soapui.streams.direct.model.PropertiesDirect import eu.k5.soapui.streams.model.SuuProperties import eu.k5.soapui.streams.model.test.SuuTestStepProperties class TestStepPropertiesDirect( testCase: TestCaseDirect, private val step: WsdlPropertiesTestStep ) : AbstractTestStepDirect(testCase,step), SuuTestStepProperties { override val properties: SuuProperties get() = PropertiesDirect(step, ArrayList()) { val newProperty = step.addProperty(it) newProperty } }
5
Kotlin
0
0
665e54e4ac65d6c7e9805bb1b44f30f9ec702ce3
842
soapui-utils
Apache License 2.0
net.akehurst.games.pong/computational/game/src/commonMain/kotlin/Game.kt
dhakehurst
297,353,435
false
null
/** * Copyright (C) 2016 Dr. <NAME> (http://dr.david.h.akehurst.net) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package net.akehurst.games.pong.computational.game import net.akehurst.games.pong.computational.user.api.UserNotification import net.akehurst.games.pong.computational.user.api.UserRequest import net.akehurst.games.pong.information.BatIdentity import net.akehurst.games.pong.information.BatPosition import net.akehurst.games.pong.information.ScreenSize class Game : UserRequest { lateinit var userNotification: UserNotification private lateinit var userScreenSize:ScreenSize private lateinit var opponentScreenSize:ScreenSize // --- UserRequest --- override fun requestStartGame(screenSize: ScreenSize) { userNotification.notifyWaitingForOpponent() } override fun requestQuitGame() { TODO("not implemented") } override fun requestMoveLeft() { TODO("not implemented") } override fun requestMoveRight() { TODO("not implemented") } }
0
Kotlin
0
0
5d62ff6d7118fd21315966f284920e72ff7a1ecc
1,556
games.pong
Apache License 2.0
sdk/src/main/java/com/exponea/sdk/repository/UniqueIdentifierRepositoryImpl.kt
exponea
134,699,893
false
null
package com.exponea.sdk.repository import com.exponea.sdk.preferences.ExponeaPreferences import java.util.UUID internal class UniqueIdentifierRepositoryImpl(private val preferences: ExponeaPreferences) : UniqueIdentifierRepository { private val key = "ExponeaUniqueIdentifierToken" override fun get(): String { var token = preferences.getString(key, "") if (token.isEmpty()) { token = UUID.randomUUID().toString() preferences.setString(key, token) } return token } override fun clear(): Boolean { return preferences.remove(key) } }
0
null
16
17
150999cffec54fa2266e0d9db07c16143dc17a26
630
exponea-android-sdk
MIT License
src/main/kotlin/no/nav/tiltaksarrangor/client/dto/TiltakDto.kt
navikt
616,496,742
false
null
package no.nav.tiltaksarrangor.client.dto data class TiltakDto( val tiltakskode: String, val tiltaksnavn: String )
1
Kotlin
0
1
946b80623dfd6d45fcd16d8e6d1332b11868c4b4
118
amt-tiltaksarrangor-bff
MIT License
app/src/main/java/com/franlopez/mvpkotlin/view/base/contract/BaseView.kt
franlopjur
118,064,184
false
null
package com.franlopez.mvpkotlin.view.base.contract import android.content.Context import com.franlopez.mvpkotlin.view.base.presenter.BasePresenter interface BaseView { fun showError(error: String) fun setPresenter(presenter: BasePresenter<*>) fun getContext(): Context }
0
Kotlin
2
2
443a13e235e0366ec94ae406dcad22040e85e294
284
MVPKotlin
Apache License 2.0
android/src/main/kotlin/com/example/get_share_options/data_classes/activity_info.kt
MoGaaber
301,588,930
false
null
package com.example.get_share_options.data_classes import android.content.pm.ActivityInfo data class ActivityInfoData(val name :String, val packageName :String) { constructor(activityInfo: ActivityInfo):this(activityInfo.name,activityInfo.packageName) companion object { fun from(map: Map<String, String>) = object { val name by map val packageName by map val data = ActivityInfoData(name, packageName) }.data } fun toMap(): Map<String, String> { return mapOf("name" to name, "packageName" to packageName) } }
0
Kotlin
0
0
418d2dc2257639b8f90457e508751a5ebbdc71f2
600
share_options
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/filled/Drone.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.filled import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Filled.Drone: ImageVector get() { if (_drone != null) { return _drone!! } _drone = Builder(name = "Drone", 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(18.293f, 19.707f) lineToRelative(1.414f, -1.414f) lineToRelative(-3.586f, -3.585f) curveToRelative(-0.723f, -0.723f, -1.121f, -1.685f, -1.121f, -2.708f) reflectiveCurveToRelative(0.398f, -1.984f, 1.121f, -2.707f) lineToRelative(3.586f, -3.586f) lineToRelative(-1.414f, -1.414f) lineToRelative(-3.586f, 3.586f) curveToRelative(-1.446f, 1.447f, -3.968f, 1.446f, -5.415f, 0.0f) lineToRelative(-3.585f, -3.586f) lineToRelative(-1.414f, 1.414f) lineToRelative(3.585f, 3.586f) curveToRelative(0.723f, 0.724f, 1.122f, 1.685f, 1.122f, 2.707f) reflectiveCurveToRelative(-0.398f, 1.984f, -1.122f, 2.708f) lineToRelative(-3.585f, 3.585f) lineToRelative(1.414f, 1.414f) lineToRelative(3.585f, -3.585f) curveToRelative(1.447f, -1.446f, 3.967f, -1.446f, 5.415f, 0.0f) lineToRelative(3.586f, 3.585f) close() moveTo(14.06f, 5.572f) curveToRelative(-0.169f, -1.465f, 0.286f, -2.989f, 1.407f, -4.11f) curveToRelative(1.949f, -1.949f, 5.122f, -1.949f, 7.071f, 0.0f) curveToRelative(1.949f, 1.949f, 1.949f, 5.122f, 0.0f, 7.071f) curveToRelative(-1.231f, 1.231f, -2.948f, 1.68f, -4.538f, 1.357f) curveToRelative(1.226f, -1.047f, 2.558f, -2.205f, 3.124f, -2.771f) curveToRelative(1.17f, -1.17f, 1.17f, -3.073f, 0.0f, -4.243f) curveToRelative(-1.17f, -1.17f, -3.073f, -1.17f, -4.243f, 0.0f) curveToRelative(-0.575f, 0.575f, -1.762f, 1.7f, -2.821f, 2.696f) close() moveTo(1.462f, 8.533f) curveTo(-0.487f, 6.584f, -0.487f, 3.411f, 1.462f, 1.462f) curveTo(3.411f, -0.487f, 6.584f, -0.487f, 8.533f, 1.462f) curveToRelative(1.231f, 1.231f, 1.68f, 2.948f, 1.357f, 4.538f) curveToRelative(-1.047f, -1.226f, -2.205f, -2.558f, -2.771f, -3.124f) curveToRelative(-1.17f, -1.17f, -3.073f, -1.17f, -4.243f, 0.0f) curveToRelative(-1.17f, 1.17f, -1.17f, 3.073f, 0.0f, 4.243f) curveToRelative(0.575f, 0.575f, 1.7f, 1.762f, 2.696f, 2.821f) curveToRelative(-1.465f, 0.169f, -2.989f, -0.286f, -4.11f, -1.407f) close() moveTo(22.538f, 15.467f) curveToRelative(1.949f, 1.949f, 1.949f, 5.122f, 0.0f, 7.071f) curveToRelative(-1.949f, 1.949f, -5.122f, 1.949f, -7.071f, 0.0f) curveToRelative(-1.121f, -1.121f, -1.576f, -2.645f, -1.407f, -4.11f) curveToRelative(1.06f, 0.996f, 2.247f, 2.121f, 2.821f, 2.696f) curveToRelative(1.17f, 1.17f, 3.073f, 1.17f, 4.243f, 0.0f) curveToRelative(1.17f, -1.17f, 1.17f, -3.073f, 0.0f, -4.243f) curveToRelative(-0.566f, -0.566f, -1.898f, -1.724f, -3.124f, -2.771f) curveToRelative(1.59f, -0.323f, 3.308f, 0.126f, 4.538f, 1.357f) close() moveTo(9.89f, 18.0f) curveToRelative(0.323f, 1.59f, -0.126f, 3.308f, -1.357f, 4.538f) curveToRelative(-1.949f, 1.949f, -5.122f, 1.949f, -7.071f, 0.0f) curveToRelative(-1.949f, -1.949f, -1.949f, -5.122f, 0.0f, -7.071f) curveToRelative(1.121f, -1.121f, 2.645f, -1.576f, 4.11f, -1.407f) curveToRelative(-0.996f, 1.06f, -2.121f, 2.247f, -2.696f, 2.821f) curveToRelative(-1.17f, 1.17f, -1.17f, 3.073f, 0.0f, 4.243f) curveToRelative(1.17f, 1.17f, 3.073f, 1.17f, 4.243f, 0.0f) curveToRelative(0.566f, -0.566f, 1.724f, -1.898f, 2.771f, -3.124f) close() } } .build() return _drone!! } private var _drone: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
5,130
icons
MIT License
app/src/main/java/io/github/achmadhafid/sample_app/MainActivity.kt
AchmadHafid
205,050,508
false
null
package io.github.achmadhafid.sample_app import android.os.Bundle import android.view.Menu import android.view.MenuItem import androidx.appcompat.app.AppCompatActivity import io.github.achmadhafid.sample_app.activity.DemoActivity import io.github.achmadhafid.sample_app.databinding.ActivityMainBinding import io.github.achmadhafid.sample_app.fragment.FragmentDemoActivity import io.github.achmadhafid.sample_app.service.ServiceDemoActivity import io.github.achmadhafid.simpleloc.SimpleLocClient import io.github.achmadhafid.simplepref.SimplePref import io.github.achmadhafid.simplepref.simplePref import io.github.achmadhafid.zpack.extension.intent import io.github.achmadhafid.zpack.extension.toggleTheme class MainActivity : AppCompatActivity(), SimpleLocClient, SimplePref { //region Preference private var appTheme: Int? by simplePref(PREFERENCE_KEY_THEME) //endregion //region View Binding private val binding: ActivityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } //endregion //region Lifecycle Callback override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) setSupportActionBar(binding.toolbar) binding.apply { btnDemoActivity.setOnClickListener { startActivity(intent<DemoActivity>()) } btnDemoFragment.setOnClickListener { startActivity(intent<FragmentDemoActivity>()) } btnDemoService.setOnClickListener { startActivity(intent<ServiceDemoActivity>()) } } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.main_toolbar, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.action_toggle_theme -> { appTheme = toggleTheme() true } else -> super.onOptionsItemSelected(item) } //endregion }
0
Kotlin
0
1
1e3764623c66d41679407d870c77d5cf9245d675
2,094
SimpleLoc
Apache License 2.0
increase-kotlin-core/src/test/kotlin/com/increase/api/services/blocking/CardDisputeServiceTest.kt
Increase
614,596,742
false
null
// File generated from our OpenAPI spec by Stainless. package com.increase.api.services.blocking import com.increase.api.TestServerExtension import com.increase.api.client.okhttp.IncreaseOkHttpClient import com.increase.api.models.* import com.increase.api.models.CardDisputeListParams import org.junit.jupiter.api.Test import org.junit.jupiter.api.extension.ExtendWith @ExtendWith(TestServerExtension::class) class CardDisputeServiceTest { @Test fun callCreate() { val client = IncreaseOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val cardDisputeService = client.cardDisputes() val cardDispute = cardDisputeService.create( CardDisputeCreateParams.builder() .disputedTransactionId("string") .explanation("x") .build() ) println(cardDispute) cardDispute.validate() } @Test fun callRetrieve() { val client = IncreaseOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val cardDisputeService = client.cardDisputes() val cardDispute = cardDisputeService.retrieve( CardDisputeRetrieveParams.builder().cardDisputeId("string").build() ) println(cardDispute) cardDispute.validate() } @Test fun callList() { val client = IncreaseOkHttpClient.builder() .baseUrl(TestServerExtension.BASE_URL) .apiKey("My API Key") .build() val cardDisputeService = client.cardDisputes() val cardDisputeList = cardDisputeService.list(CardDisputeListParams.builder().build()) println(cardDisputeList) cardDisputeList.data().forEach { it.validate() } } }
2
null
0
5
dc1361d08cb41ff45817c2e7638f53356f15cf8e
1,996
increase-kotlin
Apache License 2.0
src/main/kotlin/DiceParser.kt
LeoColman
371,689,729
false
{"Java": 15344, "Kotlin": 14350, "ANTLR": 852}
/* * Copyright 2021 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package br.com.colman.dicehelper import org.antlr.v4.runtime.CharStreams.fromString import org.antlr.v4.runtime.CommonTokenStream /** * Returns all dice in a dice notation ignoring operations * * Useful when you're rolling simple dice that doesn't require notation evaluation. Usually followed by [rollAll] to * obtain results. * * "17d4".dice() // Returns listOf(RandomDice(amount = 17, mqxFaceValue = 4)) */ public fun String.dice(): List<Dice> = diceNotation().allDice /** * Parses a dice notation * * Useful to parse more complex dice notation. Usually followed by [DiceNotation.roll] to roll all the dice in the * notation and evaluate the expression to find the final result. * * "5d4 + 2d5 - 10".diceNotation().roll() // Work with results */ public fun String.diceNotation(): DiceNotation = DiceNotation(diceNotationParser.notation()) private val String.diceNotationParser get() = DiceNotationParser(CommonTokenStream(DiceNotationLexer(fromString(this))))
10
Java
1
5
b46186698681384f93b19e3e49e258602bc03acf
1,578
dice-helper
Apache License 2.0
core-android-api/src/main/java/com/jraska/github/client/core/android/HasViewModelFactory.kt
jraska
52,918,490
false
{"Kotlin": 377058}
package com.jraska.github.client.core.android import androidx.fragment.app.FragmentActivity import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider interface HasViewModelFactory { fun factory(): ViewModelProvider.Factory } fun <T : ViewModel> FragmentActivity.viewModel(modelClass: Class<T>): T { val factory = (application as HasViewModelFactory).factory() return ViewModelProvider(this, factory).get(modelClass) }
6
Kotlin
27
228
f68f30a22be01b18647025da513276a995aed9a2
449
github-client
Apache License 2.0
app/src/main/java/com/nux/studio/dvor/ui/components/molecules/games/InstalledGamesList.kt
AKSUMRUS
611,184,462
false
null
package com.nux.studio.dvor.ui.components.molecules.games import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.navigation.NavController import com.nux.studio.dvor.R import com.nux.studio.dvor.data.local.game.Game import com.nux.studio.dvor.data.local.profile.ProfileEvent import com.nux.studio.dvor.presentation.GamesViewModel import com.nux.studio.dvor.presentation.ProfileViewModel import com.nux.studio.dvor.presentation.UserViewModel import com.nux.studio.dvor.ui.components.molecules.EmptyScreen import com.nux.studio.dvor.ui.navigation.ScreenRoutes @Composable fun InstalledGamesList( games: List<Game>, navController: NavController, gamesViewModel: GamesViewModel, profileViewModel: ProfileViewModel, userViewModel: UserViewModel ) { fun onClick(packageName: String) { gamesViewModel.getGame(packageName) profileViewModel.onEvent( ProfileEvent.InviteFriends( accessToken = profileViewModel.state.profile!!.access_token, friends_ids = userViewModel.state.inviteFriends.toList(), app_id = gamesViewModel.state.game!!.id ) ) navController.navigate(ScreenRoutes.FINISH_INVITING_FRIENDS) { popUpTo(ScreenRoutes.FINISH_INVITING_FRIENDS) launchSingleTop = true } } LazyVerticalGrid( columns = GridCells.Fixed(2), contentPadding = PaddingValues(top = 80.dp, start = 0.dp, end = 0.dp), modifier = Modifier, ) { item( span = { GridItemSpan(2) }, ) { Column( modifier = Modifier .fillMaxWidth() .padding(start = 20.dp, end = 20.dp), ) { TitleQuickGame( title = stringResource(id = R.string.choose_game), ) } } if (games.isEmpty()) { // gamesViewModel.onEvent() item(span = { GridItemSpan(2) }) { EmptyScreen(title = stringResource(id = R.string.not_online_games)) } } else { items(games) { game -> GameInList( packageName = game.android_package_name, name = game.name, icon = game.icon_preview!!, onClick = { onClick(game.android_package_name) }, ) } } } }
0
null
0
0
f9b171c33807325ad068e79fa3f9dd52f685f4d1
3,007
nux-application
MIT License
browser-kotlin/src/jsMain/kotlin/web/remoteplayback/RemotePlaybackState.kt
karakum-team
393,199,102
false
{"Kotlin": 6272741}
// Automatically generated - do not modify! package web.remoteplayback import seskar.js.JsValue sealed external interface RemotePlaybackState { companion object { @JsValue("connected") val connected: RemotePlaybackState @JsValue("connecting") val connecting: RemotePlaybackState @JsValue("disconnected") val disconnected: RemotePlaybackState } }
0
Kotlin
8
36
95b065622a9445caf058ad2581f4c91f9e2b0d91
407
types-kotlin
Apache License 2.0
domain/src/main/kotlin/com/yapp/bol/group/Group.kt
YAPP-Github
634,125,780
false
null
package com.yapp.bol.group import com.yapp.bol.InvalidGroupDescriptionException import com.yapp.bol.InvalidGroupNameException import com.yapp.bol.InvalidGroupOrganizationException @JvmInline value class GroupId(val value: Long) data class Group( val id: GroupId = GroupId(0), val name: String, val description: String, val organization: String?, val profileImageUrl: String = DEFAULT_PROFILE_IMAGE_URL, val accessCode: String = generateAccessCode(), ) { init { if (name.length > MAX_NAME_LENGTH) { throw InvalidGroupNameException } if (description.length > MAX_DESCRIPTION_LENGTH) { throw InvalidGroupDescriptionException } if (organization?.length ?: 0 > MAX_ORGANIZATION_LENGTH) { throw InvalidGroupOrganizationException } } companion object { const val MAX_NAME_LENGTH = 14 const val MAX_DESCRIPTION_LENGTH = 72 const val MAX_ORGANIZATION_LENGTH = 15 const val ACCESS_CODE_LENGTH = 6 const val DEFAULT_PROFILE_IMAGE_URL = "https://github.com/YAPP-Github" + "/22nd-Android-Team-2-BE" + "/assets/46865281/2a3caefb-e0ab-4f60-b745-273a889f0c96" // FIXME: 임시 이미지 private fun generateAccessCode(): String { val chars = ('A'..'Z') + ('0'..'9') return (1..ACCESS_CODE_LENGTH) .map { chars.random() } .joinToString("") } } }
4
Kotlin
0
9
0e61952c5f0b448737de1729f0df9a376875577e
1,508
22nd-Android-Team-2-BE
Apache License 2.0
plugins/kotlin/fir/testData/quickDoc/JavaClassConstructorUsedInKotlin.kt
ingokegel
72,937,917
false
null
fun testing() { SomeClassWithParen("param", 1<caret>) } //INFO: <div class='definition'><pre><i><span style="color:#808000;">@</span><a href="psi_element://org.jetbrains.annotations.Contract"><code><span style="color:#808000;">Contract</span></code></a><span style="">(</span><span style="">pure</span><span style=""> = </span><span style="color:#000080;font-weight:bold;">true</span><span style="">)</span></i><sup><font color="808080" size="3"><i>i</i></font></sup><a href="inferred.annotations"><icon src="AllIcons.Ide.External_link_arrow"></a>&nbsp; //INFO: <span style="color:#000080;font-weight:bold;">public</span>&nbsp;<span style="color:#000000;">SomeClassWithParen</span><span style="">(</span><br> <a href="psi_element://java.lang.String"><code><span style="color:#000000;">String</span></code></a>&nbsp;<span style="">str</span><span style="">,</span> //INFO: <span style="color:#000080;font-weight:bold;">int</span>&nbsp;<span style="">num</span><br><span style="">)</span></pre></div><table class='sections'><p></table><div class="bottom"><icon src="AllIcons.Nodes.Class">&nbsp;<a href="psi_element://SomeClassWithParen"><code><span style="color:#000000;">SomeClassWithParen</span></code></a></div>
284
null
5162
2
b07eabd319ad5b591373d63c8f502761c2b2dfe8
1,225
intellij-community
Apache License 2.0
app/src/main/java/org/fossasia/openevent/general/auth/ProfileFragment.kt
G-LOKi
178,464,508
true
{"Kotlin": 342899, "Java": 3836, "Shell": 3765}
package org.fossasia.openevent.general.auth import androidx.appcompat.app.AlertDialog import android.content.ActivityNotFoundException import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.lifecycle.Observer import androidx.navigation.Navigation.findNavController import com.squareup.picasso.Picasso import kotlinx.android.synthetic.main.fragment_profile.view.profileCoordinatorLayout import kotlinx.android.synthetic.main.fragment_profile.view.avatar import kotlinx.android.synthetic.main.fragment_profile.view.email import kotlinx.android.synthetic.main.fragment_profile.view.name import kotlinx.android.synthetic.main.fragment_profile.view.progressBar import kotlinx.android.synthetic.main.fragment_profile.view.editProfileRL import kotlinx.android.synthetic.main.fragment_profile.view.logoutLL import kotlinx.android.synthetic.main.fragment_profile.view.manageEventsLL import kotlinx.android.synthetic.main.fragment_profile.view.settingsLL import kotlinx.android.synthetic.main.fragment_profile.view.ticketIssuesLL import kotlinx.android.synthetic.main.fragment_profile.view.loginButton import org.fossasia.openevent.general.CircleTransform import org.fossasia.openevent.general.R import org.fossasia.openevent.general.utils.Utils import org.fossasia.openevent.general.utils.Utils.requireDrawable import org.fossasia.openevent.general.utils.extensions.nonNull import org.fossasia.openevent.general.utils.nullToEmpty import org.koin.androidx.viewmodel.ext.android.viewModel import org.fossasia.openevent.general.utils.Utils.setToolbar import org.jetbrains.anko.design.snackbar const val PROFILE_FRAGMENT = "profileFragment" class ProfileFragment : Fragment() { private val profileViewModel by viewModel<ProfileViewModel>() private lateinit var rootView: View private var emailSettings: String? = null private fun redirectToLogin() { findNavController(rootView).navigate(ProfileFragmentDirections.actionProfileToAuth(null, PROFILE_FRAGMENT)) } private fun redirectToEventsFragment() { findNavController(rootView).popBackStack(R.id.eventsFragment, false) } override fun onStart() { super.onStart() handleLayoutVisibility(profileViewModel.isLoggedIn()) } private fun handleLayoutVisibility(isLoggedIn: Boolean) { rootView.editProfileRL.isVisible = isLoggedIn rootView.logoutLL.isVisible = isLoggedIn rootView.loginButton.isVisible = !isLoggedIn } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { rootView = inflater.inflate(R.layout.fragment_profile, container, false) profileViewModel.progress .nonNull() .observe(viewLifecycleOwner, Observer { rootView.progressBar.isVisible = it }) profileViewModel.error .nonNull() .observe(viewLifecycleOwner, Observer { rootView.profileCoordinatorLayout.snackbar(it) }) profileViewModel.user .nonNull() .observe(viewLifecycleOwner, Observer { rootView.name.text = "${it.firstName.nullToEmpty()} ${it.lastName.nullToEmpty()}" rootView.email.text = it.email emailSettings = it.email Picasso.get() .load(it.avatarUrl) .placeholder(requireDrawable(requireContext(), R.drawable.ic_account_circle_grey)) .transform(CircleTransform()) .into(rootView.avatar) rootView.editProfileRL.setOnClickListener { findNavController(rootView).navigate(ProfileFragmentDirections.actionProfileToEditProfile()) } }) if (profileViewModel.isLoggedIn()) fetchProfile() rootView.manageEventsLL.setOnClickListener { startOrgaApp("com.eventyay.organizer") } rootView.settingsLL.setOnClickListener { findNavController(rootView).navigate(ProfileFragmentDirections.actionProfileToSettings(emailSettings)) } rootView.ticketIssuesLL.setOnClickListener { Utils.openUrl(requireContext(), resources.getString(R.string.ticket_issues_url)) } rootView.logoutLL.setOnClickListener { showLogoutDialog() } rootView.loginButton.setOnClickListener { redirectToLogin() } return rootView } private fun startOrgaApp(packageName: String) { val manager = activity?.packageManager try { val intent = manager?.getLaunchIntentForPackage(packageName) ?: throw ActivityNotFoundException() intent.addCategory(Intent.CATEGORY_LAUNCHER) startActivity(intent) } catch (e: ActivityNotFoundException) { showInMarket(packageName) } } private fun showInMarket(packageName: String) { try { val intent = Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=$packageName")) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK startActivity(intent) } catch (e: ActivityNotFoundException) { val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=$packageName")) intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK startActivity(intent) } } private fun fetchProfile() { if (!profileViewModel.isLoggedIn()) return rootView.progressBar.isIndeterminate = true profileViewModel.fetchProfile() } override fun onResume() { setToolbar(activity, getString(R.string.profile), false) super.onResume() } private fun showLogoutDialog() { AlertDialog.Builder(requireContext()).setMessage(resources.getString(R.string.message)) .setPositiveButton(resources.getString(R.string.logout)) { _, _ -> if (profileViewModel.isLoggedIn()) { profileViewModel.logout() redirectToEventsFragment() } } .setNegativeButton(resources.getString(R.string.cancel)) { dialog, _ -> dialog.cancel() } .show() } }
0
Kotlin
0
1
7e6d70dbfcbeb014ac9dc02ccfd66cc575697c87
6,532
open-event-android
Apache License 2.0
Android/examples/demo/src/main/java/com/didi/aoe/examples/demo/features/classification/MnnClassifier.kt
benson3
228,999,923
true
{"C++": 330969, "Java": 205329, "C": 197512, "Objective-C": 156327, "Kotlin": 78179, "Objective-C++": 19382, "Ruby": 13304, "Python": 6162, "Dart": 3291, "CMake": 1580, "Shell": 1286, "Swift": 927}
/* * Copyright 2019 The AoE Authors. * * 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.didi.aoe.examples.demo.features.classification import android.content.Context import android.graphics.Bitmap import com.didi.aoe.features.recognize.RecognizeMnnInterpreter import com.didi.aoe.library.core.AoeClient /** * * * @author noctis * @since 1.1.0 */ class MnnClassifier constructor(context: Context) : Classifier { private val mClient: AoeClient = AoeClient(context, "recognize-mnn", AoeClient.Options() .setInterpreter(RecognizeMnnInterpreter::class.java) .useRemoteService(false), "recognize-mnn") override fun init(listener: AoeClient.OnInitListener) { mClient.init(listener) } override fun classifier(bitmap: Bitmap): Any? { return mClient.process(bitmap) } override fun release() { mClient.release() } }
0
null
0
0
e089ff5a77c6445a7a45c8ce2c691a70c09fd76a
1,453
AoE
Apache License 2.0
src/main/kotlin/de/hennihaus/services/StatisticService.kt
hennihaus
484,714,079
false
null
package de.hennihaus.services import de.hennihaus.bamdatamodel.Statistic import de.hennihaus.repositories.StatisticRepository import de.hennihaus.repositories.StatisticRepository.Companion.ZERO_REQUESTS import de.hennihaus.utils.toUUID import io.ktor.server.plugins.NotFoundException import org.koin.core.annotation.Single @Single class StatisticService(private val repository: StatisticRepository) { suspend fun saveStatistics(bankId: String) = bankId.toUUID { uuid -> repository.saveAll( bankId = uuid, ) } suspend fun deleteStatistics(bankId: String) = bankId.toUUID { uuid -> repository.deleteAll( bankId = uuid, ) } suspend fun recreateStatistics(limit: Long) = repository.recreateAll( limit = limit.takeIf { limit > ZERO_REQUESTS } ?: ZERO_REQUESTS, ) suspend fun incrementRequest(statistic: Statistic): Statistic { return repository.incrementRequest(entry = statistic) ?: throw NotFoundException(message = STATISTIC_NOT_FOUND_MESSAGE) } companion object { const val STATISTIC_NOT_FOUND_MESSAGE = "statistic not found by bankId and teamId" } }
32
Kotlin
0
0
d9e57a5ca5f0712671cf4e26c578c1fb22c0262f
1,189
bamconfigbackend
Apache License 2.0
app/src/main/java/io/vicknesh/passportkyc/ui/validators/DateRule.kt
roninprogrammer
350,161,963
false
null
package io.vicknesh.passportkyc.ui.validators import android.content.Context import androidx.appcompat.widget.AppCompatEditText import com.mobsandgeeks.saripaar.QuickRule import io.vicknesh.passportkyc.R import java.util.regex.Pattern class DateRule : QuickRule<AppCompatEditText>() { override fun isValid(editText: AppCompatEditText): Boolean { val text = editText.text!!.toString().trim { it <= ' ' } val patternDate = Pattern.compile(REGEX) val matcherDate = patternDate.matcher(text) return matcherDate.find() } override fun getMessage(context: Context): String { return context.getString(R.string.error_validation_date) } companion object { private val REGEX = "[0-9]{6}$" } }
0
Kotlin
0
0
d7172d891072db54eba5fa5d2262aa0a56934063
760
kyc-passport-android
Apache License 2.0
periodisering/test/no/nav/tiltakspenger/libs/periodisering/periode/PeriodeTest.kt
navikt
585,932,206
false
{"Kotlin": 206433, "Shell": 1193}
package no.nav.tiltakspenger.libs.periodisering.periode import io.kotest.matchers.shouldBe import no.nav.tiltakspenger.libs.periodisering.Periode import no.nav.tiltakspenger.libs.periodisering.inneholderOverlapp import no.nav.tiltakspenger.libs.periodisering.juni import no.nav.tiltakspenger.libs.periodisering.leggSammen import no.nav.tiltakspenger.libs.periodisering.leggSammenMed import no.nav.tiltakspenger.libs.periodisering.mai import no.nav.tiltakspenger.libs.periodisering.overlappendePerioder import no.nav.tiltakspenger.libs.periodisering.trekkFra import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertNotEquals import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.Test import java.time.LocalDate class PeriodeTest { private val periode1 = Periode(fraOgMed = 13.mai(2022), tilOgMed = 18.mai(2022)) private val periode2 = Periode(fraOgMed = 17.mai(2022), tilOgMed = 21.mai(2022)) private val periode3 = Periode(fraOgMed = 19.mai(2022), tilOgMed = 20.mai(2022)) @Test fun inneholderHele() { assertTrue(periode1.inneholderHele(periode1)) assertTrue(periode2.inneholderHele(periode3)) assertFalse(periode1.inneholderHele(periode2)) } @Test fun overlapperMed() { assertTrue(periode1.overlapperMed(periode1)) assertTrue(periode1.overlapperMed(periode2)) assertFalse(periode1.overlapperMed(periode3)) } @Test fun intersect() { val fellesperiode = Periode(fraOgMed = 17.mai(2022), tilOgMed = 18.mai(2022)) assertEquals(periode1, periode1.overlappendePeriode(periode1)) assertEquals(fellesperiode, periode1.overlappendePeriode(periode2)) assertEquals(fellesperiode, periode2.overlappendePeriode(periode1)) assertNotEquals(fellesperiode, periode2.overlappendePeriode(periode2)) } @Test fun overlapperIkkeMed() { val periodeSomIkkeOverlapper = Periode(fraOgMed = 13.mai(2022), tilOgMed = 16.mai(2022)) assertEquals(periodeSomIkkeOverlapper, periode1.ikkeOverlappendePeriode(periode2).first()) } @Test fun `to komplett overlappende perioder skal gi tomt svar`() { assertEquals(emptyList<Periode>(), periode1.ikkeOverlappendePeriode(periode1)) } @Test fun `to overlappende perioder`() { val periodeEn = Periode(fraOgMed = 13.mai(2022), tilOgMed = 16.mai(2022)) val periodeTo = Periode(fraOgMed = 13.mai(2022), tilOgMed = 15.mai(2022)) val fasit = Periode(fraOgMed = 16.mai(2022), tilOgMed = 16.mai(2022)) assertEquals(fasit, periodeEn.ikkeOverlappendePeriode(periodeTo).first()) assertEquals(1, periodeEn.ikkeOverlappendePeriode(periodeTo).size) } @Test fun `ikkeOverlappendePerioder fjerner overlapp mellom flere perioder --fengsel---kvp---`() { val periodeEn = Periode(fraOgMed = 1.mai(2022), tilOgMed = 15.mai(2022)) val fengselPeriode = Periode(fraOgMed = 5.mai(2022), tilOgMed = 6.mai(2022)) val kvpPeriode = Periode(fraOgMed = 11.mai(2022), tilOgMed = 12.mai(2022)) val result = periodeEn.ikkeOverlappendePerioder( listOf( fengselPeriode, kvpPeriode, ), ) assertEquals(3, result.size) assertEquals( listOf( Periode(fraOgMed = 1.mai(2022), tilOgMed = 4.mai(2022)), Periode(fraOgMed = 7.mai(2022), tilOgMed = 10.mai(2022)), Periode(fraOgMed = 13.mai(2022), tilOgMed = 15.mai(2022)), ), result, ) } @Test fun `ikkeOverlappendePerioder fjerner overlapp mellom flere perioder --fengselOgKvp---`() { val periodeEn = Periode(fraOgMed = 1.mai(2022), tilOgMed = 15.mai(2022)) val fengselPeriode = Periode(fraOgMed = 5.mai(2022), tilOgMed = 11.mai(2022)) val kvpPeriode = Periode(fraOgMed = 10.mai(2022), tilOgMed = 12.mai(2022)) val result = periodeEn.ikkeOverlappendePerioder( listOf( fengselPeriode, kvpPeriode, ), ) assertEquals(2, result.size) assertEquals( listOf( Periode(fraOgMed = 1.mai(2022), tilOgMed = 4.mai(2022)), Periode(fraOgMed = 13.mai(2022), tilOgMed = 15.mai(2022)), ), result, ) } @Test fun `man kan trekke en periode fra en annen periode`() { val periodeEn = Periode(fraOgMed = 3.mai(2022), tilOgMed = 15.mai(2022)) val periodeTo = Periode(fraOgMed = 6.mai(2022), tilOgMed = 12.mai(2022)) val perioder = periodeEn.trekkFra(listOf(periodeTo)) assertEquals(2, perioder.size) assertEquals(3.mai(2022), perioder[0].fraOgMed) assertEquals(5.mai(2022), perioder[0].tilOgMed) assertEquals(13.mai(2022), perioder[1].fraOgMed) assertEquals(15.mai(2022), perioder[1].tilOgMed) } @Test fun `man kan trekke en periode fra en annen ikke-overlappende periode`() { val periodeEn = Periode(fraOgMed = 3.mai(2022), tilOgMed = 15.mai(2022)) val periodeTo = Periode(fraOgMed = 6.mai(2022), tilOgMed = 18.mai(2022)) val perioder = periodeEn.trekkFra(listOf(periodeTo)) assertEquals(1, perioder.size) assertEquals(3.mai(2022), perioder[0].fraOgMed) assertEquals(5.mai(2022), perioder[0].tilOgMed) } @Test fun `man kan trekke flere perioder fra en annen periode`() { val periodeEn = Periode(fraOgMed = 3.mai(2022), tilOgMed = 15.mai(2022)) val periodeTo = Periode(fraOgMed = 6.mai(2022), tilOgMed = 8.mai(2022)) val periodeTre = Periode(fraOgMed = 10.mai(2022), tilOgMed = 12.mai(2022)) val perioder = periodeEn.trekkFra(listOf(periodeTo, periodeTre)) assertEquals(3, perioder.size) assertEquals(3.mai(2022), perioder[0].fraOgMed) assertEquals(5.mai(2022), perioder[0].tilOgMed) assertEquals(9.mai(2022), perioder[1].fraOgMed) assertEquals(9.mai(2022), perioder[1].tilOgMed) assertEquals(13.mai(2022), perioder[2].fraOgMed) assertEquals(15.mai(2022), perioder[2].tilOgMed) } @Test fun `man kan trekke flere connected perioder fra en annen periode`() { val periodeEn = Periode(fraOgMed = 3.mai(2022), tilOgMed = 15.mai(2022)) val periodeTo = Periode(fraOgMed = 6.mai(2022), tilOgMed = 9.mai(2022)) val periodeTre = Periode(fraOgMed = 10.mai(2022), tilOgMed = 12.mai(2022)) val perioder = periodeEn.trekkFra(listOf(periodeTo, periodeTre)) assertEquals(2, perioder.size) assertEquals(3.mai(2022), perioder[0].fraOgMed) assertEquals(5.mai(2022), perioder[0].tilOgMed) assertEquals(13.mai(2022), perioder[1].fraOgMed) assertEquals(15.mai(2022), perioder[1].tilOgMed) } @Test fun `man kan ikke trekke flere overlappende perioder fra en annen periode`() { val periodeEn = Periode(fraOgMed = 3.mai(2022), tilOgMed = 15.mai(2022)) val periodeTo = Periode(fraOgMed = 6.mai(2022), tilOgMed = 10.mai(2022)) val periodeTre = Periode(fraOgMed = 9.mai(2022), tilOgMed = 12.mai(2022)) Assertions.assertThrows(IllegalArgumentException::class.java) { periodeEn.trekkFra(listOf(periodeTo, periodeTre)) } } @Test fun `hvis man legger sammen to perioder som overlapper får man en periode`() { val periodeEn = Periode(fraOgMed = 3.mai(2022), tilOgMed = 15.mai(2022)) val periodeTo = Periode(fraOgMed = 10.mai(2022), tilOgMed = 20.mai(2022)) val periodeTre = Periode(fraOgMed = 3.mai(2022), tilOgMed = 20.mai(2022)) assertEquals(periodeTre, listOf(periodeEn, periodeTo).leggSammen().first()) } @Test fun `hvis man legger sammen to tilstøtende perioder får man en periode`() { val periodeEn = Periode(fraOgMed = 6.mai(2022), tilOgMed = 15.mai(2022)) val periodeTo = Periode(fraOgMed = 1.mai(2022), tilOgMed = 5.mai(2022)) val periodeTre = Periode(fraOgMed = 1.mai(2022), tilOgMed = 15.mai(2022)) assertEquals(1, listOf(periodeEn, periodeTo).leggSammen().size) assertEquals(periodeTre, listOf(periodeEn, periodeTo).leggSammen().first()) } @Test fun `hvis man legger sammen to tilstøtende perioder og en tredje separat periode får man to perioder`() { val periodeEn = Periode(fraOgMed = 6.mai(2022), tilOgMed = 15.mai(2022)) val periodeTo = Periode(fraOgMed = 1.mai(2022), tilOgMed = 5.mai(2022)) val periodeFasitEn = Periode(fraOgMed = 1.mai(2022), tilOgMed = 15.mai(2022)) val periodeTre = Periode(fraOgMed = 18.mai(2022), tilOgMed = 20.mai(2022)) val periodeFasitTo = Periode(fraOgMed = 18.mai(2022), tilOgMed = 20.mai(2022)) assertEquals(periodeFasitEn, listOf(periodeEn, periodeTo, periodeTre).leggSammen().first()) assertEquals(periodeFasitTo, listOf(periodeEn, periodeTo, periodeTre).leggSammen().last()) } @Test fun `to overlappende perioder gir overlapp`() { val periodeEn = Periode(fraOgMed = 6.mai(2022), tilOgMed = 15.mai(2022)) val periodeTo = Periode(fraOgMed = 1.mai(2022), tilOgMed = 7.mai(2022)) assertEquals(true, listOf(periodeEn, periodeTo).inneholderOverlapp()) } @Test fun `to ikke-overlappende perioder gir ikke overlapp`() { val periodeEn = Periode(fraOgMed = 8.mai(2022), tilOgMed = 15.mai(2022)) val periodeTo = Periode(fraOgMed = 1.mai(2022), tilOgMed = 7.mai(2022)) assertEquals(false, listOf(periodeEn, periodeTo).inneholderOverlapp()) } @Test fun `tre ikke-overlappende perioder der den tredje er mellom de to første gir ikke overlapp`() { val periodeEn = Periode(fraOgMed = 1.mai(2022), tilOgMed = 10.mai(2022)) val periodeTo = Periode(fraOgMed = 20.mai(2022), tilOgMed = 25.mai(2022)) val periodeTre = Periode(fraOgMed = 11.mai(2022), tilOgMed = 19.mai(2022)) assertEquals(false, listOf(periodeEn, periodeTo, periodeTre).inneholderOverlapp()) } @Test fun `tre ikke-overlappende perioder der den tredje med den andre gir overlapp`() { val periodeEn = Periode(fraOgMed = 1.mai(2022), tilOgMed = 10.mai(2022)) val periodeTo = Periode(fraOgMed = 20.mai(2022), tilOgMed = 25.mai(2022)) val periodeTre = Periode(fraOgMed = 11.mai(2022), tilOgMed = 20.mai(2022)) assertEquals(true, listOf(periodeEn, periodeTo, periodeTre).inneholderOverlapp()) } @Test fun testTrekkFraPerioder() { val perioder1 = listOf(Periode(LocalDate.of(2020, 10, 1), LocalDate.of(2023, 10, 10))) val perioder2 = listOf(Periode(LocalDate.of(2020, 10, 1), LocalDate.of(2023, 10, 10))) val tomPeriode = perioder1.trekkFra(perioder2) tomPeriode.size shouldBe 0 } @Test fun `perioder som er adjacent skal legges sammen og bli en periode`() { val periode1 = Periode(fraOgMed = 13.mai(2022), tilOgMed = 18.mai(2022)) val periode2 = Periode(fraOgMed = 19.mai(2022), tilOgMed = 21.mai(2022)) val periode3 = Periode(fraOgMed = 22.mai(2022), tilOgMed = 27.mai(2022)) val periode4 = Periode(fraOgMed = 27.mai(2022), tilOgMed = 30.mai(2022)) val nyePerioder = listOf(periode1, periode2).leggSammenMed(listOf(periode3, periode4)) nyePerioder.size shouldBe 1 nyePerioder.first() shouldBe Periode(fraOgMed = 13.mai(2022), tilOgMed = 30.mai(2022)) } @Test fun `perioder som er adjacent skal ikke ha noen overlappende periode`() { val periode1 = Periode(fraOgMed = 13.mai(2022), tilOgMed = 18.mai(2022)) val periode2 = Periode(fraOgMed = 19.mai(2022), tilOgMed = 21.mai(2022)) val periode3 = Periode(fraOgMed = 22.mai(2022), tilOgMed = 27.mai(2022)) val periode4 = Periode(fraOgMed = 27.mai(2022), tilOgMed = 30.mai(2022)) val overlappendePerioder = listOf(periode1, periode2).overlappendePerioder(listOf(periode3, periode4)) overlappendePerioder.size shouldBe 0 } @Test fun `perioder som er delvis overlappende skal ha en overlappende periode`() { val periode1 = Periode(fraOgMed = 13.mai(2022), tilOgMed = 18.mai(2022)) val periode2 = Periode(fraOgMed = 19.mai(2022), tilOgMed = 25.mai(2022)) val periode3 = Periode(fraOgMed = 22.mai(2022), tilOgMed = 23.mai(2022)) val periode4 = Periode(fraOgMed = 24.mai(2022), tilOgMed = 30.mai(2022)) val overlappendePerioder = listOf(periode1, periode2).overlappendePerioder(listOf(periode3, periode4)) overlappendePerioder.size shouldBe 1 overlappendePerioder.first() shouldBe Periode(fraOgMed = 22.mai(2022), tilOgMed = 25.mai(2022)) } @Test fun `perioder som er fullstendig overlappende skal ha en overlappende periode som er lik den minste perioden`() { val periode1 = Periode(fraOgMed = 13.mai(2022), tilOgMed = 25.mai(2022)) val periode2 = Periode(fraOgMed = 19.mai(2022), tilOgMed = 1.juni(2022)) val periode3 = Periode(fraOgMed = 22.mai(2022), tilOgMed = 23.mai(2022)) val periode4 = Periode(fraOgMed = 24.mai(2022), tilOgMed = 30.mai(2022)) val overlappendePerioder = listOf(periode1, periode2).overlappendePerioder(listOf(periode3, periode4)) overlappendePerioder.size shouldBe 1 overlappendePerioder.first() shouldBe Periode(fraOgMed = 22.mai(2022), tilOgMed = 30.mai(2022)) } @Test fun `overlappende perioder skal fungere uansett hvilken liste som er subjekt og objekt`() { val periode1 = Periode(fraOgMed = 13.mai(2022), tilOgMed = 25.mai(2022)) val periode2 = Periode(fraOgMed = 19.mai(2022), tilOgMed = 1.juni(2022)) val periode3 = Periode(fraOgMed = 22.mai(2022), tilOgMed = 23.mai(2022)) val periode4 = Periode(fraOgMed = 24.mai(2022), tilOgMed = 30.mai(2022)) val overlappendePerioder = listOf(periode1, periode2).overlappendePerioder(listOf(periode3, periode4)) val overlappendePerioder2 = listOf(periode3, periode4).overlappendePerioder(listOf(periode1, periode2)) overlappendePerioder.size shouldBe 1 overlappendePerioder2.size shouldBe 1 overlappendePerioder.first() shouldBe overlappendePerioder2.first() } @Test fun `perioder som er adjacent med periode skal ikke ha noen overlappende periode`() { val periode1 = Periode(fraOgMed = 13.mai(2022), tilOgMed = 21.mai(2022)) val periode3 = Periode(fraOgMed = 22.mai(2022), tilOgMed = 27.mai(2022)) val periode4 = Periode(fraOgMed = 27.mai(2022), tilOgMed = 30.mai(2022)) val overlappendePerioder = periode1.overlappendePerioder(listOf(periode3, periode4)) overlappendePerioder.size shouldBe 0 } @Test fun `perioder som er delvis overlappende med periode skal ha en overlappende periode`() { val periode1 = Periode(fraOgMed = 13.mai(2022), tilOgMed = 25.mai(2022)) val periode3 = Periode(fraOgMed = 22.mai(2022), tilOgMed = 23.mai(2022)) val periode4 = Periode(fraOgMed = 24.mai(2022), tilOgMed = 30.mai(2022)) val overlappendePerioder = periode1.overlappendePerioder(listOf(periode3, periode4)) overlappendePerioder.size shouldBe 1 overlappendePerioder.first() shouldBe Periode(fraOgMed = 22.mai(2022), tilOgMed = 25.mai(2022)) } @Test fun `perioder som er fullstendig overlappende med periode skal ha en overlappende periode som er lik den minste perioden`() { val periode1 = Periode(fraOgMed = 13.mai(2022), tilOgMed = 1.juni(2022)) val periode3 = Periode(fraOgMed = 22.mai(2022), tilOgMed = 23.mai(2022)) val periode4 = Periode(fraOgMed = 24.mai(2022), tilOgMed = 30.mai(2022)) val overlappendePerioder = periode1.overlappendePerioder(listOf(periode3, periode4)) overlappendePerioder.size shouldBe 1 overlappendePerioder.first() shouldBe Periode(fraOgMed = 22.mai(2022), tilOgMed = 30.mai(2022)) } @Test fun `Støtt Periode(MIN,MAX)`() { Periode(LocalDate.MIN, LocalDate.MAX) } }
0
Kotlin
0
0
5b1ad349d6e355fcc67d9150ac3654ecee834dac
16,354
tiltakspenger-libs
MIT License
ui/feature/list/src/main/kotlin/com/houlis/haris/picfind/feature/list/ui/viewmodel/PicturesViewModel.kt
HarisHoulis
595,512,452
false
{"Kotlin": 89899, "Shell": 135}
package com.houlis.haris.picfind.feature.list.ui.viewmodel import com.houlis.haris.picfind.data.pictures.api.model.Picture import com.houlis.haris.picfind.domain.coroutines.CloseableCoroutineScope import com.houlis.haris.picfind.feature.list.ui.viewmodel.PicturesAction.OnNavigated import com.houlis.haris.picfind.feature.list.ui.viewmodel.PicturesAction.OnPictureClicked import com.houlis.haris.picfind.feature.list.ui.viewmodel.PicturesAction.SearchFor import com.houlis.haris.picfind.ui.common.mvi.MviViewModel import com.houlis.haris.picfind.ui.common.mvi.MwProvider import com.houlis.haris.picfind.ui.common.navigation.PicIdArg import com.houlis.haris.picfind.ui.common.savedstate.SaveState import dagger.hilt.android.lifecycle.HiltViewModel import javax.inject.Inject @HiltViewModel internal class PicturesViewModel @Inject constructor( @PicIdArg private val picIdArg: String, private val saveState: SaveState<String>, scope: CloseableCoroutineScope, reducer: PicturesReducer, mwProvider: MwProvider<PicturesState, PicturesAction>, ) : MviViewModel<PicturesState, PicturesAction>(scope, reducer, mwProvider, PicturesState()) { fun searchFor(query: String) { dispatch(SearchFor(query)) } fun onPictureClicked(picture: Picture) { saveState(picIdArg, picture.id) dispatch(OnPictureClicked(picture)) } fun onNavigated() { dispatch(OnNavigated) } }
9
Kotlin
0
0
0e6b4ad83ace186069861f3fc61cd4b7480a2b51
1,431
PicFind
Apache License 2.0
portal/src/jvmMain/kotlin/com/sourceplusplus/portal/display/views/TracesView.kt
kaizhiyu
327,907,510
true
{"Kotlin": 571623, "Java": 10932, "CSS": 8168, "JavaScript": 3693, "HTML": 2027}
package com.sourceplusplus.portal.display.views import com.sourceplusplus.portal.model.TraceDisplayType import com.sourceplusplus.protocol.artifact.trace.TraceOrderType import com.sourceplusplus.protocol.artifact.trace.TraceResult import com.sourceplusplus.protocol.artifact.trace.TraceStack import com.sourceplusplus.protocol.artifact.trace.TraceStackPath import java.util.concurrent.ConcurrentHashMap import kotlin.collections.HashMap /** * Holds the current view for the Traces portal tab. * * @since 0.1.0 * @author [<NAME>](mailto:<EMAIL>) */ class TracesView { var traceResultCache = ConcurrentHashMap<TraceOrderType, TraceResult>() var traceStacks = HashMap<String, TraceStack>() //todo: evicting cache var traceStack: TraceStack? = null var orderType = TraceOrderType.LATEST_TRACES var viewType = TraceDisplayType.TRACES var traceId: String? = null var traceStackPath: TraceStackPath? = null var spanId: Int = 0 var viewTraceAmount = 10 var innerTraceStack = false var rootArtifactQualifiedName: String? = null fun cacheArtifactTraceResult(artifactTraceResult: TraceResult) { val currentTraceResult = traceResultCache[artifactTraceResult.orderType] if (currentTraceResult != null) { val mergedArtifactTraceResult = artifactTraceResult.mergeWith(currentTraceResult) traceResultCache[mergedArtifactTraceResult.orderType] = mergedArtifactTraceResult.truncate(viewTraceAmount) } else { traceResultCache[artifactTraceResult.orderType] = artifactTraceResult.truncate(viewTraceAmount) } } val artifactTraceResult: TraceResult? get() = traceResultCache[orderType] fun cacheTraceStack(traceId: String, traceStack: TraceStack) { traceStacks[traceId] = traceStack } fun getTraceStack(traceId: String): TraceStack? { return traceStacks[traceId] } fun cloneView(view: TracesView) { traceResultCache = ConcurrentHashMap(view.traceResultCache) traceStacks = HashMap(view.traceStacks) traceStack = if (view.traceStack != null) { view.traceStack!!.copy(traceSpans = view.traceStack!!.traceSpans.toList()) } else { null } traceStackPath = if (view.traceStackPath != null) { view.traceStackPath!!.copy(path = view.traceStackPath!!.path.toMutableList()) } else { null } orderType = view.orderType viewType = view.viewType traceId = view.traceId spanId = view.spanId } }
0
null
0
0
f5f1549c1e0d5a65bf1745bbbef69702854e99ee
2,587
SourceMarker
Apache License 2.0
portal/src/jvmMain/kotlin/com/sourceplusplus/portal/display/views/TracesView.kt
kaizhiyu
327,907,510
true
{"Kotlin": 571623, "Java": 10932, "CSS": 8168, "JavaScript": 3693, "HTML": 2027}
package com.sourceplusplus.portal.display.views import com.sourceplusplus.portal.model.TraceDisplayType import com.sourceplusplus.protocol.artifact.trace.TraceOrderType import com.sourceplusplus.protocol.artifact.trace.TraceResult import com.sourceplusplus.protocol.artifact.trace.TraceStack import com.sourceplusplus.protocol.artifact.trace.TraceStackPath import java.util.concurrent.ConcurrentHashMap import kotlin.collections.HashMap /** * Holds the current view for the Traces portal tab. * * @since 0.1.0 * @author [<NAME>](mailto:<EMAIL>) */ class TracesView { var traceResultCache = ConcurrentHashMap<TraceOrderType, TraceResult>() var traceStacks = HashMap<String, TraceStack>() //todo: evicting cache var traceStack: TraceStack? = null var orderType = TraceOrderType.LATEST_TRACES var viewType = TraceDisplayType.TRACES var traceId: String? = null var traceStackPath: TraceStackPath? = null var spanId: Int = 0 var viewTraceAmount = 10 var innerTraceStack = false var rootArtifactQualifiedName: String? = null fun cacheArtifactTraceResult(artifactTraceResult: TraceResult) { val currentTraceResult = traceResultCache[artifactTraceResult.orderType] if (currentTraceResult != null) { val mergedArtifactTraceResult = artifactTraceResult.mergeWith(currentTraceResult) traceResultCache[mergedArtifactTraceResult.orderType] = mergedArtifactTraceResult.truncate(viewTraceAmount) } else { traceResultCache[artifactTraceResult.orderType] = artifactTraceResult.truncate(viewTraceAmount) } } val artifactTraceResult: TraceResult? get() = traceResultCache[orderType] fun cacheTraceStack(traceId: String, traceStack: TraceStack) { traceStacks[traceId] = traceStack } fun getTraceStack(traceId: String): TraceStack? { return traceStacks[traceId] } fun cloneView(view: TracesView) { traceResultCache = ConcurrentHashMap(view.traceResultCache) traceStacks = HashMap(view.traceStacks) traceStack = if (view.traceStack != null) { view.traceStack!!.copy(traceSpans = view.traceStack!!.traceSpans.toList()) } else { null } traceStackPath = if (view.traceStackPath != null) { view.traceStackPath!!.copy(path = view.traceStackPath!!.path.toMutableList()) } else { null } orderType = view.orderType viewType = view.viewType traceId = view.traceId spanId = view.spanId } }
0
null
0
0
f5f1549c1e0d5a65bf1745bbbef69702854e99ee
2,587
SourceMarker
Apache License 2.0
app/src/main/java/com/lucianghimpu/matchmefy/presentation/settings/SettingsViewModel.kt
GhimpuLucianEduard
234,163,348
false
null
package com.lucianghimpu.matchmefy.presentation.settings import android.app.Application import android.content.Context import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.viewModelScope import com.lucianghimpu.matchmefy.BuildConfig import com.lucianghimpu.matchmefy.MatchmefyApp import com.lucianghimpu.matchmefy.R import com.lucianghimpu.matchmefy.appServices.AppAnalytics import com.lucianghimpu.matchmefy.appServices.PreferencesService import com.lucianghimpu.matchmefy.data.dataModels.User import com.lucianghimpu.matchmefy.data.dataServices.MatchmefyService import com.lucianghimpu.matchmefy.presentation.BaseViewModel import com.lucianghimpu.matchmefy.presentation.dialogs.doubleButton.DoubleButtonDialog import com.lucianghimpu.matchmefy.presentation.dialogs.doubleButton.DoubleButtonDialogListener import com.lucianghimpu.matchmefy.presentation.dialogs.loading.LoadingDialog import com.lucianghimpu.matchmefy.utilities.ColoredTextSpan import com.lucianghimpu.matchmefy.utilities.Event import com.lucianghimpu.matchmefy.utilities.PreferencesConstants import com.lucianghimpu.matchmefy.utilities.WebConstants import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import timber.log.Timber class SettingsViewModel( application: Application, preferencesService: PreferencesService, private val matchmefyService: MatchmefyService ) : BaseViewModel(application, preferencesService) { private val context: Context = this.getApplication<MatchmefyApp>().applicationContext private var _user = MutableLiveData<User>() val user: LiveData<User> get() = _user private var _appVersion = MutableLiveData<String>() val appVersion: LiveData<String> get() = _appVersion private var _openLinkInBrowserEvent = MutableLiveData<Event<String>>() val openLinkInBrowserEvent: MutableLiveData<Event<String>> get() = _openLinkInBrowserEvent private var _openLinkInBrowserAboutEvent = MutableLiveData<Event<String>>() val openLinkInBrowserAboutEvent: MutableLiveData<Event<String>> get() = _openLinkInBrowserAboutEvent private var _openEmailEvent = MutableLiveData<Event<Any>>() val openEmailEvent: MutableLiveData<Event<Any>> get() = _openEmailEvent init { _user.value = preferencesService.getObject( PreferencesConstants.USER_PROFILE_KEY, User::class ) _appVersion.value = "AppVersion: ${BuildConfig.VERSION_NAME}" } fun openPrivacyPolicy() { AppAnalytics.trackEvent("privacy_policy_settings_clicked") _openLinkInBrowserEvent.value = Event(WebConstants.MATCHMEFY_MOBILE_PRIVACY_POLICY) } fun openTerms() { AppAnalytics.trackEvent("terms_settings_clicked") _openLinkInBrowserEvent.value = Event(WebConstants.MATCHMEFY_MOBILE_TERMS) } fun onAboutClicked() { AppAnalytics.trackEvent("about_clicked") navigate(SettingsFragmentDirections.actionSettingsFragmentToAboutFragment()) } fun openGitHubPage() { AppAnalytics.trackEvent("github_clicked") _openLinkInBrowserAboutEvent.value = Event(WebConstants.MATCHMEFY_GITHUB) } fun openWebsite() { AppAnalytics.trackEvent("website_clicked") _openLinkInBrowserAboutEvent.value = Event(WebConstants.MATCHMEFY_WEB) } fun openEmail() { AppAnalytics.trackEvent("email_clicked") _openEmailEvent.value = Event(Any()) } fun onSignOutClicked() { AppAnalytics.trackEvent("sign_out_clicked") val signOutDialog = DoubleButtonDialog( title = context.getString(R.string.sign_out_dialog_title), description = context.getString(R.string.sign_out_dialog_description), descriptionSpan = ColoredTextSpan( 50, 53 ), positiveButtonText = context.getString(R.string.sign_out_dialog_button), negativeButtonText = context.getString(R.string.cancel_dialog_button), imageId = R.drawable.dialog_warning, listener = object : DoubleButtonDialogListener { override fun onPositiveButtonClicked() { AppAnalytics.trackEvent("sign_out") signOut() } override fun onNegativeButtonClicked() { AppAnalytics.trackEvent("cancel_sign_out") } } ) showDialog(signOutDialog) } fun onDeleteDataClicked() { AppAnalytics.trackEvent("delete_data_clicked") val deleteUserDataDialog = DoubleButtonDialog( title = context.getString(R.string.delete_data_dialog_title), description = context.getString(R.string.delete_data_dialog_description), descriptionSpan = ColoredTextSpan( 51, 63 ), positiveButtonText = context.getString(R.string.delete_data_dialog_button), negativeButtonText = context.getString(R.string.cancel_dialog_button), imageId = R.drawable.dialog_delete, listener = object : DoubleButtonDialogListener { override fun onPositiveButtonClicked() { AppAnalytics.trackEvent("delete_data") deleteUserData() } override fun onNegativeButtonClicked() { AppAnalytics.trackEvent("cancel_delete_data") } } ) showDialog(deleteUserDataDialog) } private fun deleteUserData() { showDialog(LoadingDialog()) viewModelScope.launch { try { withContext(Dispatchers.IO) { matchmefyService.deleteUserData(_user.value!!.id) } hideLoadingDialog() signOut() Timber.d("User data deleted") } catch (ex: Exception) { hideLoadingDialog() handleError(ex) } } // N.B. don't hide the loading dialog in a finally clause } private fun signOut() { matchmefyService.deleteAll() preferencesService.deleteAll() navigate(SettingsFragmentDirections.actionSettingsFragmentToLoginFragment()) } }
0
Kotlin
0
2
5a34aef2592417e05386ee3cff334f0ca9e4fe53
6,410
Matchmefy
MIT License
android/src/main/java/com/reactnativeawesomemodule/AwesomeModuleModule.kt
appscore-ahmed
292,494,705
false
{"Java": 6327, "Ruby": 4174, "Kotlin": 3583, "Objective-C": 3492, "TypeScript": 2024, "JavaScript": 1419, "Swift": 310, "C": 103}
package com.reactnativeawesomemodule import com.facebook.react.bridge.Promise import com.facebook.react.bridge.ReactApplicationContext import com.facebook.react.bridge.ReactContextBaseJavaModule import com.facebook.react.bridge.ReactMethod class AwesomeModuleModule(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) { override fun getName(): String { return "AwesomeModule" } // Example method // See https://facebook.github.io/react-native/docs/native-modules-android @ReactMethod fun multiply(a: Int, b: Int, promise: Promise) { promise.resolve(a * b) } @ReactMethod fun add(a: Int, b: Int, promise: Promise) { promise.resolve(a + b) } }
1
null
1
1
2d28b8d9b673ad9fdd52ab5bd8d9c07ef75f83cf
712
native-modules
MIT License
viewmodel-inject-processor/src/main/java/com/rightpoint/inject/viewmodel/processor/internal/javapoet.kt
Rightpoint
160,531,828
false
{"Gradle": 6, "Java Properties": 1, "Shell": 1, "Text": 1, "Ignore List": 5, "Batchfile": 1, "Markdown": 1, "INI": 1, "Proguard": 3, "XML": 15, "Kotlin": 17, "Java": 3, "YAML": 1}
package com.rightpoint.inject.viewmodel.processor.internal import com.squareup.javapoet.ClassName import com.squareup.javapoet.TypeName import javax.lang.model.element.TypeElement import javax.lang.model.type.TypeMirror import kotlin.reflect.KClass fun TypeElement.toClassName(): ClassName = ClassName.get(this) fun TypeMirror.toTypeName(): TypeName = TypeName.get(this) fun KClass<*>.toClassName(): ClassName = ClassName.get(java) /** * Like [ClassName.peerClass] except instead of honoring the enclosing class names they are * concatenated with `$` similar to the reflection name. `foo.Bar.Baz` invoking this function with * `Fuzz` will produce `foo.Baz$Fuzz`. */ fun ClassName.peerClassWithReflectionNesting(name: String): ClassName { var prefix = "" var peek = this while (true) { peek = peek.enclosingClassName() ?: break prefix = peek.simpleName() + "$" + prefix } return ClassName.get(packageName(), prefix + name) }
0
Kotlin
0
2
0202d3f4fb6d63e21e5a621dce564e66cef257d0
966
viewmodel-inject
Apache License 2.0
plugins/kotlin/idea/tests/testData/quickfix/typeMismatch/wrongPrimitive/longToDouble.kt
JetBrains
2,489,216
false
null
// "Change to '1.0'" "true" val a : Double = 1L<caret> // FUS_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.WrongPrimitiveLiteralFix // FUS_K2_QUICKFIX_NAME: org.jetbrains.kotlin.idea.quickfix.fixes.WrongPrimitiveLiteralFix
284
null
5162
16,707
def6433a5dd9f0a984cbc6e2835d27c97f2cb5f0
227
intellij-community
Apache License 2.0
beam-client/src/commonMain/kotlin/dev/d1s/beam/client/SpaceModificationBuilder.kt
d1snin
632,895,652
false
{"Kotlin": 442067, "Shell": 1236, "JavaScript": 597}
/* * Copyright 2023 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package dev.d1s.beam.client import dev.d1s.beam.commons.* @DslMarker internal annotation class BuilderDsl @BuilderDsl public class RootSpaceModificationBuilder { private var metadata: Metadata = metadataOf() private var view: ViewConfiguration? = null public fun view(build: ViewConfigurationBuilder.() -> Unit) { view = ViewConfigurationBuilder().apply(build).build() } internal fun build() = RootSpaceModification( metadata, view ?: error("View is undefined") ) } @BuilderDsl public class SpaceModificationBuilder { public var slug: SpaceSlug? = null public var metadata: Metadata = metadataOf() private var view: ViewConfiguration? = null public fun view(build: ViewConfigurationBuilder.() -> Unit) { view = ViewConfigurationBuilder().apply(build).build() } internal fun build() = SpaceModification( slug ?: error("Space slug is undefined"), metadata, view ?: error("View is undefined") ) } @BuilderDsl public class ViewConfigurationBuilder { public var theme: SpaceThemeName? = null public var icon: SpaceIconUrl? = null private var favicon: SpaceFavicon? = null public var title: SpaceTitle? = null public var description: SpaceDescription? = null public fun favicon(build: SpaceFaviconBuilder.() -> Unit) { favicon = SpaceFaviconBuilder().apply(build).build() } internal fun build() = ViewConfiguration( theme ?: error("Space theme is undefined"), icon, favicon, title, description ) } @BuilderDsl public class SpaceFaviconBuilder { public var appleTouch: SpaceIconUrl? = null public var favicon16: SpaceIconUrl? = null public var favicon32: SpaceIconUrl? = null public var faviconIco: SpaceIconUrl? = null public var browserconfig: Url? = null public var maskIcon: SpaceIconUrl? = null public var maskIconColor: String? = null internal fun build() = SpaceFavicon( appleTouch, favicon16, favicon32, faviconIco, browserconfig, maskIcon, maskIconColor ) }
1
Kotlin
0
0
21e4f15c74bc3b6f5cfed0363c9fefd0eb64b8b0
2,880
beam
Apache License 2.0
bottombarview/src/main/java/ksughosh/github/com/bottombarview/BottomBarItemView.kt
ksughosh
135,302,255
false
{"Kotlin": 43729, "Java": 1171}
package ksughosh.github.com.bottombarview import android.annotation.SuppressLint import android.content.Context import android.content.res.ColorStateList import android.graphics.drawable.Drawable import android.support.annotation.DrawableRes import android.support.annotation.LayoutRes import android.support.v4.content.ContextCompat import android.support.v4.graphics.drawable.DrawableCompat import android.support.v4.view.PointerIconCompat import android.support.v4.view.ViewCompat import android.support.v7.view.menu.MenuItemImpl import android.support.v7.widget.TooltipCompat import android.util.AttributeSet import android.view.Gravity import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.FrameLayout import android.widget.TextView import kotlinx.android.synthetic.main.design_bottom_bar_item.view.* @Suppress("MemberVisibilityCanBePrivate") @SuppressLint("RestrictedApi") open class BottomBarItemView : FrameLayout, BottomItemView { var mode: BottomAnimationMode = BottomAnimationMode.SHIFTING private var itemData: MenuItemImpl? = null protected var defaultMargin: Int = 0 protected var shiftAmount: Int = 0 protected var scaleUpFactor: Float = 0f protected var scaleDownFactor: Float = 0f protected open var disableText = false var itemPosition = INVALID_ITEM_POSITION var iconTintList: ColorStateList? = null set(value) { field = value if (itemData != null) { setIcon(itemData?.icon) } } protected open val badgeText: TextView? by lazy { var badgeText: TextView? = null badge?.forEachChild { if (it is TextView) { badgeText = it return@forEachChild } else if (it is ViewGroup && it.childCount > 0) { it.forEachChild innerLoop@{ if (it is TextView) { badgeText = it return@innerLoop } } if (badgeText != null) return@forEachChild } } badgeText } constructor(context: Context?) : this(context, null) constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0) constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { val resource = resources ?: return val inactiveLabelSize = resource.getDimensionPixelSize(R.dimen.design_bottom_bar_text_size) val activeLabelSize = resource.getDimensionPixelSize(R.dimen.design_bottom_bar_active_text_size) defaultMargin = resource.getDimensionPixelOffset(R.dimen.design_bottom_bar_margin) shiftAmount = inactiveLabelSize - activeLabelSize scaleUpFactor = 1f * activeLabelSize / inactiveLabelSize scaleDownFactor = 1f * inactiveLabelSize / activeLabelSize inflate(R.layout.design_bottom_bar_item, true) setBackgroundResource(R.drawable.design_bottom_bar_item_background) } @SuppressLint("RestrictedApi") override fun initialize(itemData: MenuItemImpl?, menuType: Int) { this.itemData = itemData ?: return setCheckable(itemData.isCheckable) setChecked(itemData.isChecked) isEnabled = itemData.isEnabled setIcon(itemData.icon) setTitle(itemData.title) id = itemData.itemId contentDescription = itemData.contentDescription TooltipCompat.setTooltipText(this, itemData.tooltipText) } override fun getItemData(): MenuItemImpl? = itemData override fun setCheckable(checkable: Boolean) { refreshDrawableState() } override fun setTitle(title: CharSequence?) { smallLabel?.text = title largeLabel?.text = title } override fun setChecked(checked: Boolean) { largeLabel?.apply { pivotX = (width / 2).toFloat() pivotY = (height / 2).toFloat() } smallLabel?.apply { pivotX = (width / 2).toFloat() pivotY = (height / 2).toFloat() } when (mode) { BottomAnimationMode.SHIFTING -> { if (checked) { val params = icon?.layoutParams as? LayoutParams params?.apply { this.gravity = Gravity.CENTER_HORIZONTAL or Gravity.TOP topMargin = defaultMargin icon?.layoutParams = this } if (disableText) { largeLabel?.makeGone() smallLabel?.makeGone() } else { largeLabel?.makeVisible() largeLabel?.scaleX = 1f largeLabel?.scaleY = 1f } } else { val params = icon?.layoutParams as? LayoutParams params?.apply { this.gravity = Gravity.CENTER topMargin = defaultMargin icon?.layoutParams = this } if (disableText) { largeLabel?.makeGone() smallLabel?.makeGone() } else { largeLabel?.hide() largeLabel?.scaleX = 0.5f largeLabel?.scaleY = 0.5f } } if (!disableText) { smallLabel?.hide() } } BottomAnimationMode.SCALE -> { if (checked) { val params = icon?.layoutParams as? LayoutParams params?.apply { this.gravity = Gravity.CENTER_HORIZONTAL or Gravity.TOP topMargin = defaultMargin + shiftAmount icon?.layoutParams = this } if (disableText) { largeLabel?.makeGone() smallLabel?.makeGone() } else { largeLabel?.makeVisible() smallLabel?.hide() largeLabel?.scaleX = 1f largeLabel?.scaleY = 1f smallLabel?.scaleX = scaleUpFactor smallLabel?.scaleY = scaleUpFactor } } else { val params = icon?.layoutParams as? LayoutParams params?.apply { this.gravity = Gravity.CENTER_HORIZONTAL or Gravity.TOP topMargin = defaultMargin icon?.layoutParams = this } if (disableText) { largeLabel?.makeGone() smallLabel?.makeGone() } else { largeLabel?.hide() smallLabel?.makeVisible() largeLabel?.scaleX = scaleDownFactor largeLabel?.scaleY = scaleDownFactor smallLabel?.scaleX = 1f smallLabel?.scaleY = 1f } } } BottomAnimationMode.NONE -> { val params = icon?.layoutParams as? LayoutParams params?.apply { this.gravity = Gravity.CENTER_HORIZONTAL or Gravity.TOP topMargin = defaultMargin icon?.layoutParams = this } if (disableText) { largeLabel?.makeGone() smallLabel?.makeGone() } else { largeLabel?.makeGone() if (checked) { smallLabel?.makeVisible() largeLabel?.scaleX = 1f largeLabel?.scaleY = 1f } else { smallLabel?.makeVisible() smallLabel?.scaleX = 1f smallLabel?.scaleY = 1f } } } } } fun disableText() { disableText = true largeLabel?.makeGone() smallLabel?.makeGone() } override fun setEnabled(enabled: Boolean) { super.setEnabled(enabled) smallLabel?.isEnabled = enabled largeLabel?.isEnabled = enabled icon?.isEnabled = enabled badge?.isEnabled = enabled if (enabled) { ViewCompat.setPointerIcon(this, PointerIconCompat.getSystemIcon(context, PointerIconCompat.TYPE_HAND)) } else { ViewCompat.setPointerIcon(this, null) } } @SuppressLint("RestrictedApi") override fun onCreateDrawableState(extraSpace: Int): IntArray { val drawableState = super.onCreateDrawableState(extraSpace + 1) if (itemData != null && itemData?.isCheckable == true && itemData?.isChecked == true) { mergeDrawableStates(drawableState, CHECKED_STATE_SET) } return drawableState } override fun setIcon(ic: Drawable?) { var icons = ic if (icons != null) { val state = icons.constantState icons = DrawableCompat.wrap(if (state == null) icons else state.newDrawable()).mutate() DrawableCompat.setTintList(icons, iconTintList) } icon?.setImageDrawable(icons) } override fun showsIcon(): Boolean = true override fun prefersCondensedTitle(): Boolean = false override fun setShortcut(showShortcut: Boolean, shortcutKey: Char) {} fun setItemBackground(background: Int) { val backgroundDrawable = if (background == 0) null else context?.getDrawableFromResource(background) ViewCompat.setBackground(this, backgroundDrawable) } fun setTextColor(colorStateList: ColorStateList) { largeLabel?.setTextColor(colorStateList) smallLabel?.setTextColor(colorStateList) } override fun setBadge(@LayoutRes resource: Int) { badge?.makeVisible() badge?.inflate(resource, true) } override fun removeBadge() { badge?.makeGone() } fun updateBadgeText(updatedText: CharSequence) { badge?.makeVisible() badgeText?.text = updatedText } override fun getBadgeLayout(): FrameLayout? = badge private fun ViewGroup.inflate(@LayoutRes resource: Int, attachToRoot: Boolean): View? = context?.let { LayoutInflater.from(it).inflate(resource, this, attachToRoot) } private fun ViewGroup.forEachChild(func: (View) -> Unit) { for (i in 0 until childCount) { func(getChildAt(i)) } } private fun View.makeVisible() { if (visibility != VISIBLE) { visibility = VISIBLE } } private fun View.hide() { if (visibility != INVISIBLE) { visibility = INVISIBLE } } private fun View.makeGone() { if (visibility != GONE) { visibility = GONE } } private fun Context.getDrawableFromResource(@DrawableRes resource: Int) = ContextCompat.getDrawable(this, resource) fun setBadgeDrawable(drawableFromResource: Drawable) { badge?.makeVisible() val simpleBadge = FrameLayout(context) val size = context?.resources?.getDimensionPixelSize(R.dimen.design_bottom_bar_badge_min_size) size?.apply { simpleBadge.layoutParams = FrameLayout.LayoutParams(this, this) } simpleBadge.background = drawableFromResource badge?.addView(simpleBadge) } companion object { const val INVALID_ITEM_POSITION = -1 val CHECKED_STATE_SET = intArrayOf(android.R.attr.state_checked) } }
0
Kotlin
0
0
9d8a500f89bdea6cb8c6f8bfebce028d938182b8
12,015
BottomBarExtended
Apache License 2.0
plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalShellCommandAction.kt
MariEliseeva
274,344,817
false
{"Text": 4090, "XML": 4734, "Ant Build System": 13, "Shell": 537, "Markdown": 309, "Ignore List": 80, "Git Attributes": 9, "Batchfile": 30, "SVG": 2098, "Java": 66424, "C++": 20, "HTML": 2392, "Kotlin": 6013, "DTrace": 1, "Gradle": 59, "Java Properties": 109, "INI": 280, "JFlex": 27, "CSS": 53, "Objective-C": 19, "Groovy": 3389, "XSLT": 112, "JavaScript": 160, "JSON": 1104, "desktop": 1, "Python": 10743, "JAR Manifest": 14, "PHP": 46, "YAML": 387, "C#": 37, "Smalltalk": 17, "Diff": 129, "Erlang": 1, "Rich Text Format": 2, "AspectJ": 2, "Perl": 6, "HLSL": 2, "CoffeeScript": 3, "JSON with Comments": 59, "EditorConfig": 213, "Vue": 17, "OpenStep Property List": 42, "PlantUML": 3, "Protocol Buffer": 2, "fish": 1, "Dockerfile": 2, "Prolog": 2, "ColdFusion": 2, "Turtle": 2, "TeX": 11, "Elixir": 2, "Ruby": 4, "XML Property List": 80, "Starlark": 2, "E-mail": 18, "Roff": 35, "Roff Manpage": 1, "Checksums": 58, "Java Server Pages": 8, "GraphQL": 42, "C": 42, "AMPL": 4, "Linux Kernel Module": 1, "Makefile": 1, "CMake": 6, "Microsoft Visual Studio Solution": 6, "VBScript": 1, "NSIS": 6, "TOML": 2, "Thrift": 3, "Cython": 10, "reStructuredText": 54, "Regular Expression": 3, "JSON5": 4}
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.terminal import com.intellij.openapi.actionSystem.AnAction import com.intellij.openapi.actionSystem.AnActionEvent class TerminalShellCommandAction : AnAction() { override fun actionPerformed(e: AnActionEvent) {} }
1
null
1
1
49e18fabdfc048f1d304e5d62b7a91a4552eb46c
388
intellij-community
Apache License 2.0
src/test/kotlin/QValueTest.kt
farble1670
542,793,187
false
{"Kotlin": 4740}
import org.junit.Assert.assertEquals import org.junit.Assert.assertNotNull import org.junit.Assert.assertTrue import org.junit.Test class QValueTest { @Test fun testNullValue() { val values = QValue.decode(null) assertNotNull(values) assertTrue(values.isEmpty()) } @Test fun testEmptyValue() { val values = QValue.decode("") assertNotNull(values) assertTrue(values.isEmpty()) } @Test fun testNotParsableValue1() { val values = QValue.decode("foo?baz?bar") assertNotNull(values) assertTrue(values.isEmpty()) } @Test fun testNotParsableValue2() { val values = QValue.decode("foo*baz") assertNotNull(values) assertTrue(values.isEmpty()) } @Test fun testSingleValue() { val encodings = QValue.decode("foo") assertNotNull(encodings) assertEquals(1, encodings.size) assertTrue(encodings.contains(QValue("foo", 1.0f))) } @Test fun testSingleValueWithQuality() { val values = QValue.decode("foo;q=0.5") assertNotNull(values) assertTrue(values.contains(QValue("foo", 0.5f))) } @Test fun testSingleValueWithInvalidQuality() { val values = QValue.decode("foo;q=XXX") assertNotNull(values) assertTrue(values.isEmpty()) } @Test fun testMultiValue() { val values = QValue.decode("foo,bar,baz") assertNotNull(values) assertEquals(3, values.size) assertTrue(values.contains(QValue("foo"))) assertTrue(values.contains(QValue("bar"))) assertTrue(values.contains(QValue("baz"))) } @Test fun testMultiValueWithQuality() { val values = QValue.decode("foo;q=0.1,bar;q=0.5,baz;q=1.0") assertNotNull(values) assertEquals(3, values.size) assertTrue(values.contains(QValue("foo", 0.1f))) assertTrue(values.contains(QValue("bar", 0.5f))) assertTrue(values.contains(QValue("baz", 1.0f))) } @Test fun testEncodeEmpty() { val values = listOf<QValue>() val encoded = values.encode() assertNotNull(encoded) assertEquals(0, encoded.length) } @Test fun testEncodeSingle() { val values = listOf(QValue("foo")) val encoded = values.encode() assertNotNull(encoded) assertEquals("foo;q=1.0", encoded) } @Test fun testEncodeMultiple() { val values = listOf(QValue("foo", 0.1f), QValue("bar", 0.5f), QValue("baz", 1.0f)) val encoded = values.encode() assertNotNull(encoded) assertEquals("foo;q=0.1, bar;q=0.5, baz;q=1.0", encoded) } @Test fun testParseEncoded() { val values = listOf(QValue("foo", 0.1f), QValue("bar", 0.5f), QValue("baz", 1.0f)) assertEquals(values, QValue.decode(values.encode())) } }
0
Kotlin
0
0
faf52c7a3c2c2f5be846775248729f63c77a2364
2,646
qualitylist
Apache License 2.0
app/src/main/java/com/example/neoticket/view/main/movie/DetailMovieInCinemaFragment.kt
rybakova-auca-2021
747,738,666
false
{"Kotlin": 442862}
package com.example.neoticket.view.main.movie import DetailImageAdapter import ScheduleAdapter import android.annotation.SuppressLint import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.example.neoticket.R import com.example.neoticket.databinding.FragmentDetailMovieInCinemaBinding import com.example.neoticket.model.DetailImage import com.example.neoticket.model.ShowTime import com.example.neoticket.model.StartTime import com.example.neoticket.viewModel.cinema.GetShowTimeViewModel import com.example.neoticket.viewModel.cinema.MovieDetailViewModel import com.harrywhewell.scrolldatepicker.DayScrollDatePicker import com.harrywhewell.scrolldatepicker.OnDateSelectedListener import jp.wasabeef.glide.transformations.BlurTransformation import jp.wasabeef.glide.transformations.RoundedCornersTransformation import java.text.SimpleDateFormat import java.util.Date import javax.annotation.Nullable class DetailMovieInCinemaFragment : Fragment() { private lateinit var binding: FragmentDetailMovieInCinemaBinding private val viewModel: MovieDetailViewModel by viewModels() private val timeViewModel: GetShowTimeViewModel by viewModels() private lateinit var adapter: DetailImageAdapter private lateinit var scheduleAdapter: ScheduleAdapter private lateinit var recyclerView: RecyclerView private lateinit var scheduleRV: RecyclerView private lateinit var mPicker: DayScrollDatePicker override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { binding = FragmentDetailMovieInCinemaBinding.inflate(inflater, container, false) recyclerView = binding.rvMovieImages scheduleRV = binding.rvCinemas mPicker = binding.date return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val id = arguments?.getInt("id") setupAdapter() getValue() if (id != null) { getMovieDetail(id) getShowTime(id) setupNavigation(id) } } private fun setupAdapter() { adapter = DetailImageAdapter(emptyList()) recyclerView.layoutManager = LinearLayoutManager(requireContext()) recyclerView.adapter = adapter scheduleAdapter = ScheduleAdapter( emptyList(), navigateToTicketPurchasePage = { startTime, item -> navigateToTicketPurchasePage(startTime, item) } ) scheduleRV.layoutManager = LinearLayoutManager(requireContext()) scheduleRV.adapter = scheduleAdapter } private fun setupNavigation(id: Int) { adapter.setOnItemClickListener(object : DetailImageAdapter.OnItemClickListener { override fun onImageClick(item: DetailImage) { val bundle = Bundle() bundle.putString("image", item.image) findNavController().navigate(R.id.imageDialogFragment, bundle) } }) binding.btnMovieDetails.setOnClickListener { val bundle = Bundle() bundle.putInt("id", id) findNavController().navigate(R.id.action_detailMovieInCinemaFragment_to_descriptionFragment, bundle) } binding.btnSchedule.setOnClickListener { val bundle = Bundle() bundle.putInt("id", id) findNavController().navigate(R.id.scheduleFragment, bundle) } binding.btnBack.setOnClickListener { when (arguments?.getString("sourceFragment")) { "mainPageFragment" -> findNavController().navigate(R.id.mainPageFragment) "nowInCinema" -> findNavController().navigate(R.id.cinemaFragment) else -> findNavController().navigate(R.id.cinemaFragment) } } } private fun navigateToTicketPurchasePage(startTime: StartTime, showTime: ShowTime) { val bundle = Bundle() bundle.putInt("movie", showTime.movie) bundle.putInt("showTimeId", showTime.id) findNavController().navigate(R.id.chooseTicketFragment, bundle) } private fun getMovieDetail(id: Int) { viewModel.movieDetailLiveData.observe(viewLifecycleOwner, Observer { result -> binding.movieTitle.text = result?.title val genresNames = result?.genres?.joinToString(", ") { it.name } binding.movieCategory.text = genresNames if (result != null) { binding.movieDuration.text = "${result.country_of_origin}, ${result.film_duration}, ${result.age_limit}+" } binding.movieRate.text = result?.rating.toString() binding.movieDescription.text = result?.description result?.detail_images?.let { adapter.updateData(it) } Glide.with(binding.imgOverlay.context) .applyDefaultRequestOptions(RequestOptions.bitmapTransform(BlurTransformation(25, 3))) .load(result?.image) .into(binding.imgOverlay) Glide.with(binding.imageView4.context) .applyDefaultRequestOptions(RequestOptions.bitmapTransform(RoundedCornersTransformation(15, 5))) .load(result?.image) .into(binding.imageView4) }) viewModel.getCinemaDetail(id) } private fun getValue() { mPicker.setStartDate(3, 2, 2024) // val currentDate = Date() // val startDate = SimpleDateFormat("yyyy-MM-dd").format(currentDate) scheduleAdapter.filterByDateTime("2024-02-03") scheduleAdapter.notifyDataSetChanged() mPicker.getSelectedDate(object : OnDateSelectedListener { @SuppressLint("SimpleDateFormat") override fun onDateSelected(@Nullable date: Date?) { date?.let { val selectedDate = SimpleDateFormat("yyyy-MM-dd").format(date) scheduleAdapter.filterByDateTime(selectedDate) scheduleAdapter.notifyDataSetChanged() } } }) } private fun getShowTime(id: Int) { timeViewModel.showTimeLiveData.observe(viewLifecycleOwner, Observer { result -> if (result != null) { val desiredDate = "2024-02-03" val filteredData = result.filter { it.start_date == desiredDate } scheduleAdapter.updateData(filteredData) } }) timeViewModel.getShowTimeByMovie(id.toString()) } }
0
Kotlin
0
0
7b7a198cc176704e613ee794176463935480b3aa
7,039
NeoTicket
MIT License
idea/idea-gradle/src/org/jetbrains/kotlin/idea/inspections/gradle/GradleKotlinxCoroutinesDeprecationInspection.kt
latheesh123
141,489,330
true
{"Kotlin": 28539168, "Java": 7544965, "JavaScript": 153376, "HTML": 65245, "Lex": 18269, "ANTLR": 9797, "IDL": 8755, "Shell": 6769, "CSS": 4679, "Batchfile": 4437, "Groovy": 4358}
/* * Copyright 2010-2018 JetBrains s.r.o. 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.idea.inspections.gradle import com.intellij.codeInspection.CleanupLocalInspectionTool import com.intellij.codeInspection.ProblemHighlightType import com.intellij.openapi.roots.ProjectRootManager import com.intellij.psi.PsiElement import com.intellij.psi.PsiFile import org.jetbrains.kotlin.config.LanguageVersion import org.jetbrains.kotlin.idea.configuration.getWholeModuleGroup import org.jetbrains.kotlin.idea.inspections.gradle.GradleHeuristicHelper.PRODUCTION_DEPENDENCY_STATEMENTS import org.jetbrains.kotlin.idea.project.languageVersionSettings import org.jetbrains.kotlin.idea.versions.LibInfo import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType import org.jetbrains.plugins.gradle.codeInspection.GradleBaseInspection import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression private val LibInfo.gradleMarker get() = "$groupId:$name:" private data class DeprecatedForKotlinLibInfo( val lib: LibInfo, val sinceKotlinLanguageVersion: LanguageVersion, val message: String ) @Suppress("SpellCheckingInspection") private fun kotlinxCoroutinesDeprecation(name: String): org.jetbrains.kotlin.idea.inspections.gradle.DeprecatedForKotlinLibInfo { return DeprecatedForKotlinLibInfo( lib = LibInfo("org.jetbrains.kotlinx", name), sinceKotlinLanguageVersion = LanguageVersion.KOTLIN_1_3, message = "Library should be updated to be compatible with Kotlin 1.3" ) } @Suppress("SpellCheckingInspection") private val DEPRECATED_COROUTINES_LIBRARIES_INFORMATION = listOf( kotlinxCoroutinesDeprecation("kotlinx-coroutines"), kotlinxCoroutinesDeprecation("kotlinx-coroutines-android"), kotlinxCoroutinesDeprecation("kotlinx-coroutines-core"), kotlinxCoroutinesDeprecation("kotlinx-coroutines-core-common"), kotlinxCoroutinesDeprecation("kotlinx-coroutines-core-js"), kotlinxCoroutinesDeprecation("kotlinx-coroutines-guava"), kotlinxCoroutinesDeprecation("kotlinx-coroutines-io"), kotlinxCoroutinesDeprecation("kotlinx-coroutines-javafx"), kotlinxCoroutinesDeprecation("kotlinx-coroutines-jdk8"), kotlinxCoroutinesDeprecation("kotlinx-coroutines-nio"), kotlinxCoroutinesDeprecation("kotlinx-coroutines-quasar"), kotlinxCoroutinesDeprecation("kotlinx-coroutines-reactive"), kotlinxCoroutinesDeprecation("kotlinx-coroutines-reactor"), kotlinxCoroutinesDeprecation("kotlinx-coroutines-rx1"), kotlinxCoroutinesDeprecation("kotlinx-coroutines-rx2"), kotlinxCoroutinesDeprecation("kotlinx-coroutines-swing") ) @Suppress("SpellCheckingInspection") class GradleKotlinxCoroutinesDeprecationInspection : GradleBaseInspection(), CleanupLocalInspectionTool { override fun buildVisitor(): BaseInspectionVisitor = DependencyFinder() private open class DependencyFinder : KotlinGradleInspectionVisitor() { override fun visitClosure(closure: GrClosableBlock) { super.visitClosure(closure) val dependenciesCall = closure.getStrictParentOfType<GrMethodCall>() ?: return if (dependenciesCall.invokedExpression.text != "dependencies") return val dependencyEntries = GradleHeuristicHelper.findStatementWithPrefixes(closure, PRODUCTION_DEPENDENCY_STATEMENTS) for (dependencyStatement in dependencyEntries) { for (outdatedInfo in DEPRECATED_COROUTINES_LIBRARIES_INFORMATION) { val dependencyText = dependencyStatement.text val libMarker = outdatedInfo.lib.gradleMarker if (!dependencyText.contains(libMarker)) continue if (!checkKotlinVersion(dependencyStatement.containingFile, outdatedInfo.sinceKotlinLanguageVersion)) { // Same result will be for all invocations in this file, so exit return } val reportOnElement = reportOnElement(dependencyStatement, outdatedInfo) registerError( reportOnElement, outdatedInfo.message, emptyArray(), ProblemHighlightType.GENERIC_ERROR_OR_WARNING ) break } } } private fun reportOnElement(classpathEntry: GrCallExpression, deprecatedForKotlinInfo: DeprecatedForKotlinLibInfo): PsiElement { val indexOf = classpathEntry.text.indexOf(deprecatedForKotlinInfo.lib.name) if (indexOf < 0) return classpathEntry return classpathEntry.findElementAt(indexOf) ?: classpathEntry } private fun checkKotlinVersion(file: PsiFile, languageVersion: LanguageVersion): Boolean { val module = ProjectRootManager.getInstance(file.project).fileIndex.getModuleForFile(file.virtualFile) ?: return false val moduleGroup = module.getWholeModuleGroup() return moduleGroup.sourceRootModules.any { moduleInGroup -> moduleInGroup.languageVersionSettings.languageVersion >= languageVersion } } } }
0
Kotlin
0
0
094cb6be1d351022a1d6a8cdcd1c30f74a6c82e3
5,536
kotlin
Apache License 2.0
app/src/main/kotlin/com/androidvip/sysctlgui/di/PresentationModule.kt
Lennoard
203,049,890
false
{"Kotlin": 209071}
package com.androidvip.sysctlgui.di import com.androidvip.sysctlgui.ui.export.ExportOptionsViewModel import com.androidvip.sysctlgui.ui.main.MainViewModel import com.androidvip.sysctlgui.ui.params.browse.BrowseParamsViewModel import com.androidvip.sysctlgui.ui.params.edit.EditParamViewModel import com.androidvip.sysctlgui.ui.params.list.ListParamsViewModel import com.androidvip.sysctlgui.ui.params.user.UserParamsViewModel import com.androidvip.sysctlgui.widgets.FavoriteWidgetParamUpdater import org.koin.android.ext.koin.androidContext import org.koin.androidx.viewmodel.dsl.viewModel import org.koin.androidx.viewmodel.dsl.viewModelOf import org.koin.dsl.module internal val presentationModules = module { viewModel { BrowseParamsViewModel(get(), get()) } viewModelOf(::ListParamsViewModel) viewModelOf(::UserParamsViewModel) viewModelOf(::EditParamViewModel) viewModelOf(::MainViewModel) viewModel { ExportOptionsViewModel(get(), get(), get()) } single { FavoriteWidgetParamUpdater(androidContext()).getListener() } }
2
Kotlin
8
61
ab2654de5326a131d03cc0e6883aa860822ed0de
1,056
SysctlGUI
MIT License
client/src/commonTest/kotlin/documentation/guides/results/mustdo/GuideConfigureSearchableAttributes.kt
algolia
153,273,215
false
{"Kotlin": 1346247, "Dockerfile": 163}
package documentation.guides.results.mustdo import com.algolia.search.dsl.searchableAttributes import com.algolia.search.dsl.settings import documentation.index import runBlocking import kotlin.test.Ignore import kotlin.test.Test @Ignore internal class GuideConfigureSearchableAttributes { @Test fun snippet1() { runBlocking { val settings = settings { searchableAttributes { +"title" +"director" +"actor" } } index.setSettings(settings) } } @Test fun snippet2() { runBlocking { val settings = settings { searchableAttributes { +"movie_title,actor_name,director_name" +"cast" +"filmography" } } index.setSettings(settings) } } @Test fun snippet3() { runBlocking { val settings = settings { searchableAttributes { +Unordered("title") +"cast" } } index.setSettings(settings) } } }
8
Kotlin
23
59
21f0c6bd3c6c69387d1dd4ea09f69a220c5eaff4
1,235
algoliasearch-client-kotlin
MIT License
rumascot-common/src/commonMain/kotlin/models/AdFilterRum.kt
mathemator
586,045,497
false
null
package ru.otus.otuskotlin.marketplace.common.models data class AdFilterRum( var searchString: String = "", var ownerId: UserIdRum? = null, var dealSide: DealSideRum = DealSideRum.NONE, )
2
Kotlin
0
0
633640f3c74b3d5a352052bbce9fd6358881953a
201
goppeav-kotlin-2022-12
Apache License 2.0
app/src/main/java/com/example/mear/playback/service/MusicService.kt
mura-t
218,382,597
true
{"Kotlin": 86112, "C++": 45505, "CMake": 2421, "C": 389}
package com.example.mear.playback.service import android.app.Service import android.content.Context import android.content.Intent import android.media.MediaPlayer import android.net.Uri import android.os.Binder import android.os.Environment import android.os.IBinder import android.widget.Toast import java.lang.Exception import kotlin.random.Random import com.example.mear.constants.ControlTypes import com.example.mear.constants.Interval import com.example.mear.management.MusicFiles import com.example.mear.management.TrackManager import com.example.mear.models.PlayControls import com.example.mear.models.APIInfo import com.example.mear.models.Song import com.example.mear.models.Token import com.example.mear.models.Track import com.example.mear.repositories.* import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch class MusicService(var appPath: String = ""): Service() { companion object { //fun curSongIndex(): Int = currentSongIndex } private var trackPlayer: MediaPlayer? = null private var trackMgr: TrackManager? = null private var songQueue = mutableListOf<Song>() private var currentTrack = Track() private var currentSong = Song() private var currentSongIndex: Int? = null private var addingMusic: Boolean? = false private var shuffleOn: Boolean? = null private var repeatOn: Boolean? = null private val mBinder = LocalBinder() private val seconds = Interval.SONG_REWIND inner class LocalBinder : Binder() { internal val service: MusicService get() = this@MusicService } private enum class PlayTypes { PlayNextSong, PlaySong, PlayPreviousSong } override fun onCreate() { initializeMediaPlayer() } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { val b = intent.extras appPath = b!!.get("appPath") as String initializeMediaPlayer() return Service.START_STICKY } override fun onDestroy() { val intent = Intent(this, mBinder.javaClass) onUnbind(intent) Toast.makeText(this, "Music Service Stopped", Toast.LENGTH_SHORT).show() } override fun onBind(intent: Intent): IBinder? { return mBinder } override fun onUnbind(intent: Intent?): Boolean { return super.onUnbind(intent) } fun icarusPlaySong(token: Token, song: Song, apiInfo: APIInfo) { val uri = APIRepository.retrieveSongStreamUri(apiInfo, song) val hddr = APIRepository.retrieveSongStreamHeader(token) try { trackPlayer!!.reset() trackPlayer!!.setDataSource(this, uri, hddr) trackPlayer!!.prepare() trackPlayer!!.start() } catch (ex: Exception) { val msg = ex.message } } fun goToPosition(progress: Int) { trackPlayer!!.seekTo(progress) } fun playSongTrack() { try { trackPlayer!!.start() } catch (ex: Exception ) { val exMsg = ex.message } } fun pauseSongTrack() { try { trackPlayer!!.pause() } catch (ex: Exception) { val exMsg = ex.message } } fun playPreviousTrack() { try { val duration = trackPlayer!!.currentPosition / 1000 shuffleOn = retrieveShuffleMode() val apiRepo = APIRepository() val tokenRepo = TokenRepository() val token = tokenRepo.retrieveToken(appPath) val apiInfo = apiRepo.retrieveRecord(appPath) currentSong = songQueue[Random.nextInt(0, songQueue.size - 1)] trackPlayer!!.reset() if (duration > seconds) { trackPlayer!!.setDataSource(this, APIRepository.retrieveSongStreamUri(apiInfo, currentSong), APIRepository.retrieveSongStreamHeader(token)) trackPlayer!!.prepare() trackPlayer!!.start() } else { trackPlayer!!.setDataSource(this, APIRepository.retrieveSongStreamUri(apiInfo, currentSong), APIRepository.retrieveSongStreamHeader(token)) trackPlayer!!.prepare() trackPlayer!!.start() } } catch (ex: Exception) { val exMsg = ex.message } } fun playNextTrack() { try { trackPlayer!!.reset() shuffleOn = retrieveShuffleMode() val apiRepo = APIRepository() val tokenRepo = TokenRepository() val token = tokenRepo.retrieveToken(appPath) val apiInfo = apiRepo.retrieveRecord(appPath) currentSong = songQueue[Random.nextInt(0, songQueue.size - 1)] trackPlayer!!.setDataSource(this, APIRepository.retrieveSongStreamUri(apiInfo, currentSong), APIRepository.retrieveSongStreamHeader(token)) trackPlayer!!.prepare() trackPlayer!!.start() } catch (ex: Exception) { val exMsg = ex.message } } fun configureControl(controls: PlayControls) { shuffleOn = controls.shuffleOn repeatOn = controls.repeatOn } fun getCurrentSong(): Song { return currentSong } fun currentPositionOfTrack(): Int { return trackPlayer!!.currentPosition } fun durationOfTrack(): Int { return trackPlayer!!.duration } fun isPlaying(): Boolean { return trackPlayer!!.isPlaying } private fun initializeMediaPlayer() { try { if (trackPlayer == null) { trackPlayer = MediaPlayer() } if (appPath.isEmpty()) { return } val trackRepo = TrackRepository() val apiRepo = APIRepository() val tokenRepo = TokenRepository() val token = tokenRepo.retrieveToken(appPath) val apiInfo = apiRepo.retrieveRecord(appPath) val songs = trackRepo.fetchSongs(token, apiInfo.uri) songQueue = songs.toMutableList() currentSong = songQueue[Random.nextInt(0, songs.size - 1)] trackPlayer!!.setDataSource(this, APIRepository.retrieveSongStreamUri(apiInfo, currentSong), APIRepository.retrieveSongStreamHeader(token)) trackPlayer!!.prepareAsync() trackPlayer!!.setOnCompletionListener { playNextTrack() } } catch (ex: Exception) { val exMsg = ex.message } } private fun initializeShuffleMode() { try { val shuffleMode = ShuffleRepository(this).getShuffleMode() when (shuffleMode) { ControlTypes.SHUFFLE_ON -> { shuffleOn = true } ControlTypes.SHUFFLE_OFF -> { shuffleOn = false } } } catch (ex: Exception) { val exMsg = ex.message } } private fun initializeRepeatMode() { try { val repeatMode = RepeatRepository(this).getRepeatMode() when (repeatMode) { ControlTypes.REPEAT_ON -> { repeatOn = true } ControlTypes.REPEAT_OFF -> { repeatOn = false } } } catch (ex: Exception) { val exMsg = ex.message } } private fun retrieveShuffleMode(): Boolean? { val shuffleMode = ShuffleRepository(this).getShuffleMode() when (shuffleMode) { ControlTypes.SHUFFLE_ON -> { return true } ControlTypes.SHUFFLE_OFF -> { return false } else -> { return false } } } private fun retrieveRepeatMode(): Boolean? { val repeatMode = RepeatRepository(this).getRepeatMode() when (repeatMode) { ControlTypes.REPEAT_ON -> { return true } ControlTypes.REPEAT_OFF -> { return false } else -> { return false } } } }
0
null
0
0
6221969d6b50b88092b117d29bccb7a1ecd5ccd2
8,455
Mear
MIT License
app/src/main/java/pl/serfa/thingspeaker/database/UserChannelDao.kt
sgozdzik
187,772,330
false
null
package pl.serfa.thingspeaker.database import androidx.room.* import pl.serfa.thingspeaker.models.UserChannel @Dao interface UserChannelDao { @Query("SELECT * FROM channels") suspend fun getAll(): List<UserChannel> @Insert suspend fun insert(userChannel: UserChannel) @Insert suspend fun insertAll(channelsParameters: List<UserChannel>) @Update suspend fun update(userChannel: UserChannel) @Delete suspend fun delete(userChannel: UserChannel) }
11
Kotlin
0
0
bdc76ade979081d4da7b932c77fd9b12340cc35c
492
thingspeaker
Apache License 2.0
src/jvmTest/kotlin/lt/libredrop/peerdiscovery/PeerDiscoveryTest.kt
libredrop
207,655,407
false
null
package lt.libredrop.peerdiscovery import com.nhaarman.mockitokotlin2.* import kotlinx.coroutines.* import kotlinx.coroutines.flow.* import lt.libredrop.peerdiscovery.data.Peer import lt.libredrop.peerdiscovery.network.NetworkDriver import lt.libredrop.peerdiscovery.network.randomUUID import lt.libredrop.peerdiscovery.test.runTest import org.awaitility.Awaitility import java.util.concurrent.TimeUnit import kotlin.test.Test import kotlin.test.assertEquals class PeerDiscoveryTest { val networkDriver = spy(NetworkDriver()) val serviceName = "test" val uuid = randomUUID() //Add some randomization in order to reduce random failures val port = networkDriver.getFreePort() val fixture = PeerDiscovery.Builder() .networkDriver(networkDriver) .interval(100) .port(port) .build() @Test fun start_doNotHearSelf() = runTest { withTimeoutOrNull(1000) { val peer = fixture.start(serviceName, uuid).filter { it.uuid == uuid }.first() throw AssertionError("Service heart self: $peer") } } @Test fun start_shoutSentFewTimes() = runTest { val job = launch(Dispatchers.IO) { fixture.start(serviceName, uuid).filter { it.uuid == uuid }.toList() } Awaitility.with().atMost(1, TimeUnit.SECONDS).untilAsserted { runBlocking { verify(networkDriver, atLeast(3)).broadcast(any(), any()) } } job.cancel() } @Test fun stop_noMoreShouts() = runTest { val job = launch(Dispatchers.IO) { fixture.start(serviceName, uuid).filter { it.uuid == uuid }.toList() } delay(100) job.cancelAndJoin() clearInvocations(networkDriver) //Give some time to send message delay(200) verify(networkDriver, never()).broadcast(any(), any()) } @Test fun peerFromSameServiceIsShouting_callbackIsExpected() = runTest { val future = async(Dispatchers.IO) { fixture.start(serviceName, uuid).take(1).toList() } delay(100) val peerFromAnotherService = Peer(serviceName = serviceName) networkDriver.broadcast(peerFromAnotherService, port) delay(100) val heard = withTimeout(100) { future.await().single() } assertEquals(peerFromAnotherService.uuid, heard.uuid) } @Test fun peerFromAnotherServiceIsShouting_doNotCallback() = runTest { val job = launch(Dispatchers.IO) { fixture.start(serviceName, uuid).collect { throw AssertionError("No callback is expected, but got: $it") } } delay(100) networkDriver.broadcast(Peer(serviceName = "Some not existing"), port) delay(1000) job.cancel() } @Test fun modeShout() = runTest { val job = launch(Dispatchers.IO) { fixture.start(serviceName, uuid, mode = PeerDiscovery.Mode.SHOUT).collect { error("This peer is not expected to collect any peer") } } delay(100) verify(networkDriver).broadcast(any(), any()) job.cancel() } @Test fun modeListen() = runTest { val future = async(Dispatchers.IO) { fixture.start(serviceName, mode = PeerDiscovery.Mode.LISTEN).take(1).toList() } delay(100) val peer = Peer(serviceName = serviceName) networkDriver.broadcast(peer, port) withTimeout(1000) { assertEquals(peer, future.await().single()) } } @Test fun twoPeersWithNonNormalMode_onlyListenReceivesPeer() = runTest { val resultOfListenPeer = async(Dispatchers.IO) { fixture.start(serviceName, mode = PeerDiscovery.Mode.LISTEN).take(1).toList() } delay(100) val job = launch(Dispatchers.IO) { fixture.start(serviceName, uuid, mode = PeerDiscovery.Mode.SHOUT).collect { error("This peer is not expected to collect any peer") } } withTimeout(50000) { val peers = resultOfListenPeer.await() assertEquals(uuid, peers.single().uuid) } job.cancel() } }
1
Kotlin
0
2
88bbd210fe3e6db4863717799a410a3aae1734cd
4,310
peer-discovery-kotlin
MIT License
src/main/kotlin/io/github/realyusufismail/armourandtoolsmod/common/entity/AqumarineTridentEntity.kt
RealYusufIsmail-Mc-Mods
585,447,214
false
{"Kotlin": 864508, "Java": 165671, "Batchfile": 155}
/* * Copyright 2024 RealYusufIsmail. * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.github.realyusufismail.temporalsmith.common.entity import io.github.realyusufismail.temporalsmith.core.init.EntityTypeInit import io.github.realyusufismail.temporalsmith.core.init.ItemInit import net.minecraft.world.entity.EntityType import net.minecraft.world.entity.LivingEntity import net.minecraft.world.item.ItemStack import net.minecraft.world.level.Level open class MjolnirEntity : ModTridentEntity { constructor(type: EntityType<ModTridentEntity>, world: Level) : super(type, world) { this.tridentItem = ItemStack(ItemInit.MJOLNIR.get()) this.entityData.set(ID_LOYALTY, 1.toByte()) this.allowToTriggerThunderWithoutEnchantment = true } constructor( level: Level, thrower: LivingEntity, stack: ItemStack ) : super(EntityTypeInit.MJOLNIR.get(), level, thrower, stack) { this.entityData.set(ID_LOYALTY, 1.toByte()) this.allowToTriggerThunderWithoutEnchantment = true } override fun getBaseDamage(): Double { return 15.0 } }
7
Kotlin
0
2
f778a0b824069b52d8e539734e1dc718c18d5c2f
1,651
TemporalSmith
Apache License 2.0
common/src/commonMain/kotlin/io/xorum/codeforceswatcher/network/responses/codeforces/CodeforcesContestsResponse.kt
dush1729
363,466,510
true
{"Kotlin": 218758, "Swift": 206579, "Ruby": 2648}
package io.xorum.codeforceswatcher.network.responses.codeforces import io.xorum.codeforceswatcher.features.contests.models.Contest import kotlinx.serialization.Serializable @Serializable internal data class CodeforcesContestsResponse( val status: String, val result: List<Contest> )
0
null
0
1
29f2ecf89cac7d414ab73b057abbc94212d785ff
300
codeforces_watcher
MIT License
domain/core/data/source/src/test/kotlin/net/meilcli/hubber/core/data/source/store/PickPreferenceDataTest.kt
MeilCli
634,432,059
false
null
package net.meilcli.hubber.core.data.source.store import androidx.datastore.preferences.core.PreferenceDataStoreFactory import androidx.datastore.preferences.core.intPreferencesKey import com.google.common.truth.Truth import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.runTest import org.junit.Rule import org.junit.Test import org.junit.rules.TemporaryFolder import java.io.File @ExperimentalCoroutinesApi class PickPreferenceDataTest { private val preferenceKey = intPreferencesKey("test_key") private val coroutineDispatcher = UnconfinedTestDispatcher() @get:Rule val temporaryFolder = TemporaryFolder() @Test fun testInitialData() = runTest(coroutineDispatcher) { val defaultValue = 1 val data = PickPreferenceData( PreferenceData( jetpackDataStoreCreator = { PreferenceDataStoreFactory.create( produceFile = { File(temporaryFolder.root, "data.preferences_pb") }, scope = CoroutineScope(coroutineDispatcher + SupervisorJob()) ) } ), preferenceKey, defaultValue ) val actual = data.getData() Truth.assertThat(actual).isEqualTo(defaultValue) } @Test fun testUpdateData() = runTest(UnconfinedTestDispatcher()) { val defaultValue = 1 val data = PickPreferenceData( PreferenceData( jetpackDataStoreCreator = { PreferenceDataStoreFactory.create( produceFile = { File(temporaryFolder.root, "data.preferences_pb") }, scope = CoroutineScope(coroutineDispatcher + SupervisorJob()) ) } ), preferenceKey, defaultValue ) data.updateData { 100 } val actual = data.getData() Truth.assertThat(actual).isEqualTo(100) } }
0
Kotlin
0
0
3f9660ce2cbc23c324ab7e5ad86c43d2551893c7
2,151
hubber
MIT License
compiler-plugin/src/main/kotlin/com/google/devtools/ksp/processing/impl/MessageCollectorBasedKSPLogger.kt
davidjwiner
331,542,353
true
{"Kotlin": 633108, "Java": 10586}
/* * Copyright 2020 Google LLC * Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors. * * 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.google.devtools.ksp.processing.impl import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity import org.jetbrains.kotlin.cli.common.messages.MessageCollector import com.google.devtools.ksp.processing.KSPLogger import com.google.devtools.ksp.symbol.FileLocation import com.google.devtools.ksp.symbol.KSNode import com.google.devtools.ksp.symbol.NonExistLocation import java.io.PrintWriter import java.io.StringWriter class MessageCollectorBasedKSPLogger(private val messageCollector: MessageCollector) : KSPLogger { companion object { const val PREFIX = "[ksp] " } override var errorCount = 0 private set override var warningCount = 0 private set override var infoCount = 0 private set override var loggingCount = 0 private set override var exceptionCount = 0 private set private fun convertMessage(message: String, symbol: KSNode?): String = when (val location = symbol?.location) { is FileLocation -> "$PREFIX${location.filePath}:${location.lineNumber}: $message" is NonExistLocation, null -> "$PREFIX$message" } override fun logging(message: String, symbol: KSNode?) { loggingCount++ messageCollector.report(CompilerMessageSeverity.LOGGING, convertMessage(message, symbol)) } override fun info(message: String, symbol: KSNode?) { infoCount++ messageCollector.report(CompilerMessageSeverity.INFO, convertMessage(message, symbol)) } override fun warn(message: String, symbol: KSNode?) { warningCount++ messageCollector.report(CompilerMessageSeverity.WARNING, convertMessage(message, symbol)) } override fun error(message: String, symbol: KSNode?) { errorCount++ messageCollector.report(CompilerMessageSeverity.ERROR, convertMessage(message, symbol)) } override fun exception(e: Throwable) { exceptionCount++ val writer = StringWriter() e.printStackTrace(PrintWriter(writer)) messageCollector.report(CompilerMessageSeverity.EXCEPTION, writer.toString()) } }
0
null
0
0
3fe1c1fcceaeb598c7bf1eccce31b9dfaa197731
2,831
ksp
Apache License 2.0
app/src/main/kotlin/net/tlalka/fiszki/core/annotations/SessionScope.kt
jtlalka
52,197,843
false
null
package net.tlalka.fiszki.core.annotations import javax.inject.Scope @Scope annotation class SessionScope
0
Kotlin
0
2
7e7c2aba5d9a1634a5b295319ec1bb5a4b5a7aa0
108
fiszki
MIT License
src/test/kotlin/uk/gov/justice/digital/hmpps/prisonerfromnomismigration/incidents/IncidentsNomisApiServiceTest.kt
ministryofjustice
452,734,022
false
{"Kotlin": 2820723, "Shell": 2955, "Mustache": 1803, "Dockerfile": 1377}
package uk.gov.justice.digital.hmpps.prisonerfromnomismigration.incidents import com.github.tomakehurst.wiremock.client.WireMock.anyUrl import com.github.tomakehurst.wiremock.client.WireMock.equalTo import com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor import com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo import kotlinx.coroutines.test.runTest import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.DisplayName import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.springframework.beans.factory.annotation.Autowired import org.springframework.context.annotation.Import import org.springframework.http.HttpStatus.INTERNAL_SERVER_ERROR import org.springframework.http.HttpStatus.NOT_FOUND import org.springframework.web.reactive.function.client.WebClientResponseException import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.helper.SpringAPIServiceTest import uk.gov.justice.digital.hmpps.prisonerfromnomismigration.nomissync.model.IncidentIdResponse @SpringAPIServiceTest @Import(IncidentsNomisApiService::class, IncidentsConfiguration::class, IncidentsNomisApiMockServer::class) class IncidentsNomisApiServiceTest { @Autowired private lateinit var nomisApiService: IncidentsNomisApiService @Autowired private lateinit var incidentsNomisApiMockServer: IncidentsNomisApiMockServer @Nested @DisplayName("GET /incidents/{nomisIncidentId}") inner class GetIncident { @Test internal fun `will pass oath2 token to service`() = runTest { incidentsNomisApiMockServer.stubGetIncident() nomisApiService.getIncident(1234L) incidentsNomisApiMockServer.verify( getRequestedFor(anyUrl()).withHeader("Authorization", equalTo("Bearer ABCDE")), ) } @Test internal fun `will pass NOMIS ids to service`() = runTest { incidentsNomisApiMockServer.stubGetIncident() nomisApiService.getIncident(1234L) incidentsNomisApiMockServer.verify( getRequestedFor(urlPathEqualTo("/incidents/1234")), ) } @Test fun `will return an incident`() = runTest { incidentsNomisApiMockServer.stubGetIncident() val incident = nomisApiService.getIncident(1234L) assertThat(incident.incidentId).isEqualTo(1234) assertThat(incident.status.code).isEqualTo("AWAN") assertThat(incident.incidentDateTime).isEqualTo("2017-04-12T16:45:00") } @Test fun `will throw error when incident does not exist`() = runTest { incidentsNomisApiMockServer.stubGetIncident(NOT_FOUND) assertThrows<WebClientResponseException.NotFound> { nomisApiService.getIncident(1234L) } } @Test fun `will throw error when API returns an error`() = runTest { incidentsNomisApiMockServer.stubGetIncident(INTERNAL_SERVER_ERROR) assertThrows<WebClientResponseException.InternalServerError> { nomisApiService.getIncident(1234L) } } } @Nested @DisplayName("GET /incidents/ids") inner class GetIncidentsToMigrate { @Test internal fun `will pass oath2 token to service`() = runTest { incidentsNomisApiMockServer.stubMultipleGetIncidentIdCounts(1, 20) nomisApiService.getIncidentIds(fromDate = null, toDate = null, pageNumber = 0, pageSize = 20) incidentsNomisApiMockServer.verify( getRequestedFor(anyUrl()).withHeader("Authorization", equalTo("Bearer ABCDE")), ) } @Test internal fun `will call the Nomis endpoint`() = runTest { incidentsNomisApiMockServer.stubMultipleGetIncidentIdCounts(1, 20) nomisApiService.getIncidentIds(fromDate = null, toDate = null, pageNumber = 0, pageSize = 20) incidentsNomisApiMockServer.verify(getRequestedFor(urlPathEqualTo("/incidents/ids"))) } @Test fun `will return incidentIds`() = runTest { incidentsNomisApiMockServer.stubMultipleGetIncidentIdCounts(3, 10) val incidents = nomisApiService.getIncidentIds(fromDate = null, toDate = null, pageNumber = 0, pageSize = 20) assertThat(incidents).hasSize(3) } } @Nested @DisplayName("GET /incidents/reconciliation/agencies") inner class GetReconciliationAgencyIds { @Test internal fun `will pass oath2 token to service`() = runTest { incidentsNomisApiMockServer.stubGetIncidentAgencies() nomisApiService.getAllAgencies() incidentsNomisApiMockServer.verify( getRequestedFor(anyUrl()).withHeader("Authorization", equalTo("Bearer ABCDE")), ) } @Test fun `will return agencies`() = runTest { incidentsNomisApiMockServer.stubGetIncidentAgencies() val agencies = nomisApiService.getAllAgencies() assertThat(agencies.size).isEqualTo(3) assertThat(agencies[0].agencyId).isEqualTo("ASI") assertThat(agencies[1].agencyId).isEqualTo("BFI") assertThat(agencies[2].agencyId).isEqualTo("WWI") } @Test internal fun `will call the Nomis reconciliation endpoint`() = runTest { incidentsNomisApiMockServer.stubGetIncidentAgencies() nomisApiService.getAllAgencies() incidentsNomisApiMockServer.verify(getRequestedFor(urlPathEqualTo("/incidents/reconciliation/agencies"))) } } @Nested @DisplayName("GET /incidents/reconciliation/agency/{agencyId}/counts") inner class GetReconciliationCounts { @Test internal fun `will pass oath2 token to service`() = runTest { incidentsNomisApiMockServer.stubGetReconciliationAgencyIncidentCounts() nomisApiService.getIncidentsReconciliation("ASI") incidentsNomisApiMockServer.verify( getRequestedFor(anyUrl()).withHeader("Authorization", equalTo("Bearer ABCDE")), ) } @Test internal fun `will pass NOMIS agency id to service`() = runTest { incidentsNomisApiMockServer.stubGetReconciliationAgencyIncidentCounts() nomisApiService.getIncidentsReconciliation("ASI") incidentsNomisApiMockServer.verify( getRequestedFor(urlPathEqualTo("/incidents/reconciliation/agency/ASI/counts")), ) } @Test fun `will return agency incident counts`() = runTest { incidentsNomisApiMockServer.stubGetReconciliationAgencyIncidentCounts(closed = 4) val agencyCount = nomisApiService.getIncidentsReconciliation("ASI") assertThat(agencyCount.agencyId).isEqualTo("ASI") assertThat(agencyCount.incidentCount.openIncidents).isEqualTo(3) assertThat(agencyCount.incidentCount.closedIncidents).isEqualTo(4) } } @Nested @DisplayName("GET /incidents/reconciliation/agency/{agencyId}/ids") inner class GetReconciliationOpenIncidentIds { @Test internal fun `will pass oath2 token to service`() = runTest { incidentsNomisApiMockServer.stubGetReconciliationOpenIncidentIds("ASI", 33, 35) nomisApiService.getOpenIncidentIds("ASI", 2, 5) incidentsNomisApiMockServer.verify( getRequestedFor(anyUrl()).withHeader("Authorization", equalTo("Bearer ABCDE")), ) } @Test internal fun `will pass NOMIS agency id to service`() = runTest { incidentsNomisApiMockServer.stubGetReconciliationOpenIncidentIds("ASI", 33, 35) nomisApiService.getOpenIncidentIds("ASI", 2, 5) incidentsNomisApiMockServer.verify( getRequestedFor(urlPathEqualTo("/incidents/reconciliation/agency/ASI/ids")), ) } @Test fun `will return open incident Ids`() = runTest { incidentsNomisApiMockServer.stubGetReconciliationOpenIncidentIds("ASI", 33, 35) val incidentIds = nomisApiService.getOpenIncidentIds("ASI", 2, 5) assertThat(incidentIds.totalElements).isEqualTo(40) assertThat(incidentIds.content.size).isEqualTo(3) assertThat(incidentIds.content).extracting<Long>(IncidentIdResponse::incidentId).containsExactly(33, 34, 35) } } }
1
Kotlin
1
2
1e1dcd50796c5d6412167ba62e855e3d7935b3cd
7,889
hmpps-prisoner-from-nomis-migration
MIT License
app/src/main/java/np/com/siddharthaghimire/shuffly/data/api/TiktokApi.kt
ghimiresiddhartha
826,586,560
false
{"Kotlin": 82328}
/* * Copyright 2024 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package np.com.siddharthaghimire.shuffly.data.api import np.com.siddharthaghimire.shuffly.BuildConfig.HEADER_T import np.com.siddharthaghimire.shuffly.BuildConfig.MAX_RESULT import np.com.siddharthaghimire.shuffly.BuildConfig.SEARCH_ENDPOINT import np.com.siddharthaghimire.shuffly.BuildConfig.T_SEARCH_KEYWORD import np.com.siddharthaghimire.shuffly.BuildConfig.T_TRENDING_ENDPOINT import np.com.siddharthaghimire.shuffly.data.models.tiktok.search.TiktokSearchResponse import np.com.siddharthaghimire.shuffly.data.models.tiktok.trending.TiktokTrendingResponse import retrofit2.Response import retrofit2.http.GET import retrofit2.http.Headers import retrofit2.http.Query interface TiktokApi { @GET(T_TRENDING_ENDPOINT) @Headers(HEADER_T) suspend fun fetchTiktokTrendingVideos( @retrofit2.http.Header("X-RapidAPI-Key") apiKey: String, @Query("region") region: String, @Query("count") count: Int = MAX_RESULT ): Response<TiktokTrendingResponse> @GET(SEARCH_ENDPOINT) @Headers(HEADER_T) suspend fun fetchTiktokSearchVideos( @retrofit2.http.Header("X-RapidAPI-Key") apiKey: String, @Query("region") region: String, @Query("cursor") cursor: Int, @Query("keywords") keyword: String = T_SEARCH_KEYWORD, @Query("count") count: Int = MAX_RESULT, @Query("publish_time") publishTime: Int = 0, @Query("sort_type") sortType: Int = 0 ): Response<TiktokSearchResponse> }
0
Kotlin
0
0
b292f04ca27d554f635d914656ddc386746dba52
2,088
shuffly-app
Apache License 2.0
app/src/main/java/com/alpha/dev/schedule_dark_theme/ThemeDialog.kt
shank03
285,741,412
false
null
/* * Copyright (c) 2023, Shashank Verma <shashank.verma2002@gmail.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. */ package com.alpha.dev.schedule_dark_theme import android.content.Context import android.os.Bundle import androidx.appcompat.app.AppCompatDelegate import androidx.appcompat.app.AppCompatDialog import com.alpha.dev.schedule_dark_theme.databinding.ThemeDialogBinding class ThemeDialog(context: Context) : AppCompatDialog(context) { private val ctx = context private lateinit var binding: ThemeDialogBinding override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ThemeDialogBinding.inflate(layoutInflater) setContentView(binding.root) window!!.setBackgroundDrawableResource(R.drawable.bg_recent) when (PreferenceHelper(ctx).getInt(THEME, defTheme)) { AppCompatDelegate.MODE_NIGHT_YES -> binding.darkCheck.isChecked = true AppCompatDelegate.MODE_NIGHT_NO -> binding.lightCheck.isChecked = true AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM -> binding.defaultCheck.isChecked = true } binding.lightCheck.setOnCheckedChangeListener { compoundButton, _ -> if (compoundButton.isChecked) { log("Theme", "App Theme -> MODE_NIGHT_NO", ctx) saveTheme(AppCompatDelegate.MODE_NIGHT_NO) AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) dismiss() } } binding.darkCheck.setOnCheckedChangeListener { compoundButton, _ -> if (compoundButton.isChecked) { log("Theme", "App Theme -> MODE_NIGHT_YES", ctx) saveTheme(AppCompatDelegate.MODE_NIGHT_YES) AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) dismiss() } } binding.defaultCheck.setOnCheckedChangeListener { compoundButton, _ -> if (compoundButton.isChecked) { log("Theme", "App Theme -> MODE_NIGHT_FOLLOW_SYSTEM", ctx) saveTheme(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM) dismiss() } } } private fun saveTheme(int: Int) { PreferenceHelper(ctx).putInt(THEME, int) } }
1
null
1
1
de1a89678e610c7f712da08ca0c3f61ee5995cc5
2,971
Schedule-Dark-Theme
MIT License
src/sketches/FlowLines.kt
JBWills
291,822,812
false
null
package sketches import appletExtensions.withStroke import controls.controlsealedclasses.Slider.Companion.slider import controls.controlsealedclasses.Toggle.Companion.toggle import controls.panels.ControlStyle import controls.panels.TabsBuilder.Companion.tabs import controls.panels.panelext.noisePanel import controls.props.PropData import coordinate.BoundRect import coordinate.Circ import coordinate.Deg import coordinate.Point import fastnoise.Noise import kotlinx.serialization.Serializable import org.locationtech.jts.geom.Envelope import sketches.base.SimpleCanvasSketch import util.algorithms.packMemo import util.algorithms.streamLines import util.layers.LayerSVGConfig import util.numbers.sqrt import util.polylines.PolyLine import util.print.Pen import util.quadTree.GQuadtree import util.random.randItem import util.random.randomLightColor import java.awt.Color import kotlin.random.Random /** * Flow lines */ class FlowLinesSketch : SimpleCanvasSketch<FlowLinesData>("FlowLines", FlowLinesData()) { private fun Point.toEnvelope(dist: Double) = Envelope( x - dist, x + dist, y - dist, y + dist, ) private fun Random.generateCircles(generatorData: FlowGeneratorData): List<Circ> { val bound = boundRect.expandPercent(0.5) return packMemo( this, generatorData.placementRandomSeed, bound, (bound.area / generatorData.numPoints).sqrt() / 2, generatorData.numPoints, generatorData.numAttempts, ) } private fun Point.generateFlowLine( bound: BoundRect, generatorData: FlowGeneratorData, linesData: FlowLineData, pointTree: GQuadtree<Point> ): PolyLine? { val steps = max(1, (linesData.length / linesData.step).toInt()) val resultLine = mutableListOf<Point>() var lastPoint = this var length = 0.0 for (stepIndex in 0..steps) { resultLine.add(lastPoint) val direction = Deg(generatorData.fieldNoise.get(lastPoint) * 360) val newPoint = lastPoint + direction.unitVector * linesData.step if (linesData.limitDistanceToOtherLines && pointTree.query(newPoint.toEnvelope(linesData.maxDistanceFromOtherLines / 2)) .any { it.dist(newPoint) < linesData.maxDistanceFromOtherLines } ) { break } if (!bound.contains(newPoint)) { break } length += linesData.step lastPoint = newPoint } return if (length > linesData.minLength) resultLine else null } private fun List<PolyLine>.groupByColor( random: Random, colorData: FlowColorData ): List<Pair<Color, PolyLine>> { val colors = Array(colorData.numColors) { random.randomLightColor() } return map { line -> random.randItem(colors) to line } } override fun drawLayers(drawInfo: DrawInfo, onNextLayer: (LayerSVGConfig) -> Unit) { val (generatorData, linesData, colorData) = drawInfo.dataValues val maxDistDiv2 = linesData.maxDistanceFromOtherLines / 2 onNextLayer(LayerSVGConfig(nextLayerName = "Circles", style = Pen.GellyColorDarkPeach.style)) val r = Random(generatorData.placementRandomSeed) val circles = r.generateCircles(generatorData) onNextLayer(LayerSVGConfig(nextLayerName = "Lines", style = Pen.GellyColorBlue.style)) val pointTree = GQuadtree<Point> { Envelope( x - maxDistDiv2, x + maxDistDiv2, y - maxDistDiv2, y + maxDistDiv2, ) } val lines = if (!linesData.useOldVersion) { streamLines( generatorData.placementRandomSeed, boundRect.expand(0.5), distance = linesData.maxDistanceFromOtherLines, lengthRange = linesData.minLength..(if (linesData.enforceMaxLength) linesData.length else Double.MAX_VALUE), step = linesData.step, dTest = linesData.maxDistanceFromOtherLines * linesData.dTest, ) { Deg(generatorData.fieldNoise.get(it) * 360 * generatorData.angleScale) } } else { circles .shuffled() .asSequence() .map(Circ::origin) .map { point -> val line = point.generateFlowLine( boundRect.expandPercent(0.5), generatorData, linesData, pointTree, ) if (linesData.limitDistanceToOtherLines) { line?.map { pointTree.insert(it) } } line } .filterNotNull() .toList() } lines.groupByColor(r, colorData).map { (color, lines) -> withStroke(color) { lines.draw(boundRect) } } } } @Serializable data class FlowColorData( var numColors: Int = 2, ) @Serializable data class FlowLineData( var step: Double = 3.0, var length: Double = 10.0, var enforceMaxLength: Boolean = false, var minLength: Double = 0.0, var maxDistanceFromOtherLines: Double = 0.0, var dTest: Double = 0.5, var limitDistanceToOtherLines: Boolean = false, var useOldVersion: Boolean = false, ) @Serializable data class FlowGeneratorData( var fieldNoise: Noise = Noise.DEFAULT, var angleScale: Double = 1.0, var placementRandomSeed: Int = 0, var numPoints: Int = 1_000, var numAttempts: Int = 5, ) @Serializable data class FlowLinesData( var generatorData: FlowGeneratorData = FlowGeneratorData(), var linesData: FlowLineData = FlowLineData(), var colorData: FlowColorData = FlowColorData(), ) : PropData<FlowLinesData> { override fun bind() = tabs { tab("Global") { noisePanel(generatorData::fieldNoise, showStrengthSliders = false, style = ControlStyle.Gray) slider(generatorData::angleScale, 0.01..2.0) row { slider(generatorData::placementRandomSeed, 0..1000) slider(generatorData::numAttempts, 1..50) } slider(generatorData::numPoints, 1..100_000) } tab("Lines") { slider(linesData::step, 0.1..10.0) row { slider(linesData::length, 0.0..800.0) col { widthRatio = 0.3 toggle(linesData::enforceMaxLength) } } slider(linesData::minLength, 0.0..100.0) row { slider(linesData::maxDistanceFromOtherLines, 0..100) slider(linesData::dTest, 0.0..1.0) } row { toggle(linesData::limitDistanceToOtherLines) toggle(linesData::useOldVersion) } } tab("Colors") { slider(colorData::numColors, 1..5) } } override fun clone() = copy() override fun toSerializer() = serializer() } fun main() = FlowLinesSketch().run()
0
Kotlin
0
0
569b27c1cb1dc6b2c37e79dfa527b9396c7a2f88
6,516
processing-sketches
MIT License
integration-tests/hibernate-reactive-panache-kotlin/src/main/kotlin/io/quarkus/it/panache/reactive/kotlin/TestEndpoint.kt
patrox
377,393,180
false
null
@file:Suppress("ReactiveStreamsUnusedPublisher") package io.quarkus.it.panache.reactive.kotlin import io.quarkus.hibernate.reactive.panache.Panache import io.quarkus.hibernate.reactive.panache.common.runtime.ReactiveTransactional import io.quarkus.hibernate.reactive.panache.kotlin.PanacheEntityBase import io.quarkus.hibernate.reactive.panache.kotlin.PanacheQuery import io.quarkus.panache.common.Page import io.quarkus.panache.common.Page.ofSize import io.quarkus.panache.common.Parameters.with import io.quarkus.panache.common.Sort import io.quarkus.panache.common.exception.PanacheQueryException import io.smallrye.mutiny.Uni import jakarta.inject.Inject import jakarta.persistence.LockModeType import jakarta.persistence.NoResultException import jakarta.persistence.NonUniqueResultException import jakarta.ws.rs.GET import jakarta.ws.rs.Path import java.util.function.Supplier import java.util.stream.Stream import org.hibernate.engine.spi.SelfDirtinessTracker import org.junit.jupiter.api.Assertions import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue @Path("test") class TestEndpoint { @Inject lateinit var bug5274EntityRepository: Bug5274EntityRepository @Inject lateinit var bug5885EntityRepository: Bug5885EntityRepository @Inject lateinit var personDao: PersonRepository @Inject lateinit var dogDao: DogDao @Inject lateinit var addressDao: AddressDao @Inject lateinit var namedQueryRepository: NamedQueryRepository @Inject lateinit var namedQueryWith2QueriesRepository: NamedQueryWith2QueriesRepository @GET @Path("ignored-properties") fun ignoredProperties(): Person { Person::class.java.getMethod("\$\$_hibernate_read_id") Person::class.java.getMethod("\$\$_hibernate_read_name") Assertions.assertThrows(NoSuchMethodException::class.java) { Person::class.java.getMethod("\$\$_hibernate_read_persistent") } // no need to persist it, we can fake it val person = Person() person.id = 666L person.name = "Eddie" person.status = Status.DECEASED return person } @GET @Path("5274") fun testBug5274(): Uni<String> { return bug5274EntityRepository.count().map { "OK" } } @GET @Path("5885") fun testBug5885(): Uni<String> { return bug5885EntityRepository.findById(1L).map { "OK" } } @GET @Path("7721") fun testBug7721(): Uni<String> { val entity = Bug7721Entity() return Panache.withTransaction { entity.persist<Bug7721Entity>().flatMap { entity.delete() }.map { "OK" } } } @GET @Path("8254") @ReactiveTransactional fun testBug8254(): Uni<String> { val owner = CatOwner("8254") return owner .persist<CatOwner>() .flatMap { Cat(owner).persist<Cat>() } .flatMap { Cat(owner).persist<Cat>() } .flatMap { Cat(owner).persist<Cat>() } // This used to fail with an invalid query "SELECT COUNT(*) SELECT DISTINCT cat.owner // FROM Cat cat WHERE cat.owner = ?1" // Should now result in a valid query "SELECT COUNT(DISTINCT cat.owner) FROM Cat cat // WHERE cat.owner = ?1" .flatMap { CatOwner.find("SELECT DISTINCT cat.owner FROM Cat cat WHERE cat.owner = ?1", owner) .count() } .flatMap { count -> assertEquals(1L, count) CatOwner.find("SELECT cat.owner FROM Cat cat WHERE cat.owner = ?1", owner).count() } .flatMap { count -> assertEquals(3L, count) Cat.find("SELECT cat FROM Cat cat WHERE cat.owner = ?1", owner).count() } .flatMap { count -> assertEquals(3L, count) Cat.find("FROM Cat WHERE owner = ?1", owner).count() } .flatMap { count -> assertEquals(3L, count) Cat.find("owner", owner).count() } .flatMap { count -> assertEquals(3L, count) CatOwner.find("name = ?1", "8254").count() } .map { count -> assertEquals(1L, count) "OK" } } @GET @Path("9025") @ReactiveTransactional fun testBug9025(): Uni<String> { val apple = Fruit("apple", "red") val orange = Fruit("orange", "orange") val banana = Fruit("banana", "yellow") return Fruit.persist(apple, orange, banana).flatMap { val query = Fruit.find("select name, color from Fruit").page(ofSize(1)) query.list().flatMap { query.pageCount() }.map { "OK" } } } @GET @Path("9036") @ReactiveTransactional fun testBug9036(): Uni<String> { return Person.deleteAll() .flatMap { Person().persist<Person>() } .flatMap { val deadPerson = Person() deadPerson.name = "Stef" deadPerson.status = Status.DECEASED deadPerson.persist<PanacheEntityBase>() } .flatMap { val livePerson = Person() livePerson.name = "Stef" livePerson.status = Status.LIVING livePerson.persist<PanacheEntityBase>() } .flatMap { Person.count() } .flatMap { count -> assertEquals(3, count) Person.listAll() } .flatMap { list -> assertEquals(3, list.size) Person.find("status", Status.LIVING).firstResult() } .flatMap { livePerson -> // should be filtered val query = Person.findAll(Sort.by("id")) .filter("Person.isAlive") .filter("Person.hasName", with("name", "Stef")) query .count() .flatMap { count -> assertEquals(1, count) query.list() } .flatMap { list -> assertEquals(1, list.size) query.firstResult() } .flatMap { result -> assertEquals(livePerson, result) query.singleResult() } .flatMap { result -> assertEquals(livePerson, result) Person.count() } .flatMap { count -> assertEquals(3, count) Person.listAll() } .flatMap { list -> assertEquals(3, list.size) Person.deleteAll() } .map { "OK" } } } @GET @Path("composite") @ReactiveTransactional fun testCompositeKey(): Uni<String> { val obj = ObjectWithCompositeId() obj.part1 = "part1" obj.part2 = "part2" obj.description = "description" return obj.persist<ObjectWithCompositeId>().flatMap { val key = ObjectWithCompositeId.ObjectKey("part1", "part2") ObjectWithCompositeId.findById(key) .flatMap { result -> Assertions.assertNotNull(result) ObjectWithCompositeId.deleteById(key) } .flatMap { deleted -> assertTrue(deleted) ObjectWithCompositeId.deleteById(key) } .flatMap { deleted -> assertFalse(deleted) val embeddedKey = ObjectWithEmbeddableId.ObjectKey("part1", "part2") val embeddable = ObjectWithEmbeddableId() embeddable.key = embeddedKey embeddable.description = "description" embeddable .persist<ObjectWithEmbeddableId>() .flatMap { ObjectWithEmbeddableId.findById(embeddedKey) } .flatMap { embeddableResult -> Assertions.assertNotNull(embeddableResult) ObjectWithEmbeddableId.deleteById(embeddedKey) } .flatMap { deleted2 -> assertTrue(deleted2) ObjectWithEmbeddableId.deleteById( ObjectWithEmbeddableId.ObjectKey("notexist1", "notexist2") ) } .map { deleted2 -> assertFalse(deleted2) "OK" } } } } @GET @Path("model") @ReactiveTransactional fun testModel(): Uni<String> { return Person.findAll() .list() .flatMap { persons -> assertEquals(0, persons.size) Person.listAll() } .flatMap { persons -> assertEquals(0, persons.size) assertThrows(NoResultException::class.java) { Person.findAll().singleResult() } } .flatMap { result -> Assertions.assertNull(result) makeSavedPerson() } .flatMap { person -> Assertions.assertNotNull(person.id) person.id as Long Person.count() .flatMap { count -> assertEquals(1, count) Person.count("name = ?1", "stef") } .flatMap { count -> assertEquals(1, count) Person.count("name = :name", with("name", "stef").map()) } .flatMap { count -> assertEquals(1, count) Person.count("name = :name", with("name", "stef")) } .flatMap { count -> assertEquals(1, count) Person.count("name", "stef") } .flatMap { count -> assertEquals(1, count) Dog.count() } .flatMap { count -> assertEquals(1, count) // FIXME: fetch assertEquals(1, person.dogs.size) Person.findAll().list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) Person.listAll() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) Person.findAll().firstResult() } .flatMap { personResult -> assertEquals(person, personResult) Person.findAll().singleResult() } .flatMap { personResult -> assertEquals(person, personResult) Person.find("name = ?1", "stef").list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) Person.find("FROM Person2 WHERE name = ?1", "stef").list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) Person.find("name = ?1", "stef") .withLock(LockModeType.PESSIMISTIC_READ) .list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) Person.list("name = ?1", "stef") } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) Person.find("name = :name", with("name", "stef").map()).list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) Person.find("name = :name", with("name", "stef")).list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) Person.list("name = :name", with("name", "stef").map()) } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) Person.find("name = :name", with("name", "stef").map()).list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) Person.list("name = :name", with("name", "stef")) } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) Person.find("name", "stef").list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) Person.find("name", "stef").firstResult() } .flatMap { personResult -> assertEquals(person, personResult) Person.find("name", "stef").singleResult() } .flatMap { personResult -> assertEquals(person, personResult) Person.find("name", "stef").singleResult() } .flatMap { personResult -> assertEquals(person, personResult) Person.list("#Person.getByName", with("name", "stef")) } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) assertThrows(PanacheQueryException::class.java) { Person.find("#Person.namedQueryNotFound").list() } } .flatMap { assertThrows(IllegalArgumentException::class.java) { Person.list("#Person.getByName", Sort.by("name"), with("name", "stef")) } } .flatMap { NamedQueryEntity.list("#NamedQueryMappedSuperClass.getAll") } .flatMap { NamedQueryEntity.list("#NamedQueryEntity.getAll") } .flatMap { NamedQueryWith2QueriesEntity.list("#NamedQueryWith2QueriesEntity.getAll1") } .flatMap { NamedQueryWith2QueriesEntity.list("#NamedQueryWith2QueriesEntity.getAll2") } .flatMap { Person.find("").list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) Person.findById(person.id!!) } .flatMap { byId -> assertEquals(person, byId) assertEquals("Person<" + person.id + ">", byId.toString()) Person.findById(person.id!!, LockModeType.PESSIMISTIC_READ) } .flatMap { byId -> assertEquals(person, byId) assertEquals("Person<" + person.id + ">", byId.toString()) person.delete() } .flatMap { Person.count() } .flatMap { count -> assertEquals(0, count) makeSavedPerson() } } .flatMap { person -> Person.count() .flatMap { count -> assertEquals(1, count) Person.delete("name = ?1", "emmanuel") } .flatMap { count -> assertEquals(0, count) Dog.delete("owner = ?1", person) } .flatMap { count -> assertEquals(1, count) Person.delete("name", "stef") } .flatMap { count -> assertEquals(1, count) makeSavedPerson() } } .flatMap { person -> Dog.delete("owner = :owner", with("owner", person).map()) .flatMap { count -> assertEquals(1, count) Person.delete("name", "stef") } .flatMap { count -> assertEquals(1, count) makeSavedPerson() } } .flatMap { person -> Dog.delete("owner = :owner", with("owner", person)) .flatMap { count -> assertEquals(1, count) Person.delete("name", "stef") } .flatMap { count -> assertEquals(1, count) makeSavedPerson() } } .flatMap { person -> Dog.delete("FROM Dog WHERE owner = :owner", with("owner", person)) .flatMap { count -> assertEquals(1, count) Person.delete("FROM Person2 WHERE name = ?1", "stef") } .flatMap { count -> assertEquals(1, count) makeSavedPerson() } } .flatMap { person -> Dog.delete("DELETE FROM Dog WHERE owner = :owner", with("owner", person)) .flatMap { count -> assertEquals(1, count) Person.delete("DELETE FROM Person2 WHERE name = ?1", "stef") } .map { count -> assertEquals(1, count) null } } .flatMap { Person.deleteAll() } .flatMap { count -> assertEquals(0, count) makeSavedPerson() } .flatMap { Dog.deleteAll() .flatMap { count -> assertEquals(1, count) Person.deleteAll() } .map { count -> assertEquals(1, count) null } } .flatMap { testPersist(PersistTest.Variadic) } .flatMap { testPersist(PersistTest.Iterable) } .flatMap { testPersist(PersistTest.Stream) } .flatMap { Person.deleteAll() } .flatMap { count -> assertEquals(6, count) testSorting() } // paging .flatMap { makeSavedPerson("0") } .flatMap { makeSavedPerson("1") } .flatMap { makeSavedPerson("2") } .flatMap { makeSavedPerson("3") } .flatMap { makeSavedPerson("4") } .flatMap { makeSavedPerson("5") } .flatMap { makeSavedPerson("6") } .flatMap { testPaging(Person.findAll()) } .flatMap { testPaging(Person.find("ORDER BY name")) } // range .flatMap { testRange(Person.findAll()) } .flatMap { testRange(Person.find("ORDER BY name")) } .flatMap { assertThrows(NonUniqueResultException::class.java) { Person.findAll().singleResult() } } .flatMap { Person.findAll().firstResult() } .flatMap { person -> Assertions.assertNotNull(person) Person.deleteAll() } .flatMap { count -> assertEquals(7, count) testUpdate() } .flatMap { Person.deleteById(666L) // not existing } .flatMap { deleted -> assertFalse(deleted) // persistAndFlush val person1 = Person() person1.name = "testFLush1" person1.uniqueName = "unique" person1.persist<Person>() } .flatMap { Person.deleteAll() } .map { "OK" } } @GET @Path("model1") @ReactiveTransactional @Suppress("CAST_NEVER_SUCCEEDS") fun testModel1(): Uni<String> { return Person.count() .flatMap { count -> assertEquals(0, count) makeSavedPerson("") } .flatMap { person -> val trackingPerson = person as SelfDirtinessTracker var dirtyAttributes = trackingPerson.`$$_hibernate_getDirtyAttributes`() assertEquals(0, dirtyAttributes.size) person.name = "1" dirtyAttributes = trackingPerson.`$$_hibernate_getDirtyAttributes`() assertEquals(1, dirtyAttributes.size) Person.count() } .map { count -> assertEquals(1, count) "OK" } } @GET @Path("model2") @ReactiveTransactional fun testModel2(): Uni<String> { return Person.count() .flatMap { count -> assertEquals(1, count) Person.findAll().firstResult() } .map { person -> assertEquals("1", person?.name) person?.name = "2" "OK" } } @GET @Path("projection1") @ReactiveTransactional fun testProjection(): Uni<String> { return Person.count() .flatMap { count -> assertEquals(1, count) Person.findAll().project(PersonName::class.java).firstResult() } .flatMap { person -> assertEquals("2", person?.name) Person.find("name", "2").project(PersonName::class.java).firstResult() } .flatMap { person -> assertEquals("2", person?.name) Person.find("name = ?1", "2").project(PersonName::class.java).firstResult() } .flatMap { person -> assertEquals("2", person?.name) Person.find("name = :name", with("name", "2")) .project(PersonName::class.java) .firstResult() } .flatMap { person -> assertEquals("2", person?.name) val query: PanacheQuery<PersonName> = Person.findAll().project(PersonName::class.java).page(0, 2) query .list() .flatMap { results -> assertEquals(1, results.size) query.nextPage() query.list() } .flatMap { results -> assertEquals(0, results.size) Person.findAll().project(PersonName::class.java).count() } .map { count -> assertEquals(1, count) "OK" } } } @GET @Path("projection2") @ReactiveTransactional fun testProjection2(): Uni<String> { val ownerName = "Julie" val catName = "Bubulle" val catWeight = 8.5 val catOwner = CatOwner(ownerName) return catOwner .persist<CatOwner>() .flatMap { Cat(catName, catOwner, catWeight).persist<Cat>() } .flatMap { Cat.find("name", catName).project(CatDto::class.java).firstResult() } .flatMap { cat -> assertEquals(catName, cat?.name) assertEquals(ownerName, cat?.ownerName) Cat.find( "select c.name, c.owner.name as ownerName from Cat c where c.name = :name", with("name", catName) ) .project(CatProjectionBean::class.java) .singleResult() } .flatMap { catView -> assertEquals(catName, catView.name) assertEquals(ownerName, catView.ownerName) Assertions.assertNull(catView.weight) Cat.find("select 'fake_cat', 'fake_owner', 12.5D from Cat c") .project(CatProjectionBean::class.java) .firstResult() } .map { catView -> assertEquals("fake_cat", catView?.name) assertEquals("fake_owner", catView?.ownerName) assertEquals(12.5, catView?.weight) // The spaces at the beginning are intentional Cat.find( " SELECT c.name, cast(null as string), SUM(c.weight) from Cat c where name = :name group by name ", with("name", catName) ) .project(CatProjectionBean::class.java) } .flatMap { projectionQuery: PanacheQuery<CatProjectionBean> -> projectionQuery.firstResult().map { catView: CatProjectionBean? -> assertEquals(catName, catView?.name) Assertions.assertNull(catView?.ownerName) assertEquals(catWeight, catView?.weight) } projectionQuery.count() } .map { count -> assertEquals(1L, count) // The spaces at the beginning are intentional Cat.find( " SELECT disTINct c.name, cast(null as string), SUM(c.weight) from Cat c where " + "name = :name group by name ", with("name", catName) ) .project(CatProjectionBean::class.java) } .flatMap { projectionQuery -> projectionQuery.firstResult().map { catView -> assertEquals(catName, catView?.name) Assertions.assertNull(catView?.ownerName) assertEquals(catWeight, catView?.weight) } projectionQuery.count() } .map { count -> assertEquals(1L, count) val exception = Assertions.assertThrows(PanacheQueryException::class.java) { Cat.find("select new FakeClass('fake_cat', 'fake_owner', 12.5) from Cat c") .project(CatProjectionBean::class.java) } assertTrue( exception.message!!.startsWith( "Unable to perform a projection on a 'select [distinct]? new' query" ) ) "OK" } } @GET @Path("model3") @ReactiveTransactional fun testModel3(): Uni<String> { return Person.count() .flatMap { count -> assertEquals(1, count) Person.findAll().firstResult() } .flatMap { person -> assertEquals("2", person?.name) Dog.deleteAll() } .flatMap { Person.deleteAll() } .flatMap { Address.deleteAll() } .flatMap { Person.count() } .map { count -> assertEquals(0, count) "OK" } } @GET @Path("model-dao") @ReactiveTransactional fun testModelDao(): Uni<String> { return personDao .findAll() .list() .flatMap { persons -> assertEquals(0, persons.size) personDao.listAll() } .flatMap { persons -> assertEquals(0, persons.size) assertThrows(NoResultException::class.java) { personDao.findAll().singleResult() } } .flatMap { personDao.findAll().firstResult() } .flatMap { result -> Assertions.assertNull(result) makeSavedPersonDao() } .flatMap { person -> Assertions.assertNotNull(person.id) personDao .count() .flatMap { count -> assertEquals(1, count) personDao.count("name = ?1", "stef") } .flatMap { count -> assertEquals(1, count) personDao.count("name = :name", with("name", "stef").map()) } .flatMap { count -> assertEquals(1, count) personDao.count("name = :name", with("name", "stef")) } .flatMap { count -> assertEquals(1, count) personDao.count("name", "stef") } .flatMap { count -> assertEquals(1, count) dogDao.count() } .flatMap { count -> assertEquals(1, count) // FIXME: fetch assertEquals(1, person.dogs.size) personDao.findAll().list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) personDao.listAll() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) personDao.findAll().firstResult() } .flatMap { personResult -> assertEquals(person, personResult) personDao.findAll().singleResult() } .flatMap { personResult -> assertEquals(person, personResult) personDao.find("name = ?1", "stef").list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) personDao .find("name = ?1", "stef") .withLock(LockModeType.PESSIMISTIC_READ) .list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) personDao.list("name = ?1", "stef") } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) personDao.find("name = :name", with("name", "stef").map()).list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) personDao.find("name = :name", with("name", "stef")).list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) personDao.list("name = :name", with("name", "stef").map()) } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) personDao.find("name = :name", with("name", "stef").map()).list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) personDao.list("name = :name", with("name", "stef")) } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) personDao.find("name", "stef").list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) personDao.find("name", "stef").firstResult() } .flatMap { personResult -> assertEquals(person, personResult) personDao.find("name", "stef").singleResult() } .flatMap { personResult -> assertEquals(person, personResult) personDao.find("name", "stef").singleResult() } .flatMap { personResult -> assertEquals(person, personResult) personDao.list("#Person.getByName", with("name", "stef")) } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) assertThrows(PanacheQueryException::class.java) { personDao.find("#Person.namedQueryNotFound").list() } } .flatMap { assertThrows(IllegalArgumentException::class.java) { personDao.list( "#Person.getByName", Sort.by("name"), with("name", "stef") ) } } .flatMap { namedQueryRepository.list("#NamedQueryMappedSuperClass.getAll") } .flatMap { namedQueryRepository.list("#NamedQueryEntity.getAll") } .flatMap { namedQueryWith2QueriesRepository.list( "#NamedQueryWith2QueriesEntity.getAll1" ) } .flatMap { namedQueryWith2QueriesRepository.list( "#NamedQueryWith2QueriesEntity.getAll2" ) } .flatMap { personDao.find("").list() } .flatMap { persons -> assertEquals(1, persons.size) assertEquals(person, persons[0]) personDao.findById(person.id!!) } .flatMap { byId -> assertEquals(person, byId) assertEquals("Person<${person.id}>", byId.toString()) personDao.findById(person.id!!, LockModeType.PESSIMISTIC_READ) } .flatMap { byId -> assertEquals(person, byId) assertEquals("Person<${person.id}>", byId.toString()) person.delete() } .flatMap { personDao.count() } .flatMap { count -> assertEquals(0, count) makeSavedPersonDao() } .flatMap { Person.count("#Person.countAll") .flatMap { count -> assertEquals(1, count) Person.count("#Person.countByName", with("name", "stef").map()) } .flatMap { count -> assertEquals(1, count) Person.count("#Person.countByName", with("name", "stef")) } .flatMap { count -> assertEquals(1, count) Person.count("#Person.countByName.ordinal", "stef") } .flatMap { count -> assertEquals(1, count) Uni.createFrom().voidItem() } } .flatMap { Person.update("#Person.updateAllNames", with("name", "stef2").map()) .flatMap { count -> assertEquals(1, count) Person.find("#Person.getByName", with("name", "stef2")).list() } .flatMap { persons -> assertEquals(1, persons.size) Person.update("#Person.updateAllNames", with("name", "stef3")) } .flatMap { count -> assertEquals(1, count) Person.find("#Person.getByName", with("name", "stef3")).list() } .flatMap { persons -> assertEquals(1, persons.size) Person.update( "#Person.updateNameById", with("name", "stef2").and("id", persons[0].id).map() ) } .flatMap { count -> assertEquals(1, count) Person.find("#Person.getByName", with("name", "stef2")).list() } .flatMap { persons -> assertEquals(1, persons.size) Person.update( "#Person.updateNameById", with("name", "stef3").and("id", persons[0].id) ) } .flatMap { count -> assertEquals(1, count) Person.find("#Person.getByName", with("name", "stef3")).list() } .flatMap { persons -> assertEquals(1, persons.size) Person.update( "#Person.updateNameById.ordinal", "stef", persons[0].id!! ) } .flatMap { count -> assertEquals(1, count) Person.find("#Person.getByName", with("name", "stef")).list() } .flatMap { persons -> assertEquals(1, persons.size) Uni.createFrom().voidItem() } } .flatMap { Dog.deleteAll() .flatMap { Person.delete("#Person.deleteAll") } .flatMap { count -> assertEquals(1, count) Person.find("").list() } .flatMap { persons -> assertEquals(0, persons.size) Uni.createFrom().voidItem() } } .flatMap { makeSavedPerson().flatMap { personToDelete -> Dog.deleteAll() .flatMap { Person.find("").list() } .flatMap { persons -> assertEquals(1, persons.size) Person.delete( "#Person.deleteById", with("id", personToDelete.id).map() ) } .flatMap { count -> assertEquals(1, count) Person.find("").list() } .flatMap { persons -> assertEquals(0, persons.size) Uni.createFrom().voidItem() } } } .flatMap { makeSavedPerson().flatMap { personToDelete -> Dog.deleteAll() .flatMap { Person.find("").list() } .flatMap { persons -> assertEquals(1, persons.size) Person.delete( "#Person.deleteById", with("id", personToDelete.id) ) } .flatMap { count -> assertEquals(1, count) Person.find("").list() } .flatMap { persons -> assertEquals(0, persons.size) Uni.createFrom().voidItem() } } } .flatMap { makeSavedPerson().flatMap { personToDelete -> Dog.deleteAll() .flatMap { Person.find("").list() } .flatMap { persons -> assertEquals(1, persons.size) Person.delete("#Person.deleteById.ordinal", personToDelete.id!!) } .flatMap { count -> assertEquals(1, count) Person.find("").list() } .flatMap { persons -> assertEquals(0, persons.size) makeSavedPersonDao() } } } } .flatMap { person -> personDao .count() .flatMap { count -> assertEquals(1, count) personDao.delete("name = ?1", "emmanuel") } .flatMap { count -> assertEquals(0, count) dogDao.delete("owner = ?1", person) } .flatMap { count -> assertEquals(1, count) personDao.delete("name", "stef") } .flatMap { count -> assertEquals(1, count) makeSavedPersonDao() } } .flatMap { person -> dogDao .delete("owner = :owner", with("owner", person).map()) .flatMap { count -> assertEquals(1, count) personDao.delete("name", "stef") } .flatMap { count -> assertEquals(1, count) makeSavedPersonDao() } } .flatMap { person -> dogDao .delete("owner = :owner", with("owner", person)) .flatMap { count -> assertEquals(1, count) personDao.delete("name", "stef") } .flatMap { count -> assertEquals(1, count) makeSavedPersonDao() } } .flatMap { person -> dogDao .delete("FROM Dog WHERE owner = :owner", with("owner", person)) .flatMap { count -> assertEquals(1, count) personDao.delete("FROM Person2 WHERE name = ?1", "stef") } .flatMap { count -> assertEquals(1, count) makeSavedPersonDao() } } .flatMap { person -> dogDao .delete("DELETE FROM Dog WHERE owner = :owner", with("owner", person)) .flatMap { count -> assertEquals(1, count) personDao.delete("DELETE FROM Person2 WHERE name = ?1", "stef") } .map { count -> assertEquals(1, count) null } } .flatMap { v -> personDao.deleteAll() } .flatMap { count -> assertEquals(0, count) makeSavedPersonDao() } .flatMap { person -> dogDao .deleteAll() .flatMap { count -> assertEquals(1, count) personDao.deleteAll() } .map { count -> assertEquals(1, count) null } } .flatMap { testPersistDao(PersistTest.Iterable) } .flatMap { v -> testPersistDao(PersistTest.Stream) } .flatMap { v -> testPersistDao(PersistTest.Variadic) } .flatMap { personDao.deleteAll() } .flatMap { count -> assertEquals(6, count) testSorting() } .flatMap { makeSavedPersonDao("0") } .flatMap { makeSavedPersonDao("1") } .flatMap { makeSavedPersonDao("2") } .flatMap { makeSavedPersonDao("3") } .flatMap { makeSavedPersonDao("4") } .flatMap { makeSavedPersonDao("5") } .flatMap { makeSavedPersonDao("6") } .flatMap { testPaging(personDao.findAll()) } .flatMap { v -> testPaging(personDao.find("ORDER BY name")) } // range .flatMap { testRange(personDao.findAll()) } .flatMap { testRange(personDao.find("ORDER BY name")) } .flatMap { assertThrows(NonUniqueResultException::class.java) { personDao.findAll().singleResult() } } .flatMap { personDao.findAll().firstResult() } .flatMap { person -> Assertions.assertNotNull(person) personDao.deleteAll() } .flatMap { count -> assertEquals(7, count) testUpdateDao() } .flatMap { // delete by id val toRemove = Person() toRemove.name = "testDeleteById" toRemove.uniqueName = "testDeleteByIdUnique" toRemove.persist<Person>().flatMap { personDao.deleteById(toRemove.id!!) } } .flatMap { deleted -> assertTrue(deleted) personDao.deleteById(666L) // not existing } .flatMap { deleted -> assertFalse(deleted) // persistAndFlush val person1 = Person() person1.name = "testFLush1" person1.uniqueName = "unique" personDao.persistAndFlush(person1) } .flatMap { personDao.deleteAll() } .map { "OK" } } @GET @Path("testSortByNullPrecedence") @ReactiveTransactional fun testSortByNullPrecedence(): Uni<String> { return Person.deleteAll() .flatMap { val stefPerson = Person() stefPerson.name = "Stef" stefPerson.uniqueName = "stef" val josePerson = Person() josePerson.name = null josePerson.uniqueName = "jose" Person.persist(stefPerson, josePerson) } .flatMap { Person.findAll(Sort.by("name", Sort.NullPrecedence.NULLS_FIRST)).list() } .flatMap { list -> assertEquals("jose", list[0].uniqueName) Person.findAll(Sort.by("name", Sort.NullPrecedence.NULLS_LAST)).list() } .flatMap { list -> assertEquals("jose", list[list.size - 1].uniqueName) Person.deleteAll() } .map { "OK" } } private fun makeSavedPerson(): Uni<Person> { val uni: Uni<Person> = makeSavedPerson("") return uni.flatMap { person -> val dog = Dog("octave", "dalmatian") dog.owner = person person.dogs.add(dog) dog.persist<Dog>().map { person } } } private fun makeSavedPerson(suffix: String = ""): Uni<Person> { val address = Address() address.street = "stef street" val person = Person() person.name = "stef$suffix" person.status = Status.LIVING person.address = address return person.address!!.persist<Address>().flatMap { person.persist() } } private fun assertThrows(exceptionClass: Class<out Throwable>, f: Supplier<Uni<*>>): Uni<Void> { val uni = try { f.get() } catch (t: Throwable) { Uni.createFrom().failure<Any>(t) } return uni.onItemOrFailure() .invoke { r: Any?, t: Throwable? -> System.err.println("Got back val: $r and exception $t") } .onItem() .invoke { _ -> Assertions.fail("Did not throw " + exceptionClass.name) } .onFailure(exceptionClass) .recoverWithItem { -> null } .map { it: Any? -> null } } private fun testPersist(persistsTest: PersistTest): Uni<Void> { val person1 = Person() person1.name = "stef1" val person2 = Person() person2.name = "stef2" assertFalse(person1.isPersistent()) assertFalse(person2.isPersistent()) return when (persistsTest) { PersistTest.Iterable -> Person.persist(listOf(person1, person2)) PersistTest.Stream -> Person.persist(Stream.of(person1, person2)) PersistTest.Variadic -> Person.persist(person1, person2) }.map { assertTrue(person1.isPersistent()) assertTrue(person2.isPersistent()) null } } private fun testSorting(): Uni<Unit> { val person1 = Person() person1.name = "stef" person1.status = Status.LIVING val person2 = Person() person2.name = "stef" person2.status = Status.DECEASED val person3 = Person() person3.name = "emmanuel" person3.status = Status.LIVING return person1 .persist<Person>() .flatMap { person2.persist<Person>() } .flatMap { person3.persist<Person>() } .flatMap { val sort1 = Sort.by("name", "status") val order1 = listOf(person3, person2, person1) val sort2 = Sort.descending("name", "status") val order2 = listOf(person1, person2) Person.findAll(sort1) .list() .flatMap { list -> assertEquals(order1, list) Person.listAll(sort1) } .flatMap { list -> assertEquals(order1, list) Person.find("name", sort2, "stef").list() } .flatMap { list -> assertEquals(order2, list) Person.list("name", sort2, "stef") } .flatMap { list -> assertEquals(order2, list) Person.find("name = :name", sort2, with("name", "stef").map()).list() } .flatMap { list -> assertEquals(order2, list) Person.list("name = :name", sort2, with("name", "stef").map()) } .flatMap { list -> assertEquals(order2, list) Person.find("name = :name", sort2, with("name", "stef")).list() } .flatMap { list -> assertEquals(order2, list) Person.list("name = :name", sort2, with("name", "stef")) } } .flatMap { Person.deleteAll() } .map { count -> assertEquals(3, count) } } private fun testPaging(query: PanacheQuery<Person>): Uni<Void> { // No paging allowed until a page is set up Assertions.assertThrows(UnsupportedOperationException::class.java) { query.firstPage() } Assertions.assertThrows(UnsupportedOperationException::class.java) { query.previousPage() } Assertions.assertThrows(UnsupportedOperationException::class.java) { query.nextPage() } Assertions.assertThrows(UnsupportedOperationException::class.java) { query.lastPage() } Assertions.assertThrows(UnsupportedOperationException::class.java) { query.hasNextPage() } Assertions.assertThrows(UnsupportedOperationException::class.java) { query.hasPreviousPage() } Assertions.assertThrows(UnsupportedOperationException::class.java) { query.page() } Assertions.assertThrows(UnsupportedOperationException::class.java) { query.pageCount() } return query .page(0, 3) .list() .flatMap { persons: List<Person> -> assertEquals(3, persons.size) assertEquals("stef0", persons[0].name) assertEquals("stef1", persons[1].name) assertEquals("stef2", persons[2].name) query.page(1, 3).list() } .flatMap { persons: List<Person> -> assertEquals(3, persons.size) assertEquals("stef3", persons[0].name) assertEquals("stef4", persons[1].name) assertEquals("stef5", persons[2].name) query.page(2, 3).list() } .flatMap { persons: List<Person> -> assertEquals(1, persons.size) assertEquals("stef6", persons[0].name) query.page(2, 4).list() } .flatMap { persons: List<Person> -> assertEquals(0, persons.size) query.page(Page(3)).list() } .flatMap { persons: List<Person> -> assertEquals(3, persons.size) assertEquals("stef0", persons[0].name) assertEquals("stef1", persons[1].name) assertEquals("stef2", persons[2].name) query.page(Page(1, 3)).list() } .flatMap { persons: List<Person> -> assertEquals(3, persons.size) assertEquals("stef3", persons[0].name) assertEquals("stef4", persons[1].name) assertEquals("stef5", persons[2].name) query.page(Page(2, 3)).list() } .flatMap { persons: List<Person> -> assertEquals(1, persons.size) assertEquals("stef6", persons[0].name) query.page(Page(3, 3)).list() } .flatMap { persons: List<Person> -> assertEquals(0, persons.size) query.page(Page(3)).list() } .flatMap { persons: List<Person> -> assertEquals(3, persons.size) assertEquals("stef0", persons[0].name) assertEquals("stef1", persons[1].name) assertEquals("stef2", persons[2].name) query.hasNextPage() } .flatMap { hasNextPage: Boolean -> assertTrue(hasNextPage) assertFalse(query.hasPreviousPage()) query.nextPage().list() } .flatMap { persons: List<Person> -> assertEquals(1, query.page().index) assertEquals(3, query.page().size) assertEquals(3, persons.size) assertEquals("stef3", persons[0].name) assertEquals("stef4", persons[1].name) assertEquals("stef5", persons[2].name) query.hasNextPage() } .flatMap { hasNextPage: Boolean -> assertTrue(hasNextPage) assertTrue(query.hasPreviousPage()) query.nextPage().list() } .flatMap { persons: List<Person> -> assertEquals(1, persons.size) assertEquals("stef6", persons[0].name) query.hasNextPage() } .flatMap { hasNextPage: Boolean -> assertFalse(hasNextPage) assertTrue(query.hasPreviousPage()) query.nextPage().list() } .flatMap { persons: List<Person> -> assertEquals(0, persons.size) query.count() } .flatMap { count -> assertEquals(7, count) query.pageCount() } .flatMap { count -> assertEquals(3, count) query.page(0, 3).range(0, 1).list() } .map { persons: List<Person> -> assertEquals(2, persons.size) assertEquals("stef0", persons[0].name) assertEquals("stef1", persons[1].name) null } } private fun testRange(query: PanacheQuery<Person>): Uni<Void> { return query .range(0, 2) .list() .flatMap { persons: List<Person> -> assertEquals(3, persons.size) assertEquals("stef0", persons[0].name) assertEquals("stef1", persons[1].name) assertEquals("stef2", persons[2].name) query.range(3, 5).list() } .flatMap { persons: List<Person> -> assertEquals(3, persons.size) assertEquals("stef3", persons[0].name) assertEquals("stef4", persons[1].name) assertEquals("stef5", persons[2].name) query.range(6, 8).list() } .flatMap { persons: List<Person> -> assertEquals(1, persons.size) assertEquals("stef6", persons[0].name) query.range(8, 12).list() } .flatMap { persons: List<Person> -> assertEquals(0, persons.size) // mix range with page Assertions.assertThrows(UnsupportedOperationException::class.java) { query.range(0, 2).nextPage() } Assertions.assertThrows(UnsupportedOperationException::class.java) { query.range(0, 2).previousPage() } Assertions.assertThrows(UnsupportedOperationException::class.java) { query.range(0, 2).pageCount() } // Assertions.assertThrows(UnsupportedOperationException.class, // () -> query.range(0, 2).lastPage()); Assertions.assertThrows(UnsupportedOperationException::class.java) { query.range(0, 2).firstPage() } Assertions.assertThrows(UnsupportedOperationException::class.java) { query.range(0, 2).hasPreviousPage() } Assertions.assertThrows(UnsupportedOperationException::class.java) { query.range(0, 2).hasNextPage() } Assertions.assertThrows(UnsupportedOperationException::class.java) { query.range(0, 2).page() } query.range(0, 2).page(0, 3).list() } .map { persons: List<Person> -> assertEquals(3, persons.size) assertEquals("stef0", persons[0].name) assertEquals("stef1", persons[1].name) assertEquals("stef2", persons[2].name) null } } private fun testUpdate(): Uni<Void> { return makeSavedPerson("p1") .flatMap { makeSavedPerson("p2") } .flatMap { Person.update( "update from Person2 p set p.name = 'stefNEW' where p.name = ?1", "stefp1" ) } .flatMap { updateByIndexParameter -> assertEquals(1, updateByIndexParameter, "More than one Person updated") Person.update( "update from Person2 p set p.name = 'stefNEW' where p.name = :pName", with("pName", "stefp2").map() ) } .flatMap { updateByNamedParameter -> assertEquals(1, updateByNamedParameter, "More than one Person updated") Person.deleteAll() } .flatMap { count -> assertEquals(2L, count) makeSavedPerson("p1") } .flatMap { makeSavedPerson("p2") } .flatMap { Person.update("from Person2 p set p.name = 'stefNEW' where p.name = ?1", "stefp1") } .flatMap { updateByIndexParameter -> assertEquals(1, updateByIndexParameter, "More than one Person updated") Person.update( "from Person2 p set p.name = 'stefNEW' where p.name = :pName", with("pName", "stefp2").map() ) } .flatMap { updateByNamedParameter -> assertEquals(1, updateByNamedParameter, "More than one Person updated") Person.deleteAll() } .flatMap { count -> assertEquals(2, count) makeSavedPerson("p1") } .flatMap { makeSavedPerson("p2") } .flatMap { Person.update("set name = 'stefNEW' where name = ?1", "stefp1") } .flatMap { updateByIndexParameter -> assertEquals(1, updateByIndexParameter, "More than one Person updated") Person.update( "set name = 'stefNEW' where name = :pName", with("pName", "stefp2").map() ) } .flatMap { updateByNamedParameter -> assertEquals(1, updateByNamedParameter, "More than one Person updated") Person.deleteAll() } .flatMap { count -> assertEquals(2, count) makeSavedPerson("p1") } .flatMap { makeSavedPerson("p2") } .flatMap { Person.update("name = 'stefNEW' where name = ?1", "stefp1") } .flatMap { updateByIndexParameter: Any -> assertEquals(1, updateByIndexParameter, "More than one Person updated") Person.update("name = 'stefNEW' where name = :pName", with("pName", "stefp2").map()) } .flatMap { updateByNamedParameter -> assertEquals(1, updateByNamedParameter, "More than one Person updated") Person.deleteAll() } .flatMap { count -> assertEquals(2, count) makeSavedPerson("p1") } .flatMap { makeSavedPerson("p2") } .flatMap { Person.update("name = 'stefNEW' where name = ?1", "stefp1") } .flatMap { updateByIndexParameter -> assertEquals(1, updateByIndexParameter, "More than one Person updated") Person.update("name = 'stefNEW' where name = :pName", with("pName", "stefp2")) } .flatMap { updateByNamedParameter -> assertEquals(1, updateByNamedParameter, "More than one Person updated") Person.deleteAll() } .flatMap { assertThrows(PanacheQueryException::class.java) { Person.update(" ") } } } private fun makeSavedPersonDao(): Uni<Person> { val uni: Uni<Person> = makeSavedPersonDao("") return uni.flatMap { person: Person -> val dog = Dog("octave", "dalmatian") dog.owner = person person.dogs.add(dog) dog.persist<Dog>().map { person } } } private fun makeSavedPersonDao(suffix: String): Uni<Person> { val person = Person() person.name = "stef$suffix" person.status = Status.LIVING person.address = Address("stef street") return addressDao.persist(person.address!!).flatMap { personDao.persist(person) } } private fun testPersistDao(persistTest: PersistTest): Uni<Void> { val person1 = Person() person1.name = "stef1" val person2 = Person() person2.name = "stef2" assertFalse(personDao.isPersistent(person1)) assertFalse(personDao.isPersistent(person2)) val persist = when (persistTest) { PersistTest.Iterable -> personDao.persist(listOf(person1, person2)) PersistTest.Stream -> personDao.persist(Stream.of(person1, person2)) PersistTest.Variadic -> personDao.persist(person1, person2) } return persist.map { assertTrue(personDao.isPersistent(person1)) assertTrue(personDao.isPersistent(person2)) null } } private fun testUpdateDao(): Uni<Void> { return makeSavedPersonDao("p1") .flatMap { makeSavedPersonDao("p2") } .flatMap { personDao.update( "update from Person2 p set p.name = 'stefNEW' where p.name = ?1", "stefp1" ) } .flatMap { updateByIndexParameter -> assertEquals(1, updateByIndexParameter, "More than one Person updated") personDao.update( "update from Person2 p set p.name = 'stefNEW' where p.name = :pName", with("pName", "stefp2").map() ) } .flatMap { updateByNamedParameter -> assertEquals(1, updateByNamedParameter, "More than one Person updated") personDao.deleteAll() } .flatMap { count -> assertEquals(2, count) makeSavedPersonDao("p1") } .flatMap { makeSavedPersonDao("p2") } .flatMap { personDao.update( "from Person2 p set p.name = 'stefNEW' where p.name = ?1", "stefp1" ) } .flatMap { updateByIndexParameter -> assertEquals(1, updateByIndexParameter, "More than one Person updated") personDao.update( "from Person2 p set p.name = 'stefNEW' where p.name = :pName", with("pName", "stefp2").map() ) } .flatMap { updateByNamedParameter -> assertEquals(1, updateByNamedParameter, "More than one Person updated") personDao.deleteAll() } .flatMap { count -> assertEquals(2, count) makeSavedPersonDao("p1") } .flatMap { makeSavedPersonDao("p2") } .flatMap { personDao.update("set name = 'stefNEW' where name = ?1", "stefp1") } .flatMap { updateByIndexParameter -> assertEquals(1, updateByIndexParameter, "More than one Person updated") personDao.update( "set name = 'stefNEW' where name = :pName", with("pName", "stefp2").map() ) } .flatMap { updateByNamedParameter -> assertEquals(1, updateByNamedParameter, "More than one Person updated") personDao.deleteAll() } .flatMap { count -> assertEquals(2, count) makeSavedPersonDao("p1") } .flatMap { makeSavedPersonDao("p2") } .flatMap { personDao.update("name = 'stefNEW' where name = ?1", "stefp1") } .flatMap { updateByIndexParameter -> assertEquals(1, updateByIndexParameter, "More than one Person updated") personDao.update( "name = 'stefNEW' where name = :pName", with("pName", "stefp2").map() ) } .flatMap { updateByNamedParameter -> assertEquals(1, updateByNamedParameter, "More than one Person updated") personDao.deleteAll() } .flatMap { count -> assertEquals(2, count) makeSavedPersonDao("p1") } .flatMap { makeSavedPersonDao("p2") } .flatMap { personDao.update("name = 'stefNEW' where name = ?1", "stefp1") } .flatMap { updateByIndexParameter -> assertEquals(1, updateByIndexParameter, "More than one Person updated") personDao.update("name = 'stefNEW' where name = :pName", with("pName", "stefp2")) } .flatMap { updateByNamedParameter -> assertEquals(1, updateByNamedParameter, "More than one Person updated") personDao.deleteAll() } .flatMap { count -> assertEquals(2, count) assertThrows(PanacheQueryException::class.java) { personDao.update(" ") } } } enum class PersistTest { Iterable, Variadic, Stream } }
22
null
4
3
f29b28887af4b50e7484dd1faf252b15f1a9f61a
73,043
quarkus
Apache License 2.0
fastjson1_compatible/src/test/java/com/alibaba/json/bvt/issue_3200/Issue3274.kt
wenshao
484,097,799
false
null
package com.alibaba.json.bvt.issue_3200 import com.alibaba.fastjson.JSON import junit.framework.Assert.assertEquals import org.junit.Test import java.util.* class TestFJ { @Test fun test() { val str = """ {"data": {"id": "1", "name":"n1"}} """.trimIndent() val d1 = JSON.parseObject(str, Data2::class.java) val data = JSON.parseObject(str) val d2 = data.getObject("data", Data::class.java) assertEquals(1, d1.data.id) assertEquals(1, d2.id) } } data class Data( val id: Int = 0, val name: String = "", val date: Date? = null ) data class Data2( val data: Data )
458
null
6516
6
bcbf4a6b9b797405e5f5ccfec450a0425ada1efb
681
fastjson2
Apache License 2.0
kotlinpleaseanimate/src/main/java/com/github/florent37/kotlin/pleaseanimate/core/Expectations.kt
prashant31191
132,580,495
true
{"Kotlin": 80512, "Java": 1291, "Shell": 165}
package com.github.florent37.kotlin.pleaseanimate.core import android.view.View import com.github.florent37.kotlin.pleaseanimate.GravityIntDef import com.github.florent37.kotlin.pleaseanimate.GravityScaleHorizontalIntDef import com.github.florent37.kotlin.pleaseanimate.GravityScaleVerticalIntDef import com.github.florent37.kotlin.pleaseanimate.PleaseAnim import com.github.florent37.kotlin.pleaseanimate.core.alpha.AlphaAnimExpectation import com.github.florent37.kotlin.pleaseanimate.core.alpha.AlphaAnimExpectationValue import com.github.florent37.kotlin.pleaseanimate.core.custom.CustomAnimExpectation import com.github.florent37.kotlin.pleaseanimate.core.custom.TextColorAnimExpectation import com.github.florent37.kotlin.pleaseanimate.core.custom.ViewBackgroundAlphaAnimExpectation import com.github.florent37.kotlin.pleaseanimate.core.position.* import com.github.florent37.kotlin.pleaseanimate.core.rotation.RotationExpectation import com.github.florent37.kotlin.pleaseanimate.core.rotation.RotationExpectationOriginal import com.github.florent37.kotlin.pleaseanimate.core.rotation.RotationExpectationValue import com.github.florent37.kotlin.pleaseanimate.core.rotation.RotationFlipExpectationValue import com.github.florent37.kotlin.pleaseanimate.core.scale.* class Expectations(private val pleaseAnim: PleaseAnim) { internal val expectations = mutableListOf<AnimExpectation>() internal val startActions: MutableList<() -> Unit> = mutableListOf() internal val endActions: MutableList<() -> Unit> = mutableListOf() fun withEndAction(listener: (PleaseAnim) -> Unit) { this.pleaseAnim.withEndAction(listener) } fun withStartAction(listener: (PleaseAnim) -> Unit) { this.pleaseAnim.withStartAction(listener) } fun rightOf(view: View, marginDp: Float? = null, margin: Float? = null): PositionAnimExpectation { return PositionAnimExpectationRightOf(view).apply { expectations.add(this) this.marginDp = marginDp this.margin = margin } } fun leftOf(view: View, marginDp: Float? = null, margin: Float? = null): PositionAnimExpectation { return PositionAnimExpectationLeftOf(view).apply { expectations.add(this) this.marginDp = marginDp this.margin = margin } } fun belowOf(view: View, marginDp: Float? = null, margin: Float? = null): PositionAnimExpectation { return PositionAnimExpectationBelowOf(view).apply { expectations.add(this) this.marginDp = marginDp this.margin = margin } } fun aboveOf(view: View, marginDp: Float? = null, margin: Float? = null): PositionAnimExpectation { return PositionAnimExpectationAboveOf(view).apply { expectations.add(this) this.marginDp = marginDp this.margin = margin } } fun originalPosition(): PositionAnimExpectation { return PositionAnimExpectationOriginal().apply { expectations.add(this) } } fun sameCenterAs(view: View, horizontal: Boolean = false, vertical: Boolean = false): PositionAnimExpectation { return PositionAnimExpectationSameCenterAs(view, horizontal, vertical).apply { expectations.add(this) } } fun sameCenterHorizontalAs(view: View): PositionAnimExpectation { return sameCenterAs(view, true, false).apply { expectations.add(this) } } fun sameCenterVerticalAs(view: View): PositionAnimExpectation { return sameCenterAs(view, false, true).apply { expectations.add(this) } } fun centerInParent(horizontal: Boolean, vertical: Boolean): PositionAnimExpectation { return PositionAnimExpectationCenterInParent(horizontal, vertical).apply { expectations.add(this) } } fun centerVerticalInParent(): PositionAnimExpectation { return centerInParent(false, true).apply { expectations.add(this) } } fun centerHorizontalInParent(): PositionAnimExpectation { return centerInParent(true, false).apply { expectations.add(this) } } fun outOfScreen(@GravityIntDef vararg gravities: Int): PositionAnimExpectation { return PositionAnimExpectationOutOfScreen(gravities).apply { expectations.add(this) } } fun centerBetweenViews(view1: View, view2: View, horizontal: Boolean = false, vertical: Boolean = false): PositionAnimExpectation { return PositionAnimExpectationCenterBetweenViews(view1, view2, horizontal, vertical).apply { expectations.add(this) } } fun topOfItsParent(marginDp: Float? = null, margin: Float? = null): PositionAnimExpectation { return PositionAnimExpectationTopOfParent().apply { expectations.add(this) this.marginDp = marginDp this.margin = margin } } fun rightOfItsParent(marginDp: Float? = null, margin: Float? = null): PositionAnimExpectation { return PositionAnimExpectationRightOfParent().apply { expectations.add(this) this.marginDp = marginDp this.margin = margin } } fun bottomOfItsParent(marginDp: Float? = null, margin: Float? = null): PositionAnimExpectation { return PositionAnimExpectationBottomOfParent().apply { expectations.add(this) this.marginDp = marginDp this.margin = margin } } fun leftOfItsParent(marginDp: Float? = null, margin: Float? = null): PositionAnimExpectation { return PositionAnimExpectationLeftOfParent().apply { expectations.add(this) this.marginDp = marginDp this.margin = margin } } fun centerBetweenViewAndItsParent(otherView: View, horizontal: Boolean, vertical: Boolean, toBeOnRight: Boolean, toBeOnBottom: Boolean, marginDp: Float? = null, margin: Float? = null): PositionAnimExpectation { return PositionAnimExpectationCenterBetweenViewAndParent(otherView, horizontal, vertical, toBeOnRight, toBeOnBottom).apply { expectations.add(this) this.marginDp = marginDp this.margin = margin } } fun alignBottom(otherView: View, marginDp: Float? = null, margin: Float? = null): PositionAnimExpectation { return PositionAnimExpectationAlignBottom(otherView).apply { expectations.add(this) this.marginDp = marginDp this.margin = margin } } fun alignTop(otherView: View, marginDp: Float? = null, margin: Float? = null): PositionAnimExpectation { return PositionAnimExpectationAlignTop(otherView).apply { expectations.add(this) this.marginDp = marginDp this.margin = margin } } fun alignLeft(otherView: View, marginDp: Float? = null, margin: Float? = null): PositionAnimExpectation { return PositionAnimExpectationAlignLeft(otherView).apply { expectations.add(this) this.marginDp = marginDp this.margin = margin } } fun alignRight(otherView: View, marginDp: Float? = null, margin: Float? = null): PositionAnimExpectation { return PositionAnimExpectationAlignRight(otherView).apply { expectations.add(this) this.marginDp = marginDp this.margin = margin } } fun originalScale(): ScaleAnimExpectation { return ScaleAnimExpectationOriginalScale().apply { expectations.add(this) } } fun scale(scaleX: Float, scaleY: Float, @GravityScaleHorizontalIntDef gravityHorizontal: Int, @GravityScaleVerticalIntDef gravityVertical: Int): ScaleAnimExpectation { return ScaleAnimExpectationValues(scaleX, scaleY, gravityHorizontal, gravityVertical).apply { expectations.add(this) } } fun scale(scaleX: Float, scaleY: Float): ScaleAnimExpectation { return ScaleAnimExpectationValues(scaleX, scaleY, null, null).apply { expectations.add(this) } } fun height(height: Int, @GravityScaleHorizontalIntDef horizontalGravity: Int? = null, @GravityScaleVerticalIntDef verticalGravity: Int? = null, keepRatio: Boolean = false, toDp: Boolean = false): ScaleAnimExpectation { return ScaleAnimExpectationHeight(height, horizontalGravity, verticalGravity).apply { this.keepRatio = keepRatio this.toDp = toDp expectations.add(this) } } fun width(width: Int, @GravityScaleHorizontalIntDef horizontalGravity: Int? = null, @GravityScaleVerticalIntDef verticalGravity: Int? = null, keepRatio: Boolean = false, toDp: Boolean = false): ScaleAnimExpectation { return ScaleAnimExpectationWidth(width, horizontalGravity, verticalGravity).apply { expectations.add(this) this.keepRatio = keepRatio this.toDp = toDp } } fun sameScaleAs(otherView: View): ScaleAnimExpectation { return ScaleAnimExpectationSameScaleAs(otherView).apply { expectations.add(this) } } fun sameWidthAs(otherView: View): ScaleAnimExpectation { return ScaleAnimExpectationSameWidthAs(otherView, null, null).apply { expectations.add(this) } } fun sameHeightAs(otherView: View): ScaleAnimExpectation { return ScaleAnimExpectationSameHeightAs(otherView, null, null).apply { expectations.add(this) } } fun alpha(alpha: Float): AlphaAnimExpectation { return AlphaAnimExpectationValue(alpha).apply { expectations.add(this) } } fun sameAlphaAs(otherView: View): AlphaAnimExpectation { return AlphaAnimExpectationValue(otherView.alpha).apply { expectations.add(this) } } fun visible(): AlphaAnimExpectation { return AlphaAnimExpectationValue(1f).apply { expectations.add(this) } } fun invisible(): AlphaAnimExpectation { return AlphaAnimExpectationValue(0f).apply { expectations.add(this) } } fun textColor(textColor: Int): CustomAnimExpectation { return TextColorAnimExpectation(textColor).apply { expectations.add(this) } } fun backgroundAlpha(alpha: Float): CustomAnimExpectation { return ViewBackgroundAlphaAnimExpectation(alpha).apply { expectations.add(this) } } fun toBeRotated(rotation: Float): RotationExpectation { return RotationExpectationValue(rotation).apply { expectations.add(this) } } fun flippedHorizontally(): RotationExpectation { return RotationFlipExpectationValue(0f, 180f).apply { expectations.add(this) } } fun flippedVertically(): RotationExpectation { return RotationFlipExpectationValue(180f, 0f).apply { expectations.add(this) } } fun flippedHorizontallyAndVertically(): RotationExpectation { return RotationFlipExpectationValue(180f, 180f).apply { expectations.add(this) } } fun vertical(bottomOfViewAtLeft: Boolean): RotationExpectation { val expect: RotationExpectation if (bottomOfViewAtLeft) { expect = RotationExpectationValue(90f) } else { expect = RotationExpectationValue(270f) } expectations.add(expect) return expect } fun originalRotation(): RotationExpectation { return RotationExpectationOriginal().apply { expectations.add(this) } } fun custom(expectation: CustomAnimExpectation): CustomAnimExpectation { return expectation.apply { expectations.add(this) } } }
0
Kotlin
0
0
5d833fc28651ab2d50d6b1b29a190feb9d8d2a38
11,965
KotlinPleaseAnimate
Apache License 2.0
sdks/android/sdk/channel-sdk/src/main/java/com/zello/channel/sdk/platform/PowerManagerReceiver.kt
Allanksr
234,402,022
true
{"Kotlin": 138788, "Java": 79058, "JavaScript": 71505, "Objective-C": 56519, "HTML": 46852, "C++": 29497, "SCSS": 4600, "Makefile": 4082, "Go": 2473, "PHP": 1546, "C": 810, "Ruby": 441}
package com.zello.channel.sdk.platform import android.content.BroadcastReceiver import android.content.Context import android.content.Intent internal class PowerManagerReceiver : BroadcastReceiver() { override fun onReceive(context: Context, intent: Intent) { PowerManager.get(context).onTimerBroadcast(intent) } }
0
Kotlin
0
1
221ee2ef809acfd5bbb3de4bff03e40a35cd4218
323
zello-channel-api
MIT License
core/src/main/kotlin/SourceUtilities.kt
cs124-illinois
584,151,809
false
null
@file:Suppress("TooManyFunctions", "SpellCheckingInspection") package edu.illinois.cs.cs125.jeed.core import edu.illinois.cs.cs125.jeed.core.antlr.JavaLexer import edu.illinois.cs.cs125.jeed.core.antlr.JavaParser import edu.illinois.cs.cs125.jeed.core.antlr.JavaParserBaseListener import edu.illinois.cs.cs125.jeed.core.antlr.KotlinLexer import edu.illinois.cs.cs125.jeed.core.antlr.KotlinParser import edu.illinois.cs.cs125.jeed.core.antlr.KotlinParserBaseListener import edu.illinois.cs.cs125.jeed.core.antlr.SnippetLexer import net.sf.extjwnl.data.POS import net.sf.extjwnl.dictionary.Dictionary import org.antlr.v4.runtime.CharStreams import org.antlr.v4.runtime.misc.Interval import org.antlr.v4.runtime.tree.ParseTreeWalker fun String.stripComments(type: Source.FileType): String { val charStream = CharStreams.fromString(this) return when (type) { Source.FileType.JAVA -> SnippetLexer(charStream).allTokens.filter { it.channel != 1 }.joinToString("") { it.text } Source.FileType.KOTLIN -> KotlinLexer(charStream).allTokens.filter { it.channel != 1 }.joinToString("") { it.text } } } fun Source.stripComments() = Source(sources.mapValues { (_, contents) -> contents.stripComments(type) }) internal fun String.identifiers(type: Source.FileType): Set<String> { val charStream = CharStreams.fromString(this) return when (type) { Source.FileType.JAVA -> SnippetLexer(charStream).allTokens.filter { it.type == SnippetLexer.IDENTIFIER }.map { it.text }.toSet() Source.FileType.KOTLIN -> KotlinLexer(charStream).allTokens.filter { it.type == KotlinLexer.Identifier }.map { it.text }.toSet() } } fun Source.identifiers() = mutableSetOf<String>().apply { sources.mapValues { (_, contents) -> addAll(contents.identifiers(type)) } }.toSet() internal fun Source.ParsedSource.strings(type: Source.FileType): Set<String> { return when (type) { Source.FileType.JAVA -> { val charStream = CharStreams.fromString(contents) JavaLexer(charStream).allTokens .filter { it.type == JavaLexer.STRING_LITERAL || it.type == JavaLexer.TEXT_BLOCK_LITERAL } .map { when (it.type) { JavaLexer.STRING_LITERAL -> it.text.removeSurrounding("\"").trim() JavaLexer.TEXT_BLOCK_LITERAL -> it.text.removeSurrounding("\"\"\"").trim() else -> error("Bad token type") } } .toSet() } Source.FileType.KOTLIN -> { object : KotlinParserBaseListener() { val strings = mutableSetOf<String>() override fun enterStringLiteral(ctx: KotlinParser.StringLiteralContext) { ctx.lineStringLiteral()?.also { strings += it.text.removeSurrounding("\"").trim() } ctx.multiLineStringLiteral()?.also { strings += it.text.removeSurrounding("\"\"\"").trim() } } init { ParseTreeWalker.DEFAULT.walk(this, tree) } }.strings } } } fun Source.strings() = mutableSetOf<String>().apply { sources.mapValues { (filename, _) -> addAll(getParsed(filename).strings(type)) } }.toSet() fun Source.ParsedSource.stripAssertionMessages(type: Source.FileType): String { val keep = when (type) { Source.FileType.JAVA -> object : JavaParserBaseListener() { val keep = mutableListOf<Any>() var currentStart = 0 override fun enterStatement(ctx: JavaParser.StatementContext) { ctx.ASSERT()?.also { ctx.expression(1)?.also { val start = ctx.expression(0).stop.stopIndex + 1 keep += (currentStart until start) as Any currentStart = ctx.expression(1).stop.stopIndex + 1 } } } init { ParseTreeWalker.DEFAULT.walk(this, tree) keep += (currentStart until stream.size()) as Any } }.keep Source.FileType.KOTLIN -> { object : KotlinParserBaseListener() { var currentStart = 0 val keep = mutableListOf<Any>() override fun enterPostfixUnaryExpression(ctx: KotlinParser.PostfixUnaryExpressionContext) { val identifier = ctx.primaryExpression()?.simpleIdentifier()?.text if (identifier != null && listOf("assert", "check", "require").contains(identifier)) { ctx.postfixUnarySuffix(0)?.callSuffix()?.annotatedLambda()?.also { val start = it.start.startIndex keep += (currentStart until start) as Any currentStart = it.stop.stopIndex + 1 } } if (identifier == "error") { ctx.postfixUnarySuffix(0)?.callSuffix()?.valueArguments()?.also { val start = it.start.startIndex keep += (currentStart until start + 1) as Any keep += "\"error\"" currentStart = it.stop.stopIndex } } } init { ParseTreeWalker.DEFAULT.walk(this, tree) keep += (currentStart until stream.size()) as Any } }.keep } } return keep.joinToString("") { when (it) { is IntRange -> stream.getText(Interval(it.first, it.last)) is String -> it else -> error("Bad type for $it") } } } fun Source.stripAssertionMessages() = Source(sources.mapValues { (filename, _) -> getParsed(filename).stripAssertionMessages(type) }) fun Source.trimLines() = Source(sources.mapValues { (_, contents) -> contents.lines().joinToString("\n") { it.trimEnd() } }) private fun levenshteinDistance(first: List<Int>, second: List<Int>): Int { val costs = IntArray(second.size + 1) { it } for (i in 1..first.size) { costs[0] = i var nw = i - 1 for (j in 1..second.size) { val cj = (1 + costs[j].coerceAtMost(costs[j - 1])).coerceAtMost( if (first[i - 1] == second[j - 1]) { nw } else { nw + 1 } ) nw = costs[j] costs[j] = cj } } return costs[second.size] } fun String.lineDifferenceCount(other: String) = levenshteinDistance(lines().map { it.trimEnd().hashCode() }, other.lines().map { it.trimEnd().hashCode() }) val WORDS by lazy { object {}::class.java.getResource("/bad.txt")!!.readText().lines().map { it.trim().lowercase() }.toSet() } val LARGEST_WORD = WORDS.maxOf { it.length } val DICTIONARY = Dictionary.getDefaultResourceInstance()!! fun String.fromCamelCase() = split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])".toRegex()) fun String.separateCamelCase() = split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])".toRegex()) .joinToString(" ") val okWords = setOf("something", "throwable") @Suppress("ComplexCondition", "ComplexMethod", "NestedBlockDepth") fun String.getBadWords(separateCamelCase: Boolean = false, whitelist: Set<String> = setOf()): Set<String> { val badWords = mutableSetOf<String>() val words = if (separateCamelCase) { separateCamelCase() } else { this }.lowercase().replace("""[^ a-zA-Z]""".toRegex(), "") if (words.isEmpty()) { return badWords } words.split(" ").forEach { input -> if (input in okWords) { return@forEach } for (start in input.indices) { var offset = 1 while (offset < input.length + 1 - start && offset < LARGEST_WORD) { val wordToCheck = input.substring(start, start + offset) WORDS.filter { word -> if (word in whitelist) { false } else if (word == "hell" && input.contains("hello")) { false } else if (wordToCheck.length <= 2 && input.length > 2) { false } else if (word == wordToCheck) { !( word.length < input.length && POS.values().any { DICTIONARY.getIndexWord(it, input) != null || DICTIONARY.getIndexWord(it, input.removeSuffix("ed")) != null || DICTIONARY.getIndexWord(it, input.removeSuffix("er")) != null } ) } else { false } }.forEach { badWords += it } offset++ } } } return badWords } @Suppress("ReturnCount") fun Source.hasBadWords(whitelist: Set<String> = setOf()): String? { fun Set<String>.check(splitCamelCase: Boolean): String? { forEach { identifier -> identifier.trim().split(" ").forEach { string -> string.trim().getBadWords(splitCamelCase, whitelist).firstOrNull()?.also { return it } } } return null } sources.entries.forEach { (filename, contents) -> contents.identifiers(type).check(true)?.also { return it } getParsed(filename).strings(type).check(false)?.also { return it } } return null } fun Source.getBadWords(whitelist: Set<String> = setOf()): Set<String> { val badWords = mutableSetOf<String>() fun Set<String>.check(splitCamelCase: Boolean) = forEach { identifier -> identifier.trim().split(" ").forEach { string -> badWords += string.trim().getBadWords(splitCamelCase, whitelist) } } sources.entries.forEach { (filename, contents) -> contents.identifiers(type).check(true) getParsed(filename).strings(type).check(false) } return badWords }
4
null
9
2
d79493ae6d80a44f89fea02355f30e32608d93c7
10,601
jeed
MIT License
idea/src/org/jetbrains/kotlin/idea/intentions/RemoveSingleExpressionStringTemplateIntention.kt
JetBrains
278,369,660
false
null
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.kotlin.idea.intentions import com.intellij.openapi.editor.Editor import org.jetbrains.kotlin.builtins.KotlinBuiltIns import org.jetbrains.kotlin.idea.KotlinBundle import org.jetbrains.kotlin.idea.caches.resolve.analyze import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection import org.jetbrains.kotlin.psi.KtExpression import org.jetbrains.kotlin.psi.KtPsiFactory import org.jetbrains.kotlin.psi.KtStringTemplateExpression import org.jetbrains.kotlin.psi.createExpressionByPattern import org.jetbrains.kotlin.resolve.calls.util.getType private fun KtStringTemplateExpression.singleExpressionOrNull() = children.singleOrNull()?.children?.firstOrNull() as? KtExpression class RemoveSingleExpressionStringTemplateInspection : IntentionBasedInspection<KtStringTemplateExpression>( RemoveSingleExpressionStringTemplateIntention::class, additionalChecker = { templateExpression -> templateExpression.singleExpressionOrNull()?.let { KotlinBuiltIns.isString(it.getType(it.analyze())) } ?: false } ) { override val problemText = KotlinBundle.message("redundant.string.template") } class RemoveSingleExpressionStringTemplateIntention : SelfTargetingOffsetIndependentIntention<KtStringTemplateExpression>( KtStringTemplateExpression::class.java, KotlinBundle.lazyMessage("remove.single.expression.string.template") ) { override fun isApplicableTo(element: KtStringTemplateExpression) = element.singleExpressionOrNull() != null override fun applyTo(element: KtStringTemplateExpression, editor: Editor?) { val expression = element.singleExpressionOrNull() ?: return val type = expression.getType(expression.analyze()) val newElement = if (KotlinBuiltIns.isString(type)) expression else KtPsiFactory(element).createExpressionByPattern("$0.$1()", expression, "toString") element.replace(newElement) } }
191
null
4372
82
cc81d7505bc3e9ad503d706998ae8026c067e838
2,118
intellij-kotlin
Apache License 2.0
app/src/main/java/com/game/collider/MainActivity.kt
holman57
387,668,866
false
null
package com.game.collider import android.os.Bundle import androidx.appcompat.app.AppCompatActivity import com.game.collider.components.GameView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(GameView(this)) } }
0
Kotlin
0
1
593b033732a70767189a5be16028bf26256199f6
336
collider
Apache License 2.0
app/src/main/java/com/kickstarter/viewmodels/usecases/LoginUseCase.kt
kickstarter
76,278,501
false
null
package com.kickstarter.viewmodels.usecases import com.kickstarter.libs.Environment import com.kickstarter.libs.rx.transformers.Transformers import com.kickstarter.models.User import rx.Observable class LoginUseCase(environment: Environment) { private val currentUser = requireNotNull(environment.currentUser()) private val currentUserV2 = requireNotNull(environment.currentUserV2()) private val apolloClient = requireNotNull(environment.apolloClient()) private val apolloClientV2 = requireNotNull(environment.apolloClientV2()) fun login(newUser: User, accessToken: String) { currentUser.login(newUser, accessToken) currentUserV2.login(newUser, accessToken) } fun loginAndUpdateUserPrivacy(newUser: User, accessToken: String): Observable<User> { login(newUser, accessToken) return GetUserPrivacyUseCase(apolloClient).getUserPrivacy() .compose(Transformers.neverError()) .map { newUser.toBuilder() .email(it.me()?.email()) .isCreator(it.me()?.isCreator) .isDeliverable(it.me()?.isDeliverable) .isEmailVerified(it.me()?.isEmailVerified) .hasPassword(it.me()?.hasPassword()).build() } } fun loginAndUpdateUserPrivacyV2(newUser: User, accessToken: String): io.reactivex.Observable<User> { login(newUser, accessToken) return GetUserPrivacyUseCaseV2(apolloClientV2).getUserPrivacy() .compose(Transformers.neverErrorV2()) .map { newUser.toBuilder() .email(it.email) .isCreator(it.isCreator) .isDeliverable(it.isDeliverable) .isEmailVerified(it.isEmailVerified) .hasPassword(it.hasPassword).build() } } }
8
null
995
5,726
ef09e761e98f5c4efa0388003678ff3d7b78b61e
1,894
android-oss
Apache License 2.0
src/main/kotlin/io/provenance/p8e/plugin/Dsl.kt
provenance-io
353,052,402
false
null
package io.provenance.p8e.plugin // TODO implement type safe builders // https://kotlinlang.org/docs/type-safe-builders.html#how-it-works open class P8ePartyExtension { var publicKey: String = "" } open class P8eLocationExtension { var encryptionPrivateKey: String? = "" var signingPrivateKey: String? = "" var osUrl: String? = "" var provenanceUrl: String? = "" var audience: Map<String, P8ePartyExtension> = emptyMap() var chainId: String? = "" var mainNet: Boolean = chainId == "pio-mainnet-1" var txBatchSize: String = "10" var txFeeAdjustment: String = "1.25" } open class P8eExtension { var contractProject: String = "contract" var protoProject: String = "proto" // TODO what is a good default package path that is somehow derived from the current project? var contractHashPackage: String = "" var protoHashPackage: String = "" var language: String = "java" var locations: Map<String, P8eLocationExtension> = emptyMap() }
2
Kotlin
1
2
620057b8df915893989435284befdc7a0f05bfc4
999
p8e-gradle-plugin
Apache License 2.0
Demos/Micronaut/src/main/kotlin/com/groupdocs/ui/config/ApplicationConfigFactory.kt
groupdocs-comparison
65,550,714
false
null
package com.groupdocs.ui.viewer.micronaut.config import com.typesafe.config.ConfigFactory import io.github.config4k.extract import io.micronaut.context.annotation.Factory import jakarta.inject.Singleton @Factory class ApplicationConfigFactory { @Singleton fun config(): ApplicationConfig { val parsedConfig = ConfigFactory.parseResources("application.conf").resolve() return parsedConfig.extract("application") } }
5
null
9
7
4d289958d8fc6ab338bbcfca8e82d237b71838be
445
GroupDocs.Comparison-for-Java
MIT License
ts-socket/src/main/kotlin/cn/tursom/datagram/server/ServerNioDatagram.kt
tursom
213,611,087
false
{"YAML": 1, "Gradle Kotlin DSL": 45, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "Kotlin": 616, "Java": 6, "INI": 1, "Markdown": 3}
package cn.tursom.datagram.server import cn.tursom.core.buffer.ByteBuffer import cn.tursom.core.pool.MemoryPool import cn.tursom.core.timer.TimerTask import cn.tursom.core.timer.WheelTimer import cn.tursom.datagram.NioDatagram import cn.tursom.niothread.NioThread import kotlinx.coroutines.suspendCancellableCoroutine import java.net.SocketAddress import java.nio.channels.DatagramChannel import java.nio.channels.SelectionKey import java.util.concurrent.ConcurrentLinkedQueue import java.util.concurrent.TimeoutException import kotlin.coroutines.Continuation import kotlin.coroutines.resumeWithException class ServerNioDatagram( override val remoteAddress: SocketAddress, val server: AsyncDatagramServer, channel: DatagramChannel, key: SelectionKey, nioThread: NioThread, ) : NioDatagram(channel, key, nioThread) { companion object { val timer = WheelTimer.timer } private val bufferList = ConcurrentLinkedQueue<ByteBuffer>() private var readBuffer: ByteBuffer? = null var cont: Continuation<Int>? = null private var timeoutTask: TimerTask? = null fun addBuffer(buffer: ByteBuffer) { bufferList.add(buffer) } override suspend fun waitRead(timeout: Long) { suspendCancellableCoroutine<Int> { cont -> this.cont = cont if (timeout > 0) { timeoutTask = timer.exec(timeout) { cont.resumeWithException(TimeoutException()) } } } cont = null timeoutTask?.cancel() } override suspend fun read(pool: MemoryPool, timeout: Long): ByteBuffer { if (bufferList.isEmpty()) waitRead() val buf = pool.get() read(buf, timeout) return buf } override fun close() { server.closeChannel(remoteAddress) } override fun toString(): String { return "ServerNioDatagram(remoteAddress=$remoteAddress, localAddress=${channel.localAddress})" } }
0
Kotlin
2
8
fc31966b5c49a7aaf94a4ff7327be7f5ebd6806a
1,856
TursomServer
MIT License
kzen-lib-common/src/jvmMain/kotlin/tech/kzen/lib/platform/PlatformMirror.kt
alexoooo
130,935,552
false
null
package tech.kzen.lib.platform import tech.kzen.lib.common.reflect.ClassMirror import kotlin.reflect.full.primaryConstructor actual object PlatformMirror: ClassMirror { actual override fun contains(className: ClassName): Boolean { return try { Class.forName(className.get()) true } catch (e: ClassNotFoundException) { false } } actual override fun constructorArgumentNames(className: ClassName): List<String> { val type = Class.forName(className.get()).kotlin return type.primaryConstructor!!.parameters.map { it.name!! } } actual override fun create(className: ClassName, constructorArguments: List<Any?>): Any { try { val type = Class.forName(className.get()).kotlin return type.primaryConstructor!!.call(*constructorArguments.toTypedArray()) } catch (e: Throwable) { throw IllegalArgumentException("Unable to create $className - $constructorArguments", e) } } }
1
Kotlin
0
0
9c0d41824ec965855a6dd0beaccd3f638184327b
1,047
kzen-lib
MIT License
android/src/com/android/tools/idea/res/ResourceIdManagerImpl.kt
JetBrains
60,701,247
false
{"Kotlin": 49550960, "Java": 35837871, "HTML": 1217714, "Starlark": 909188, "C++": 357481, "Python": 106384, "C": 71782, "Lex": 66732, "NSIS": 58538, "AIDL": 35382, "Shell": 26938, "CMake": 26798, "JavaScript": 18437, "Smali": 7580, "Batchfile": 6951, "RenderScript": 4411, "Makefile": 2495, "IDL": 269, "QMake": 18}
/* * Copyright (C) 2023 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.tools.idea.res import com.intellij.openapi.module.Module import org.jetbrains.android.facet.AndroidFacet /** Studio-specific implementation of [ResourceIdManager]. */ class ResourceIdManagerImpl private constructor(val module: Module) : ResourceIdManagerBase( AndroidFacetResourceIdManagerModelModule( AndroidFacet.getInstance(module) ?: error("${ResourceIdManager::class.qualifiedName} used on a non-Android module.") ) )
3
Kotlin
228
921
dbd9aeae0dc5b8c56ce2c7d51208ba26ea0f169b
1,082
android
Apache License 2.0
android/quest/src/main/java/org/smartregister/fhircore/quest/ui/geowidget/GeoWidgetLauncherViewModel.kt
opensrp
339,242,809
false
{"Kotlin": 3034140, "Java": 4967, "JavaScript": 3548, "CSS": 459}
/* * Copyright 2021-2024 Ona Systems, 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.smartregister.fhircore.quest.ui.geowidget import android.content.Context import android.graphics.Bitmap import androidx.compose.runtime.mutableStateMapOf import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.google.android.fhir.datacapture.extensions.logicalId import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import javax.inject.Inject import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.serialization.json.JsonPrimitive import org.hl7.fhir.r4.model.Enumerations import org.hl7.fhir.r4.model.IdType import org.hl7.fhir.r4.model.Location import org.hl7.fhir.r4.model.ResourceType import org.smartregister.fhircore.engine.configuration.ConfigType import org.smartregister.fhircore.engine.configuration.ConfigurationRegistry import org.smartregister.fhircore.engine.configuration.QuestionnaireConfig import org.smartregister.fhircore.engine.configuration.app.ApplicationConfiguration import org.smartregister.fhircore.engine.configuration.geowidget.GeoWidgetConfiguration import org.smartregister.fhircore.engine.configuration.register.ActiveResourceFilterConfig import org.smartregister.fhircore.engine.data.local.DefaultRepository import org.smartregister.fhircore.engine.domain.model.ActionParameter import org.smartregister.fhircore.engine.domain.model.ActionParameterType import org.smartregister.fhircore.engine.domain.model.SnackBarMessageConfig import org.smartregister.fhircore.engine.rulesengine.ResourceDataRulesExecutor import org.smartregister.fhircore.engine.util.DispatcherProvider import org.smartregister.fhircore.engine.util.SharedPreferenceKey import org.smartregister.fhircore.engine.util.SharedPreferencesHelper import org.smartregister.fhircore.engine.util.extension.extractLogicalIdUuid import org.smartregister.fhircore.engine.util.extension.interpolate import org.smartregister.fhircore.engine.util.extension.retrieveRelatedEntitySyncLocationIds import org.smartregister.fhircore.geowidget.model.GeoJsonFeature import org.smartregister.fhircore.geowidget.model.Geometry import org.smartregister.fhircore.quest.ui.shared.QuestionnaireHandler import org.smartregister.fhircore.quest.util.extensions.referenceToBitmap @HiltViewModel class GeoWidgetLauncherViewModel @Inject constructor( val defaultRepository: DefaultRepository, val dispatcherProvider: DispatcherProvider, val sharedPreferencesHelper: SharedPreferencesHelper, val resourceDataRulesExecutor: ResourceDataRulesExecutor, val configurationRegistry: ConfigurationRegistry, @ApplicationContext val context: Context, ) : ViewModel() { private val _snackBarStateFlow = MutableSharedFlow<SnackBarMessageConfig>() val snackBarStateFlow = _snackBarStateFlow.asSharedFlow() private val _noLocationFoundDialog = MutableLiveData<Boolean>() val noLocationFoundDialog: LiveData<Boolean> get() = _noLocationFoundDialog private val applicationConfiguration by lazy { configurationRegistry.retrieveConfiguration<ApplicationConfiguration>(ConfigType.Application) } val geoJsonFeatures: MutableStateFlow<List<GeoJsonFeature>> = MutableStateFlow(emptyList()) private val decodedImageMap = mutableStateMapOf<String, Bitmap>() fun retrieveLocations(geoWidgetConfig: GeoWidgetConfiguration, searchText: String?) { viewModelScope.launch { val totalCount = withContext(dispatcherProvider.io()) { defaultRepository.countResources( filterByRelatedEntityLocation = geoWidgetConfig.filterDataByRelatedEntityLocation == true, baseResourceConfig = geoWidgetConfig.resourceConfig.baseResource, filterActiveResources = listOf( ActiveResourceFilterConfig( resourceType = ResourceType.Patient, active = true, ), ActiveResourceFilterConfig( resourceType = ResourceType.Group, active = true, ), ), configComputedRuleValues = emptyMap(), ) } if (totalCount == 0L) { showNoLocationDialog(geoWidgetConfig) return@launch } var count = 0 var pageNumber = 0 while (count < totalCount) { val registerData = defaultRepository .searchResourcesRecursively( filterActiveResources = null, fhirResourceConfig = geoWidgetConfig.resourceConfig, configRules = null, secondaryResourceConfigs = null, filterByRelatedEntityLocationMetaTag = geoWidgetConfig.filterDataByRelatedEntityLocation == true, currentPage = pageNumber, pageSize = DefaultRepository.DEFAULT_BATCH_SIZE, ) .asSequence() .filter { it.resource is Location } .filter { (it.resource as Location).hasPosition() } .filter { with((it.resource as Location).position) { hasLongitude() && hasLatitude() } } .map { Pair( it.resource as Location, resourceDataRulesExecutor.processResourceData( repositoryResourceData = it, ruleConfigs = geoWidgetConfig.servicePointConfig?.rules ?: emptyList(), params = emptyMap(), ), ) } .map { (location, resourceData) -> GeoJsonFeature( id = location.logicalId, geometry = Geometry( coordinates = // MapBox coordinates are represented as Long,Lat (NOT Lat,Long) listOf( location.position.longitude.toDouble(), location.position.latitude.toDouble(), ), ), properties = geoWidgetConfig.servicePointConfig?.servicePointProperties?.mapValues { JsonPrimitive(it.value.interpolate(resourceData.computedValuesMap)) } ?: emptyMap(), ) } .toList() geoJsonFeatures.value = if (searchText.isNullOrBlank()) { registerData } else { registerData.filter { geoJsonFeature: GeoJsonFeature -> geoWidgetConfig.topScreenSection?.searchBar?.computedRules?.any { ruleName -> // if ruleName not found in map return {-1}; check always return false hence no data val value = geoJsonFeature.properties[ruleName]?.toString() ?: "{-1}" value.contains(other = searchText, ignoreCase = true) } == true } } pageNumber++ count += DefaultRepository.DEFAULT_BATCH_SIZE } } } fun onEvent(geoWidgetEvent: GeoWidgetEvent) { when (geoWidgetEvent) { is GeoWidgetEvent.SearchFeatures -> retrieveLocations(geoWidgetEvent.geoWidgetConfig, geoWidgetEvent.searchQuery.query) } } suspend fun showNoLocationDialog(geoWidgetConfiguration: GeoWidgetConfiguration) { geoWidgetConfiguration.noResults?.let { _noLocationFoundDialog.postValue(context.retrieveRelatedEntitySyncLocationIds().isEmpty()) } } suspend fun onQuestionnaireSubmission( extractedResourceIds: List<IdType>, emitFeature: (GeoJsonFeature) -> Unit, ) { val locationId = extractedResourceIds.firstOrNull { it.resourceType == ResourceType.Location.name } ?: return val location = defaultRepository.loadResource<Location>(locationId.valueAsString.extractLogicalIdUuid()) ?: return val feature = GeoJsonFeature( id = location.id, geometry = Geometry( coordinates = // MapBox coordinates are represented as Long,Lat (NOT Lat,Long) listOf( location.position.longitude.toDouble(), location.position.latitude.toDouble(), ), ), ) emitFeature(feature) } fun launchQuestionnaire( questionnaireConfig: QuestionnaireConfig, feature: GeoJsonFeature, context: Context, ) { val params = addMatchingCoordinatesToActionParameters( feature.geometry?.coordinates?.get(0), feature.geometry?.coordinates?.get(1), questionnaireConfig.extraParams, ) if (context is QuestionnaireHandler) { context.launchQuestionnaire( context = context, questionnaireConfig = questionnaireConfig, actionParams = params, ) } } /** * Adds coordinates into the correct action parameter as [ActionParameter.value] if the * [ActionParameter.key] matches with [KEY_LATITUDE] or [KEY_LONGITUDE] constants. * */ private fun addMatchingCoordinatesToActionParameters( latitude: Double?, longitude: Double?, params: List<ActionParameter>?, ): List<ActionParameter> { if (latitude == null || longitude == null) { throw IllegalArgumentException("Latitude or Longitude must not be null") } params ?: return emptyList() return params .filter { it.paramType == ActionParameterType.PREPOPULATE && it.dataType == Enumerations.DataType.STRING } .map { return@map when (it.key) { KEY_LATITUDE -> it.copy(value = latitude.toString()) KEY_LONGITUDE -> it.copy(value = longitude.toString()) else -> it } } } suspend fun emitSnackBarState(snackBarMessageConfig: SnackBarMessageConfig) { _snackBarStateFlow.emit(snackBarMessageConfig) } fun isFirstTime(): Boolean = sharedPreferencesHelper .read(SharedPreferenceKey.LAST_SYNC_TIMESTAMP.name, null) .isNullOrEmpty() && applicationConfiguration.usePractitionerAssignedLocationOnSync fun getImageBitmap(reference: String) = runBlocking { reference.referenceToBitmap(defaultRepository.fhirEngine, decodedImageMap) } private companion object { const val KEY_LATITUDE = "positionLatitude" const val KEY_LONGITUDE = "positionLongitude" } }
192
Kotlin
56
56
64a55e6920cb6280cf02a0d68152d9c03266518d
11,085
fhircore
Apache License 2.0
app/app/src/main/java/com/ingjuanocampo/enfila/android/home/history/FragmentHistory.kt
ingjuanocampo
387,043,993
false
{"Kotlin": 240432}
package com.ingjuanocampo.enfila.android.home.history import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.Observer import androidx.navigation.fragment.NavHostFragment.findNavController import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.OrientationHelper import androidx.recyclerview.widget.RecyclerView import com.ingjuanocampo.cdapter.CompositeDelegateAdapter import com.ingjuanocampo.enfila.android.R import com.ingjuanocampo.enfila.android.home.list.adapter.DelegateShift import com.ingjuanocampo.enfila.android.home.list.viewmodel.ViewModelListItems import com.ingjuanocampo.enfila.android.navigation.NavigationDestinations import com.ingjuanocampo.enfila.android.utils.ViewTypes import com.ingjuanocampo.enfila.android.utils.navigateToCustomDest import dagger.hilt.android.AndroidEntryPoint import javax.inject.Inject @AndroidEntryPoint class FragmentHistory : Fragment() { @Inject lateinit var navigationDestinations: NavigationDestinations private val navController by lazy { findNavController(this) } companion object { fun newInstance() = FragmentHistory() } private lateinit var adapter: CompositeDelegateAdapter val viewModel: ViewModelListItems by viewModels() override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?, ): View? { return inflater.inflate(R.layout.fragment_list_items, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val recycler: RecyclerView = view.findViewById(R.id.recycler) adapter = CompositeDelegateAdapter(1).apply { appendDelegate( ViewTypes.SHIFT.ordinal, ) { DelegateShift(it, onShiftListener = { navController.navigateToCustomDest(navigationDestinations.navigateToShiftDetails(it)) }) } } recycler.addItemDecoration(DividerItemDecoration(requireContext(), OrientationHelper.VERTICAL)) recycler.adapter = adapter viewModel.state.observe( viewLifecycleOwner, Observer { adapter.updateItems(it) }, ) viewModel.load(false) } }
0
Kotlin
0
0
decebb226be191ec6382a7d60a97c5598d3f1bdf
2,496
EnFila-Android
MIT License
schedule/src/main/kotlin/com/itavgur/omul/schedule/config/TransportPersonnelMockConfig.kt
itAvgur
211,451,348
false
{"Kotlin": 295751, "Smarty": 4371, "Dockerfile": 1120}
package com.itavgur.omul.schedule.config import com.itavgur.omul.schedule.domain.PersonnelInfo import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.context.annotation.Configuration @Configuration @ConditionalOnProperty("transport.personnel.type", havingValue = "mock", matchIfMissing = false) class TransportPersonnelMockConfig { companion object { val mockResponseFromPersonnelServer = PersonnelInfo( personnelId = 11, firstName = "mockedFirstName", lastName = "mockedLastName", qualification = "mockedQualification" ) } }
1
Kotlin
1
0
332e2ae6213bfdec1179949d98b37fc84a234cdb
653
omul
The Unlicense
app/src/main/java/com/android/mindmaster/Model/AppBlockModel.kt
ArmanKhanTech
661,690,640
false
null
package com.android.mindmaster.Model import android.graphics.drawable.Drawable data class AppBlockModel( val appName: String, val packageName: String, val icon: Drawable, val extra: String, val blocked: Boolean? )
0
null
0
11
6f1678269e516d9765a8e759714a9c77af052ab7
235
MindMaster
MIT License
token-validation-core/src/main/kotlin/no/nav/security/token/support/core/exceptions/AnnotationRequiredException.kt
navikt
124,397,000
false
{"Kotlin": 363248}
package no.nav.security.token.support.core.exceptions import java.lang.reflect.Method import no.nav.security.token.support.core.validation.JwtTokenAnnotationHandler.Companion.SUPPORTED_ANNOTATIONS class AnnotationRequiredException(message : String) : RuntimeException(message) { constructor(method : Method) : this("Server misconfigured - controller/method [${method.declaringClass.name}.${method.name}] not annotated with any of $SUPPORTED_ANNOTATIONS or added to ignore list") }
8
Kotlin
7
15
ce4dae36cfdd452cfbbe5477657bd2ea0ff1f346
485
token-support
MIT License
src/main/kotlin/com/tang/hwplib/builder/etc/UnknownRecordBuilder.kt
accforaus
169,677,219
false
null
package com.tang.hwplib.builder.etc import com.tang.hwplib.builder.interfaces.HWPBuilder import com.tang.hwplib.objects.etc.UnknownRecord class UnknownRecordBuilder : HWPBuilder<UnknownRecord> { private val unknownRecord : UnknownRecord = UnknownRecord.build() fun setHeader(headerBuilder: HWPRecordHeaderBuilder) : UnknownRecordBuilder = this.apply { unknownRecord.header = headerBuilder.build() } fun setBody(body: ByteArray) : UnknownRecordBuilder = this.apply { unknownRecord.body = body } override fun build(): UnknownRecord = unknownRecord }
1
null
7
22
b828271f12a885dece5af5aa6281a1b2cf84d459
592
libhwp
Apache License 2.0
app/src/main/kotlin/org/andstatus/app/net/social/ConnectionTwitterGnuSocial.kt
andstatus
3,040,264
false
null
/* * Copyright (C) 2013 yvolk (<NAME>), http://yurivolkov.com * * 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.andstatus.app.net.social import android.net.Uri import io.vavr.control.Try import org.andstatus.app.data.DownloadStatus import org.andstatus.app.data.TextMediaType import org.andstatus.app.net.http.ConnectionException import org.andstatus.app.net.http.HttpReadResult import org.andstatus.app.net.http.HttpRequest import org.andstatus.app.net.http.USER_AGENT import org.andstatus.app.origin.OriginConfig import org.andstatus.app.util.JsonUtils import org.andstatus.app.util.MyLog import org.andstatus.app.util.MyStringBuilder import org.andstatus.app.util.RelativeTime import org.andstatus.app.util.TryUtils import org.andstatus.app.util.UriUtils import org.andstatus.app.util.UriUtils.isRealOid import org.andstatus.app.util.UriUtils.nonRealOid import org.json.JSONArray import org.json.JSONException import org.json.JSONObject import java.util.regex.Pattern /** * Specific implementation of the Twitter API in GNU Social * @author <EMAIL> */ class ConnectionTwitterGnuSocial : ConnectionTwitterLike() { override fun getApiPathFromOrigin(routine: ApiRoutineEnum): String { val url: String = when (routine) { ApiRoutineEnum.GET_CONFIG -> "statusnet/config.json" ApiRoutineEnum.GET_CONVERSATION -> "statusnet/conversation/%noteId%.json" ApiRoutineEnum.GET_OPEN_INSTANCES -> "http://gstools.org/api/get_open_instances" ApiRoutineEnum.PUBLIC_TIMELINE -> "statuses/public_timeline.json" ApiRoutineEnum.SEARCH_NOTES -> "search.json" else -> "" } return if (url.isEmpty()) { super.getApiPathFromOrigin(routine) } else partialPathToApiPath(url) } override fun getFriendsOrFollowersIds(apiRoutine: ApiRoutineEnum, actorOid: String): Try<List<String>> { return getApiPath(apiRoutine) .map { obj: Uri -> obj.buildUpon() } .map { builder: Uri.Builder -> builder.appendQueryParameter("user_id", actorOid) } .map { it.build() } .map { uri: Uri -> HttpRequest.of(apiRoutine, uri) } .flatMap(::execute) .flatMap { obj: HttpReadResult -> obj.getJsonArray() } .flatMap { jsonArray: JSONArray? -> val list: MutableList<String> = ArrayList() try { var index = 0 while (jsonArray != null && index < jsonArray.length()) { list.add(jsonArray.getString(index)) index++ } Try.success(list) } catch (e: JSONException) { Try.failure(ConnectionException.loggedJsonException(this, apiRoutine.name, e, jsonArray)) } } } override fun rateLimitStatus(): Try<RateLimitStatus> { val apiRoutine = ApiRoutineEnum.ACCOUNT_RATE_LIMIT_STATUS return getApiPath(apiRoutine) .map { uri: Uri -> HttpRequest.of(apiRoutine, uri) } .flatMap(::execute) .flatMap { obj: HttpReadResult -> obj.getJsonObject() } .flatMap { result: JSONObject? -> val status = RateLimitStatus() if (result != null) { status.remaining = result.optInt("remaining_hits") status.limit = result.optInt("hourly_limit") } Try.success(status) } } override fun updateNote2(note: Note): Try<AActivity> { val formParams = JSONObject() try { super.updateNoteSetFields(note, formParams) // This parameter was removed from Twitter API, but it still is in GNUsocial formParams.put("source", USER_AGENT) } catch (e: JSONException) { return Try.failure(e) } return tryApiPath(data.getAccountActor(), ApiRoutineEnum.UPDATE_NOTE) .map { uri: Uri -> HttpRequest.of(ApiRoutineEnum.UPDATE_NOTE, uri) .withPostParams(formParams) .withMediaPartName("media") .withAttachmentToPost(note.attachments.firstToUpload) } .flatMap(::execute) .flatMap { obj: HttpReadResult -> obj.getJsonObject() } .map { jso: JSONObject? -> activityFromJson(jso) } } override fun getConfig(): Try<OriginConfig> { val apiRoutine = ApiRoutineEnum.GET_CONFIG return getApiPath(apiRoutine) .map { uri: Uri -> HttpRequest.of(apiRoutine, uri) } .flatMap(::execute) .flatMap { obj: HttpReadResult -> obj.getJsonObject() } .map { result: JSONObject? -> var config: OriginConfig = OriginConfig.getEmpty() if (result != null) { val site = result.optJSONObject("site") if (site != null) { val textLimit = site.optInt("textlimit") var uploadLimit = 0 val attachments = site.optJSONObject("attachments") if (attachments != null && site.optBoolean("uploads")) { uploadLimit = site.optInt("file_quota") } config = OriginConfig.fromTextLimit(textLimit, uploadLimit.toLong()) // "shorturllength" is not used } } config } } override fun getConversation(conversationOid: String): Try<List<AActivity>> { if (conversationOid.nonRealOid) return TryUtils.emptyList() val apiRoutine = ApiRoutineEnum.GET_CONVERSATION return getApiPathWithNoteId(apiRoutine, conversationOid) .map { uri: Uri -> HttpRequest.of(apiRoutine, uri) } .flatMap(::execute) .flatMap { obj: HttpReadResult -> obj.getJsonArray() } .flatMap { jsonArray: JSONArray? -> jArrToTimeline(jsonArray, apiRoutine) } } override fun setNoteBodyFromJson(note: Note, jso: JSONObject) { if (data.getOrigin().isHtmlContentAllowed() && !jso.isNull(HTML_BODY_FIELD_NAME)) { note.setContent(jso.getString(HTML_BODY_FIELD_NAME), TextMediaType.HTML) } else if (jso.has("text")) { note.setContent(jso.getString("text"), TextMediaType.PLAIN) } } override fun activityFromJson2(jso: JSONObject?): AActivity { if (jso == null) return AActivity.EMPTY val method = "activityFromJson2" val activity = super.activityFromJson2(jso) val note = activity.getNote() note.url = JsonUtils.optString(jso, "external_url") note.setConversationOid(JsonUtils.optString(jso, CONVERSATION_ID_FIELD_NAME)) if (!jso.isNull(ATTACHMENTS_FIELD_NAME)) { try { val jArr = jso.getJSONArray(ATTACHMENTS_FIELD_NAME) for (ind in 0 until jArr.length()) { val jsonAttachment = jArr[ind] as JSONObject val uri = UriUtils.fromAlternativeTags(jsonAttachment, "url", "thumb_url") val attachment: Attachment = Attachment.fromUriAndMimeType(uri, JsonUtils.optString(jsonAttachment, "mimetype")) if (attachment.isValid()) { activity.addAttachment(attachment) } else { MyLog.d(this, "$method; invalid attachment #$ind; $jArr") } } } catch (e: JSONException) { MyLog.d(this, method, e) } } return createLikeActivity(activity) } override fun actorBuilderFromJson(jso: JSONObject?): Actor { return if (jso == null) Actor.EMPTY else super.actorBuilderFromJson(jso) .setProfileUrl(JsonUtils.optString(jso, "statusnet_profile_url")) } override fun getOpenInstances(): Try<List<Server>> { val apiRoutine = ApiRoutineEnum.GET_OPEN_INSTANCES return getApiPath(apiRoutine) .map { path: Uri -> HttpRequest.of(apiRoutine, path) .withAuthenticate(false) } .flatMap(http::execute) .flatMap { obj: HttpReadResult -> obj.getJsonObject() } .map { result: JSONObject? -> val origins: MutableList<Server> = ArrayList() val logMessage = StringBuilder(apiRoutine.toString()) var error = false if (result == null) { MyStringBuilder.appendWithSpace(logMessage, "Response is null JSON") error = true } else if (!error && JsonUtils.optString(result, "status") != "OK") { MyStringBuilder.appendWithSpace( logMessage, "gtools service returned the error: '" + JsonUtils.optString(result, "error") + "'" ) error = true } if (!error && result != null) { val data = result.optJSONObject("data") if (data != null) { try { val iterator = data.keys() while (iterator.hasNext()) { val key = iterator.next() val instance = data.getJSONObject(key) origins.add( Server( JsonUtils.optString(instance, "instance_name"), JsonUtils.optString(instance, "instance_address"), instance.optLong("users_count"), instance.optLong("notices_count") ) ) } } catch (e: JSONException) { throw ConnectionException.loggedJsonException(this, logMessage.toString(), e, data) } } } if (error) { throw ConnectionException(logMessage.toString()) } origins } } companion object { private val ATTACHMENTS_FIELD_NAME: String = "attachments" private val CONVERSATION_ID_FIELD_NAME: String = "statusnet_conversation_id" private val HTML_BODY_FIELD_NAME: String = "statusnet_html" private val GNU_SOCIAL_FAVORITED_SOMETHING_BY_PATTERN = Pattern.compile( "(?s)([^ ]+) favorited something by [^ ]+ (.+)" ) private val GNU_SOCIAL_FAVOURITED_A_STATUS_BY_PATTERN = Pattern.compile( "(?s)([^ ]+) favourited (a status by [^ ]+)" ) fun createLikeActivity(activityIn: AActivity): AActivity { val noteIn = activityIn.getNote() var matcher = GNU_SOCIAL_FAVORITED_SOMETHING_BY_PATTERN.matcher(noteIn.content) if (!matcher.matches()) { matcher = GNU_SOCIAL_FAVOURITED_A_STATUS_BY_PATTERN.matcher(noteIn.content) } if (!matcher.matches()) return activityIn val inReplyTo = noteIn.inReplyTo val favoritedActivity: AActivity if (inReplyTo.getNote().oid.isRealOid) { favoritedActivity = inReplyTo } else { favoritedActivity = AActivity.from(activityIn.accountActor, ActivityType.UPDATE) favoritedActivity.setActor(activityIn.getActor()) favoritedActivity.setNote(noteIn) } favoritedActivity.setUpdatedDate(RelativeTime.SOME_TIME_AGO) val note = favoritedActivity.getNote() note.setContent(matcher.replaceFirst("$2"), TextMediaType.HTML) note.updatedDate = RelativeTime.SOME_TIME_AGO note.setStatus(DownloadStatus.LOADED) // TODO: Maybe we need to invent some other status for partially loaded... note.setInReplyTo(AActivity.EMPTY) val activity: AActivity = AActivity.from(activityIn.accountActor, ActivityType.LIKE) activity.setOid(activityIn.getOid()) activity.setActor(activityIn.getActor()) activity.setUpdatedDate(activityIn.getUpdatedDate()) activity.setActivity(favoritedActivity) return activity } } }
86
null
69
306
6166aded1f115e6e6a7e66ca3756f39f0434663e
13,192
andstatus
Apache License 2.0
app/src/main/java/com/breezemobilearndemo/features/photoReg/present/DsStatusListner.kt
DebashisINT
865,412,474
false
{"Kotlin": 17660089, "Java": 1030592}
package com.breezemobilearndemo.features.photoReg.present import com.breezemobilearndemo.app.domain.ProspectEntity import com.breezemobilearndemo.features.photoReg.model.UserListResponseModel interface DsStatusListner { fun getDSInfoOnLick(obj: ProspectEntity) }
0
Kotlin
0
0
39c92ae61a900f4760abfa9e177272e2bc4d47da
268
MobiLearn_Demo
Apache License 2.0
context/vehicle/src/main/kotlin/com/github/caay2000/ttk/context/vehicle/world/secondary/database/InMemoryWorldRepository.kt
caay2000
489,137,393
false
{"Kotlin": 177204, "Python": 1616}
package com.github.caay2000.ttk.context.vehicle.world.secondary.database import arrow.core.Either import arrow.core.Option import arrow.core.flatten import arrow.core.toOption import com.github.caay2000.ttk.context.shared.domain.StopId import com.github.caay2000.ttk.context.shared.domain.WorldId import com.github.caay2000.ttk.context.vehicle.world.domain.World import com.github.caay2000.ttk.context.vehicle.world.domain.WorldRepository import com.github.caay2000.ttk.lib.database.InMemoryDatabase class InMemoryWorldRepository(private val database: InMemoryDatabase) : WorldRepository { // TODO create a DTO object for world override fun save(world: World) = Either.catch { database.save(DATABASE_TABLE, world.id.rawId, world) as World } override fun get(id: WorldId): Option<World> = Option.catch { database.getById(DATABASE_TABLE, id.rawId) as World } override fun exists(id: WorldId): Boolean = database.exists(DATABASE_TABLE, id.rawId) override fun getStop(worldId: WorldId, stopId: StopId) = Option.catch { this.get(worldId) .flatMap { world -> world.stops.first { it.id == stopId }.toOption() } }.flatten() companion object { private const val DATABASE_TABLE = "VEHICLE_CTX_world" } }
0
Kotlin
0
0
7691e2c8922aab61374b40481b945886401a77b9
1,322
transport-tycoon-kata
MIT License
vertx/core/src/test/kotlin/io/bluetape4k/vertx/AbstractVertxTest.kt
debop
625,161,599
false
{"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82}
package io.bluetape4k.vertx import io.bluetape4k.logging.KLogging abstract class AbstractVertxTest { companion object: KLogging() }
0
Kotlin
0
1
ce3da5b6bddadd29271303840d334b71db7766d2
138
bluetape4k
MIT License
src/main/kotlin/no/nav/familie/ef/søknad/infrastruktur/health/FamilieIntegrasjonHealthIndicator.kt
navikt
204,012,464
false
{"Kotlin": 377198, "Dockerfile": 215}
package no.nav.familie.ef.søknad.infrastruktur.health import no.nav.familie.ef.søknad.kodeverk.FamilieIntegrasjonerClient import no.nav.familie.http.health.AbstractHealthIndicator import org.springframework.stereotype.Component @Component internal class FamilieIntegrasjonHealthIndicator(familieIntegrasjonerClient: FamilieIntegrasjonerClient) : AbstractHealthIndicator(familieIntegrasjonerClient, "familie.integrasjoner")
0
Kotlin
1
1
36a1235f6e63719a3f595477290c288f454503e9
429
familie-ef-soknad-api
MIT License
app/src/main/java/br/com/heiderlopes/pokemonwstemplatev2/presentation/formpokemon/FormPokemonViewModel.kt
DaniloP85
573,220,233
false
null
package br.com.heiderlopes.pokemonwstemplatev2.presentation.formpokemon import androidx.lifecycle.LiveData import androidx.lifecycle.MutableLiveData import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import br.com.heiderlopes.pokemonwstemplatev2.domain.model.Pokemon import br.com.heiderlopes.pokemonwstemplatev2.domain.model.ViewState import br.com.heiderlopes.pokemonwstemplatev2.domain.usecase.GetPokemonUseCase import br.com.heiderlopes.pokemonwstemplatev2.domain.usecase.UpdatePokemonUseCase import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch class FormPokemonViewModel( val getPokemonUseCase: GetPokemonUseCase, val updatePokemonUseCase: UpdatePokemonUseCase ) : ViewModel() { private val _pokemonResult = MutableLiveData<ViewState<Pokemon>>() private val _pokemonUpdateResult = MutableLiveData<ViewState<Pokemon>>() val pokemonUpdateResult : LiveData<ViewState<Pokemon>> get() = _pokemonUpdateResult val pokemonResult : LiveData<ViewState<Pokemon>> get() = _pokemonResult fun getPokemon(number: String) { _pokemonResult .postValue( ViewState.Loading) viewModelScope.launch(Dispatchers .IO) { runCatching { getPokemonUseCase (number) }.onSuccess { _pokemonResult .postValue( ViewState.Success(it.getOrDefault(Pokemon("", "", "", 0,0,0,0)))) }.onFailure { _pokemonResult .postValue( ViewState.Failure(it)) } } } fun update(pokemon: Pokemon) { _pokemonUpdateResult.postValue(ViewState.Loading) viewModelScope.launch(Dispatchers.IO) { runCatching { updatePokemonUseCase(pokemon) }.onSuccess { _pokemonUpdateResult.postValue(ViewState.Success(it.getOrDefault(Pokemon("", "", "", 0,0,0,0)))) }.onFailure { _pokemonUpdateResult.postValue(ViewState.Failure(it)) } } } }
0
Kotlin
0
1
509d623a55fad8b99243c274be97a3faf01a02fa
2,020
pokedex-25mob
MIT License
app/src/main/java/com/merxury/blocker/util/StringUtil.kt
lihenggui
115,417,337
false
null
package com.merxury.blocker.util import java.io.PrintWriter import java.io.StringWriter object StringUtil { @JvmStatic fun getStackTrace(error: Throwable): String { val errors = StringWriter() error.printStackTrace(PrintWriter(errors)) return errors.toString() } }
14
Kotlin
37
323
bf2979d5b94c60ab3a172cfec0fff38420e10519
302
blocker
Apache License 2.0
src/main/kotlin/com/dorachat/templates/recipes/app_package/res/layout/swipeLayoutActivityXml.kt
dora4
515,769,230
false
{"Kotlin": 56529}
/* * Copyright (C) 2022 The Dora Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.dorachat.templates.recipes.app_package.res.layout fun menuPanelActivityXml( packageName: String, activityClass: String ) = """ <?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" tools:context="${packageName}.${activityClass}"> <data> </data> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <dora.widget.DoraTitleBar android:id="@+id/titleBar" android:layout_width="match_parent" android:layout_height="50dp" app:dview_title="@string/app_name" android:background="@color/colorPrimary"/> <dora.widget.panel.MenuPanel android:id="@+id/menuPanel" android:layout_width="match_parent" android:layout_height="match_parent" /> </LinearLayout> </layout> """
0
Kotlin
5
8
bdbc66bb809f7b9bf72f94ea9c89b090f313f6c6
1,692
dora-studio-plugin
Apache License 2.0
lattekit-core/src/main/java/io/lattekit/plugin/css/CssAccessory.kt
maannajjar
54,922,229
false
null
package io.lattekit.plugin.css import android.content.res.ColorStateList import android.content.res.Resources import android.graphics.Color import android.graphics.Outline import android.graphics.Rect import android.graphics.drawable.* import android.os.Build import android.view.View import android.view.ViewGroup import android.view.ViewOutlineProvider import android.widget.Button import android.widget.ProgressBar import android.widget.Switch import io.lattekit.R import io.lattekit.drawable.BorderDrawable import io.lattekit.view.ClippableImageView import io.lattekit.view.NativeView /** * Created by maan on 2/25/16. */ inline fun NativeView.getCss() : CssAccessory { return CssAccessory.getCssAccessory(this); } inline fun NativeView.getStyle() : NodeStyle { return CssAccessory.getCssAccessory(this).style; } // //class SelectorQuery(selectors : List<String>) { // var segments: List<String> = selectors; // var currentIndex : Int = 0 // var type : Int = 0; // val DESCENDANT_TYPE = 1; // val CHILD_TYPE = 2; // // val isMatched : Boolean // get() = currentIndex == segments.size // // init { // advance() // } // // fun advance() { // if (currentIndex+1 < segments.size) { // currentIndex += 1 // // } // } // // fun match(viewType : String, viewClasses : List<String>, viewId : String) : SelectorQuery? { // if (currentIndex >= segments.size) { // return null // } // var currentEl = segments[currentIndex] // if (currentEl.startsWith(".") && viewClasses.contains(currentEl.substring(1))) { // // } // } // // //} class CssAccessory(view : NativeView) { var style : NodeStyle = NodeStyle(view) var shapeDrawable : ShapeDrawable = ShapeDrawable() var gradientDrawable : GradientDrawable = GradientDrawable() var borderDrawable : BorderDrawable = BorderDrawable() var rippleDrawable : Drawable? = null; var layerDrawable : LayerDrawable? = null var clipRadius : Float = 0f; companion object { fun getCssAccessory(view : NativeView) : CssAccessory { var accessory = view.data("css:accessory") if (accessory == null) { accessory = CssAccessory(view) view.data("css:accessory",accessory) } return accessory as CssAccessory } } init { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { rippleDrawable = view.androidView!!.resources.getDrawable(R.drawable.ripple).mutate(); var drawable = rippleDrawable as RippleDrawable if (view.androidView is Button) { drawable.setDrawableByLayerId(R.id.button_bg_layer, gradientDrawable) } else { drawable.setDrawableByLayerId(R.id.background_layer, gradientDrawable) } drawable.setDrawableByLayerId(android.R.id.mask, shapeDrawable) var nativeBackground = view.androidView?.background; if (view.androidView?.background != null) { drawable.setDrawableByLayerId(R.id.native_background_layer,view.androidView?.background); } view.androidView?.outlineProvider = object: ViewOutlineProvider() { override fun getOutline(v: View, outline: Outline) { var padding = Rect(0,0,0,0); if (v is Button || view.androidView?.javaClass?.name == "android.support.design.widget.FloatingActionButton") { nativeBackground?.getOutline(outline); } else { outline?.setRoundRect(Rect(padding.left, padding.top, v.width - padding.right, v.height - padding.bottom), clipRadius) } } } view.androidView?.clipToOutline = view.androidView !is Switch if (view.androidView is ViewGroup) { (view.androidView as ViewGroup).clipToPadding = false; } if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M && view.androidView !is ClippableImageView) { // Foreground is not supported for this view, we will have to use it as background layer drawable.setDrawableByLayerId(R.id.border_layer, borderDrawable) } var backgroundOverride = view.props["background"]; if (backgroundOverride is Int) { try { drawable.setDrawableByLayerId(R.id.native_background_layer, view.androidView!!.resources.getDrawable(backgroundOverride)) } catch(nfe : Resources.NotFoundException) { try { drawable.setDrawableByLayerId(R.id.native_background_layer, ColorDrawable(view.androidView!!.resources.getColor(backgroundOverride))) } catch (nfe2: Resources.NotFoundException) { //TODO: Warn } } } else if (backgroundOverride is Drawable) { drawable.setDrawableByLayerId(R.id.native_background_layer, backgroundOverride) } } else { var rippleColor = ColorStateList(arrayOf(intArrayOf()), intArrayOf(Color.TRANSPARENT)); var layerDrawable : LayerDrawable = LayerDrawable(arrayOf(gradientDrawable, ColorDrawable(), ColorDrawable(),borderDrawable)) layerDrawable.setId(0, 0) layerDrawable.setId(1, 1) layerDrawable.setId(2, 2) layerDrawable.setId(3,3) rippleDrawable = codetail.graphics.drawables.RippleDrawable(rippleColor, layerDrawable, shapeDrawable); if (view.androidView?.background != null) { layerDrawable.setDrawableByLayerId(2,view.androidView?.background); } var backgroundOverride = view.props["background"]; if (backgroundOverride is Int) { try { layerDrawable.setDrawableByLayerId(2, view.androidView!!.resources.getDrawable(backgroundOverride)) } catch(nfe : Resources.NotFoundException) { try { layerDrawable.setDrawableByLayerId(2, ColorDrawable(view.androidView!!.resources.getColor(backgroundOverride))) } catch (nfe2: Resources.NotFoundException) { //TODO: Warn } } } else if (backgroundOverride is Drawable) { layerDrawable.setDrawableByLayerId(2, backgroundOverride) } } this.layerDrawable = layerDrawable view.androidView?.background = rippleDrawable; if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { view.androidView?.foreground = borderDrawable; } else if (view.androidView is ClippableImageView) { (view.androidView as ClippableImageView).foregroundDrawable = borderDrawable; } } fun setBackgroundDrawable(drawable: Drawable) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { (rippleDrawable as RippleDrawable).setDrawableByLayerId(R.id.native_background_layer, drawable) rippleDrawable?.invalidateSelf() } else { layerDrawable?.setDrawableByLayerId(R.id.native_background_layer, drawable) layerDrawable?.invalidateSelf() } } fun setRadius(radius : Float) { borderDrawable.topLeftRadiusV = radius borderDrawable.topLeftRadiusH = radius borderDrawable.topRightRadiusV = radius borderDrawable.topRightRadiusH = radius borderDrawable.bottomLeftRadiusV = radius borderDrawable.bottomLeftRadiusH = radius borderDrawable.bottomRightRadiusV = radius borderDrawable.bottomRightRadiusH = radius clipRadius = radius // rippleDrawable?.invalidateSelf() } fun setRippleColor(color : Int) { var rippleColor = ColorStateList(arrayOf(intArrayOf()), intArrayOf(color)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { (rippleDrawable as RippleDrawable).setColor(rippleColor) } else { (rippleDrawable as codetail.graphics.drawables.RippleDrawable).setColor(rippleColor) } } }
12
Kotlin
18
173
bcc1e4e759c5be62db30b6398de63555c5b24726
8,443
lattekit
MIT License
src/main/kotlin/pl/karol202/sock/connection/Connection.kt
karol-202
158,872,049
false
null
package pl.karol202.sock.connection import pl.karol202.plumber.TerminalBiLayer import pl.karol202.sock.PublicApi @PublicApi interface Connection : TerminalBiLayer<ByteArray> { @PublicApi fun connect() @PublicApi fun read(): ByteArray @PublicApi fun send(data: ByteArray) @PublicApi fun close() override fun transform(input: ByteArray) = send(input) override fun transformBack(input: Unit) = read() }
0
Kotlin
0
0
1447eece9f25b2a88799a7c46d7f88f450ef667d
417
Sock
MIT License
src/main/kotlin/no/nav/k9/los/aksjonspunktbehandling/AksjonspunktStreamK9.kt
navikt
238,874,021
false
{"Kotlin": 1849311, "Shell": 899, "JavaScript": 741, "Dockerfile": 447, "PLpgSQL": 167}
package no.nav.k9.los.aksjonspunktbehandling import no.nav.k9.los.Configuration import no.nav.k9.los.integrasjon.kafka.IKafkaConfig import no.nav.k9.los.integrasjon.kafka.ManagedKafkaStreams import no.nav.k9.los.integrasjon.kafka.ManagedStreamHealthy import no.nav.k9.los.integrasjon.kafka.ManagedStreamReady import org.apache.kafka.clients.consumer.OffsetResetStrategy import org.apache.kafka.streams.StreamsBuilder import org.apache.kafka.streams.Topology import org.apache.kafka.streams.kstream.Consumed import org.slf4j.LoggerFactory import kotlin.system.measureTimeMillis internal class AksjonspunktStreamK9 constructor( kafkaConfig: IKafkaConfig, configuration: Configuration, k9sakEventHandler: K9sakEventHandler ) { private val stream = ManagedKafkaStreams( name = NAME, properties = kafkaConfig.stream(NAME, OffsetResetStrategy.EARLIEST), topology = topology( configuration = configuration, k9sakEventHandler = k9sakEventHandler ), unreadyAfterStreamStoppedIn = kafkaConfig.unreadyAfterStreamStoppedIn ) internal val ready = ManagedStreamReady(stream) internal val healthy = ManagedStreamHealthy(stream) private companion object { private const val NAME = "AksjonspunktLagetV1" private val log = LoggerFactory.getLogger(AksjonspunktStreamK9::class.java) private fun topology( configuration: Configuration, k9sakEventHandler: K9sakEventHandler ): Topology { val builder = StreamsBuilder() val fromTopic = Topic( name = configuration.getAksjonspunkthendelseTopic(), serDes = AksjonspunktLaget() ) builder .stream( fromTopic.name, Consumed.with(fromTopic.keySerde, fromTopic.valueSerde) ).peek { _, e -> log.info("--> Behandlingsprosesshendelse fra k9sak: ${e.tryggToString() }") } .foreach { _, entry -> if (entry != null) { val tid = measureTimeMillis { k9sakEventHandler.prosesser(entry) } if (tid > 5000) { // Logger som warning ved over 5sekunder fordi det kan oppleves som at oppgaver blir liggende igjen på benken log.warn("Prosessering av Behandlingsprosesshendelse fra k9sak for ${entry.saksnummer}-${entry.eksternId} tok $tid") } else { log.info("Prosessering av Behandlingsprosesshendelse fra k9sak for ${entry.saksnummer}-${entry.eksternId} tok $tid") } } } return builder.build() } } internal fun stop() = stream.stop(becauseOfError = false) }
9
Kotlin
0
0
ffcb0509d7ddde1da6f0e6d4fc7aab873301efd6
2,907
k9-los-api
MIT License
rounded/src/commonMain/kotlin/me/localx/icons/rounded/filled/Escalator.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.filled 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.Filled.Escalator: ImageVector get() { if (_escalator != null) { return _escalator!! } _escalator = Builder(name = "Escalator", defaultWidth = 512.0.dp, defaultHeight = 512.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(8.5f, 0.0f) curveTo(9.881f, 0.0f, 11.0f, 1.119f, 11.0f, 2.5f) reflectiveCurveToRelative(-1.119f, 2.5f, -2.5f, 2.5f) reflectiveCurveToRelative(-2.5f, -1.119f, -2.5f, -2.5f) reflectiveCurveTo(7.119f, 0.0f, 8.5f, 0.0f) close() moveTo(9.044f, 22.58f) lineToRelative(11.322f, -9.58f) horizontalLineToRelative(0.134f) curveToRelative(1.93f, 0.0f, 3.5f, -1.57f, 3.5f, -3.5f) reflectiveCurveToRelative(-1.57f, -3.5f, -3.5f, -3.5f) horizontalLineToRelative(-1.669f) curveToRelative(-1.417f, 0.0f, -2.793f, 0.504f, -3.875f, 1.42f) lineTo(3.634f, 17.0f) horizontalLineToRelative(-0.134f) curveToRelative(-1.93f, 0.0f, -3.5f, 1.57f, -3.5f, 3.5f) reflectiveCurveToRelative(1.57f, 3.5f, 3.5f, 3.5f) horizontalLineToRelative(1.669f) curveToRelative(1.417f, 0.0f, 2.793f, -0.504f, 3.875f, -1.42f) close() moveTo(11.499f, 7.725f) curveToRelative(-0.611f, -1.027f, -1.72f, -1.725f, -2.999f, -1.725f) curveToRelative(-1.93f, 0.0f, -3.5f, 1.57f, -3.5f, 3.5f) verticalLineToRelative(3.725f) lineToRelative(6.499f, -5.5f) close() } } .build() return _escalator!! } private var _escalator: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,654
icons
MIT License
services/match-service/domain/src/main/kotlin/nl/runnable/gigmatch/domain/vacancy/VacancyCancelledEvent.kt
laurens-runnable
595,664,400
false
null
package nl.runnable.gigmatch.domain.vacancy class VacancyCancelledEvent
0
Kotlin
0
0
961260f0c6e96be9d8e17c9772adb5169ea11bf0
73
gigmatch
The Unlicense
buildSrc/src/main/java/Dependencies.kt
VladimirWrites
79,385,776
false
null
object Versions { const val kotlin = "2.0.20" const val android_x = "1.7.0" const val circleindicator = "2.1.6" const val junit = "4.13.2" const val mockito_core = "4.5.1" const val mockito_kotlin = "4.0.0" const val truth = "1.1.3" const val robolectric = "4.7.3" const val gradle_android = "8.6.0" const val jacoco = "0.8.8" const val min_sdk = 14 const val sample_min_sdk = 21 const val target_sdk = 35 const val compile_sdk = 35 const val lemniscate_version_code = 204 const val lemniscate_version_name = "2.0.4" const val sample_version_code = 144 const val sample_version_name = "1.4.4" } object Deps { const val kotlin_stdlib = "org.jetbrains.kotlin:kotlin-stdlib:${Versions.kotlin}" const val appcompat = "androidx.appcompat:appcompat:${Versions.android_x}" const val circleindicator = "me.relex:circleindicator:${Versions.circleindicator}" const val junit = "junit:junit:${Versions.junit}" const val mockito_core = "org.mockito:mockito-core:${Versions.mockito_core}" const val mockito_kotlin = "org.mockito.kotlin:mockito-kotlin:${Versions.mockito_kotlin}" const val truth = "com.google.truth:truth:${Versions.truth}" const val robolectric = "org.robolectric:robolectric:${Versions.robolectric}" const val android_gradle_plugin = "com.android.tools.build:gradle:${Versions.gradle_android}" const val kotlin_gradle_plugin = "org.jetbrains.kotlin:kotlin-gradle-plugin:${Versions.kotlin}" }
0
Kotlin
43
427
e2410addd33d5379157ff8b22d4d3909f0d2b303
1,522
Lemniscate
Apache License 2.0
video_trimmer_library/src/main/java/com/amp/trimmy/utils/UiThreadExecutor.kt
Amal92
272,075,455
false
null
/** * Copyright (C) 2010-2016 eBusiness Information, Excilys Group * * * 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.lb.video_trimmer_library.utils import android.os.Handler import android.os.Looper import android.os.Message import android.os.SystemClock import java.util.* /** * This class provide operations for * UiThread tasks. */ internal object UiThreadExecutor { private val HANDLER = object : Handler(Looper.getMainLooper()) { override fun handleMessage(msg: Message) { val callback = msg.callback if (callback != null) { callback.run() decrementToken(msg.obj as Token) } else { super.handleMessage(msg) } } } private val TOKENS = HashMap<String, Token>() /** * Store a new task in the map for providing cancellation. This method is * used by AndroidAnnotations and not intended to be called by clients. * * @param id the identifier of the task * @param task the task itself * @param delay the delay or zero to run immediately */ fun runTask(id: String, task: Runnable, delay: Long) { if ("" == id) { HANDLER.postDelayed(task, delay) return } val time = SystemClock.uptimeMillis() + delay HANDLER.postAtTime(task, nextToken(id), time) } private fun nextToken(id: String): Token { synchronized(TOKENS) { var token = TOKENS[id] if (token == null) { token = Token(id) TOKENS[id] = token } ++token.runnablesCount return token } } private fun decrementToken(token: Token) { synchronized(TOKENS) { if (--token.runnablesCount == 0) { val id = token.id val old = TOKENS.remove(id) if (old != token && old != null) { // a runnable finished after cancelling, we just removed a // wrong token, lets put it back TOKENS[id] = old } } } } /** * Cancel all tasks having the specified `id`. * * @param id the cancellation identifier */ fun cancelAll(id: String) { val token: Token? synchronized(TOKENS) { token = TOKENS.remove(id) } if (token == null) { // nothing to cancel return } HANDLER.removeCallbacksAndMessages(token) } // should not be instantiated private class Token constructor(internal val id: String) { internal var runnablesCount = 0 } }
2
null
22
5
219cc279c35251bd383a0583d3d4c2e735935948
3,242
Trimmy
MIT License
video_trimmer_library/src/main/java/com/amp/trimmy/utils/UiThreadExecutor.kt
Amal92
272,075,455
false
null
/** * Copyright (C) 2010-2016 eBusiness Information, Excilys Group * * * 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.lb.video_trimmer_library.utils import android.os.Handler import android.os.Looper import android.os.Message import android.os.SystemClock import java.util.* /** * This class provide operations for * UiThread tasks. */ internal object UiThreadExecutor { private val HANDLER = object : Handler(Looper.getMainLooper()) { override fun handleMessage(msg: Message) { val callback = msg.callback if (callback != null) { callback.run() decrementToken(msg.obj as Token) } else { super.handleMessage(msg) } } } private val TOKENS = HashMap<String, Token>() /** * Store a new task in the map for providing cancellation. This method is * used by AndroidAnnotations and not intended to be called by clients. * * @param id the identifier of the task * @param task the task itself * @param delay the delay or zero to run immediately */ fun runTask(id: String, task: Runnable, delay: Long) { if ("" == id) { HANDLER.postDelayed(task, delay) return } val time = SystemClock.uptimeMillis() + delay HANDLER.postAtTime(task, nextToken(id), time) } private fun nextToken(id: String): Token { synchronized(TOKENS) { var token = TOKENS[id] if (token == null) { token = Token(id) TOKENS[id] = token } ++token.runnablesCount return token } } private fun decrementToken(token: Token) { synchronized(TOKENS) { if (--token.runnablesCount == 0) { val id = token.id val old = TOKENS.remove(id) if (old != token && old != null) { // a runnable finished after cancelling, we just removed a // wrong token, lets put it back TOKENS[id] = old } } } } /** * Cancel all tasks having the specified `id`. * * @param id the cancellation identifier */ fun cancelAll(id: String) { val token: Token? synchronized(TOKENS) { token = TOKENS.remove(id) } if (token == null) { // nothing to cancel return } HANDLER.removeCallbacksAndMessages(token) } // should not be instantiated private class Token constructor(internal val id: String) { internal var runnablesCount = 0 } }
2
null
22
5
219cc279c35251bd383a0583d3d4c2e735935948
3,242
Trimmy
MIT License
app/src/main/java/nerd/tuxmobil/fahrplan/congress/schedule/SessionViewDrawer.kt
johnjohndoe
12,616,092
false
null
package nerd.tuxmobil.fahrplan.congress.schedule import android.content.Context import android.view.View import android.widget.ImageView import android.widget.TextView import androidx.annotation.ColorInt import androidx.annotation.ColorRes import androidx.core.content.ContextCompat import androidx.core.view.ViewCompat import androidx.core.view.isVisible import nerd.tuxmobil.fahrplan.congress.R import nerd.tuxmobil.fahrplan.congress.extensions.requireViewByIdCompat import nerd.tuxmobil.fahrplan.congress.models.Session import nerd.tuxmobil.fahrplan.congress.repositories.AppRepository import nerd.tuxmobil.fahrplan.congress.utils.ContentDescriptionFormatter import nerd.tuxmobil.fahrplan.congress.utils.Font import nerd.tuxmobil.fahrplan.congress.utils.SessionPropertiesFormatter import nerd.tuxmobil.fahrplan.congress.utils.TypefaceFactory internal class SessionViewDrawer( context: Context, private val sessionPropertiesFormatter: SessionPropertiesFormatter, private val contentDescriptionFormatter: ContentDescriptionFormatter, private val getSessionPadding: () -> Int, private val isAlternativeHighlightingEnabled: () -> Boolean = { // Must load the latest alternative highlighting value every time a session is redrawn. AppRepository.readAlternativeHighlightingEnabled() } ) { private val resources = context.resources private val boldCondensed = TypefaceFactory.getNewInstance(context).getTypeface(Font.Roboto.BoldCondensed) private val sessionDrawableInsetTop = resources.getDimensionPixelSize(R.dimen.session_drawable_inset_top) private val sessionDrawableInsetLeft = resources.getDimensionPixelSize(R.dimen.session_drawable_inset_left) private val sessionDrawableInsetRight = resources.getDimensionPixelSize(R.dimen.session_drawable_inset_right) private val sessionDrawableCornerRadius = resources.getDimensionPixelSize(R.dimen.session_drawable_corner_radius) private val sessionDrawableStrokeWidth = resources.getDimensionPixelSize(R.dimen.session_drawable_selection_stroke_width) private val sessionDrawableStrokeColor = ContextCompat.getColor(context, R.color.session_drawable_selection_stroke) private val sessionDrawableRippleColor = ContextCompat.getColor(context, R.color.session_drawable_ripple) private val trackNameBackgroundColorDefaultPairs = TrackBackgrounds.getTrackNameBackgroundColorDefaultPairs(context) private val trackNameBackgroundColorHighlightPairs = TrackBackgrounds.getTrackNameBackgroundColorHighlightPairs(context) fun updateSessionView(sessionView: View, session: Session, useDeviceTimeZone: Boolean) { val bell = sessionView.requireViewByIdCompat<ImageView>(R.id.session_bell_view) bell.isVisible = session.hasAlarm bell.contentDescription = sessionView.context.getString(R.string.session_item_has_alarm_content_description) var textView = sessionView.requireViewByIdCompat<TextView>(R.id.session_title_view) textView.typeface = boldCondensed textView.text = session.title textView.contentDescription = contentDescriptionFormatter .getTitleContentDescription(session.title) textView = sessionView.requireViewByIdCompat(R.id.session_subtitle_view) textView.text = session.subtitle textView.contentDescription = contentDescriptionFormatter .getSubtitleContentDescription(session.subtitle) textView = sessionView.requireViewByIdCompat(R.id.session_speakers_view) val speakerNames = sessionPropertiesFormatter.getFormattedSpeakers(session) textView.text = speakerNames textView.contentDescription = contentDescriptionFormatter .getSpeakersContentDescription(session.speakers.size, speakerNames) textView = sessionView.requireViewByIdCompat(R.id.session_track_view) textView.text = sessionPropertiesFormatter.getFormattedTrackLanguageText(session) textView.contentDescription = contentDescriptionFormatter .getFormattedTrackContentDescription(session.track, sessionPropertiesFormatter.getLanguageText(session)) val recordingOptOut = sessionView.findViewById<View>(R.id.session_no_video_view) if (recordingOptOut != null) { recordingOptOut.isVisible = session.recordingOptOut } ViewCompat.setStateDescription(sessionView, contentDescriptionFormatter .getStateContentDescription(session, useDeviceTimeZone)) setSessionBackground(session.highlight, session.track, sessionView) setSessionTextColor(session.highlight, sessionView) sessionView.tag = session } fun setSessionBackground(isFavored: Boolean, track: String, sessionView: View) { val context = sessionView.context @ColorRes val backgroundColorResId = if (isFavored) { trackNameBackgroundColorHighlightPairs[track] ?: R.color.track_background_highlight } else { trackNameBackgroundColorDefaultPairs[track] ?: R.color.track_background_default } @ColorInt val backgroundColor = ContextCompat.getColor(context, backgroundColorResId) val sessionDrawable = if (isFavored && isAlternativeHighlightingEnabled()) { SessionDrawable( backgroundColor, sessionDrawableCornerRadius.toFloat(), sessionDrawableRippleColor, sessionDrawableStrokeColor, sessionDrawableStrokeWidth.toFloat()) } else { SessionDrawable( backgroundColor, sessionDrawableCornerRadius.toFloat(), sessionDrawableRippleColor) } sessionDrawable.setLayerInset(SessionDrawable.BACKGROUND_LAYER_INDEX, sessionDrawableInsetLeft, sessionDrawableInsetTop, sessionDrawableInsetRight, 0) sessionDrawable.setLayerInset(SessionDrawable.STROKE_LAYER_INDEX, sessionDrawableInsetLeft, sessionDrawableInsetTop, sessionDrawableInsetRight, 0) ViewCompat.setBackground(sessionView, sessionDrawable) val padding = getSessionPadding() sessionView.setPadding(padding, padding, padding, padding) } companion object { const val LOG_TAG = "SessionViewDrawer" fun setSessionTextColor(isFavored: Boolean, view: View) { val title = view.requireViewByIdCompat<TextView>(R.id.session_title_view) val subtitle = view.requireViewByIdCompat<TextView>(R.id.session_subtitle_view) val speakers = view.requireViewByIdCompat<TextView>(R.id.session_speakers_view) val track = view.requireViewByIdCompat<TextView>(R.id.session_track_view) val colorResId = if (isFavored) R.color.session_item_text_on_highlight_background else R.color.session_item_text_on_default_background val textColor = ContextCompat.getColor(view.context, colorResId) title.setTextColor(textColor) subtitle.setTextColor(textColor) speakers.setTextColor(textColor) track.setTextColor(textColor) } } }
69
null
99
27
4b91d7dcdfbc8de965a928b3ebfbfe595ec06b3f
7,322
CampFahrplan
Apache License 2.0
data/src/main/java/db/DriverFactory.android.kt
TheSetox
767,301,777
false
{"Kotlin": 28104, "Swift": 669, "HTML": 304}
package db import android.content.Context import app.cash.sqldelight.db.SqlDriver import app.cash.sqldelight.driver.android.AndroidSqliteDriver import org.example.project.db.SampleDataBase actual class DriverFactory(private val context: Context) { actual fun createDriver(): SqlDriver { return AndroidSqliteDriver( schema = SampleDataBase.Schema, context = context, name = "SampleDatabase.db" ) } }
8
Kotlin
0
3
43aa092e4b9cfcdf356f153c652d6d0a7eb67126
461
KMP-Fun-Clean-Architecture
Apache License 2.0
components/src/main/java/dev/medzik/android/components/icons/TopAppBarBackIcon.kt
M3DZIK
698,762,035
false
{"Kotlin": 56449}
package dev.medzik.android.components.icons import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.ArrowBack import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.runtime.Composable import androidx.navigation.NavController /** * A back arrow icon in the app bar. When clicked, * it navigates back in the navigation stack using the provided [NavController]. * * @param navController the [NavController] instance for navigating back */ @Composable fun TopAppBarBackIcon(navController: NavController) { IconButton(onClick = { navController.popBackStack() }) { Icon( imageVector = Icons.AutoMirrored.Filled.ArrowBack, contentDescription = null ) } }
1
Kotlin
0
1
d3d214c4532be17e523cc9bf9ccb9cd4337ca51e
804
android-utils
MIT License
src/main/kotlin/ru/mdashlw/kda/Dsl.kt
mdashlw
193,076,704
false
null
package ru.mdashlw.kda import net.dv8tion.jda.api.JDA import net.dv8tion.jda.api.entities.MessageEmbed import ru.mdashlw.kda.builder.Builder import ru.mdashlw.kda.builder.impl.EmbedBuilder import ru.mdashlw.kda.builder.impl.JdaBuilder import ru.mdashlw.kda.builder.impl.PaginationBuilder import ru.mdashlw.kda.command.Colors import ru.mdashlw.kda.command.Command import ru.mdashlw.kda.command.Emotes import ru.mdashlw.kda.command.Replies import ru.mdashlw.kda.command.manager.CommandManager import ru.mdashlw.kda.pagination.Pagination inline fun <B : Builder<T>, T> build(builder: B, block: B.() -> Unit): T = builder.apply(block).build() inline fun jda(block: JdaBuilder.() -> Unit): JDA = build(JdaBuilder(), block) inline fun embed(parent: MessageEmbed? = null, block: EmbedBuilder.() -> Unit): MessageEmbed = build(EmbedBuilder(parent), block) inline fun <T> pagination(content: Collection<T>, block: PaginationBuilder<T>.() -> Unit): Pagination<T> = build(PaginationBuilder(content), block) fun command(block: Command.() -> Unit) { Command().apply(block).run { CommandManager.commands[name] = this aliases.forEach { CommandManager.commands[it] = this } hiddenAliases.forEach { CommandManager.commands[it] = this } } } fun Command.command(block: Command.() -> Unit) { Command(this).apply(block).run { this@command.commands[name] = this aliases.forEach { this@command.commands[it] = this } hiddenAliases.forEach { this@command.commands[it] = this } } } fun Command.action(minArgs: Int = 0, maxArgs: Int = 0, typing: Boolean = false, block: Command.Context.() -> Unit) { actions += Command.Action(minArgs, maxArgs, typing, block) } fun Command.access(block: Command.Context.() -> Boolean) { access = block } inline fun CommandManager.replies(block: Replies.() -> Unit) { replies = replies.apply(block) } inline fun CommandManager.colors(block: Colors.() -> Unit) { colors = colors.apply(block) } inline fun CommandManager.emotes(block: Emotes.() -> Unit) { emotes = emotes.apply(block) }
0
Kotlin
0
0
ffe644cd3a10145b6c413a121a4a112b8200adb8
2,098
KDA
MIT License
core/src/com/pimuseum/game/chinesechess/engine/actor/ChessmanActor.kt
Pimuseum
180,344,692
false
{"Gradle": 6, "Markdown": 1, "INI": 2, "Shell": 1, "Text": 1, "Ignore List": 1, "Batchfile": 1, "YAML": 1, "Kotlin": 28, "Java Properties": 2, "Proguard": 1, "XML": 10, "Java": 2, "JSON": 2}
package com.pimuseum.game.chinesechess.engine.actor import com.badlogic.gdx.graphics.g2d.TextureRegion import com.pimuseum.game.chinesechess.model.ChessHelper import com.pimuseum.game.chinesechess.model.chessman.Chessman import com.pimuseum.game.chinesechess.model.companion.ChessType /** * Desc : ChessmanActor * Author : Jiervs * Date : 2019/5/17 */ class ChessmanActor : ImageActor { var chessman : Chessman? = null constructor() : super() constructor(region: TextureRegion): super(region) constructor(region: TextureRegion,chessman : Chessman): super(region) { this.chessman = chessman } /** * 根据第一人称视角放置棋子位置 */ fun setCenterByRoleType(row : Int , column : Int , originLocationX : Float ,originLocationY :Float , chessboardUnitWidth : Float , chessboardUnitHeight : Float) { if (ChessHelper.myRoleType == ChessType.Red) { setCenter( originLocationX + (column * chessboardUnitWidth), originLocationY + (row * chessboardUnitHeight)) } else { setCenter( originLocationX + ((ChessHelper.ColumnCapacity - column) * chessboardUnitWidth), originLocationY + ((ChessHelper.RowCapacity - row) * chessboardUnitHeight)) } } }
0
Kotlin
3
17
bf6930643b78ee4320398b43f95c3f65747da658
1,368
pi-game-chinesechess-demo
Apache License 2.0