path
stringlengths
4
280
owner
stringlengths
2
39
repo_id
int64
21.1k
879M
is_fork
bool
2 classes
languages_distribution
stringlengths
13
1.95k
content
stringlengths
7
482k
issues
int64
0
13.9k
main_language
stringclasses
121 values
forks
stringlengths
1
5
stars
int64
0
111k
commit_sha
stringlengths
40
40
size
int64
7
482k
name
stringlengths
1
100
license
stringclasses
93 values
app/src/main/java/com/example/wordle/MainActivity.kt
Alisasa
535,782,627
false
{"Kotlin": 8049}
package com.example.wordle import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.view.View import android.widget.Button import android.widget.EditText import android.widget.TextView import android.widget.Toast import org.w3c.dom.Text import java.security.KeyStore class MainActivity : AppCompatActivity() { var counter = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var wordToGuess = FourLetterWordList.getRandomFourLetterWord() // get a random word // function to check if guess if correct fun checkGuess(guess: String) : String { var result = "" for (i in 0..3) { if (guess[i] == wordToGuess[i]) { result += "O" } else if (guess[i] in wordToGuess) { result += "+" } else { result += "X" } } return result } fun reset() { } var btnCheck = findViewById<Button>(R.id.btncheck) var btnRestart = findViewById<Button>(R.id.btnRestart) val txFirstGuess = findViewById<TextView>(R.id.txFirstGuess) val txFirstCheck = findViewById<TextView>(R.id.txFirstCheck) val txSecondGuess = findViewById<TextView>(R.id.txSecondGuess) val txSecondCheck = findViewById<TextView>(R.id.txSecondCheck) val txThirdGuess = findViewById<TextView>(R.id.txThirdGuess) val txThirdCheck = findViewById<TextView>(R.id.txThirdCheck) var firstStatus = findViewById<TextView>(R.id.firstStatus) var firstStatusCheck = findViewById<TextView>(R.id.firstStatusCheck) var secondStatus = findViewById<TextView>(R.id.secondStatus) var secondStatusCheck = findViewById<TextView>(R.id.secondStatusCheck) var thirdStatus = findViewById<TextView>(R.id.thirdStatus) var thirdStatusCheck = findViewById<TextView>(R.id.thirdStatusCheck) var enterWord = findViewById<EditText>(R.id.enterWord) var word = findViewById<TextView>(R.id.word) //var strValue = word.text.toString() btnCheck.setOnClickListener { //Toast.makeText(it.context,"Clicked Button!", Toast.LENGTH_SHORT).show() counter ++ if (counter == 1){ // show the four letter word entered in editText to firstStatus line firstStatus.text == enterWord.text.toString() //??unable to show? I used this method and both strValue method, both were unble to make it show // check if the word is same as wordToGuess word var result = checkGuess(enterWord.text.toString()) // reflect the result in firstStatusCheck line firstStatusCheck.text == result } if (counter == 2){ secondStatus.text == enterWord.text.toString() var result = checkGuess(enterWord.text.toString()) secondStatusCheck.text = result } if (counter == 3){ thirdStatus.text == enterWord.text.toString() var result = checkGuess(enterWord.text.toString()) thirdStatusCheck.text = result } if (counter == 4){ word.text == wordToGuess word.visibility = View.VISIBLE btnRestart.visibility = View.VISIBLE btnRestart.setOnClickListener { //Toast.makeText(it.context,"Clicked Button!", Toast.LENGTH_SHORT).show() // reset the app reset() /* var wordToGuess = FourLetterWordList.getRandomFourLetterWord() firstStatus.text = "guess 1 word" firstStatusCheck.text = "guess 1 check" secondStatus.text = "guess 2 word" secondStatusCheck.text = "guess 2 check" thirdStatus.text = "guess 3 word" thirdStatusCheck.text = "guess 3 check" btnRestart.visibility = View.INVISIBLE word.visibility = View.INVISIBLE */ } } } } }
1
Kotlin
0
0
7441c6e6cc0338a202b795c1c40f6a73ffe9005c
4,397
Wordle-Codepath
Apache License 2.0
app/src/main/java/com/aliernfrog/pftool/data/Language.kt
aliernfrog
491,592,330
false
{"Kotlin": 327043, "AIDL": 714}
package com.aliernfrog.pftool.data data class Language( val languageCode: String, val countryCode: String?, val fullCode: String, val localizedName: String )
0
Kotlin
0
8
ac7f2758f6e66d3fb53de1765f06f89bc8c67c29
174
pf-tool
MIT License
app/src/main/java/com/duckduckgo/app/firebutton/FireButtonStore.kt
hojat72elect
822,396,044
false
{"Kotlin": 11626231, "HTML": 65873, "Ruby": 16984, "C++": 10312, "JavaScript": 5520, "CMake": 1992, "C": 1076, "Shell": 784}
package com.duckduckgo.app.firebutton import androidx.core.content.edit import com.duckduckgo.data.store.api.SharedPreferencesProvider import com.duckduckgo.di.scopes.AppScope import com.squareup.anvil.annotations.ContributesBinding import javax.inject.Inject interface FireButtonStore { val fireButttonUseCount: Int fun incrementFireButtonUseCount() } @ContributesBinding(AppScope::class) class RealFireButtonStore @Inject constructor( private val sharedPreferencesProvider: SharedPreferencesProvider, ) : FireButtonStore { private val preferences by lazy { sharedPreferencesProvider.getSharedPreferences(FILENAME) } override val fireButttonUseCount: Int get() = preferences.getInt(KEY_FIREBUTTON_USE_COUNT, 0) override fun incrementFireButtonUseCount() { val currentCount = fireButttonUseCount preferences.edit { putInt(KEY_FIREBUTTON_USE_COUNT, currentCount + 1) } } companion object { const val FILENAME = "com.duckduckgo.app.firebutton" const val KEY_FIREBUTTON_USE_COUNT = "FIREBUTTON_USE_COUNT" } }
0
Kotlin
0
0
b89591136b60933d6a03fac43a38ee183116b7f8
1,122
DuckDuckGo
Apache License 2.0
sdk/src/main/java/me/digi/sdk/callbacks/DMEPushClientCallbacks.kt
osirisinferi
257,033,937
true
{"Kotlin": 110995}
package me.digi.sdk.callbacks import me.digi.sdk.DMEError import me.digi.sdk.entities.DMEPostbox typealias DMEPostboxCreationCompletion = (DMEPostbox?, error: DMEError?) -> Unit typealias DMEPostboxPushCompletion = (error: DMEError?) -> Unit
0
null
0
0
d47b423bf00e1c969ff7d9563100d3b921eccd6c
244
digime-sdk-android
Apache License 2.0
app/src/main/java/in/kaligotla/allpermissionsimpl/presentation/main/permissions/bodySensors/sensorStates/LinearAccelerationSensorState.kt
deepakkaligotla
722,851,480
false
{"Kotlin": 353541}
package `in`.kaligotla.allpermissionsimpl.presentation.main.permissions.bodySensors.sensorStates import android.os.Build import androidx.annotation.RequiresApi import androidx.compose.runtime.Composable import androidx.compose.runtime.Immutable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import `in`.kaligotla.allpermissionsimpl.presentation.main.permissions.bodySensors.common.SensorDelay import `in`.kaligotla.allpermissionsimpl.presentation.main.permissions.bodySensors.common.SensorStateListener import `in`.kaligotla.allpermissionsimpl.presentation.main.permissions.bodySensors.common.SensorType import `in`.kaligotla.allpermissionsimpl.presentation.main.permissions.bodySensors.common.rememberSensorState @Immutable class LinearAccelerationSensorState internal constructor( val xForce: Float = 0f, val yForce: Float = 0f, val zForce: Float = 0f, val isAvailable: Boolean = false, val accuracy: Int = 0, private val startListeningEvents: (() -> Unit)? = null, private val stopListeningEvents: (() -> Unit)? = null, ) : SensorStateListener { override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is LinearAccelerationSensorState) return false if (xForce != other.xForce) return false if (yForce != other.yForce) return false if (zForce != other.zForce) return false if (isAvailable != other.isAvailable) return false if (accuracy != other.accuracy) return false if (startListeningEvents != other.startListeningEvents) return false if (stopListeningEvents != other.stopListeningEvents) return false return true } override fun hashCode(): Int { var result = xForce.hashCode() result = 31 * result + yForce.hashCode() result = 31 * result + zForce.hashCode() result = 31 * result + isAvailable.hashCode() result = 31 * result + accuracy.hashCode() result = 31 * result + startListeningEvents.hashCode() result = 31 * result + stopListeningEvents.hashCode() return result } override fun toString(): String { return "LinearAccelerationSensorState(xForce=$xForce, yForce=$yForce, zForce=$zForce, " + "isAvailable=$isAvailable, accuracy=$accuracy)" } override fun startListening() { startListeningEvents?.invoke() } override fun stopListening() { stopListeningEvents?.invoke() } } @RequiresApi(Build.VERSION_CODES.TIRAMISU) @Composable fun rememberLinearAccelerationSensorState( autoStart: Boolean = true, sensorDelay: SensorDelay = SensorDelay.Normal, onError: (throwable: Throwable) -> Unit = {}, ): LinearAccelerationSensorState { val sensorState = rememberSensorState( sensorType = SensorType.LinearAcceleration, sensorDelay = sensorDelay, autoStart = autoStart, onError = onError ) val linearAccelerationSensorState = remember { mutableStateOf( LinearAccelerationSensorState( startListeningEvents = sensorState::startListening, stopListeningEvents = sensorState::stopListening ) ) } LaunchedEffect( key1 = sensorState, block = { val sensorStateValues = sensorState.data if (sensorStateValues.isNotEmpty()) { linearAccelerationSensorState.value = LinearAccelerationSensorState( xForce = sensorStateValues[0], yForce = sensorStateValues[1], zForce = sensorStateValues[2], isAvailable = sensorState.isAvailable, accuracy = sensorState.accuracy, startListeningEvents = sensorState::startListening, stopListeningEvents = sensorState::stopListening ) } } ) return linearAccelerationSensorState.value }
0
Kotlin
0
0
78aa5df02ddb7b7d81aca06dcdcc8e8edc11255a
4,062
android_permissions
The Unlicense
aws-runtime/aws-config/common/test/aws/sdk/kotlin/runtime/config/retries/ResolveRetryStrategyTest.kt
awslabs
121,333,316
false
null
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package aws.sdk.kotlin.runtime.config.retries import aws.sdk.kotlin.runtime.ConfigurationException import aws.sdk.kotlin.runtime.config.AwsSdkSetting import aws.smithy.kotlin.runtime.ClientException import aws.smithy.kotlin.runtime.retries.AdaptiveRetryStrategy import aws.smithy.kotlin.runtime.retries.StandardRetryStrategy import aws.smithy.kotlin.runtime.util.TestPlatformProvider import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.test.runTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith import kotlin.test.assertIs @OptIn(ExperimentalCoroutinesApi::class) class ResolveRetryStrategyTest { @Test fun itResolvesMaxAttemptsFromEnvironmentVariables() = runTest { val expectedMaxAttempts = 50 val platform = TestPlatformProvider( env = mapOf(AwsSdkSetting.AwsMaxAttempts.envVar to expectedMaxAttempts.toString()), ) val strategy = assertIs<StandardRetryStrategy>(resolveRetryStrategy(platform)) assertEquals(expectedMaxAttempts, strategy.config.maxAttempts) } @Test fun itResolvesMaxAttemptsFromSystemProperties() = runTest { val expectedMaxAttempts = 10 val platform = TestPlatformProvider( props = mapOf(AwsSdkSetting.AwsMaxAttempts.sysProp to expectedMaxAttempts.toString()), ) val strategy = assertIs<StandardRetryStrategy>(resolveRetryStrategy(platform)) assertEquals(expectedMaxAttempts, strategy.config.maxAttempts) } @Test fun itResolvesMaxAttemptsFromProfile() = runTest { val expectedMaxAttempts = 30 val platform = TestPlatformProvider( env = mapOf("AWS_CONFIG_FILE" to "config"), fs = mapOf( "config" to """ [default] max_attempts=$expectedMaxAttempts """.trimIndent(), ), ) val strategy = assertIs<StandardRetryStrategy>(resolveRetryStrategy(platform)) assertEquals(expectedMaxAttempts, strategy.config.maxAttempts) } @Test fun itThrowsOnInvalidMaxAttemptsValues() = runTest { val invalidMaxAttemptsValues = listOf(-91, -5, 0) for (invalidMaxAttempts in invalidMaxAttemptsValues) { val platform = TestPlatformProvider( env = mapOf(AwsSdkSetting.AwsMaxAttempts.envVar to invalidMaxAttempts.toString()), ) assertFailsWith<ConfigurationException> { resolveRetryStrategy(platform) } } } @Test fun itThrowsOnUnsupportedRetryModes() = runTest { val retryMode = "unsupported-retry-mode" val platform = TestPlatformProvider( env = mapOf(AwsSdkSetting.AwsRetryMode.envVar to retryMode), ) assertFailsWith<ClientException> { resolveRetryStrategy(platform) } } @Test fun itThrowsOnUnsupportedRetryModesFromProfile() = runTest { val expectedMaxAttempts = 30 val retryMode = "unsupported-retry-mode" val platform = TestPlatformProvider( env = mapOf("AWS_CONFIG_FILE" to "config"), fs = mapOf( "config" to """ [default] max_attempts=$expectedMaxAttempts retry_mode=$retryMode """.trimIndent(), ), ) assertFailsWith<ConfigurationException> { resolveRetryStrategy(platform) } } @Test fun itResolvesAdaptiveRetryStrategy() = runTest { val expectedMaxAttempts = StandardRetryStrategy.Config.DEFAULT_MAX_ATTEMPTS val adaptiveRetryMode = "adaptive" val platform = TestPlatformProvider( env = mapOf(AwsSdkSetting.AwsRetryMode.envVar to adaptiveRetryMode), ) val strategy = assertIs<AdaptiveRetryStrategy>(resolveRetryStrategy(platform)) assertEquals(expectedMaxAttempts, strategy.config.maxAttempts) } @Test fun itResolvesNonLowercaseRetryModeValuesFromEnvironmentVariables() = runTest { val expectedMaxAttempts = 16 val retryMode = "lEgACY" val platform = TestPlatformProvider( env = mapOf( AwsSdkSetting.AwsMaxAttempts.envVar to expectedMaxAttempts.toString(), AwsSdkSetting.AwsRetryMode.envVar to retryMode, ), ) assertEquals(expectedMaxAttempts, resolveRetryStrategy(platform).config.maxAttempts) } @Test fun itResolvesNonLowercaseRetryModeValuesFromProfile() = runTest { val expectedMaxAttempts = 19 val retryMode = "aDAPtive" val platform = TestPlatformProvider( env = mapOf( "AWS_CONFIG_FILE" to "config", ), fs = mapOf( "config" to """ [default] max_attempts=$expectedMaxAttempts retry_mode=$retryMode """.trimIndent(), ), ) val strategy = assertIs<AdaptiveRetryStrategy>(resolveRetryStrategy(platform)) assertEquals(expectedMaxAttempts, strategy.config.maxAttempts) } @Test fun itResolvesMaxAttemptsAndRetryModeFromEnvironmentVariables() = runTest { val expectedMaxAttempts = 1 val retryMode = "legacy" val platform = TestPlatformProvider( env = mapOf( AwsSdkSetting.AwsMaxAttempts.envVar to expectedMaxAttempts.toString(), AwsSdkSetting.AwsRetryMode.envVar to retryMode, ), ) val strategy = assertIs<StandardRetryStrategy>(resolveRetryStrategy(platform)) assertEquals(expectedMaxAttempts, strategy.config.maxAttempts) } @Test fun itResolvesMaxAttemptsAndRetryModeFromEnvironmentVariablesAndSystemProperty() = runTest { val expectedMaxAttempts = 90 val retryMode = "legacy" val platform = TestPlatformProvider( env = mapOf( AwsSdkSetting.AwsRetryMode.envVar to retryMode, ), props = mapOf( AwsSdkSetting.AwsMaxAttempts.sysProp to expectedMaxAttempts.toString(), ), ) val strategy = assertIs<StandardRetryStrategy>(resolveRetryStrategy(platform)) assertEquals(expectedMaxAttempts, strategy.config.maxAttempts) } @Test fun itResolvesMaxAttemptsAndRetryModeFromEnvironmentVariablesAndProfile() = runTest { val expectedMaxAttempts = 33 val retryMode = "standard" val platform = TestPlatformProvider( env = mapOf( "AWS_CONFIG_FILE" to "config", AwsSdkSetting.AwsRetryMode.envVar to retryMode, ), fs = mapOf( "config" to """ [default] max_attempts=$expectedMaxAttempts retry_mode=invalid-retry-mode-should-be-ignored """.trimIndent(), ), ) val strategy = assertIs<StandardRetryStrategy>(resolveRetryStrategy(platform)) assertEquals(expectedMaxAttempts, strategy.config.maxAttempts) } @Test fun itResolvesWithEnvironmentVariablePriority() = runTest { // set the profile and environment variable max_attempts. resolution should prioritize environment variables val expectedMaxAttempts = 40 val retryMode = "standard" val platform = TestPlatformProvider( env = mapOf( "AWS_CONFIG_FILE" to "config", AwsSdkSetting.AwsRetryMode.envVar to retryMode, AwsSdkSetting.AwsMaxAttempts.envVar to expectedMaxAttempts.toString(), ), fs = mapOf( "config" to """ [default] max_attempts=55 retry_mode=invalid-retry-mode-should-be-ignored """.trimIndent(), ), ) val strategy = assertIs<StandardRetryStrategy>(resolveRetryStrategy(platform)) assertEquals(expectedMaxAttempts, strategy.config.maxAttempts) } @Test fun itUsesDefaultMaxAttemptsWhenNoneAreProvided() = runTest { val expectedMaxAttempts = StandardRetryStrategy.Config.DEFAULT_MAX_ATTEMPTS val platform = TestPlatformProvider() // no environment variables / system properties / profile val strategy = assertIs<StandardRetryStrategy>(resolveRetryStrategy(platform)) assertEquals(expectedMaxAttempts, strategy.config.maxAttempts) } }
88
null
49
407
287408211f193624d37678d66b0f31f457017d08
8,641
aws-sdk-kotlin
Apache License 2.0
app/src/androidTest/java/com/google/samples/apps/sunflower/viewmodels/PlantDetailViewModelTest.kt
isfaaghyth
286,004,498
true
{"Kotlin": 107166, "Shell": 1529}
/* * Copyright 2018 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.samples.apps.sunflower.viewmodels import androidx.arch.core.executor.testing.InstantTaskExecutorRule import androidx.test.ext.junit.runners.AndroidJUnit4 import com.google.samples.apps.sunflower.data.AppDatabase import com.google.samples.apps.sunflower.data.repository.GardenPlantingRepository import com.google.samples.apps.sunflower.data.repository.PlantRepository import com.google.samples.apps.sunflower.utilities.getValue import com.google.samples.apps.sunflower.utilities.testPlant import dagger.hilt.android.testing.HiltAndroidRule import dagger.hilt.android.testing.HiltAndroidTest import org.junit.Assert.assertFalse import org.junit.Before import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain import org.junit.runner.RunWith import javax.inject.Inject @HiltAndroidTest @RunWith(AndroidJUnit4::class) class PlantDetailViewModelTest { private val hiltRule: HiltAndroidRule by lazy { HiltAndroidRule(this) } private val instantTaskExecutorRule = InstantTaskExecutorRule() @get:Rule val chain: RuleChain = RuleChain .outerRule(hiltRule) .around(instantTaskExecutorRule) private lateinit var appDatabase: AppDatabase private lateinit var viewModel: PlantDetailViewModel @Inject lateinit var gardenPlantingRepository: GardenPlantingRepository @Inject lateinit var plantRepository: PlantRepository @Before fun setUp() { hiltRule.inject() viewModel = PlantDetailViewModel( plantRepository, gardenPlantingRepository, testPlant.plantId ) } @Test @Throws(InterruptedException::class) fun testDefaultValues() { assertFalse(getValue(viewModel.isPlanted)) } }
0
Kotlin
0
3
43798280bfd555ed2629d19c31d5e430d4a36210
2,366
sunflower
Apache License 2.0
library/springboot/springboot/src/test/kotlin/de/lise/fluxflow/springboot/ioc/testservices/SpringIocProviderTestService.kt
lisegmbh
740,936,659
false
{"Kotlin": 732955}
package de.lise.fluxflow.springboot.ioc.testservices import org.springframework.stereotype.Service @Service class SpringIocProviderTestService
20
Kotlin
0
7
03a99c536434660fc2cde3df9e220991ff487599
144
fluxflow
Apache License 2.0
src/main/kotlin/dk/cachet/carp/webservices/common/serialisers/ApplicationRequestSerializer.kt
cph-cachet
674,650,033
false
{"Kotlin": 613954, "TypeScript": 109044, "HTML": 9317, "FreeMarker": 4300, "Shell": 4202, "CSS": 1656, "Dockerfile": 1264, "JavaScript": 706}
package dk.cachet.carp.webservices.common.serialisers import dk.cachet.carp.common.application.services.ApplicationService import dk.cachet.carp.common.infrastructure.services.ApplicationServiceRequest import dk.cachet.carp.webservices.common.input.WS_JSON import kotlinx.serialization.KSerializer /** * Serializes and deserializes requests to and from the application service. * This is used to serialize requests to the application service and deserialize responses from the application service. * * @param TRequest The type of request which can be serialized and deserialized. */ abstract class ApplicationRequestSerializer<TRequest : ApplicationServiceRequest<*, *>> { companion object { val json = WS_JSON } /** * Deserialize the request from the specified [content]. * * @param serializer The serializer to use to deserialize the request. * @param content The content to deserialize from. * @return The deserialized request object. */ fun <TRequest> deserializeRequest( serializer: KSerializer<TRequest>, content: String, ): TRequest { return json.decodeFromString(serializer, content) } /** * Serialize the specified [request] to a string. * * @param request The request body to serialize. * @param content The content to serialize. * @return The serialized request string. */ abstract fun <TService : ApplicationService<TService, *>> serializeResponse( request: ApplicationServiceRequest<TService, *>, content: Any?, ): Any? }
16
Kotlin
2
3
e28763e0058a34fb6c6efd864d6b8ca65c50a13c
1,588
carp-webservices-spring
MIT License
app/src/main/java/org/mydaily/data/remote/datasource/GoalRemoteDataSource.kt
TeamMyDaily
325,142,861
false
null
package org.mydaily.data.remote.datasource import org.mydaily.data.model.network.request.ReqGoalPost import org.mydaily.data.model.network.request.ReqGoalPut import org.mydaily.data.model.network.response.Response import org.mydaily.data.model.network.response.ResGoalGet import org.mydaily.data.model.network.response.ResGoalPost import retrofit2.Call interface GoalRemoteDataSource { fun getGoals(start: Long, end: Long): Call<ResGoalGet> fun postGoals(body: ReqGoalPost): Call<ResGoalPost> fun putGoals(id: Int, body: ReqGoalPut): Call<Response> fun putGoalsCompletion(id: Int): Call<Response> fun deleteGoal(id: Int): Call<Response> }
4
Kotlin
1
9
d820795fe1a6332de9ceb6b69ad1d137038d0910
660
4most-Android
Apache License 2.0
packages/library-base/src/commonMain/kotlin/io/realm/kotlin/types/geo/GeoPolygon.kt
realm
235,075,339
false
null
/* * Copyright 2023 Realm 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 io.realm.kotlin.types.geo import io.realm.kotlin.annotations.ExperimentalGeoSpatialApi import io.realm.kotlin.internal.geo.UnmanagedGeoPolygon /** * This class represents a polygon on the surface of the earth. It cannot be persisted - i.e you * can't declare a Realm property that is of type [GeoPolygon]. It can be only used as a query * argument for a geospatial query. * * A [GeoPolygon] describes a shape represented by 3 or more line segments. It comprises of one * outer ring and 0 or more rings representing holes with the following restrictions: * * - Each ring must consist of at least 3 line segments. The first and the last point must be the * same to indicate a closed ring (meaning you need at least 4 points to define the * polygon). * - Rings may not cross, i.e. the boundary of a ring may not intersect both the interior and * exterior of any other ring. * - Rings may not share edges, i.e. if a ring contains an edge AB, then no other ring may contain * AB or BA. * - Rings may share vertices, however no vertex may appear twice in a single ring. * - No ring may be empty. * * Holes may be nested inside each other, in which case a location will be considered "inside" the * polygon if it is included in an odd number of rings, counting the outer ring as 1. For example, * a polygon representing a square with side 10 centered at (0,0) with holes representing squares * with sides 5 and 2, centered at (0,0) will include the location (1, 1) because it is contained * in 3 rings, but not (3, 3), because it is contained in 2. * * Using it can look something like this: * * ``` * val searchArea = GeoPolygon.create( * outerRing = listOf( * GeoPoint.create(0.0, 0.0), * GeoPoint.create(0.0, 5.0), * GeoPoint.create(5.0, 5.0), * GeoPoint.create(5.0, 0.0), * GeoPoint.create(0.0, 0.0), * ), * holes = arrayOf(listOf( * GeoPoint.create(1.0, 1.0), * GeoPoint.create(1.0, 4.0), * GeoPoint.create(4.0, 4.0), * GeoPoint.create(4.0, 1.0) * )) * ) * val restaurants = realm.query<Restaurant>("location GEOWITHIN $searchArea").find() * * ``` */ @ExperimentalGeoSpatialApi public interface GeoPolygon { /** * A list of [GeoPoint]s representing the outer ring of the polygon. */ public val outerRing: List<GeoPoint> /** * A list of inner rings, each ring is inside the next. */ public val holes: List<List<GeoPoint>> /** * Returns the textual representation of the [GeoPolygon], this is also formatting it in a way * that makes it usable in queries, e.g.: * * ``` * val outerRing = listOf( * GeoPoint.create(0.0, 0.0), * GeoPoint.create(10.0, 0.0), * GeoPoint.create(10.0, 10.0), * GeoPoint.create(0.0, 10.0), * GeoPoint.create(0.0, 0.0) * ) * val searchArea = GeoPolygon.create(outerRing) * val results = realm.query<Restaurant>("location GEOWITHIN searchArea").find() */ override fun toString(): String public companion object { /** * Create a [GeoPolygon] instance. * * @param outerRing A list of [GeoPoint]s representing the outer ring of the polygon. The * outer ring must contain at least 4 unique points. The first and the last point must * be identical, but no other duplicates are allowed. Each subsequent pair of points represents * an edge in the polygon. * @param holes A list of "inner" rings. Each of these rings has the same requirements as * the [outerRing]. A point is considered "inside" the polygon if it is contained by an odd * number of rings and "outside" if it's contained by an even number of rings. * @throws IllegalArgumentException if the input polygon break some of the rules outlined * above. */ public fun create(outerRing: List<GeoPoint>, vararg holes: List<GeoPoint>): GeoPolygon = create(outerRing, holes.toList()) /** * Create a [GeoPolygon] instance. * * @param outerRing A list of [GeoPoint]s representing the outer ring of the polygon. The * outer ring must contain at least 4 unique points. The first and the last point must * be identical, but no other duplicates are allowed. Each subsequent pair of points represents * an edge in the polygon. * @param holes A list of "inner" rings. Each of these rings has the same requirements as * the [outerRing]. A point is considered "inside" the polygon if it is contained by an odd * number of rings and "outside" if it's contained by an even number of rings. * @throws IllegalArgumentException if the input polygon break some of the rules outlined * above. */ public fun create(outerRing: List<GeoPoint>, holes: List<List<GeoPoint>>): GeoPolygon { return UnmanagedGeoPolygon(outerRing, holes) } } }
199
Kotlin
50
703
c8f3e0bfd8273cc45e61abc3b51ace3ae44df3e1
5,653
realm-kotlin
Apache License 2.0
JniReference/src/main/java/com/jesen/jnireference/bean/DecFile.kt
Jesen0823
393,152,403
false
{"C": 152336, "C++": 60575, "Kotlin": 22572, "CMake": 6695, "Java": 948}
package com.jesen.jnireference.bean import android.util.Log /** * java对象类 * */ data class DecFile(var name: String = "default", var size: Int = 0){ companion object{ var path = "d:/user" @JvmStatic var times = 0 @JvmStatic fun callStaticMethod(strs: Array<String>?, num: Int): String { if (strs != null) { for (str in strs) { Log.i("DecFile", "str in array is: $str") } } return "OK" } } fun putMaxSize(size: Int){ Log.i("DecFile", "putMaxSize is: $size") } fun getCurrentPath():String{ return path } }
0
C
0
0
0df4e48883d31cd842798405d7f67421a847f2c9
686
NDK_jni_cmake
Apache License 2.0
exerlistarray.kt
animeprocoder
524,613,564
false
null
fun main(){ //Items on the desk var Items = arrayListOf("laptop", "mouse", "pen", "paper", "mug", "phone") //Removed Items for increase of productivity val removedItems = arrayListOf("pen", "paper", "mug", "phone") Items.removeAll(removedItems.toSet()) println(Items) }
0
Kotlin
0
0
45050c056e56ea30c400f06553ffa34777bd166a
293
Task1-Excersice1
Boost Software License 1.0
app/src/main/java/com/lemon/wanandroid/ui/main/MainActivity.kt
kevin-lemon
224,783,263
false
null
package com.lemon.wanandroid.ui.main import android.os.Bundle import android.view.KeyEvent import android.widget.Toast import androidx.lifecycle.LiveData import androidx.lifecycle.Observer import androidx.navigation.NavController import androidx.navigation.ui.setupActionBarWithNavController import com.lemon.wanandroid.BaseActivity import com.lemon.wanandroid.R import com.lemon.wanandroid.setupWithNavController import dagger.android.AndroidInjection import kotlinx.android.synthetic.main.activity_main.* import kotlin.system.exitProcess /** * Created by Lemon on 2019/11/29. */ class MainActivity : BaseActivity() { private var currentNavController: LiveData<NavController>? = null override fun getContentViewId(): Int { return R.layout.activity_main } override fun initView() { setupBottomNavigationBar() } override fun initData() { } override fun onResume() { super.onResume() } private fun setupBottomNavigationBar() { val navGraphIds = listOf(R.navigation.home,R.navigation.project,R.navigation.system,R.navigation.article,R.navigation.nagivation) val controller = bottom_nav.setupWithNavController( navGraphIds = navGraphIds, fragmentManager = supportFragmentManager, containerId = R.id.nav_host_container, intent = intent ) currentNavController = controller } override fun onBackPressed() { if (currentNavController?.value?.currentDestination?.label?.equals("homeFragment") == true){ moveTaskToBack(true) return } super.onBackPressed() } override fun onSupportNavigateUp(): Boolean { return currentNavController?.value?.navigateUp() ?: false } }
0
Kotlin
0
2
071aee57eda1191309f6522403e8998d580a153b
1,789
kotlin-wanAndroid
Apache License 2.0
math/src/main/java/com/kylecorry/sol/math/algebra/Matrix.kt
kylecorry31
294,668,785
false
null
package com.kylecorry.sol.math.algebra typealias Matrix = Array<Array<Float>> fun Matrix.rows(): Int { return size } fun Matrix.columns(): Int { if (rows() == 0) { return 0 } return get(0).size } operator fun Matrix.get(row: Int, column: Int): Float { return this[row][column] } operator fun Matrix.set(row: Int, column: Int, value: Float) { this[row][column] = value } fun createMatrix(rows: Int, columns: Int, init: (row: Int, col: Int) -> Float): Matrix { return Array(rows) { row -> Array(columns) { col -> init(row, col) } } }
7
Kotlin
2
3
30f81bbbe909df17504243a0500bf6cfbf3f3ad4
606
Trail-Sense-Core
MIT License
feature/auth/ui/src/main/java/com/auth/ui/screens/forgot_password/PasswordReset.kt
7pak
764,350,162
false
{"Kotlin": 496880}
package com.auth.ui.screens.forgot_password import android.widget.Toast import androidx.activity.compose.LocalOnBackPressedDispatcherOwner import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Visibility import androidx.compose.material.icons.filled.VisibilityOff import androidx.compose.material3.CircularProgressIndicator import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.res.painterResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.input.VisualTransformation import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import com.auth.ui.common_components.AuthScreenNavigator import com.auth.ui.common_components.BackHandler import com.auth.ui.common_components.ConfirmButton import com.auth.ui.common_components.OutlinedTextFieldWithLabelAndValidation import com.auth.ui.common_components.isPasswordValid import com.core.common.R import com.core.common.ui.theme.Beige import com.ramcosta.composedestinations.annotation.Destination @Destination @Composable fun PasswordResetScreen( verificationModel: VerificationModel = hiltViewModel(), navigator: AuthScreenNavigator ) { val context = LocalContext.current var passwordVisibility by rememberSaveable { mutableStateOf(false) } val passwordHasReset by verificationModel.passwordHasReset.collectAsState(false) val state = verificationModel.state val dispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher if (dispatcher != null) { BackHandler(onBackPressed = { verificationModel.cancel() navigator.navigateToLoginScreen() }, dispatcher = dispatcher) } LaunchedEffect(passwordHasReset){ if (passwordHasReset){ Toast.makeText(context, "Password has reset successfully", Toast.LENGTH_SHORT).show() verificationModel.cancel() navigator.navigateToLoginScreen() } } DisposableEffect(key1 = state.error){ if (!state.error.isNullOrEmpty()) { Toast.makeText(context, state.error, Toast.LENGTH_SHORT).show() } onDispose { verificationModel.updateState(state.copy(error = null)) } } Box(modifier = Modifier.fillMaxSize()) { Image( painter = painterResource(id = R.drawable.background_post), contentDescription = null, contentScale = ContentScale.Crop, modifier = Modifier .fillMaxSize() .align(Alignment.Center) .background(MaterialTheme.colorScheme.background) ) Column( Modifier.fillMaxSize(), horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(20.dp) ) { Text( text = "Reset your password", style = MaterialTheme.typography.titleLarge.copy( color = Beige ), modifier = Modifier.padding(top = 40.dp) ) Text( text = "Password should be at least 8 chars with at least a digit and character and special char", style = MaterialTheme.typography.bodyMedium, modifier = Modifier.padding(vertical = 15.dp, horizontal = 7.dp) ) Text( text = "type your new password", style = MaterialTheme.typography.titleSmall.copy( color = Beige.copy(alpha = 0.5f) ), modifier = Modifier.padding(vertical = 10.dp) ) OutlinedTextFieldWithLabelAndValidation( modifier = Modifier .fillMaxWidth(0.8f) .padding(vertical = 10.dp), value =state.newPassword, onValueChange = { verificationModel.updateState(state.copy(newPassword = it)) }, placeHolder = { Text(text = "Password") }, visualTransformation = if (passwordVisibility) VisualTransformation.None else PasswordVisualTransformation(), trailingIcon = { IconButton(onClick = { passwordVisibility = !passwordVisibility }) { Icon( imageVector = if (passwordVisibility) Icons.Default.Visibility else Icons.Default.VisibilityOff, contentDescription = "password visibility", tint = if (passwordVisibility) MaterialTheme.colorScheme.tertiary else Color.Gray ) } }, isError = !isPasswordValid(state.newPassword), keyboardOptions = KeyboardOptions( keyboardType = KeyboardType.Password, imeAction = ImeAction.Done ) ) ConfirmButton(text = "Confirm", onClick = { verificationModel.resetPassword() }, isEnabled = isPasswordValid(state.newPassword), testTag = "") } if (state.isLoading){ CircularProgressIndicator(modifier = Modifier.align(Alignment.Center),color = MaterialTheme.colorScheme.tertiary) } } }
0
Kotlin
0
1
2fe106a4241dfd24ef63948ebb3095ce40c6f9d7
6,741
LonePaw-PetAdoption
MIT License
src/main/kotlin/algorithms/leetcode/easy/SquaresOfASortedArray.kt
DenisLatushko
615,981,611
false
{"Kotlin": 129747}
package algorithms.leetcode.easy /** * Description: https://leetcode.com/problems/squares-of-a-sorted-array/description/ */ fun sortedSquares(nums: IntArray): IntArray { if (nums.size == 1) return nums.apply { this[0] = pow(this[0]) } var left = 0 var right = nums.lastIndex var ind = nums.lastIndex val result = IntArray(nums.size) while (left <= right) { val numLeftPow = pow(nums[left]) val numRightPow = pow(nums[right]) if (numLeftPow >= numRightPow) { result[ind] = numLeftPow left++ } else { result[ind] = numRightPow right-- } ind-- } return result } private fun pow(value: Int): Int = if (Int.MAX_VALUE / 2 >= value) { value * value } else { Int.MAX_VALUE }
0
Kotlin
0
0
3b57094ed800e5dbaf4a2def403902ebd5010c3b
830
leetcode
Apache License 2.0
rounded/src/commonMain/kotlin/me/localx/icons/rounded/outline/Speaker.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.rounded.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.rounded.Icons public val Icons.Outline.Speaker: ImageVector get() { if (_speaker != null) { return _speaker!! } _speaker = Builder(name = "Speaker", 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) { moveTo(16.0f, 0.0f) lineTo(8.0f, 0.0f) arcTo(5.006f, 5.006f, 0.0f, false, false, 3.0f, 5.0f) lineTo(3.0f, 19.0f) arcToRelative(5.006f, 5.006f, 0.0f, false, false, 5.0f, 5.0f) horizontalLineToRelative(8.0f) arcToRelative(5.006f, 5.006f, 0.0f, false, false, 5.0f, -5.0f) lineTo(21.0f, 5.0f) arcTo(5.006f, 5.006f, 0.0f, false, false, 16.0f, 0.0f) close() moveTo(19.0f, 19.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, -3.0f, 3.0f) lineTo(8.0f, 22.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, -3.0f, -3.0f) lineTo(5.0f, 5.0f) arcTo(3.0f, 3.0f, 0.0f, false, true, 8.0f, 2.0f) horizontalLineToRelative(8.0f) arcToRelative(3.0f, 3.0f, 0.0f, false, true, 3.0f, 3.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 6.0f) moveToRelative(-1.5f, 0.0f) arcToRelative(1.5f, 1.5f, 0.0f, true, true, 3.0f, 0.0f) arcToRelative(1.5f, 1.5f, 0.0f, true, true, -3.0f, 0.0f) } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 10.0f) arcToRelative(5.0f, 5.0f, 0.0f, true, false, 5.0f, 5.0f) arcTo(5.006f, 5.006f, 0.0f, false, false, 12.0f, 10.0f) close() moveTo(12.0f, 18.0f) arcToRelative(3.0f, 3.0f, 0.0f, true, true, 3.0f, -3.0f) arcTo(3.0f, 3.0f, 0.0f, false, true, 12.0f, 18.0f) close() } path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f, strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero) { moveTo(12.0f, 15.0f) moveToRelative(-1.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, true, 2.0f, 0.0f) arcToRelative(1.0f, 1.0f, 0.0f, true, true, -2.0f, 0.0f) } } .build() return _speaker!! } private var _speaker: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
3,913
icons
MIT License
src/main/kotlin/upaio/apis/adapters/JugadorResource.kt
upa-io
818,733,793
false
{"Kotlin": 9987}
import jakarta.inject.Inject import jakarta.ws.rs.Consumes import jakarta.ws.rs.GET import jakarta.ws.rs.Path import jakarta.ws.rs.Produces import jakarta.ws.rs.core.MediaType import jakarta.ws.rs.core.Response import upaio.apis.usescases.JugadorServices @Path("/upaio/apis/v1") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) class JugadorResource { @Inject lateinit var jugadorService: JugadorServices @GET @Path("/jugadores") fun listAll(): Response = Response.ok(jugadorService.doSomethingWithJugador()).build() }
0
Kotlin
0
0
7ac47a337933f0c22d77899c161d05b607336b92
569
quarkus-gradle-chassis-kotlin
Apache License 2.0
experiments/src/main/kotlin/com/kjipo/experiments/FitLineUsingFilledPixels.kt
torebre
64,392,301
false
null
package com.kjipo.experiments import com.kjipo.raster.match.MatchDistance import com.kjipo.segmentation.Matrix import com.kjipo.segmentation.fitSingleLine3 import com.kjipo.segmentation.shrinkImage import com.kjipo.skeleton.transformArraysToMatrix import com.kjipo.skeleton.transformToBooleanArrays import javafx.scene.paint.Color import java.io.File import javax.imageio.ImageIO private object FitLineUsingFilledPixels { private fun fitLine() { val readImage = ImageIO.read(File("test2.png")) val image = Matrix(readImage.height, readImage.width, { row, column -> false }) for (row in 0 until readImage.height) { for (column in 0 until readImage.width) { if (readImage.getRGB(column, row) != -1) { image[row, column] = true } } } val shrinkImage = shrinkImage(image, 64, 64) var startPair = Pair(0, 0) shrinkImage.forEachIndexed { row, column, value -> if (value) { startPair = Pair(row, column) return@forEachIndexed } } val fittedLine = fitSingleLine3(shrinkImage, startPair) println("Fitted line: $fittedLine") val distanceMatrix = transformArraysToMatrix(MatchDistance.computeDistanceMap(transformToBooleanArrays(shrinkImage))) var maxValue = Int.MIN_VALUE distanceMatrix.forEach { if (it > maxValue) { maxValue = it } } val dispImage = Matrix(shrinkImage.numberOfRows, shrinkImage.numberOfColumns, { row, column -> val distance = distanceMatrix[row, column] Color.hsb(distance.toDouble().div(maxValue).times(360), 0.5, 0.2) }) showRaster(transformToBooleanArrays(shrinkImage), listOf(listOf(fittedLine.first))) } @JvmStatic fun main(args: Array<String>) { fitLine() } }
0
Kotlin
0
0
cc49f6e7ccf5814c47f3c53ce7443eb99e4772b2
1,955
Encodings
MIT License
app/src/main/kotlin/com/boscatov/schedulercw/interactor/scheduler/SchedulerInteractor.kt
23alot
160,862,563
false
null
package com.boscatov.schedulercw.interactor.scheduler import io.reactivex.Completable interface SchedulerInteractor { /** * Получаем задачу, меняем статус на Active, меняем время начала на текущее, обновляем задачу в бд * */ fun startTaskCompletable(taskId:Long) : Completable /** * Получаем задачу, меняем статус на {@link TaskStatus.DONE} */ fun completeTaskCompletable(taskId: Long) : Completable /** * Получаем задачу, меняем статус на {@link TaskStatus.WAIT_FOR_ACTION} */ fun notifyTaskShouldBeEndedCompletable(taskId: Long) : Completable /** * Получаем задачу, меняем статус на {@link TaskStatus.ABANDONED} */ fun abandonTaskCompletable(taskId: Long) : Completable }
0
Kotlin
0
0
28ef14d8134a8555b1f2dee62bce9bef5ad6f607
755
scheduler-cw
Apache License 2.0
feature/hidden-notes-dialog/ui/core/src/main/kotlin/ru/maksonic/beresta/feature/hidden_notes_dialog/ui/core/core/Model.kt
maksonic
580,058,579
false
{"Kotlin": 1587340, "Assembly": 374}
package ru.maksonic.beresta.feature.hidden_notes_dialog.ui.core.core import androidx.compose.runtime.Immutable import androidx.compose.runtime.Stable import ru.maksonic.beresta.feature.hidden_notes_dialog.domain.PinFailInfo import ru.maksonic.beresta.feature.hidden_notes_dialog.domain.PinPrivacy import ru.maksonic.beresta.feature.hidden_notes_dialog.ui.api.ui.DialogContent import ru.maksonic.beresta.feature.hidden_notes_dialog.ui.api.ui.PinFailStatus import ru.maksonic.beresta.feature.hidden_notes_dialog.ui.core.core.biometric.BiometricState import ru.maksonic.beresta.platform.elm.core.ElmBaseModel import ru.maksonic.beresta.platform.elm.core.ElmCommand import ru.maksonic.beresta.platform.elm.core.ElmEffect import ru.maksonic.beresta.platform.elm.core.ElmMessage import ru.maksonic.beresta.platform.elm.core.ElmModel /** * @Author maksonic on 15.07.2023 */ @Stable @Immutable data class Model( val base: ElmBaseModel, val input: String, val isCachedFirstInput: Boolean, val dialogContent: DialogContent, val pinPrivacy: PinPrivacy, val pinFailInfo: PinFailInfo, val isFetchedPinInfo: Boolean, val isVisibleBiometricKeyboardButton: Boolean, val isVisibleBiometricDialog: Boolean, val isValidPin: Boolean ) : ElmModel { companion object { val Initial = Model( base = ElmBaseModel.Initial, input = "", isCachedFirstInput = false, dialogContent = DialogContent.INITIAL, pinPrivacy = PinPrivacy.INITIAL, pinFailInfo = PinFailInfo.INITIAL, isFetchedPinInfo = false, isVisibleBiometricKeyboardButton = false, isVisibleBiometricDialog = false, isValidPin = false ) } } sealed class Msg : ElmMessage { sealed class Ui : Msg() { data object ClosedDialog : Ui() data object OnBackspaceClicked : Ui() data class UpdateDialogContent(val content: DialogContent) : Ui() data object OnResetPinClicked : Ui() data object OnPinVisibilityClicked : Ui() data object OnKeyTapVisibilityClicked : Ui() data object OnKeyboardShowedBiometricDialog : Inner() } sealed class Inner : Msg() { data object FetchedPinStatusRequest : Inner() data class FetchedPinStatus( val info: PinFailInfo, val privacy: PinPrivacy, val isVisibleBiometricKeyboardButton: Boolean ) : Inner() data class UpdatedInput(val value: Int) : Inner() data class UpdatedScreenCapturePermission(val isEnabled: Boolean) : Inner() data object UpdatedCachePin : Inner() data object SuccessPinResult : Inner() data class FailurePinResult(val fail: PinFailStatus) : Inner() data object BiometricAuthSucceeded : Inner() data object BiometricAuthError : Inner() data class ShowedBiometricDialog(val state: BiometricState) : Inner() data object OnEnableBiometricAuthClicked : Inner() data object FinishedCoolDown : Inner() } } sealed class Cmd : ElmCommand { data object FetchPinStatus : Cmd() data class UpdateScreenCapturePermission(val isEnabled: Boolean) : Cmd() data class CreatePin(val code: String, val isCachedFirstInput: Boolean) : Cmd() data class VerifyPin(val code: String) : Cmd() data object ResetPin : Cmd() data object ResetCachePin : Cmd() data object ResetPinFailCounter : Cmd() data class UpdatePinVisibility(val isVisible: Boolean) : Cmd() data class UpdateKeyTapVisibility(val isVisible: Boolean) : Cmd() data class ShowPinCoolDownBlock(val failCount: Int, val endDate: Long) : Cmd() data object HidePinCoolDownBlock : Cmd() data class UpdateBiometricAuthState(val isEnabled: Boolean) : Cmd() data object ShowBiometricDialogByPinStatus : Cmd() } sealed class Eff : ElmEffect { data object NavigateToHiddenNotes : Eff() data class ShowWrongPinCodeMessage(val fail: PinFailStatus?) : Eff() data object CloseDialog : Eff() data object ShowEnableBiometricDialog : Eff() data class ShowBiometricDialog(val key: BiometricState) : Eff() }
0
Kotlin
0
0
863585ab17882e444060e5535401c728f9fc335d
4,173
Beresta
MIT License
src/test/kotlin/contorller/PaymentController.kt
shiniseong
817,683,707
false
{"Kotlin": 53064, "TypeScript": 8544}
package contorller import exceptions.PaymentException import io.github.shiniseong.bridgeApi.annotation.method.Get import io.github.shiniseong.bridgeApi.annotation.method.Post class PaymentController { @Get("") fun getAllPayments() { throw Throwable("test throwable") } @Post("") fun createPayment() { throw PaymentException("카드", "사용이 불가능한 카드입니다.") } }
0
Kotlin
0
0
b56ebd03d89f259063c29380aa909d2af723152f
395
bridge-api
MIT License
skellig-test-step-processing-rmq/src/test/kotlin/org/skellig/teststep/processor/rmq/model/RmqConsumableTestStepTest.kt
skellig-framework
263,021,995
false
{"Kotlin": 1283314, "CSS": 525991, "Java": 270216, "FreeMarker": 66859, "HTML": 11313, "ANTLR": 6165}
package org.skellig.teststep.processor.rmq.model import org.junit.jupiter.api.Assertions.* import org.junit.jupiter.api.Test class RmqConsumableTestStepTest { @Test fun testToString() { assertEquals( "name = <NAME>\n" + "execution = ASYNC\n" + "routingKey = key1\n" + "consumeFrom = [q1]\n" + "respondTo = [q3]\n", RmqConsumableTestStep.Builder() .consumeFrom(listOf("q1")) .respondTo(listOf("q3")) .routingKey("key1") .withName("<NAME>") .build() .toString() ) } }
8
Kotlin
0
3
ed375268b0e444f1928f22f4ac27603e9d1fb66b
697
skellig-core
Apache License 2.0
app/src/main/java/com/mnnit/moticlubs/ui/components/MarkdownRender.kt
CC-MNNIT
576,708,897
false
{"Kotlin": 557366, "Shell": 212}
package com.mnnit.moticlubs.ui.components import android.util.Patterns import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.contentColorFor import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.unit.dp import com.mnnit.moticlubs.domain.util.PublishedMap import com.mnnit.moticlubs.domain.util.publishedStateMapOf import com.mnnit.moticlubs.ui.theme.colorScheme @Composable fun MarkdownRender( mkd: String, modifier: Modifier = Modifier, imageReplacerMap: PublishedMap<String, String> = publishedStateMapOf(), selectable: Boolean = false, disableLinkMovementMethod: Boolean = false, onImageClick: (url: String) -> Unit = {}, ) { var preprocessText = mkd if (imageReplacerMap.value.isEmpty()) { mkd.lines().forEach { if (it.startsWith("<img src")) { val key = "[image_${imageReplacerMap.value.size}]" imageReplacerMap.value[key] = it preprocessText = preprocessText.replace(it, key) } } } var text = preprocessText imageReplacerMap.value.forEach { (key, value) -> text = text.replace(key.replace("\n", ""), value) } val list = mutableListOf<PreviewMarkdown>() val sb = StringBuilder() text.lines().forEach { if (it.startsWith("<img src")) { if (sb.isNotEmpty()) list.add(PreviewMarkdown.Text(sb.toString())) sb.clear() val matcher = Patterns.WEB_URL.matcher(it) if (matcher.find()) { list.add(PreviewMarkdown.Image(it.substring(matcher.start(), matcher.end()))) } else { sb.append(it).append("\n") } } else { sb.append(it).append("\n") } } if (sb.isNotEmpty()) list.add(PreviewMarkdown.Text(sb.toString())) LazyColumn( modifier = modifier.fillMaxWidth(), contentPadding = PaddingValues(bottom = 88.dp, top = 16.dp, start = 16.dp, end = 16.dp), ) { items(count = list.size) { idx -> if (list[idx] is PreviewMarkdown.Text) { Column(modifier = Modifier.fillMaxWidth()) { MarkdownText( markdown = list[idx].str, color = contentColorFor(backgroundColor = colorScheme.background), selectable = selectable, disableLinkMovementMethod = disableLinkMovementMethod, modifier = Modifier.fillMaxWidth(), ) } } else { Column( modifier = Modifier .fillMaxWidth() .padding(vertical = 12.dp), ) { Image( painter = LocalContext.current.getImageUrlPainter(url = list[idx].str), contentDescription = "", modifier = Modifier .align(Alignment.CenterHorizontally) .clip(RoundedCornerShape(16.dp)) .fillMaxWidth() .heightIn(0.dp, 248.dp) .clickable(true, onClick = { onImageClick(list[idx].str) }), contentScale = ContentScale.Crop, ) } } } } }
0
Kotlin
1
1
acee31b30745c6bd261fd7dd587eaea6512645e6
4,054
MotiClubs
MIT License
easypay-widgets/src/androidTest/java/com/easypaysolutions/utils/pages/AddNewCardPage.kt
Easy-Pay-Solutions
784,747,593
false
{"Kotlin": 390710, "Java": 318}
package com.easypaysolutions.utils.pages import androidx.test.espresso.Espresso.onView import androidx.test.espresso.action.ViewActions.click import androidx.test.espresso.action.ViewActions.typeText import androidx.test.espresso.matcher.RootMatchers.isDialog import androidx.test.espresso.matcher.ViewMatchers.isDescendantOfA import androidx.test.espresso.matcher.ViewMatchers.isDisplayed import androidx.test.espresso.matcher.ViewMatchers.withId import com.easypaysolutions.utils.waitUntil import com.easypaysolutions.utils.waitUntilGone import com.easypaysolutions.widgets.R import org.hamcrest.Matchers.allOf internal class AddNewCardPage { fun fillCardData(cardNumber: String = "4242 4242 4242 4242") { onView(withId(R.id.section_card_information)) .inRoot(isDialog()) .perform(waitUntil(isDisplayed())) fillField(R.id.et_card_holder_name, "Android Test ${System.currentTimeMillis()}") fillField(R.id.et_card_number, cardNumber) fillField(R.id.et_expiry_date, getRandomExpiryDate()) fillField(R.id.et_cvc, (100..999).random().toString()) fillField(R.id.et_street_address, "Test Address") fillField(R.id.et_zip, (10000..99999).random().toString()) clickOnView(R.id.et_card_holder_name) } fun clickOnPrimaryActionButton() { onView(withId(R.id.btn_complete)) .inRoot(isDialog()) .perform(click()) } fun waitForErrorText() { onView(withId(R.id.tv_main_error)) .inRoot(isDialog()) .perform(waitUntil(isDisplayed())) } fun waitUntilIsGone() { onView(withId(R.id.progress_view)) .inRoot(isDialog()) .perform(waitUntilGone(3000)) } //region Helpers private fun fillField(fieldId: Int, text: String) { onView(allOf(isDescendantOfA(withId(fieldId)), withId(R.id.edit_text))) .inRoot(isDialog()) .perform(typeText(text)) } private fun clickOnView(fieldId: Int) { onView(allOf(isDescendantOfA(withId(fieldId)), withId(R.id.edit_text))) .inRoot(isDialog()) .perform(click()) } private fun getRandomExpiryDate(): String { return "${(10..12).random()}/${(30..40).random()}" } //endregion }
0
Kotlin
0
0
56cae5dc36afc85a654a5ad0ae3c30d4a827386b
2,313
Mobile-SDK-Android
Apache License 2.0
tangem-demo/src/main/java/com/tangem/tangemtest/ucase/variants/personalize/dto/DefaultPersonalizationParams.kt
byennen
259,809,719
true
{"Kotlin": 449827}
package com.tangem.tangemtest.ucase.variants.personalize.dto import com.tangem.KeyPair import com.tangem.commands.personalization.entities.Acquirer import com.tangem.commands.personalization.entities.Issuer import com.tangem.commands.personalization.entities.Manufacturer /** * Created by <NAME> on 27/03/2020. */ interface DefaultPersonalizationParams { companion object { fun issuer(): Issuer { val name = "TANGEM SDK" return Issuer( name = name, id = name + "\u0000", dataKeyPair = KeyPair( "".toByteArray(), "11121314151617184771ED81F2BACF57479E4735EB1405083927372D40DA9E92".toByteArray() ), transactionKeyPair = KeyPair( "".toByteArray(), "11121314151617184771ED81F2BACF57479E4735EB1405081918171615141312".toByteArray() ) ) } fun acquirer(): Acquirer { val name = "Smart Cash" return Acquirer( name = name, id = name + "\u0000", keyPair = KeyPair( "".toByteArray(), "21222324252627284771ED81F2BACF57479E4735EB1405083927372D40DA9E92".toByteArray() ) ) } fun manufacturer(): Manufacturer { val keys = Manufacturer(com.tangem.tangemtest.ucase.variants.personalize.dto.Manufacturer.Mode.Developer) return Manufacturer( name = "Tangem", keyPair = KeyPair(keys.publicKey, keys.privateKey) ) } } }
0
null
0
1
92e1f653522aefde668fdc100230d62492487182
1,775
tangem-sdk-android
MIT License
src/main/kotlin/ffmpegcommand/argument/TimePositionArgument.kt
Vnicius
374,466,262
false
null
package ffmpegcommand.argument open class TimePositionArgument(override val key: String): Argument() { override val value: String get() = position private var position: String = "" fun setPosition(seconds: Int) { position = seconds.toString() } fun setPosition(seconds: Float) { position = seconds.toString() } fun setPosition(milliseconds: Long) { position = "${milliseconds}ms" } fun setPosition(position: String) { this.position = position } }
0
Kotlin
0
0
3a22f2c088f7340cbc58d50cca57db17baab201a
531
ffmpeg-dsl
MIT License
gerbera-html/src/test/kotlin/MarkdownGenTester.kt
kotpot
672,754,643
false
{"Kotlin": 21843, "HTML": 82}
import org.kotpot.gerbera.html.markdown.MarkdownConstitute import org.junit.jupiter.api.Test import java.io.File class MarkdownGenTester { private val curRoot: String = System.getProperty("user.dir") private val resourcesDir = "/src/test/resources" @Test fun genCommonMd() { val root = File(curRoot, resourcesDir) val md = File(root, "post.md") val post = MarkdownConstitute.parse(md) check(post.frontMatter.isNotEmpty()) check(post.postContent.isNotEmpty()) } }
0
Kotlin
0
4
7433916113f91e279a3093de6610492eadb0a6b9
526
gerbera
MIT License
src/main/kotlin/de/sotterbeck/traindestroy/common/LocalizationSource.kt
sotterbeck
785,913,194
false
{"Kotlin": 52385}
package de.sotterbeck.traindestroy.common import java.util.* interface LocalizationSource { fun getString(key: String, locale: Locale): String }
0
Kotlin
0
0
b32803c08c2da5a97af706ebe95b7d6c08bb4f9b
153
train-destroy
Apache License 2.0
app/src/main/java/gr/blackswamp/ratingsdiary/ui/adapters/EntryListAdapter.kt
JMavrelos
226,307,606
false
null
package gr.blackswamp.ratingsdiary.ui.adapters import android.annotation.SuppressLint import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import gr.blackswamp.core.util.asString import gr.blackswamp.core.util.toDateString import gr.blackswamp.ratingsdiary.R import gr.blackswamp.ratingsdiary.ui.model.EntryVO import java.util.* class EntryListAdapter() : RecyclerView.Adapter<EntryListAdapter.EntryItemViewHolder>() { companion object { private val LABEL_UUID = UUID(0L, 0L) const val LABEL = 0 const val ENTRY = 1 } private var listener: ((UUID) -> Unit)? = null private val entries = mutableListOf<EntryVO>() override fun getItemViewType(position: Int): Int = if (entries[position].id == LABEL_UUID) LABEL else ENTRY fun setItems(items: List<EntryVO>) { entries.clear() entries.addAll(items) } fun setSelectionListener(listener: (UUID) -> Unit) { this.listener = listener } private fun itemClicked(position: Int) { val id = entries[position].id if (id != LABEL_UUID) listener?.invoke(id) } override fun getItemCount(): Int = entries.size override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EntryItemViewHolder { return if (viewType == LABEL) { LabelViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.list_item_label, parent, false)) } else { EntryViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.list_item_entry, parent, false)) } } override fun onBindViewHolder(holder: EntryItemViewHolder, position: Int) { holder.update(entries[position]) } abstract class EntryItemViewHolder(view: View) : RecyclerView.ViewHolder(view) { abstract fun update(entry: EntryVO) } class LabelViewHolder(view: View) : EntryItemViewHolder(view) { private val label = view as TextView override fun update(entry: EntryVO) { label.text = entry.date.toDateString() } } inner class EntryViewHolder(view: View) : EntryItemViewHolder(view) { private val date: TextView = view.findViewById(R.id.date) private val rating: TextView = view.findViewById(R.id.rating) private val name: TextView = view.findViewById(R.id.name) init { view.setOnClickListener { itemClicked(adapterPosition) } } @SuppressLint("SetTextI18n") override fun update(entry: EntryVO) { date.text = entry.date.toDateString() + "\n" + entry.date.asString("HH:mm") rating.text = "${entry.rating}/10" name.text = entry.description } } }
0
Kotlin
0
0
9bf2635582fbb6c5ce82860241cf5f206f995729
2,836
RatingsDiary
Apache License 2.0
app/src/main/java/me/jonas/lmdx/LmdxBackend.kt
jonasek369
872,514,119
false
{"Kotlin": 83515}
package me.jonas.lmdx import android.app.Notification import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.app.Service import android.content.BroadcastReceiver import android.content.Context import android.content.Intent import android.content.IntentFilter import android.graphics.Bitmap import android.graphics.BitmapFactory import android.os.Build import android.os.IBinder import android.text.BoringLayout import android.widget.ProgressBar import android.widget.TextView import androidx.core.app.NotificationCompat import androidx.localbroadcastmanager.content.LocalBroadcastManager import androidx.room.Room import io.ktor.client.HttpClient import io.ktor.client.call.body import io.ktor.client.engine.cio.CIO import io.ktor.client.plugins.contentnegotiation.ContentNegotiation import io.ktor.client.request.get import io.ktor.client.statement.HttpResponse import io.ktor.client.statement.readBytes import io.ktor.http.ContentType import io.ktor.http.contentType import io.ktor.serialization.kotlinx.json.json import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Job import kotlinx.coroutines.async import kotlinx.coroutines.cancel import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.withContext import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.decodeFromJsonElement import kotlinx.serialization.json.encodeToJsonElement import kotlinx.serialization.json.int import kotlinx.serialization.json.jsonArray import kotlinx.serialization.json.jsonObject import kotlinx.serialization.json.jsonPrimitive import me.jonas.lmdx.data.ChapterInfo import me.jonas.lmdx.data.Info import me.jonas.lmdx.data.Manga import me.jonas.lmdx.data.Record import me.jonas.lmdx.data.UserInfo import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.util.concurrent.Executors import kotlin.collections.HashMap import kotlin.collections.List import kotlin.collections.Map import kotlin.collections.MutableList import kotlin.collections.MutableMap import kotlin.collections.copyOf import kotlin.collections.emptyList import kotlin.collections.hashMapOf import kotlin.collections.isNullOrEmpty import kotlin.collections.iterator import kotlin.collections.joinToString import kotlin.collections.listOf import kotlin.collections.mutableListOf import kotlin.collections.plusAssign import kotlin.collections.set import kotlin.collections.sortBy import kotlin.collections.toList import kotlin.collections.toMutableMap import kotlin.collections.withIndex @Serializable data class MangaTags( val id: String, val type: String, val attributes: JsonObject, val relationships: JsonArray ) @Serializable data class MangaAttributes( val title: JsonObject, val altTitles: JsonArray, val description: JsonObject, val isLocked: Boolean, val links: JsonObject, val originalLanguage: String, val lastVolume: String?, val lastChapter: String?, val publicationDemographic: String?, val status: String, val year: Int?, val contentRating: String, val tags: List<MangaTags>, val state: String, val chapterNumbersResetOnNewVolume: Boolean, val createdAt: String, val updatedAt: String, val version: Int?, val availableTranslatedLanguages: JsonArray, val latestUploadedChapter: String? ) @Serializable data class MangaJson( val id: String, val type: String, val attributes: MangaAttributes, val relationships: JsonArray ) data class InfoObject( val identifier: String, val name: String, val description: String?, val cover: ByteArray?, val smallCover: ByteArray?, val mangaFormat: String?, val mangaGenre: String?, val contentRating: String? ) fun toInfoFromObject(info: InfoObject): Info { return Info( identifier = info.identifier, name = info.name, description = info.description, cover = info.cover, smallCover = info.smallCover, contentRating = info.contentRating, mangaFormat = info.mangaFormat, mangaGenre = info.mangaGenre, ) } fun jsonElementToString(element: JsonElement?): String { if (element == null) { return "null" } return element.toString().trim('"') } fun tryToGet(json: JsonElement, path: List<String>): JsonElement? { println(json) try { var currentJson: JsonObject? = null for (element in path.withIndex()) { if (currentJson == null) { if (element.index == path.size) { return json.jsonObject[element.value] } currentJson = json.jsonObject[element.value]?.jsonObject } else { if (element.index == path.size) { return json.jsonObject[element.value] } currentJson = currentJson[element.value]?.jsonObject } } return null } catch (e: Exception) { println("try get ${e.message}") return null } } class MangaDexConnection(mangaDb: MangaDatabase? = null) { private val httpClient = HttpClient(CIO) { install(ContentNegotiation) { json(Json { prettyPrint = true isLenient = true }) } } private val API_URL = "https://api.mangadex.org"; private val database = mangaDb private fun getDefaultRequestParameters(): JsonElement { // default parameters for every mangadex api request // """{"contentRating[]": ["safe", "suggestive", "erotic"]}""" return Json.parseToJsonElement("""{}""") } private fun getRequest( url: String, defaultParams: MutableMap<String, JsonElement> ): HttpResponse { // makeshift url builder that is made to support mangadex arrays return runBlocking { return@runBlocking httpClient.get(url) { contentType(ContentType.Application.Json) url { for (a in defaultParams) { try { val objects = a.value.jsonArray val stringList: MutableList<String> = mutableListOf() for (obj in objects) { stringList += obj.toString().trim('"') } parameters.appendAll(a.key, stringList) } catch (e: IllegalArgumentException) { parameters.append(a.key, a.value.toString().trim('"')) } } } } } } fun searchManga( mangaName: String, limit: Int = 1, includeTagIds: List<String>? = null, excludeTagIds: List<String>? = null ): List<MangaJson>? { return runBlocking { val defaultParams = getDefaultRequestParameters().jsonObject.toMutableMap(); defaultParams["title"] = JsonPrimitive(mangaName); defaultParams["limit"] = JsonPrimitive(limit); if (includeTagIds != null) { defaultParams["includedTags[]"] = Json.encodeToJsonElement(includeTagIds) } if (excludeTagIds != null) { defaultParams["excludedTags[]"] = Json.encodeToJsonElement(excludeTagIds) } val response: HttpResponse; try { response = getRequest("$API_URL/manga", defaultParams) } catch (e: Exception) { e.printStackTrace() return@runBlocking null } println(response) val responseJson = Json.parseToJsonElement(response.body()).jsonObject["data"] ?: return@runBlocking null val mangas = Json.decodeFromJsonElement<List<MangaJson>>(responseJson); return@runBlocking mangas } } fun downloadMangaPages( chapterIdentifier: String, pagesInDatabase: List<Int> = listOf(), silent: Boolean = true, rateLimitCallback: ((Float) -> Boolean)? = null ): List<Pair<Int, ByteArray>>? { return runBlocking { val metadata = httpClient.get("$API_URL/at-home/server/$chapterIdentifier") val remainingRequests = metadata.headers["X-RateLimit-Remaining"]?.toInt() ?: 1 // This should always be supplied by the api val retryAfter = metadata.headers["X-RateLimit-Retry-After"]?.toFloat() ?: 0 // <--| if (remainingRequests <= 0) { println("Rate limit reached retry after $retryAfter") if (rateLimitCallback != null && !rateLimitCallback.invoke(retryAfter as Float)) { return@runBlocking null } } val metadataJson = Json.parseToJsonElement(metadata.body()) println("metadata = $metadataJson") val hash = metadataJson.jsonObject["chapter"]?.jsonObject?.get("hash")!!.toString().trim('"') val baseUrl = metadataJson.jsonObject["baseUrl"]!!.toString().trim('"') val pages = metadataJson.jsonObject["chapter"]?.jsonObject?.get("data")?.jsonArray?.size!! database?.let { println("setting record to $pages") it.recordDao.setRecord(Record(chapterIdentifier, pages)) } val executor = Executors.newFixedThreadPool( Math.min( pages, Runtime.getRuntime().availableProcessors() + 4 ) ) val deferreds = mutableListOf<Deferred<Pair<Int, ByteArray>>>() suspend fun downloadPage(pageCount: Int, pageDigest: String): Pair<Int, ByteArray> { val page = httpClient.get("$baseUrl/data/$hash/${pageDigest.trim('"')}") println("Getting $pageDigest") return Pair(pageCount + 1, page.readBytes()); } val downloadedPages = mutableListOf<Pair<Int, ByteArray>>() for ((pageCount, pageDigest) in metadataJson.jsonObject["chapter"]?.jsonObject?.get("data")?.jsonArray?.withIndex() ?: emptyList()) { if ((pageCount + 1) !in pagesInDatabase /*&& (generate() ?: true)*/) { val deferred = CoroutineScope(Dispatchers.IO).async { downloadPage( pageCount, pageDigest.toString() ) } deferreds.add(deferred) } else { println("already in db! $pageDigest") } } for (deferred in deferreds) { try { val (pageCount, pageContent) = deferred.await() downloadedPages.add(pageCount to pageContent) /*if (pageDownloadCb != null) { pageDownloadCb(muuid, pageCount to pageContent, pages) }*/ } catch (e: Exception) { println("An error occurred: $e") } } executor.shutdown() // sort them by downloadedPages.sortBy { it.first } return@runBlocking downloadedPages } } fun resizeImage(byteArray: ByteArray, targetWidth: Int, targetHeight: Int): ByteArray { // Convert ByteArray to Bitmap val inputStream = ByteArrayInputStream(byteArray) val bitmap = BitmapFactory.decodeStream(inputStream) // Resize Bitmap val resizedBitmap = Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, false) // Convert resized Bitmap to ByteArray val outputStream = ByteArrayOutputStream() resizedBitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream) return outputStream.toByteArray() } fun getMangaInfo(mangaIdentifier: String): InfoObject { return runBlocking { val defaultParams = getDefaultRequestParameters().jsonObject.toMutableMap(); val response = getRequest( "$API_URL/manga/$mangaIdentifier?includes%5B%5D=cover_art", defaultParams ) val mangaInfoNonagr = Json.parseToJsonElement(response.body()) val mangaFormat: MutableList<String> = mutableListOf() val mangaGenre: MutableList<String> = mutableListOf() var coverUrl: String? = null val contentRating = mangaInfoNonagr.jsonObject["data"]?.jsonObject?.get("attributes")?.jsonObject?.get("contentRating") .toString().trim('"') var image: ByteArray? = null var smallImage: ByteArray? = null for ((index, relationship) in mangaInfoNonagr.jsonObject["data"]?.jsonObject?.get("relationships")?.jsonArray?.withIndex() ?: emptyList()) { if (relationship.jsonObject["type"].toString().trim('"') == "cover_art") { val fileName = mangaInfoNonagr.jsonObject["data"]?.jsonObject?.get("relationships")?.jsonArray?.get( index )?.jsonObject?.get( "attributes" )?.jsonObject?.get("fileName").toString().trim('"') coverUrl = "https://mangadex.org/covers/$mangaIdentifier/$fileName" } } for (tag in mangaInfoNonagr.jsonObject["data"]?.jsonObject?.get("attributes")?.jsonObject?.get( "tags" )?.jsonArray ?: emptyList()) { if (tag.jsonObject["attributes"]?.jsonObject?.get("group").toString() .trim('"') == "format" ) { mangaFormat += tag.jsonObject["attributes"]?.jsonObject?.get("name")?.jsonObject?.get( "en" ) .toString().trim('"') } if (tag.jsonObject["attributes"]?.jsonObject?.get("group").toString() .trim('"') == "genre" ) { mangaGenre += tag.jsonObject["attributes"]?.jsonObject?.get("name")?.jsonObject?.get( "en" ) .toString().trim('"') } } if (coverUrl != null) { val coverArtResponse = httpClient.get(coverUrl) val coverArt = coverArtResponse.readBytes() image = coverArt.copyOf() smallImage = resizeImage(coverArt.copyOf(), 51, 80) } val title = if (mangaInfoNonagr.jsonObject["data"]?.jsonObject?.get("attributes")?.jsonObject?.get( "title" )?.jsonObject?.get( "en" ) == null ) { ((mangaInfoNonagr.jsonObject["data"]?.jsonObject?.get("attributes")?.jsonObject?.get( "title" )?.jsonObject) as Map<*, *>).values.toList()[0]?.toString() } else { mangaInfoNonagr.jsonObject["data"]?.jsonObject?.get("attributes")?.jsonObject?.get( "title" )?.jsonObject?.get( "en" ).toString() } ?: "" return@runBlocking InfoObject( identifier = mangaIdentifier, name = title, description = mangaInfoNonagr.jsonObject["data"]?.jsonObject?.get("attributes")?.jsonObject?.get( "description" )?.jsonObject?.get( "en" ) .toString(), cover = image, smallCover = smallImage, mangaFormat = mangaFormat.joinToString("|"), mangaGenre = mangaGenre.joinToString("|"), contentRating = contentRating ) } } fun getChapterList( mangaIdentifier: String, languages: List<String> = listOf("en") ): List<JsonElement> { return runBlocking { val chapters: MutableList<JsonElement> = mutableListOf(); var offset = 0 var totalChapters: Int = -1 while (true) { if ((totalChapters != -1) && (totalChapters <= offset)) { break } val defaultParams = getDefaultRequestParameters().jsonObject.toMutableMap(); defaultParams["manga"] = JsonPrimitive(mangaIdentifier) defaultParams["limit"] = JsonPrimitive(100) defaultParams["offset"] = JsonPrimitive(offset) defaultParams["translatedLanguage[]"] = Json.encodeToJsonElement(languages) defaultParams["includes[]"] = Json.encodeToJsonElement(listOf("scanlation_group")) val response = getRequest("$API_URL/chapter", defaultParams) val responseJson = Json.parseToJsonElement(response.body()) if (responseJson.jsonObject["data"] == null) { break } if (totalChapters == -1) { totalChapters = responseJson.jsonObject["total"]?.jsonPrimitive?.int ?: 581 // based on "Golgo 13" chapters } val chaptersFromApi = responseJson.jsonObject["data"]?.jsonArray?.toList() ?: listOf() chapters.addAll(chaptersFromApi) offset += 100 } return@runBlocking chapters } } fun getMangaIdentifierFromChapter(chapterIdentifier: String): String? { return runBlocking { val params = getDefaultRequestParameters() val response = getRequest("$API_URL/chapter/$chapterIdentifier", params.jsonObject.toMutableMap()) val responseJson = Json.parseToJsonElement(response.body()) for (relationship in responseJson.jsonObject["data"]?.jsonObject?.get("relationships")?.jsonArray ?: listOf()) { if (jsonElementToString(relationship.jsonObject["type"]!!) == "manga") { jsonElementToString(relationship.jsonObject["id"]!!) } } null } } fun getNextAndPrev( chapterIdentifier: String, mangaIdentifier: String? = null ): MutableMap<String, JsonElement?>? { return runBlocking { var mIdentifier: String? = mangaIdentifier if (mIdentifier == null) { mIdentifier = getMangaIdentifierFromChapter(chapterIdentifier) if (mIdentifier == null) { println("Could not get mangaIdentifier") return@runBlocking null } } if (database == null) { println("Database must be passed to backend!") return@runBlocking null } try { val nextPrev: MutableMap<String, JsonElement?> = mutableMapOf( Pair("next", JsonObject(mapOf())), Pair("prev", JsonObject(mapOf())), Pair("current", JsonObject(mapOf())) ) var chapterList: List<JsonElement> = listOf(); try { val connectionChapterList = getChapterList(mIdentifier); database.chapterInfoDao.setChapterInfo( ChapterInfo( mIdentifier, connectionChapterList.toString() ) ) chapterList = connectionChapterList } catch (e: Exception) { val connectionChapterList = database.chapterInfoDao.getChapterInfo(mIdentifier) ?: return@runBlocking null chapterList = Json.parseToJsonElement(connectionChapterList.jsonData).jsonArray } chapterList.sortedWith( compareBy( { jsonElementToString(it.jsonObject["attributes"]?.jsonObject?.get("volume")!!).toFloatOrNull() }, { jsonElementToString(it.jsonObject["attributes"]?.jsonObject?.get("chapter")!!).toFloat() }) ) for (chapter in chapterList.withIndex()) { if (jsonElementToString(chapter.value.jsonObject["id"]!!) == chapterIdentifier) { val currentMutableMap = nextPrev["current"]?.jsonObject?.toMutableMap()!! currentMutableMap["chapter"] = chapter.value.jsonObject["attributes"]?.jsonObject?.get("chapter") as JsonElement currentMutableMap["volume"] = chapter.value.jsonObject["attributes"]?.jsonObject?.get("volume") as JsonElement nextPrev["current"] = Json.encodeToJsonElement(currentMutableMap) if (chapter.index > 0) { nextPrev["prev"] = chapterList[chapter.index - 1] } if (chapter.index < chapterList.size - 1) { nextPrev["next"] = chapterList[chapter.index + 1] } } } val nextPrevJson = Json.encodeToJsonElement(nextPrev) if (!database.mangaDao.containsChapter( jsonElementToString( nextPrevJson.jsonObject["next"]?.jsonObject?.get( "id" ) ) ) ) { nextPrev["next"] = null } if (!database.mangaDao.containsChapter( jsonElementToString( nextPrevJson.jsonObject["prev"]?.jsonObject?.get( "id" ) ) ) ) { nextPrev["prev"] = null } return@runBlocking nextPrev } catch (e: Exception) { e.printStackTrace() println("caught exception ${e.message} when trying to get next and prev ") return@runBlocking null } } } } class UserInfoObject(passedDatabase: MangaDatabase) { private val database: MangaDatabase companion object { @Volatile private var instance: UserInfoObject? = null fun getInstance(database: MangaDatabase): UserInfoObject { if (instance == null) { synchronized(UserInfoObject::class.java) { if (instance == null) { instance = UserInfoObject(database) } } } return instance!! } } private var readManga: MutableMap<String, MutableList<String>> = mutableMapOf() private var settings: MutableMap<String, String> = mutableMapOf() init { database = passedDatabase var dbValue = runBlocking { database.userInfoDao.getUserInfo() } if (dbValue == null) { dbValue = runBlocking { database.userInfoDao.setUserInfo( UserInfo( readManga = """{"read_manga": {}}""", settings = "{}" ) ) database.userInfoDao.getUserInfo() } } val readMangaJson = dbValue?.let { Json.parseToJsonElement(it.readManga) } readMangaJson?.jsonObject?.toMutableMap()?.map { readManga[it.key] = it.value.jsonArray.toMutableList().map { t -> jsonElementToString(t) } .toMutableList() } val settingsJson = dbValue?.let { Json.parseToJsonElement(it.settings) } settingsJson?.jsonObject?.toMutableMap()?.map { settings[it.key] = jsonElementToString(it.value) } } } class DownloaderQueue { var jobs: MutableList<String> = mutableListOf() var uiElements: HashMap<String, Pair<ProgressBar, TextView>> = hashMapOf() var currentlyWorkingOn: String? = null companion object { @Volatile private var instance: DownloaderQueue? = null fun getInstance(): DownloaderQueue { if (instance == null) { synchronized(DownloaderQueue::class.java) { if (instance == null) { instance = DownloaderQueue() } } } return instance!! } } fun poll(): String? { return jobs.firstOrNull() } fun removeDownload(mangaIdentifier: String, context: Context) { for (job in jobs.withIndex()) { if (job.value == mangaIdentifier) { jobs.removeAt(job.index) } } if(currentlyWorkingOn == mangaIdentifier){ println("cancelling cwo!") val intent = Intent("DownloaderState") intent.putExtra("identifier", mangaIdentifier) LocalBroadcastManager.getInstance(context).sendBroadcast(intent) println("send broadcast to end") } } fun addDownload(mangaId: String): Boolean{ if(mangaId == currentlyWorkingOn) return false for(job in jobs){ if(job == mangaId){ return false } } println("adding job!") jobs.add(mangaId) println(jobs) return true } } class DownloadService : Service() { private val CHANNEL_ID = "DownloadServiceChannel" private val scope = CoroutineScope(Dispatchers.IO) private lateinit var connection: MangaDexConnection private lateinit var database: MangaDatabase private lateinit var downloadScope: CoroutineScope private var queue = DownloaderQueue.getInstance() private var isServiceRunning = false private var interruptDownload = mutableListOf<String>() private val stateReceiver = object : BroadcastReceiver() { override fun onReceive(context: Context?, intent: Intent?) { println("recieved $intent") intent?.getStringExtra("identifier")?.let { if(it !in interruptDownload ){ println("adding $it to interrupts") interruptDownload.add(it) } } } } override fun onCreate() { super.onCreate() database = Room.databaseBuilder( applicationContext, MangaDatabase::class.java, "manga" ).build() connection = MangaDexConnection(database) LocalBroadcastManager.getInstance(this) .registerReceiver(stateReceiver, IntentFilter("DownloaderState")) downloadScope = CoroutineScope(Dispatchers.IO + Job()) startForeground(1, createNotification("Waiting for downloads...")) // Start the background loop startBackgroundLoop() } private fun startBackgroundLoop() { isServiceRunning = true downloadScope.launch { while (isServiceRunning) { if(!queue.currentlyWorkingOn.isNullOrEmpty()){ delay(1000L) continue } val job = queue.poll() // Poll once, then work with the result if (!job.isNullOrEmpty()) { println("found job") downloadManga(job) } else { delay(1000L) // Sleep for 1 second if there's no job } } } } private fun notifyProgress(mangaIdentifier: String) { val intent = Intent("DownloadProgress") intent.putExtra("identifier", mangaIdentifier) intent.putExtra("finished", false) LocalBroadcastManager.getInstance(this).sendBroadcast(intent) } private fun notifyFinish(mangaIdentifier: String) { val intent = Intent("DownloadProgress") intent.putExtra("identifier", mangaIdentifier) intent.putExtra("finished", true) println("calling finish!") LocalBroadcastManager.getInstance(this).sendBroadcast(intent) } override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { createNotificationChannel() val notification = createNotification("Downloading...") startForeground(1, notification) /*val mangaIdentifier = intent?.getStringExtra("identifier") ?: return START_NOT_STICKY println("Starting service!") downloadManga(mangaIdentifier)*/ startBackgroundLoop() return START_STICKY } private fun createNotification(content: String): Notification { val intent = Intent(this, MainActivity::class.java) val pendingIntent = PendingIntent.getActivity( this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE ) return NotificationCompat.Builder(this, CHANNEL_ID) .setContentTitle("Download Service") .setContentText(content) .setSmallIcon(android.R.drawable.stat_sys_download) .setContentIntent(pendingIntent) .setPriority(NotificationCompat.PRIORITY_DEFAULT) .build() } private fun createNotificationChannel() { val serviceChannel = NotificationChannel( CHANNEL_ID, "Download Service Channel", NotificationManager.IMPORTANCE_DEFAULT ) val manager = getSystemService(NotificationManager::class.java) manager.createNotificationChannel(serviceChannel) } private fun downloadManga(mangaIdentifier: String) { scope.launch { try { queue.currentlyWorkingOn = mangaIdentifier queue.jobs.remove(mangaIdentifier) downloadChapters(mangaIdentifier).let { notifyFinish(mangaIdentifier) } queue.currentlyWorkingOn = null } catch (e: Exception) { println(e.message) } } } private suspend fun downloadChapters(mangaIdentifier: String) { withContext(Dispatchers.IO) { val chapterList = connection.getChapterList(mangaIdentifier) for (chapter in chapterList.withIndex()) { if(mangaIdentifier in interruptDownload){ interruptDownload.remove(mangaIdentifier) println("breaking download of $mangaIdentifier") break } val chapterIdentifier = chapter.value.jsonObject["id"].toString().trim('"') val dbPages = database.mangaDao.getPages(chapterIdentifier) val shouldSkip = database.recordDao.getRecord(chapterIdentifier)?.let { it.pages == dbPages.size } ?: false if (shouldSkip) { val progress = (chapter.index * 100 / chapterList.size) withContext(Dispatchers.Main) { val uiElement = queue.uiElements[mangaIdentifier] ?: return@withContext uiElement.first.progress = progress uiElement.second.text = "$progress%" } notifyProgress(mangaIdentifier) println("Skipping chapter in database") continue } var shouldExitDownload = false val downloadedPages = connection.downloadMangaPages(chapterIdentifier, dbPages, false) { println("Warning: hit the rate limit! Sleeping for $it seconds") val startTime = System.currentTimeMillis() val waitTime = (it + 5) * 1000 // wait time in milliseconds var currentTime = System.currentTimeMillis() while (currentTime - startTime < waitTime) { if(mangaIdentifier in interruptDownload){ shouldExitDownload = true break } currentTime = System.currentTimeMillis() } true } if(shouldExitDownload){ // the check will be performed next iteration continue } if (downloadedPages.isNullOrEmpty()) { println("Could not download $chapterIdentifier") continue } val infoIdentifier = database.infoDao.getInfoIdentifier(mangaIdentifier) for (page in downloadedPages) { database.mangaDao.setManga( Manga( identifier = chapterIdentifier, page = page.first, data = page.second, infoId = infoIdentifier ) ) } val progress = (chapter.index * 100 / chapterList.size) withContext(Dispatchers.Main) { val uiElement = queue.uiElements[mangaIdentifier] ?: return@withContext uiElement.first.progress = progress uiElement.second.text = "$progress%" } notifyProgress(mangaIdentifier) } } } override fun onDestroy() { println("turning off service!") LocalBroadcastManager.getInstance(this).unregisterReceiver(stateReceiver) super.onDestroy() scope.cancel() // Cancel all coroutines } override fun onBind(intent: Intent?): IBinder? { return null } } /*class DownloadManager(passedDatabase: MangaDatabase) { private var queue: DownloaderQueue = DownloaderQueue.getInstance() private var connection: MangaDexConnection private var database: MangaDatabase companion object { @Volatile private var instance: DownloadManager? = null fun getInstance(database: MangaDatabase): DownloadManager { if (instance == null) { synchronized(DownloadManager::class.java) { if (instance == null) { instance = DownloadManager(database) } } } return instance!! } } init { connection = MangaDexConnection(passedDatabase) database = passedDatabase } private fun notifyProgress(mangaIdentifier: String, progress: Int){ val intent = Intent("DownloadProgress") intent.putExtra("mangaIdentifier", mangaIdentifier) intent.putExtra("progress", progress) LocalBroadcastManager.getInstance(this).sendBroadcast(intent) } fun downloadManga(mangaIdentifier: String) { val job = CoroutineScope(Dispatchers.IO).launch { try { downloadChapters(mangaIdentifier) withContext(Dispatchers.Main) { val uiElement = queue.uiElements[mangaIdentifier] ?: return@withContext uiElement.first.progress = 100 uiElement.second.text = "Finished" } // adapter?.onFinish(mangaIdentifier) } catch (e: Exception) { println(e.message) } } queue.jobs.add(Pair(mangaIdentifier, job)) } fun removeDownload(mangaIdentifier: String) { for (job in queue.jobs.withIndex()) { if (job.value.first == mangaIdentifier) { job.value.second.cancel() queue.jobs.removeAt(job.index) break } } } private suspend fun downloadChapters(mangaIdentifier: String) { withContext(Dispatchers.IO) { val chapterList = connection.getChapterList(mangaIdentifier) for (chapter in chapterList.withIndex()) { val chapterIdentifier = chapter.value.jsonObject["id"].toString().trim('"') val dbPages = database.mangaDao.getPages(chapterIdentifier) val shouldSkip = database.recordDao.getRecord(chapterIdentifier)?.let { it.pages == dbPages.size } ?: false if (shouldSkip) { println("skipping chapter in database") continue } val downloadedPages = connection.downloadMangaPages(chapterIdentifier, dbPages, false) { println("Warning hit the rate limit! sleeping for $it seconds") Thread.sleep(((it + 5) * 1000).toLong()) true } if (downloadedPages.isNullOrEmpty()) { println("Could not download $chapterIdentifier") continue } val infoIdentifier = database.infoDao.getInfoIdentifier(mangaIdentifier) for (page in downloadedPages) { database.mangaDao.setManga( Manga( identifier = chapterIdentifier, page = page.first, data = page.second, infoId = infoIdentifier ) ) } val progress = (chapter.index * 100 / chapterList.size) withContext(Dispatchers.Main) { val uiElement = queue.uiElements[mangaIdentifier] ?: return@withContext uiElement.first.progress = progress uiElement.second.text = "$progress%" } } } } }*/
0
Kotlin
0
0
5103bf4a6b8d2fd1243effa4b8424bb65b598ea8
39,374
lmdx-android-public
MIT License
smithy-swift-codegen/src/main/kotlin/software/amazon/smithy/swift/codegen/integration/serde/xml/DynamicNodeDecodingXMLGenerator.kt
smithy-lang
242,852,561
false
{"Kotlin": 1329364, "Swift": 499468, "Smithy": 113922}
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ package software.amazon.smithy.swift.codegen.integration.serde.xml import software.amazon.smithy.codegen.core.Symbol import software.amazon.smithy.model.shapes.MemberShape import software.amazon.smithy.model.shapes.Shape import software.amazon.smithy.model.traits.XmlAttributeTrait import software.amazon.smithy.swift.codegen.ClientRuntimeTypes import software.amazon.smithy.swift.codegen.SwiftDependency import software.amazon.smithy.swift.codegen.SwiftTypes import software.amazon.smithy.swift.codegen.SwiftWriter import software.amazon.smithy.swift.codegen.integration.ProtocolGenerator import software.amazon.smithy.swift.codegen.integration.isInHttpBody import software.amazon.smithy.swift.codegen.model.bodySymbol class DynamicNodeDecodingXMLGenerator( private val ctx: ProtocolGenerator.GenerationContext, private val shape: Shape, private val isForBodyStruct: Boolean ) { fun render() { val symbol = if (isForBodyStruct) ctx.symbolProvider.toSymbol(shape).bodySymbol() else ctx.symbolProvider.toSymbol(shape) val rootNamespace = ctx.settings.moduleName val encodeSymbol = Symbol.builder() .definitionFile("./$rootNamespace/models/${symbol.name}+DynamicNodeDecoding.swift") .name(symbol.name) .build() ctx.delegator.useShapeWriter(encodeSymbol) { writer -> writer.openBlock("extension \$N: \$N {", "}", symbol, ClientRuntimeTypes.Serde.DynamicNodeDecoding) { writer.addImport(SwiftDependency.CLIENT_RUNTIME.target) renderDynamicNodeDecodingConformance(symbol.name, writer) } } } private fun renderDynamicNodeDecodingConformance(symbolName: String, writer: SwiftWriter) { val httpBodyMembers = shape.members() .filter { it.isInHttpBody() } .toList() writer.openBlock("public static func nodeDecoding(for key: \$N) -> \$N {", "}", SwiftTypes.CodingKey, ClientRuntimeTypes.Serde.NodeDecoding) { writer.openBlock("switch(key) {", "}") { for (bodyMember in httpBodyMembers) { renderBodyMember(symbolName, bodyMember, writer) } writer.write("default:") writer.indent().write("return .element") writer.dedent() } } } private fun renderBodyMember(symbolName: String, member: MemberShape, writer: SwiftWriter) { val memberName = ctx.symbolProvider.toMemberName(member).removeSurrounding("`", "`") val elementOrAttribute = if (member.hasTrait(XmlAttributeTrait::class.java)) ".attribute" else ".element" writer.write("case $symbolName.CodingKeys.$memberName: return $elementOrAttribute") } }
9
Kotlin
20
27
f6c8bc807356e1d82aadc36e9c077079e5f0f3aa
2,875
smithy-swift
Apache License 2.0
app/src/main/java/com/example/omdb/ui/home/ContentTypeCard.kt
Pro-55
195,038,410
false
{"Kotlin": 259217}
package com.example.omdb.ui.home import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.material3.ElevatedCard import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.painter.Painter import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp @Composable fun ContentTypeCard( modifier: Modifier = Modifier, icon: Painter, label: String, contentDescription: String, onClick: () -> Unit ) { ElevatedCard( modifier = modifier .fillMaxWidth(), shape = MaterialTheme.shapes.small, onClick = onClick ) { Column( modifier = Modifier .fillMaxSize() .padding(all = 16.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally ) { Icon( modifier = Modifier .size(size = 100.dp), painter = icon, contentDescription = contentDescription ) Spacer( modifier = Modifier .height(height = 16.dp) ) Text( text = label, maxLines = 2, style = MaterialTheme.typography.displaySmall.copy( fontWeight = FontWeight.Bold, textAlign = TextAlign.Center ) ) } } }
0
Kotlin
0
1
2ee54ce67c4c077ef1ccb83cd92121e3eb778c09
2,086
OMDb
Apache License 2.0
app/src/main/kotlin/com/giant/liders/notes/ViewGroupExtension.kt
BombaStudio
297,716,443
false
null
package com.giant.liders.notes import android.view.LayoutInflater import android.view.View import android.view.ViewGroup fun ViewGroup.inflate(layoutId: Int): View { val layoutInflater = LayoutInflater.from(context) return layoutInflater.inflate(layoutId, this, false) }
0
Kotlin
0
0
2aeb1501df1288133819a002e25a53df1c243f18
280
first-kotlin-app
Apache License 2.0
client-stub-jersey1/src/main/kotlin/com/github/simy4/stub/jersey1/Jersey1ResponseConverter.kt
codacy-badger
138,725,089
false
{"Kotlin": 34903}
package com.github.simy4.stub.jersey1 import com.github.simy4.stub.core.Attempt import com.github.simy4.stub.core.Response import com.sun.jersey.api.client.Client import com.sun.jersey.api.client.ClientHandlerException import com.sun.jersey.api.client.ClientRequest import com.sun.jersey.api.client.ClientResponse import com.sun.jersey.core.header.InBoundHeaders import com.sun.jersey.core.util.StringKeyIgnoreCaseMultivaluedMap import com.sun.jersey.spi.MessageBodyWorkers import java.io.ByteArrayInputStream import java.io.ByteArrayOutputStream import java.io.IOException import java.io.OutputStream import java.lang.reflect.Type import javax.ws.rs.core.GenericEntity import javax.ws.rs.core.HttpHeaders import javax.ws.rs.core.MediaType import javax.ws.rs.core.MultivaluedMap internal object Jersey1ResponseConverter : (ClientRequest, Response) -> Attempt<ClientResponse> { private val DEFAULT_CONTENT_TYPE = MediaType.APPLICATION_OCTET_STREAM_TYPE override fun invoke(request: ClientRequest, response: Response): Attempt<ClientResponse> { return Attempt { invoke0(request, response) } } @Suppress("UNCHECKED_CAST") @Throws(ClientHandlerException::class) private fun invoke0(request: ClientRequest, response: Response): ClientResponse { val body = response.body val messageBodyWorkers = request.messageBodyWorkers val responseHeaders = StringKeyIgnoreCaseMultivaluedMap<Any>() val responseBody = when (body) { null -> { responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, request.contentType) responseHeaders.putSingle(HttpHeaders.CONTENT_LENGTH, 0) ByteArray(0) } is ByteArray -> { responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, request.contentType) responseHeaders.putSingle(HttpHeaders.CONTENT_LENGTH, body.size) body } else -> { val os = ByteArrayOutputStream() try { val responseType: Class<*> val genericType: Type? val responseObject: Any? when (body) { is GenericEntity<*> -> { responseType = body.rawType genericType = body.type responseObject = body.entity } else -> { responseType = body.javaClass genericType = null responseObject = body } } val contentType = messageBodyWorkers.writeTo(responseObject, responseType as Class<Any?>, genericType, request.headers, os) val responseBody = os.toByteArray() responseHeaders.putSingle(HttpHeaders.CONTENT_TYPE, contentType) responseHeaders.putSingle(HttpHeaders.CONTENT_LENGTH, responseBody.size) responseBody } catch (io: IOException) { throw ClientHandlerException("Unable to write response payload", io) } finally { os.close() } } } val inBoundHeaders = InBoundHeaders() responseHeaders.forEach { name, values -> inBoundHeaders[name] = values.map(ClientRequest::getHeaderValue) } response.headers.forEach { name, values -> inBoundHeaders[name] = values.toList() } return ClientResponse(response.status, inBoundHeaders, ByteArrayInputStream(responseBody), messageBodyWorkers) } private val ClientRequest.contentType get() = headers.getOrDefault(HttpHeaders.ACCEPT, emptyList()).firstOrNull() ?: DEFAULT_CONTENT_TYPE private val ClientRequest.messageBodyWorkers: MessageBodyWorkers get() = properties[Client::class.java.canonicalName].let { when (it) { is Client -> it.messageBodyWorkers else -> throw ClientHandlerException("Unable to find message body workers in request context") } } @Throws(ClientHandlerException::class, IOException::class) private fun <T> MessageBodyWorkers.writeTo( t: T?, type: Class<T>, genericType: Type?, headers: MultivaluedMap<String, Any>, outputStream: OutputStream ): MediaType { val acceptedMediaTypes = headers.getOrDefault(HttpHeaders.ACCEPT, listOf(DEFAULT_CONTENT_TYPE)) .map { value -> MediaType.valueOf(value.toString()) } val contentType = getMessageBodyWriterMediaType(type, genericType, emptyArray(), acceptedMediaTypes) ?: throw ClientHandlerException("Unable to find message body writer for: $t") val messageBodyWriter = getMessageBodyWriter(type, genericType, emptyArray(), contentType) messageBodyWriter.writeTo(t, type, genericType, emptyArray(), contentType, headers, outputStream) return contentType } }
0
Kotlin
0
1
80fc785fd6e95848df90b85c8fe55eb2eed2a708
5,101
client-stub
Apache License 2.0
payments-core/src/main/java/com/stripe/android/payments/core/injection/CoroutineContextModule.kt
stripe
6,926,049
false
null
package com.stripe.android.payments.core.injection import com.stripe.android.core.injection.IOContext import com.stripe.android.core.injection.UIContext import dagger.Module import dagger.Provides import kotlinx.coroutines.Dispatchers import javax.inject.Singleton import kotlin.coroutines.CoroutineContext @Module class CoroutineContextModule { @Provides @Singleton @IOContext fun provideWorkContext(): CoroutineContext = Dispatchers.IO @Provides @Singleton @UIContext fun provideUIContext(): CoroutineContext = Dispatchers.Main }
54
Kotlin
502
866
c64b81095c36df34ffb361da276c116ffd5a2523
567
stripe-android
MIT License
app/src/main/java/me/ssttkkl/sharenote/data/service/ServiceModule.kt
ssttkkl
503,981,002
false
null
package me.ssttkkl.sharenote.data.service import dagger.Binds import dagger.Module import dagger.hilt.InstallIn import dagger.hilt.components.SingletonComponent @Module @InstallIn(SingletonComponent::class) internal abstract class ServiceModule { @Binds abstract fun publicService(impl: PublicServiceImpl): PublicService @Binds abstract fun privateService(impl: PrivateServiceImpl): PrivateService }
0
Kotlin
0
0
ea59853d8d4e62b08c8e99b98b014ae78fe5490b
418
ShareNote
Apache License 2.0
app/src/main/java/eu/innosoft/androidpoc/features/sign_up/SignUpComponent.kt
ChunyuanCai
162,724,302
false
null
package eu.innosoft.androidpoc.features.sign_up import dagger.Component import eu.innosoft.androidpoc.activities.splash.SplashComponent import eu.innosoft.androidpoc.di.FeatureScope @Component(dependencies = [(SplashComponent::class)], modules = [(SignUpModule::class)]) @FeatureScope interface SignUpComponent { fun inject(view: SignUpView) }
0
Kotlin
0
1
e162ca62405add3d3e78646d46382a5eee105abc
349
AndroidPOC
Apache License 2.0
app/src/main/kotlin/no/nav/tiltakspenger/vedtak/routes/exceptionhandling/ExceptionHandler.kt
navikt
487,246,438
false
{"Kotlin": 1042302, "Shell": 1318, "Dockerfile": 495, "HTML": 45}
package no.nav.tiltakspenger.vedtak.routes.exceptionhandling import io.ktor.http.HttpStatusCode import io.ktor.server.application.ApplicationCall import io.ktor.server.request.ContentTransformationException import io.ktor.server.request.uri import io.ktor.server.response.respond import mu.KotlinLogging import no.nav.tiltakspenger.felles.exceptions.IkkeFunnetException import no.nav.tiltakspenger.felles.exceptions.TilgangException import no.nav.tiltakspenger.felles.sikkerlogg import no.nav.tiltakspenger.vedtak.exceptions.ManglendeJWTTokenException import no.nav.tiltakspenger.vedtak.exceptions.UgyldigRequestException object ExceptionHandler { private val logger = KotlinLogging.logger {} suspend fun handle( call: ApplicationCall, cause: Throwable, ) { val uri = call.request.uri logger.error(RuntimeException("Trigger stacktrace for enklere debug.")) { "Ktor mottok exception i ytterste lag. Uri: $uri. Se sikkerlogg mer kontekst." } sikkerlogg.error(cause) { "Ktor mottok exception i ytterste lag. Uri: $uri." } when (cause) { is IllegalStateException -> { call.respondWith(HttpStatusCode.InternalServerError, cause) } is ManglendeJWTTokenException -> { call.respondWith(HttpStatusCode.Unauthorized, cause) } is UgyldigRequestException -> { call.respondWith(HttpStatusCode.BadRequest, cause) } is ContentTransformationException -> { call.respondWith(HttpStatusCode.BadRequest, cause) } is TilgangException -> { call.respondWith(HttpStatusCode.Forbidden, cause) } is IkkeFunnetException -> { call.respondWith(HttpStatusCode.NotFound, cause) } // Catch all else -> { call.respondWith(HttpStatusCode.InternalServerError, cause) } } } // TODO pre-mvp jah: Føles ikke bra at vi returnerer cause fra exceptions. Her kan vi blø data vi ikke ønsker å dele. private suspend fun ApplicationCall.respondWith( statusCode: HttpStatusCode, ex: Throwable, ) { this.respond( statusCode, ExceptionResponse(ex, statusCode), ) } }
0
Kotlin
0
1
c23890a313eac464b2eae8d6e6f143b47a4b693e
2,364
tiltakspenger-vedtak
MIT License
app/src/main/java/hr/ferit/drazen/antunovic/chatier/ui/routes/signin/SignIn.kt
Stakljar
660,216,878
false
{"Kotlin": 147262}
package hr.ferit.drazen.antunovic.chatier.ui.routes.signin import androidx.compose.runtime.Composable import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.Modifier import hr.ferit.drazen.antunovic.chatier.data.Result import hr.ferit.drazen.antunovic.chatier.ui.routes.signup.SignScreen @Composable fun SignIn( modifier: Modifier = Modifier, viewModel: SignInViewModel, onNavigateToFillPersonalInformation: () -> Unit, onNavigateToHome: () -> Unit, ) { val signInResult by viewModel.signIn.collectAsState() val deviceTokenInsertionResult by viewModel.deviceTokenInsertion.collectAsState() if (deviceTokenInsertionResult is Result.Success) { viewModel.refresh() onNavigateToHome() } else if (signInResult is Result.Success && signInResult.data == null) { viewModel.refresh() onNavigateToFillPersonalInformation() } else if (signInResult is Result.Success && deviceTokenInsertionResult !is Result.Loading) { viewModel.insertDeviceToken() } SignScreen( modifier = modifier, onClick = { email, password -> viewModel.signIn( email = email, password = <PASSWORD>, ) }, result = signInResult, ) }
0
Kotlin
0
0
5e1048088216742161d5419fe6003d4c16fe659e
1,330
chatting-app
MIT License
src/main/kotlin/me/honnold/mpq/util/ByteBufferInputStream.kt
jhonnold
276,220,774
false
{"Kotlin": 18132}
package me.honnold.mpq.util import java.io.InputStream import java.nio.ByteBuffer class ByteBufferInputStream(private val buffer: ByteBuffer): InputStream() { @ExperimentalUnsignedTypes @Synchronized override fun read() = if (this.buffer.hasRemaining()) this.buffer.get().toUByte().toInt() else -1 }
0
Kotlin
0
1
8a41cc9120f1ca20dac7060d1765960f8229c419
309
mpq
MIT License
android/khajit/app/src/main/java/com/project/khajit_app/data/models/EquipmentBSOrderModel.kt
bounswe
170,124,936
false
{"Kotlin": 416637, "Python": 210731, "SCSS": 184849, "CSS": 97799, "Less": 78481, "JavaScript": 56513, "HTML": 35601, "Dockerfile": 1032, "Shell": 76}
package com.project.khajit_app.data.models data class EquipmentBSOrderModel ( val currency : String, val amount : Double, val e_amount : Int )
31
Kotlin
2
9
40370c1e8ff7f49dead59034e8baab8a99e3adbf
155
bounswe2019group1
MIT License
src/nativeMain/kotlin/exceptions/ScanningException.kt
wordandahalf
737,967,043
false
{"Kotlin": 10178}
package exceptions class ScanningException(line: Int, char: Char) : LoxException("Unexpected character '$char' on line $line")
0
Kotlin
0
0
81603f440829e2dadaa965a9216626456b02f436
131
klox
Apache License 2.0
api/src/main/kotlin/com/wnsgml972/strada/api/v1/ordering/service/OrderingDetailDTO.kt
Coffee-Street
289,485,814
false
{"Kotlin": 267923, "Shell": 2546, "Dockerfile": 174}
package com.wnsgml972.strada.api.v1.ordering.service import com.wnsgml972.strada.api.v1.option.bean.service.BeanOptionDTO import com.wnsgml972.strada.api.v1.option.bread.service.BreadOptionDTO import com.wnsgml972.strada.api.v1.option.drink.service.DrinkOptionDTO data class OrderingDetailDTO( val id: Long, val coffeeName: String?, val nonCoffeeId: String?, val breadId: String?, val beanId: String?, val drinkOption: DrinkOptionDTO?, val breadOption: BreadOptionDTO?, val beanOption: BeanOptionDTO?, )
2
Kotlin
2
2
24422867afe6c7f547a93f98083f655ecb80c0ed
538
strada
MIT License
TeamCode/src/main/java/org/firstinspires/ftc/teamcode/util/units/time.kt
randomnetcat
208,137,961
true
{"Kotlin": 119475, "Java": 43105}
@file:Suppress("NOTHING_TO_INLINE", "OVERRIDE_BY_INLINE") package org.firstinspires.ftc.teamcode.util.units import com.acmerobotics.roadrunner.util.NanoClock typealias RawTime = Double private fun Number.toRawTime() = this.toDouble() private fun Int.toRawTime() = this.toDouble() interface Duration { companion object { fun zero() = Seconds.zero() } fun toSeconds(): Seconds } inline class Seconds(val raw: RawTime) : Duration { companion object { fun zero() = Seconds(0.0) } inline override fun toSeconds(): Seconds { return this } } inline fun Seconds(time: Seconds) = time inline fun Seconds(time: Duration) = time.toSeconds() fun Seconds(raw: Int) = Seconds(raw.toRawTime()) inline operator fun Seconds.compareTo(other: Seconds) = (this.raw).compareTo(other.raw) inline operator fun Seconds.unaryMinus() = Seconds(-this.raw) inline operator fun Seconds.plus(other: Seconds) = Seconds(this.raw + other.raw) inline operator fun Seconds.minus(other: Seconds) = Seconds(this.raw - other.raw) inline operator fun Seconds.times(num: Double) = Seconds(this.raw * num) inline operator fun Seconds.div(num: Double) = Seconds(this.raw / num) inline operator fun Seconds.div(other: Seconds) = this.raw / other.raw inline operator fun Double.times(seconds: Seconds) = seconds * this const val SECONDS_PER_MINUTE = 60 inline class Minutes(val raw: RawTime) : Duration { inline override fun toSeconds(): Seconds { return Seconds(this.raw * SECONDS_PER_MINUTE) } } inline fun Minutes(time: Seconds) = Minutes(time.raw / SECONDS_PER_MINUTE) inline fun Minutes(time: Minutes) = time fun Minutes(time: Duration) = Minutes(time.toSeconds()) fun Minutes(raw: Int) = Minutes(raw.toRawTime()) operator fun Duration.compareTo(other: Duration) = (this.toSeconds()).compareTo(other.toSeconds()) operator fun Duration.unaryMinus() = -this.toSeconds() operator fun Duration.plus(other: Duration) = this.toSeconds() + other.toSeconds() operator fun Duration.minus(other: Duration) = this.toSeconds() - other.toSeconds() operator fun Duration.times(num: Double) = this.toSeconds() * num operator fun Duration.div(num: Double) = this.toSeconds() / num operator fun Duration.div(other: Duration) = this.toSeconds() / other.toSeconds() operator fun Double.times(time: Duration) = this * time.toSeconds() interface TimePoint<Tag> { fun timeSinceEpoch(): Duration } inline class TimeSinceEpoch<Tag>(private val timeSinceEpoch: Duration) : TimePoint<Tag> { override fun timeSinceEpoch(): Duration = timeSinceEpoch } operator fun <Tag> TimePoint<Tag>.minus(other: TimePoint<Tag>) = this.timeSinceEpoch() - other.timeSinceEpoch() operator fun <Tag> TimePoint<Tag>.plus(other: Duration) = TimeSinceEpoch<Tag>(this.timeSinceEpoch() + other) operator fun <Tag> TimePoint<Tag>.compareTo(other: TimePoint<Tag>) = (this.timeSinceEpoch()).compareTo(other.timeSinceEpoch()) fun <Tag> epochTime() = TimeSinceEpoch<Tag>(Duration.zero()) object SystemTimeTag typealias SystemTime = TimePoint<SystemTimeTag> fun systemTimeEpoch(): SystemTime = epochTime() fun currentSystemTime(): SystemTime = TimeSinceEpoch(Seconds(System.nanoTime() / 1e9)) interface Clock<Tag> { fun currentTime(): TimePoint<Tag> } typealias SystemClock = Clock<SystemTimeTag> object DefaultSystemClock : SystemClock { override fun currentTime(): SystemTime = currentSystemTime() } fun SystemClock.roadrunner(): NanoClock = object : NanoClock() { override fun seconds(): Double { return Seconds(this@roadrunner.currentTime().timeSinceEpoch()).raw } }
0
Kotlin
0
0
ec4226d7aee8c3b4b8309655cdffeaf223bc22fe
3,603
SkyStone
MIT License
app/src/main/java/com/otsembo/farmersfirst/data/database/DBSeed.kt
otsembo
763,582,014
false
{"Kotlin": 251482}
package com.otsembo.farmersfirst.data.database import com.otsembo.farmersfirst.data.database.dao.ProductDao import com.otsembo.farmersfirst.data.model.Product import kotlinx.coroutines.flow.collect /** * Object responsible for providing a list of pre-defined Product objects for database seeding or display purposes. */ object DBSeed { /** * List of pre-defined Product objects. */ val productList = listOf( Product( id = 1, name = "Fertilizer", description = "Premium quality fertilizer enriched with essential nutrients to promote healthy growth and maximize crop yield. Suitable for all types of crops and soil conditions.", stock = 100, price = 25.99f, image = "https://m.media-amazon.com/images/I/713+fXLmLpL.jpg", ), Product( id = 2, name = "Pesticide", description = "Effective pesticide formulated to control a wide range of pests and insects while ensuring the safety of crops. Provides long-lasting protection for optimal crop production.", stock = 80, price = 15.49f, image = "https://c8.alamy.com/comp/PA28RB/orlando-floridaace-hardwarepesticides-insecticides-poisons-insect-spraysweed-killerroundupshelves-display-saleinterior-insidefl171029120-PA28RB.jpg", ), Product( id = 3, name = "Seeds", description = "High-quality seeds sourced from trusted suppliers, selected for superior germination rates and disease resistance. Ideal for starting a successful crop planting season.", stock = 200, price = 8.99f, image = "https://northernseeds.ca/cdn/shop/files/seed_packets.jpg?v=1668690089", ), Product( id = 4, name = "Irrigation System", description = "Advanced irrigation system designed to deliver precise and efficient watering for crops. Features customizable settings and durable construction for long-term use.", stock = 30, price = 299.99f, image = "https://www.watercalculator.org/wp-content/uploads/2017/04/iStock_000010933844_1950.jpg", ), Product( id = 5, name = "Tractor", description = "Powerful tractor equipped with cutting-edge technology for various farm operations. Offers unmatched performance, reliability, and versatility in agricultural tasks.", stock = 10, price = 15000f, image = "https://www.profi.co.uk/wp-content/uploads/sites/8/2022/01/8a._jd_7r330_ap.jpg", ), Product( id = 6, name = "Herbicide", description = "Herbicide specially formulated to control weeds effectively without harming crops or the environment. Provides targeted action for weed management in fields and gardens.", stock = 50, price = 18.75f, image = "https://www.agriplexindia.com/cdn/shop/collections/Herbicides.png?crop=center&height=500&v=1673857391&width=600", ), Product( id = 7, name = "Mulch", description = "Organic mulch made from natural materials to improve soil health and moisture retention. Helps suppress weeds, regulate soil temperature, and promote healthy plant growth.", stock = 120, price = 5.99f, image = "https://www.thespruce.com/thmb/GNryY_TSnuf_2aQ04mODi7yI58w=/4832x0/filters:no_upscale():max_bytes(150000):strip_icc()/SPR-is-dyed-mulch-safe-to-use-2131983-hero-0aef1a51041046e99d27a83b65c19f88.jpg", ), Product( id = 8, name = "Fencing", description = "Durable fencing solution designed to protect crops and livestock from unwanted intruders. Constructed from high-quality materials for strength, durability, and longevity.", stock = 40, price = 199.99f, image = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ-Qjgj92EQ30TwzCMCGN1fbCkBXTAySv80fA&usqp=CAU", ), Product( id = 9, name = "Solar Panels", description = "Solar panels harnessing renewable energy from the sun to power farm operations. Provides clean, sustainable energy for reducing electricity costs and environmental impact.", stock = 15, price = 999.99f, image = "https://cdn.britannica.com/91/222691-050-E8BDF226/installing-solar-panels.jpg", ), Product( id = 10, name = "Greenhouse Kit", description = "Complete greenhouse kit for creating a controlled environment for optimal plant growth. Features include adjustable ventilation, sturdy frame, and UV-resistant covering.", stock = 5, price = 4999.99f, image = "https://growerssolution.com/cdn/shop/files/Untitleddesign-105_1200x.png?v=1698764945", ), Product( id = 11, name = "Livestock Feed", description = "Nutritious feed formulated to meet the dietary needs of livestock for growth, health, and productivity. Contains essential vitamins, minerals, and proteins for balanced nutrition.", stock = 150, price = 12.49f, image = "https://www.partnersinfoodsolutions.com/sites/default/files/styles/blog_post/public/blog-images/IMG_6231.jpg?itok=S1B-mZGw", ), Product( id = 12, name = "Crop Protection Net", description = "Durable netting designed to protect crops from birds, pests, and harsh weather conditions. Provides reliable protection while allowing air circulation and sunlight penetration.", stock = 60, price = 29.99f, image = "https://m.media-amazon.com/images/I/61YeSepWIsL._AC_UF1000,1000_QL80_.jpg", ), Product( id = 13, name = "Soil Moisture Meter", description = "Precision soil moisture meter for accurate measurement of moisture levels in the soil. Helps optimize irrigation scheduling and prevent under or over-watering of crops.", stock = 25, price = 49.99f, image = "https://cdn11.bigcommerce.com/s-625n27otji/images/stencil/1280x1280/products/1644/2660/ph-moisture-meter-1__41741.1639395104.jpg?c=1", ), Product( id = 14, name = "Weather Station", description = "Advanced weather monitoring station for tracking temperature, humidity, rainfall, wind speed, and other meteorological parameters. Provides real-time data for informed farming decisions.", stock = 8, price = 299.99f, image = "https://store.wildernesslabs.co/cdn/shop/products/IMG_3586_1024x1024@2x.jpg?v=1684531864", ), Product( id = 15, name = "Drip Irrigation Kit", description = "Efficient drip irrigation kit for delivering water directly to the root zone of plants. Reduces water wastage, promotes healthier plants, and conserves water resources.", stock = 20, price = 99.99f, image = "https://m.media-amazon.com/images/I/81WA-RhHvcL._SL1500_.jpg", ), Product( id = 16, name = "Hand Tools Set", description = "Comprehensive set of hand tools for various farming tasks including digging, planting, pruning, and weeding. Made from durable materials for long-lasting performance.", stock = 100, price = 79.99f, image = "https://pictures-kenya.jijistatic.com/6868812_s-l1600-1_620x620.jpg", ), Product( id = 17, name = "Planting Trays", description = "Sturdy planting trays designed for seed starting and propagation. Features multiple cells for organizing seeds and promoting healthy root development in young plants.", stock = 80, price = 6.99f, image = "https://makimara.co.ke/wp-content/uploads/2023/02/seedling-trays-in-kenya.jpg", ), Product( id = 18, name = "Agricultural Sprayer", description = "Versatile agricultural sprayer for applying pesticides, fertilizers, and herbicides to crops. Offers adjustable spray patterns, ergonomic design, and efficient operation.", stock = 35, price = 129.99f, image = "https://www.deere.co.uk/assets/images/region-2/products/sprayers/john-deere-self-propelled-sprayer-wheat.jpg", ), Product( id = 19, name = "Grow Lights", description = "Energy-efficient LED grow lights for indoor farming and greenhouse cultivation. Mimics natural sunlight to promote photosynthesis and healthy growth of plants.", stock = 10, price = 149.99f, image = "https://assets.wfcdn.com/im/70729900/compr-r85/1752/175214516/yescom-grow-light.jpg", ), Product( id = 20, name = "Compost Bin", description = "Durable compost bin for recycling organic waste into nutrient-rich compost for soil improvement. Features easy-to-use design and proper aeration for efficient composting. Ideal for sustainable waste management and enhancing soil fertility.", stock = 25, price = 39.99f, image = "https://www.planetnatural.com/wp-content/uploads/2023/01/compost-tumbler.jpg", ), ) } /** * Interface representing the seeding of products into the FarmersDB database. * * This interface defines a method for adding products to the database asynchronously. */ interface IProductsSeed { /** * Asynchronously adds products to the database. */ suspend fun addProducts() } /** * Implementation of the [IProductsSeed] interface for seeding products into the FarmersDB database. * * This class initializes the database helper and provides the functionality to add products to the database. * * @param dbHelper The database helper instance for accessing the database. * @param dao The Data Access Object (DAO) for product-related database operations. */ class ProductsSeed( dbHelper: AppDatabaseHelper, private val dao: ProductDao, ) : IProductsSeed { /** * Initializes the FarmersDBSeed instance by refreshing the database. * * @param dbHelper The database helper instance for accessing the database. */ init { dbHelper.refresh(dbHelper.writableDatabase) } /** * Asynchronously adds products to the database by iterating over the list of products in the [DBSeed.productList]. * * This method maps each product in the [DBSeed.productList] to the database DAO's create method and collects the results asynchronously. */ override suspend fun addProducts() { // Map each product in the DBSeed.productList to the DAO's create method and collect the results asynchronously DBSeed.productList.map { dao.create(it) }.forEach { it.collect() } } }
0
Kotlin
0
0
5c74fa9163d77354dc5373dd31bcd4889bf9fc5e
11,852
FarmersFirst
MIT License
src/main/kotlin/eu/chainfire/kjs/sharedmemory/Atomics.kt
Chainfire
286,034,665
false
null
import eu.chainfire.kjs.sharedmemory.SharedArrayBuffer import org.khronos.webgl.ArrayBufferView import org.khronos.webgl.Int32Array external class Atomics { companion object { fun add(typedArray: ArrayBufferView, index: Int, value: Int): Int fun and(typedArray: ArrayBufferView, index: Int, value: Int): Int fun compareExchange(typedArray: ArrayBufferView, index: Int, expectedValue: Int, replacementValue: Int): Int fun exchange(typedArray: ArrayBufferView, index: Int, value: Int): Int fun isLockFree(size: Int): Boolean fun load(typedArray: ArrayBufferView, index: Int): Int fun notify(typedArray: Int32Array, index: Int, count: Int = definedExternally): Int fun or(typedArray: ArrayBufferView, index: Int, value: Int): Int fun store(typedArray: ArrayBufferView, index: Int, value: Int): Int fun sub(typedArray: ArrayBufferView, index: Int, value: Int): Int fun wait(typedArray: Int32Array, index: Int, value: Int, timeout: Int = definedExternally): String fun xor(typedArray: ArrayBufferView, index: Int, value: Int): Int } } inline fun Atomics.Companion.isSupported(): Boolean = js("typeof Atomics != 'undefined'").unsafeCast<Boolean>()
0
Kotlin
1
11
f23a3cc1f8d3c4c2f1a8404d3287d2f01dfa0aef
1,248
kotlin-js-sharedmemory
Apache License 2.0
src/main/kotlin/other_contests/company/dwacon/2016-a.kt
kirimin
197,707,422
false
null
package other_contests.company.dwacon import java.util.* fun main(args: Array<String>) { val sc = Scanner(System.`in`) val n = sc.nextLong() println(problem2016a(n)) } fun problem2016a(n: Long): Long { return (n / 25L) }
0
Kotlin
1
5
87f20b4aa2031c130867c546dd5533890f1978ee
239
AtCoderLog
The Unlicense
src/main/services/user_account/GetUserAccountService.kt
ncent-archive
150,326,270
false
{"Kotlin": 352866, "JavaScript": 7544, "Makefile": 563, "Shell": 222}
package main.services.user_account import kotlinserverless.framework.services.SOAResult import main.daos.* import framework.services.DaoService import kotlinserverless.framework.models.NotFoundException import org.jetbrains.exposed.sql.select object GetUserAccountService { fun execute(userId: Int? = null, email: String? = null, apiKey: String? = null): SOAResult<UserAccount> { return DaoService.execute { try { when { apiKey != null -> { val query = UserAccounts .innerJoin(ApiCreds) .select { ApiCreds.apiKey eq apiKey } UserAccount.wrapRows(query).toList().distinct().first() } userId != null -> { UserAccount.findById(userId)!! } email != null -> { val query = UserAccounts .innerJoin(Users) .select { Users.email eq email } UserAccount.wrapRows(query).toList().distinct().first() } else -> { throw NotFoundException() } } } catch(e: NoSuchElementException) { throw NotFoundException() } } } }
16
Kotlin
2
2
802160f3332c4b6d63d4219067848e38a689c48b
1,577
ncent-api-v2
MIT License
app/src/main/java/de/eliteschw31n/moonrakerremote/MainActivity.kt
eliteSchwein
356,925,596
false
null
package de.eliteschw31n.moonrakerremote import android.content.Context import android.os.Bundle import android.view.Menu import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import androidx.drawerlayout.widget.DrawerLayout import androidx.fragment.app.FragmentManager import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import androidx.navigation.ui.setupWithNavController import com.google.android.material.navigation.NavigationView import de.eliteschw31n.moonrakerremote.tasks.WebsocketTask import de.eliteschw31n.moonrakerremote.utils.LocalDatabase import de.eliteschw31n.moonrakerremote.utils.NavTitles import de.eliteschw31n.moonrakerremote.utils.NotificationUtil class MainActivity : AppCompatActivity() { init { instance = this } companion object { private var instance: MainActivity? = null fun applicationContext() : Context { return instance!!.applicationContext } fun runUiUpdate(task: Runnable) { instance!!.runOnUiThread(task) } fun supportFragmentManager() : FragmentManager { return instance!!.supportFragmentManager } } private lateinit var appBarConfiguration: AppBarConfiguration override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) NotificationUtil.registerChannels() LocalDatabase.readData() val toolbar: Toolbar = findViewById(R.id.toolbar) setSupportActionBar(toolbar) val drawerLayout: DrawerLayout = findViewById(R.id.drawer_layout) val navView: NavigationView = findViewById(R.id.nav_view) val printers = LocalDatabase.getData().getJSONObject("printers") val currentPrinter = LocalDatabase.getData().getString("currentPrinter") val currentPrinterJson = printers.getJSONObject(currentPrinter) WebsocketTask.connect(currentPrinterJson.getString("websocketurl")) NavTitles.setNavView(navView) NavTitles.updateTitle(currentPrinter) NavTitles.updateSubTitle(currentPrinterJson.getString("websocketurl")) val navController = findNavController(R.id.nav_host_fragment) // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. appBarConfiguration = AppBarConfiguration(setOf( R.id.nav_dashboard, R.id.nav_webcam, R.id.nav_printer_menu, R.id.nav_settings), drawerLayout) setupActionBarWithNavController(navController, appBarConfiguration) navView.setupWithNavController(navController) } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.main, menu) return true } override fun onSupportNavigateUp(): Boolean { val navController = findNavController(R.id.nav_host_fragment) return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp() } }
10
Kotlin
0
2
567beb34534ad9e0a21dee59b47bb633a94d5805
3,277
moonraker-remote-android
MIT License
app/src/main/java/com/ucsm/tylersai/amsteacher/ui/activity/AddSubjectDeanActivity.kt
hanlinag
290,556,091
false
{"Kotlin": 272592, "Java": 421, "Assembly": 9}
package com.ucsm.tylersai.amsteacher.ui.activity import android.app.ProgressDialog import android.content.DialogInterface import android.os.Bundle import android.view.Menu import android.view.MenuItem import android.view.View import android.widget.* import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import com.ucsm.tylersai.amsteacher.R import com.ucsm.tylersai.amsteacher.model.Subject class AddSubjectDeanActivity : AppCompatActivity() { private lateinit var edtSubjectCode: EditText private lateinit var edtSubjectName: EditText private lateinit var edtSubjectRoom: EditText private lateinit var edtSubjectTeacherId: EditText lateinit var spinnerDayOfWeek1: Spinner lateinit var spinnerStartHour1: Spinner lateinit var spinnerEndHour1: Spinner lateinit var spinnerDayOfWeek2: Spinner lateinit var spinnerStartHour2: Spinner lateinit var spinnerEndHour2: Spinner lateinit var spinnerDayOfWeek3: Spinner lateinit var spinnerStartHour3: Spinner lateinit var spinnerEndHour3: Spinner lateinit var spinnerDayOfWeek4: Spinner lateinit var spinnerStartHour4: Spinner lateinit var spinnerEndHour4: Spinner lateinit var spinnerDayOfWeek5: Spinner lateinit var spinnerStartHour5: Spinner lateinit var spinnerEndHour5: Spinner var subjectOfDayOfWeek1 = "" var startTime1 = "" var endTime1 = "" var subjectOfDayOfWeek2 = "" var startTime2 = "" var endTime2 = "" var subjectOfDayOfWeek3 = "" var startTime3 = "" var endTime3 = "" var subjectOfDayOfWeek4 = "" var startTime4 = "" var endTime4 = "" var subjectOfDayOfWeek5 = "" var startTime5 = "" var endTime5 = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_add_subject_dean) supportActionBar!!.title = "Add Subject" supportActionBar!!.setDisplayHomeAsUpEnabled(true) edtSubjectCode = findViewById(R.id.edt_subject_code_add_subject_dean) edtSubjectName = findViewById(R.id.edt_subject_name_add_subject_dean) edtSubjectRoom = findViewById(R.id.edt_subject_room_add_subject_dean) edtSubjectTeacherId = findViewById(R.id.edt_subject_teacher_id_add_subject_dean) spinnerDayOfWeek1 = findViewById(R.id.spinner_subject_day_add_subject_dean1) spinnerStartHour1 = findViewById(R.id.spinner_subject_start_time_add_subject_dean1) spinnerEndHour1 = findViewById(R.id.spinner_subject_end_time_add_subject_dean1) val spinnerDayofWeekAdapter1 = ArrayAdapter.createFromResource( applicationContext, R.array.day_of_week, android.R.layout.simple_expandable_list_item_1 ) spinnerDayofWeekAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerDayOfWeek1.adapter = spinnerDayofWeekAdapter1 spinnerDayOfWeek1.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { subjectOfDayOfWeek1 = spinnerDayOfWeek1.selectedItem.toString() } }//end of listener val spinnerStartHourAdapter1 = ArrayAdapter.createFromResource( applicationContext, R.array.time_of_day, android.R.layout.simple_expandable_list_item_1 ) spinnerStartHourAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerStartHour1.adapter = spinnerStartHourAdapter1 spinnerStartHour1.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { startTime1 = spinnerStartHour1.selectedItem.toString() } }//end of listener val spinnerEndHourAdapter1 = ArrayAdapter.createFromResource( applicationContext, R.array.time_of_day, android.R.layout.simple_expandable_list_item_1 ) spinnerEndHourAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerEndHour1.adapter = spinnerEndHourAdapter1 spinnerEndHour1.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { endTime1 = spinnerEndHour1.selectedItem.toString() } }//end of listener //-------------------------------------- spinnerDayOfWeek2 = findViewById(R.id.spinner_subject_day_add_subject_dean2) spinnerStartHour2 = findViewById(R.id.spinner_subject_start_time_add_subject_dean2) spinnerEndHour2 = findViewById(R.id.spinner_subject_end_time_add_subject_dean2) val spinnerDayofWeekAdapter2 = ArrayAdapter.createFromResource( applicationContext, R.array.day_of_week, android.R.layout.simple_expandable_list_item_1 ) spinnerDayofWeekAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerDayOfWeek2.adapter = spinnerDayofWeekAdapter2 spinnerDayOfWeek2.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { subjectOfDayOfWeek2 = spinnerDayOfWeek2.selectedItem.toString() } }//end of listener val spinnerStartHourAdapter2 = ArrayAdapter.createFromResource( applicationContext, R.array.time_of_day, android.R.layout.simple_expandable_list_item_1 ) spinnerStartHourAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerStartHour2.adapter = spinnerStartHourAdapter2 spinnerStartHour2.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { startTime2 = spinnerStartHour2.selectedItem.toString() } }//end of listener val spinnerEndHourAdapter2 = ArrayAdapter.createFromResource( applicationContext, R.array.time_of_day, android.R.layout.simple_expandable_list_item_1 ) spinnerEndHourAdapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerEndHour2.adapter = spinnerEndHourAdapter2 spinnerEndHour2.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { endTime2 = spinnerEndHour2.selectedItem.toString() } }//end of listener //--------------------------------- spinnerDayOfWeek3 = findViewById(R.id.spinner_subject_day_add_subject_dean3) spinnerStartHour3 = findViewById(R.id.spinner_subject_start_time_add_subject_dean3) spinnerEndHour3 = findViewById(R.id.spinner_subject_end_time_add_subject_dean3) val spinnerDayofWeekAdapter3 = ArrayAdapter.createFromResource( applicationContext, R.array.day_of_week, android.R.layout.simple_expandable_list_item_1 ) spinnerDayofWeekAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerDayOfWeek3.adapter = spinnerDayofWeekAdapter3 spinnerDayOfWeek3.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { subjectOfDayOfWeek3 = spinnerDayOfWeek3.selectedItem.toString() } }//end of listener val spinnerStartHourAdapter3 = ArrayAdapter.createFromResource( applicationContext, R.array.time_of_day, android.R.layout.simple_expandable_list_item_1 ) spinnerStartHourAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerStartHour3.adapter = spinnerStartHourAdapter3 spinnerStartHour3.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { startTime3 = spinnerStartHour3.selectedItem.toString() } }//end of listener val spinnerEndHourAdapter3 = ArrayAdapter.createFromResource( applicationContext, R.array.time_of_day, android.R.layout.simple_expandable_list_item_1 ) spinnerEndHourAdapter3.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerEndHour3.adapter = spinnerEndHourAdapter3 spinnerEndHour3.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { endTime3 = spinnerEndHour3.selectedItem.toString() } }//end of listener //--------------------------------- spinnerDayOfWeek4 = findViewById(R.id.spinner_subject_day_add_subject_dean4) spinnerStartHour4 = findViewById(R.id.spinner_subject_start_time_add_subject_dean4) spinnerEndHour4 = findViewById(R.id.spinner_subject_end_time_add_subject_dean4) val spinnerDayofWeekAdapter4 = ArrayAdapter.createFromResource( applicationContext, R.array.day_of_week, android.R.layout.simple_expandable_list_item_1 ) spinnerDayofWeekAdapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerDayOfWeek4.adapter = spinnerDayofWeekAdapter4 spinnerDayOfWeek4.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { subjectOfDayOfWeek4 = spinnerDayOfWeek4.selectedItem.toString() } }//end of listener val spinnerStartHourAdapter4 = ArrayAdapter.createFromResource( applicationContext, R.array.time_of_day, android.R.layout.simple_expandable_list_item_1 ) spinnerStartHourAdapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerStartHour4.adapter = spinnerStartHourAdapter4 spinnerStartHour4.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { startTime4 = spinnerStartHour4.selectedItem.toString() } }//end of listener val spinnerEndHourAdapter4 = ArrayAdapter.createFromResource( applicationContext, R.array.time_of_day, android.R.layout.simple_expandable_list_item_1 ) spinnerEndHourAdapter4.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerEndHour4.adapter = spinnerEndHourAdapter4 spinnerEndHour4.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { endTime4 = spinnerEndHour4.selectedItem.toString() } }//end of listener //-------------------------------- spinnerDayOfWeek5 = findViewById(R.id.spinner_subject_day_add_subject_dean5) spinnerStartHour5 = findViewById(R.id.spinner_subject_start_time_add_subject_dean5) spinnerEndHour5 = findViewById(R.id.spinner_subject_end_time_add_subject_dean5) val spinnerDayofWeekAdapter5 = ArrayAdapter.createFromResource( applicationContext, R.array.day_of_week, android.R.layout.simple_expandable_list_item_1 ) spinnerDayofWeekAdapter5.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerDayOfWeek5.adapter = spinnerDayofWeekAdapter5 spinnerDayOfWeek5.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { subjectOfDayOfWeek5 = spinnerDayOfWeek5.selectedItem.toString() } }//end of listener val spinnerStartHourAdapter5 = ArrayAdapter.createFromResource( applicationContext, R.array.time_of_day, android.R.layout.simple_expandable_list_item_1 ) spinnerStartHourAdapter5.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerStartHour5.adapter = spinnerStartHourAdapter5 spinnerStartHour5.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { startTime5 = spinnerStartHour5.selectedItem.toString() } }//end of listener val spinnerEndHourAdapter5 = ArrayAdapter.createFromResource( applicationContext, R.array.time_of_day, android.R.layout.simple_expandable_list_item_1 ) spinnerEndHourAdapter5.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinnerEndHour5.adapter = spinnerEndHourAdapter5 spinnerEndHour5.onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(p0: AdapterView<*>?) { } override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) { endTime5 = spinnerEndHour5.selectedItem.toString() } }//end of listener } override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_add_subject_dean, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> { finish() } R.id.menu_add_subject_dean_add -> { val subjectCode = edtSubjectCode.text.toString() val subjectName = edtSubjectName.text.toString() val subjectRoom = edtSubjectRoom.text.toString() val subjectTeacherId = edtSubjectTeacherId.text.toString() //check if empty if (subjectCode.isEmpty() || subjectName.isEmpty() || subjectRoom.isEmpty() || subjectTeacherId.isEmpty()) { AlertDialog.Builder(this) .setTitle("Error") .setMessage("Form not complete!") .setPositiveButton( "Ok", DialogInterface.OnClickListener { dialogInterface, i -> dialogInterface.dismiss() }) .show() } else if (startTime1 == "0" && startTime2 == "0" && startTime3 == "0" && startTime4 == "0" && startTime5 == "0" && endTime1 == "0" && endTime2 == "0" && endTime3 == "0" && endTime4 == "0" && endTime5 == "0" ) { AlertDialog.Builder(this) .setTitle("Error") .setMessage("Day & Time interval not selected!") .setPositiveButton( "Ok" ) { dialogInterface, i -> dialogInterface.dismiss() } .show() } else { //do actual job var finalday = "" var finalTime = "" if (startTime1 == "0" && endTime1 == "0") { subjectOfDayOfWeek1 = "" startTime1 = "" endTime1 = "" } else { finalday = "$finalday, $subjectOfDayOfWeek1" finalTime = "$finalTime, $startTime1-$endTime1" } if (startTime2 == "0" && endTime2 == "0") { subjectOfDayOfWeek2 = "" startTime2 = "" endTime2 = "" } else { finalday = "$finalday, $subjectOfDayOfWeek2" finalTime = "$finalTime, $startTime2-$endTime2" } if (startTime3 == "0" && endTime3 == "0") { subjectOfDayOfWeek3 = "" startTime3 = "" endTime3 = "" } else { finalday = "$finalday, $subjectOfDayOfWeek3" finalTime = "$finalTime, $startTime3-$endTime3" } if (startTime4 == "0" && endTime4 == "0") { subjectOfDayOfWeek4 = "" startTime4 = "" endTime4 = "" } else { finalday = "$finalday, $subjectOfDayOfWeek4" finalTime = "$finalTime, $startTime4-$endTime4" } if (startTime5 == "0" && endTime5 == "0") { subjectOfDayOfWeek5 = "" startTime5 = "" endTime5 = "" } else { finalday = "$finalday, $subjectOfDayOfWeek5" finalTime = "$finalTime, $startTime5-$endTime5" } finalday = finalday.substring(2) finalTime = finalTime.substring(2) AlertDialog.Builder(this) .setTitle("Confirmation") .setMessage("Are you sure you want to add this subject to database?\nSubject Code: $subjectCode\nSubject Name: $subjectName\nRoom: $subjectRoom\nTeacher ID: $subjectTeacherId\nDay: $finalday\nTime: $finalTime") .setNegativeButton( "Cancel" ) { dialogInterface, i -> dialogInterface.dismiss() } .setPositiveButton("Add") { dialogInterface, i -> dialogInterface.dismiss() val progressDialog = ProgressDialog(this) progressDialog.setMessage("Loading...") progressDialog.show() //subject table val subjectTable = FirebaseDatabase.getInstance().reference.child("ams") .child("subject") subjectTable.child(subjectCode) .addListenerForSingleValueEvent(object : ValueEventListener { override fun onCancelled(p0: DatabaseError) { Toast.makeText( this@AddSubjectDeanActivity, "Error occurred ${p0.message}", Toast.LENGTH_LONG ).show() } override fun onDataChange(dataSnapshot: DataSnapshot) { if (!dataSnapshot.exists()) { //add subject to database val subTable = FirebaseDatabase.getInstance().reference.child("ams") .child("subject") val subjectObj = Subject( finalday, subjectName, subjectRoom, subjectCode, subjectTeacherId, finalTime ) subTable.child(subjectCode).setValue(subjectObj) progressDialog.dismiss() Toast.makeText( this@AddSubjectDeanActivity, "Subject added to database!", Toast.LENGTH_LONG ).show() finish() } else { progressDialog.dismiss() Toast.makeText( this@AddSubjectDeanActivity, "Already exist!", Toast.LENGTH_LONG ) .show() } } }) } .show() } } } return super.onOptionsItemSelected(item) } }
0
Kotlin
2
4
2ea4e1408c3b74d89f4a9594a6e81994715f958b
23,224
ams-teacher
MIT License
src/main/kotlin/us/jwf/aoc2020/Day20JurassicJigsaw.kt
jasonwyatt
318,073,137
false
null
package us.jwf.aoc2020 import java.io.Reader import java.util.* import kotlin.collections.HashSet import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.collect import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.firstOrNull import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.mapNotNull import kotlinx.coroutines.flow.toList import kotlinx.coroutines.flow.transform import us.jwf.aoc.Day import us.jwf.aoc.product import us.jwf.aoc.toLineFlow /** * Day 20 of AoC 2020 */ class Day20JurassicJigsaw : Day<Long, Long> { override suspend fun executePart1(input: Reader): Long { val tiles = input.toTileFlow().toList() val matchCounts = mutableMapOf<Int, List<Long>>() tiles.forEach { first -> var matches = 0 var matchedTiles = 0 tiles.forEach inner@{ second -> if (first == second) return@inner matches += first.matchTo(second).count().also { if (it > 0) matchedTiles++ } } matchCounts[matchedTiles] = (matchCounts[matchedTiles] ?: emptyList()) + listOf(first.id) } return matchCounts[2]!!.product() } override suspend fun executePart2(input: Reader): Long { val tiles = input.toTileFlow().toList() val matchCounts = mutableMapOf<Int, List<Tile>>() tiles.forEach { first -> var matches = 0 var matchedTiles = 0 tiles.forEach inner@{ second -> if (first == second) return@inner matches += first.matchTo(second).count().also { if (it > 0) matchedTiles++ } } matchCounts[matchedTiles] = (matchCounts[matchedTiles] ?: emptyList()) + listOf(first) } // Corners are at matchCounts[2].. start at corner where we can find a right and a bottom. val imageTiles = mutableListOf<MutableList<Tile>>() imageTiles.add(mutableListOf()) val unvisitedTiles: MutableSet<Tile> = HashSet(tiles) var currentTile: Tile? = matchCounts[2]?.find { tile -> val hasRight = tiles.find { other -> tile != other && tile.matchRightTo(other) != null } != null val hasBottom = tiles.find { other -> tile != other && tile.matchBottomTo(other) != null } != null hasBottom && hasRight } while (currentTile != null) { unvisitedTiles.remove(currentTile) imageTiles.last().add(currentTile) val rightTile = unvisitedTiles.mapNotNull { currentTile!!.matchRightTo(it) }.firstOrNull() if (rightTile == null) { val firstOfThisRow = imageTiles.last().first() currentTile = unvisitedTiles .mapNotNull { firstOfThisRow.matchBottomTo(it) } .firstOrNull() if (currentTile != null) { imageTiles.add(mutableListOf()) } } else { currentTile = rightTile } } val tileSize = imageTiles[0][0].image.size val imageDimension = imageTiles.size * (tileSize - 2) val image = Array(imageDimension) { row -> BooleanArray(imageDimension) { col -> val tileRow = row / (tileSize - 2) val tilePixelRow = row % (tileSize - 2) + 1 val tileCol = col / (tileSize - 2) val tilePixelCol = col % (tileSize - 2) + 1 imageTiles[tileRow][tileCol].image[tilePixelRow][tilePixelCol] } } val monster = """ | # |# ## ## ### | # # # # # # """.trimMargin() .split("\n") .map { it.map { c -> c == '#' }.toBooleanArray() } .toTypedArray() val monsterTile = Tile(-1L, monster) val imageTile = Tile(-1L, image) val imageFilled = image.sumBy { row -> row.sumBy { if (it) 1 else 0 } } return monsterTile.orientations .mapNotNull { m -> var monstersCounted = 0 for (rowOffset in 0 until (imageDimension - m.rows)) { for (colOffset in 0 until (imageDimension - m.cols)) { if (imageTile.contains(m, rowOffset, colOffset)) monstersCounted++ } } if (monstersCounted > 0) { imageFilled - monstersCounted * 15L } else null } .toList() .maxByOrNull { it }!! } data class Tile(val id: Long, val image: Array<BooleanArray>) { val rows: Int get() = image.size val cols: Int get() = image[0].size val orientations: Flow<Tile> = flow { emit(this@Tile) rotate().also { emit(it) } .rotate().also { emit(it) } .rotate().also { emit(it) } val horizontalFlip = flipHorizontal() emit(horizontalFlip) horizontalFlip.rotate().also { emit(it) } .rotate().also { emit(it) } .rotate().also { emit(it) } val verticalFlip = flipVertical() emit(verticalFlip) verticalFlip.rotate().also { emit(it) } .rotate().also { emit(it) } .rotate().also { emit(it) } val bothFlip = flipVertical().flipHorizontal() emit(bothFlip) bothFlip.rotate().also { emit(it) } .rotate().also { emit(it) } .rotate().also { emit(it) } } fun contains(smaller: Tile, offsetRow: Int, offsetCol: Int): Boolean { for (smallerRow in 0 until smaller.rows) { for (smallerCol in 0 until smaller.cols) { if (smaller.image[smallerRow][smallerCol] && !image[smallerRow + offsetRow][smallerCol + offsetCol]) { return false } } } return true } fun rotate(): Tile { // Rotate 90 degrees to the left. // Rows become Columns. val nextArray = Array(image[0].size) { BooleanArray(image.size) { false } } image.indices.forEach { rowIndex -> image[rowIndex].indices.forEach { colIndex -> nextArray[colIndex][rowIndex] = image[rowIndex][colIndex] } } return Tile(id, nextArray) } fun flipVertical(): Tile { val nextArray = Array(image.size) { BooleanArray(image[0].size) { false } } image.indices.forEach { rowIndex -> image[rowIndex].indices.forEach { colIndex -> nextArray[nextArray.size - 1 - rowIndex][colIndex] = image[rowIndex][colIndex] } } return Tile(id, nextArray) } fun flipHorizontal(): Tile { val nextArray = Array(image.size) { BooleanArray(image[0].size) { false } } image.indices.forEach { rowIndex -> image[rowIndex].indices.forEach { colIndex -> nextArray[rowIndex][nextArray[rowIndex].size - 1 - colIndex] = image[rowIndex][colIndex] } } return Tile(id, nextArray) } fun topMatchesBottomOf(other: Tile): Boolean { return image[0].withIndex().all { (col, value) -> other.image[other.image.size - 1][col] == value } } fun bottomMatchesTopOf(other: Tile): Boolean = other.topMatchesBottomOf(this) fun rightMatchesLeftOf(other: Tile): Boolean { return image.indices.all { rowIndex -> other.image[rowIndex][0] == image[rowIndex][image[rowIndex].size - 1] } } fun leftMatchesRightOf(other: Tile): Boolean = other.rightMatchesLeftOf(this) suspend fun matchRightTo(other: Tile): Tile? { return other.orientations .filter { rightMatchesLeftOf(it) } .firstOrNull() } suspend fun matchBottomTo(other: Tile): Tile? { return other.orientations .filter { bottomMatchesTopOf(it) } .firstOrNull() } suspend fun matchTo(other: Tile): List<Tile> { return other.orientations .transform { orientation -> if ( rightMatchesLeftOf(orientation) || leftMatchesRightOf(orientation) || topMatchesBottomOf(orientation) || bottomMatchesTopOf(orientation) ) emit(orientation) } .toList() } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as Tile if (id != other.id) return false return true } override fun hashCode(): Int = id.hashCode() override fun toString(): String { return "$id" } } private fun Reader.toTileFlow(): Flow<Tile> { return flow { var id: Long = -1 var rows = mutableListOf<BooleanArray>() this@toTileFlow.toLineFlow() .collect { line -> val titleMatch = ID_PATTERN.matchEntire(line) if (titleMatch != null) { id = titleMatch.groupValues[1].toLong(10) } else if (line.isNotEmpty()) { rows.add(line.map { it == '#' }.toBooleanArray()) } else { emit(Tile(id, rows.toTypedArray())) id = -1 rows = mutableListOf() } } if (id != -1L) { emit(Tile(id, rows.toTypedArray())) } } } companion object { private val ID_PATTERN = Regex("Tile ([0-9]+):") } }
0
Kotlin
0
0
60282b121bec6b845a74507960934a03a9153178
8,831
AdventOfCode-Kotlin
Apache License 2.0
kzen-auto-js/src/main/kotlin/tech/kzen/auto/client/service/global/SessionState.kt
alexoooo
131,353,826
false
null
package tech.kzen.auto.client.service.global import tech.kzen.auto.client.util.NavigationRoute import tech.kzen.auto.common.paradigm.imperative.model.ImperativeModel import tech.kzen.lib.common.model.definition.GraphDefinitionAttempt import tech.kzen.lib.common.model.document.DocumentPath import tech.kzen.lib.common.model.structure.GraphStructure data class SessionState( val graphDefinitionAttempt: GraphDefinitionAttempt, val navigationRoute: NavigationRoute, val imperativeModel: ImperativeModel?, val activeHost: DocumentPath?, val runningHosts: Set<DocumentPath> ) { // fun activeHost(): DocumentPath? { // return imperativeModel?.frames?.get(0)?.path // } fun graphStructure(): GraphStructure { return graphDefinitionAttempt.graphStructure } }
0
Kotlin
0
1
498c920e50ec1461cd936ce5f553bb1c33924138
806
kzen-auto
MIT License
app/src/main/java/com/cornellappdev/uplift/ui/screens/LandingScreen.kt
cuappdev
596,747,757
false
{"Kotlin": 350256}
package com.cornellappdev.uplift.ui.screens import androidx.compose.animation.Crossfade import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue import androidx.compose.ui.platform.LocalContext import androidx.lifecycle.viewmodel.compose.viewModel import androidx.navigation.NavHostController import com.cornellappdev.uplift.models.LocationRepository import com.cornellappdev.uplift.networking.ApiResponse import com.cornellappdev.uplift.ui.screens.subscreens.MainError import com.cornellappdev.uplift.ui.screens.subscreens.MainLoaded import com.cornellappdev.uplift.ui.screens.subscreens.MainLoading import com.cornellappdev.uplift.ui.viewmodels.ClassDetailViewModel import com.cornellappdev.uplift.ui.viewmodels.GymDetailViewModel import com.cornellappdev.uplift.ui.viewmodels.HomeViewModel import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.rememberMultiplePermissionsState import com.valentinilk.shimmer.Shimmer import kotlinx.coroutines.delay import android.util.Log import androidx.compose.foundation.Image import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.paddingFromBaseline import androidx.compose.foundation.layout.width import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.vectorResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import com.cornellappdev.uplift.R import com.google.accompanist.systemuicontroller.SystemUiController import com.google.accompanist.systemuicontroller.rememberSystemUiController /** * The landing page during the Uplift onboarding process. */ @OptIn(ExperimentalPermissionsApi::class) @Composable fun LandingScreen() { val systemUiController: SystemUiController = rememberSystemUiController() systemUiController.isStatusBarVisible = false systemUiController.isNavigationBarVisible = false // Navigation bar systemUiController.isSystemBarsVisible = false Box( modifier = Modifier .fillMaxSize() ) { Image( painter = painterResource(id = R.drawable.ic_main_logo), contentDescription = "Uplift logo", modifier = Modifier .offset(y = (-100).dp) .height(130.dp) .width(115.dp) .align(Alignment.Center) ) Spacer(modifier = Modifier.height(387.dp)); Image( painter = painterResource(id = R.drawable.ic_appdev_logo), contentDescription = "Cornell AppDev logo", modifier = Modifier .align(Alignment.BottomCenter) .paddingFromBaseline(bottom = 80.dp) .height(26.dp) .width(158.dp) ) } }
10
Kotlin
0
1
b05cf506e5da872597bab691b1b2232b02c7bb18
3,383
uplift-android
MIT License
app/src/main/java/com/safframework/delegate/prefs/PrefsHelper.kt
fengzhizi715
136,885,430
false
null
package com.safframework.delegate.prefs import android.content.SharedPreferences /** * * @FileName: * com.safframework.delegate.prefs.PrefsHelper.java * @author: <NAME> * @date: 2018-06-28 23:43 * @version V1.0 <描述当前版本功能> */ class PrefsHelper(prefs: SharedPreferences) { var name by prefs.string("name") var password by prefs.string("<PASSWORD>") var age by prefs.int("age") var isForeigner by prefs.boolean("isForeigner") }
0
Kotlin
9
46
16aa67ec5a3745326824e28176695e3c0dbf9075
462
SAF-Object-Delegate
Apache License 2.0
kotlin_practice/src/main/java/dev/vengateshm/kotlin_practice/programs/StackImpl.kt
vengateshm
670,054,614
false
{"Kotlin": 1233929, "Java": 28903}
package dev.vengateshm.kotlin_practice.programs class Stack<T> { private val items: MutableList<T> = mutableListOf() fun push(item: T) { items.add(item) } fun pop(): T? { if (isEmpty()) return null return items.removeAt(items.size - 1) } fun peek(): T? { if (isEmpty()) return null return items[items.size - 1] } fun isEmpty(): Boolean { return items.isEmpty() } fun size(): Int { return items.size } } fun main() { val stack = Stack<Int>() stack.push(1) stack.push(2) stack.push(3) println("Stack size: ${stack.size()}") println("Top element: ${stack.peek()}") while (!stack.isEmpty()) { println("Popped: ${stack.pop()}") } }
0
Kotlin
0
1
4b74ac3f2d070382a931d08ef1acc115eb23fefe
776
Android-Kotlin-Jetpack-Compose-Practice
Apache License 2.0
src/main/kotlin/com/cuupa/mailprocessor/delegates/preprocessing/scan/DocumentSeparationDelegate.kt
Cuupa
281,472,343
false
null
package com.cuupa.mailprocessor.delegates.preprocessing.scan import com.cuupa.mailprocessor.delegates.AbstractJavaDelegate import com.cuupa.mailprocessor.process.ProcessVariables import com.cuupa.mailprocessor.services.files.content.FileFacade import com.cuupa.mailprocessor.userconfiguration.WorkDirectory import org.apache.commons.logging.Log import org.apache.commons.logging.LogFactory import org.camunda.bpm.engine.delegate.DelegateExecution class DocumentSeparationDelegate(private val workConfig: WorkDirectory ) : AbstractJavaDelegate() { override fun execute(execution: DelegateExecution?) { val variables = ProcessVariables(execution) if (!variables.patchSheets.isNullOrEmpty()) { log.error("No patch sheets found, although ${DetectPatchSheetDelegate::class.java} has detected some") } val pageSeparationSheets = variables.patchSheets .filter { it.isPageSeparationSheet() } .map { it.pageIndex } val content = getContent(variables.id!!, workConfig) val file = FileFacade.content(content).handleFileSeparationPatchSheet(pageSeparationSheets) variables.documents = file log.error("${this.javaClass.simpleName} executed") } companion object { val log: Log = LogFactory.getLog(DocumentSeparationDelegate::class.java) } }
9
Kotlin
0
0
fb308637d47a6d69ae23710db3e972297c6ffa26
1,360
mailprocessor
MIT License
base_gallery/src/main/java/com/maxmakarov/base/gallery/db/MoshiFactory.kt
maxmakarovdev
666,362,590
false
null
package com.maxmakarov.base.gallery.db import com.squareup.moshi.Moshi object MoshiFactory { val moshi = Moshi.Builder().build() }
0
Kotlin
0
1
684e69452b9a5cb3549dc9412265c437f8dbb753
136
android-unsplash-gallery-sample
Apache License 2.0
Source/packages/apps/Settings/src/com/android/settings/spa/development/UsageStatsListModel.kt
stayboogy
784,959,483
false
{"XML": 12479, "Ignore List": 14, "Markdown": 7, "Text": 104, "Shell": 20, "Makefile": 32, "INI": 11, "Soong": 58, "Java": 9482, "Gradle": 8, "Java Properties": 5, "Batchfile": 3, "Proguard": 2, "Protocol Buffer": 33, "JSON": 83, "Python": 6, "Kotlin": 469, "C++": 24, "XSLT": 1, "HTML": 5, "C": 23, "AIDL": 5, "Git Attributes": 1, "Gradle Kotlin DSL": 2, "YAML": 3}
/* * Copyright (C) 2022 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.settings.spa.development import android.app.usage.UsageStats import android.app.usage.UsageStatsManager import android.content.Context import android.content.pm.ApplicationInfo import android.text.format.DateUtils import androidx.compose.runtime.Composable import androidx.compose.runtime.State import com.android.settings.R import com.android.settings.spa.development.UsageStatsListModel.SpinnerItem.Companion.toSpinnerItem import com.android.settingslib.spa.framework.compose.stateOf import com.android.settingslib.spa.widget.ui.SpinnerOption import com.android.settingslib.spaprivileged.model.app.AppEntry import com.android.settingslib.spaprivileged.model.app.AppListModel import com.android.settingslib.spaprivileged.model.app.AppRecord import java.text.DateFormat import java.util.concurrent.TimeUnit import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.map data class UsageStatsAppRecord( override val app: ApplicationInfo, val usageStats: UsageStats?, ) : AppRecord class UsageStatsListModel(private val context: Context) : AppListModel<UsageStatsAppRecord> { private val usageStatsManager = context.getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager private val now = System.currentTimeMillis() override fun transform( userIdFlow: Flow<Int>, appListFlow: Flow<List<ApplicationInfo>>, ) = userIdFlow.map { getUsageStats() } .combine(appListFlow) { usageStatsMap, appList -> appList.map { app -> UsageStatsAppRecord(app, usageStatsMap[app.packageName]) } } override fun getSpinnerOptions(recordList: List<UsageStatsAppRecord>): List<SpinnerOption> = SpinnerItem.values().map { SpinnerOption( id = it.ordinal, text = context.getString(it.stringResId), ) } override fun filter( userIdFlow: Flow<Int>, option: Int, recordListFlow: Flow<List<UsageStatsAppRecord>>, ) = recordListFlow.map { recordList -> recordList.filter { it.usageStats != null } } override fun getComparator(option: Int) = when (option.toSpinnerItem()) { SpinnerItem.UsageTime -> compareByDescending { it.record.usageStats?.totalTimeInForeground } SpinnerItem.LastTimeUsed -> compareByDescending { it.record.usageStats?.lastTimeUsed } else -> compareBy<AppEntry<UsageStatsAppRecord>> { 0 } }.then(super.getComparator(option)) @Composable override fun getSummary(option: Int, record: UsageStatsAppRecord): State<String>? { val usageStats = record.usageStats ?: return null val lastTimeUsed = DateUtils.formatSameDayTime( usageStats.lastTimeUsed, now, DateFormat.MEDIUM, DateFormat.MEDIUM ) val lastTimeUsedLine = "${context.getString(R.string.last_time_used_label)}: $lastTimeUsed" val usageTime = DateUtils.formatElapsedTime(usageStats.totalTimeInForeground / 1000) val usageTimeLine = "${context.getString(R.string.usage_time_label)}: $usageTime" return stateOf("$lastTimeUsedLine\n$usageTimeLine") } private fun getUsageStats(): Map<String, UsageStats> { val startTime = now - TimeUnit.DAYS.toMillis(5) return usageStatsManager.queryUsageStats(UsageStatsManager.INTERVAL_BEST, startTime, now) .groupingBy { it.packageName }.reduce { _, a, b -> a.add(b); a } } private enum class SpinnerItem(val stringResId: Int) { UsageTime(R.string.usage_stats_sort_by_usage_time), LastTimeUsed(R.string.usage_stats_sort_by_last_time_used), AppName(R.string.usage_stats_sort_by_app_name); companion object { fun Int.toSpinnerItem(): SpinnerItem = values()[this] } } }
0
Java
0
0
e6132560c5e2416db150b856bd3f331d80795c4c
4,453
stayboogy_AOSimPle_Pixel-5_Redfin
Apache License 2.0
src/main/kotlin/net/bjoernpetersen/musicbot/api/module/ConfigModule.kt
fossabot
202,610,963
true
{"Kotlin": 211965}
package net.bjoernpetersen.musicbot.api.module import com.google.inject.AbstractModule import com.google.inject.Provides import net.bjoernpetersen.musicbot.api.config.ConfigManager import javax.inject.Singleton class ConfigModule(private val configManager: ConfigManager) : AbstractModule() { @Provides @Singleton fun configManager() = configManager }
0
Kotlin
0
0
1355b9a5d8970ba99f5d8365d3af197dfe186cdc
366
MusicBot
MIT License
app/src/main/java/com/example/leagueorganizer/network/TeamsApiService.kt
sahinakkaya
459,107,945
false
null
package com.example.leagueorganizer.network import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.http.GET import retrofit2.http.Headers import retrofit2.http.Query private const val BASE_URL = "https://randommer.io/api/" private val moshi = Moshi.Builder() .add(KotlinJsonAdapterFactory()) .build() private val retrofit = Retrofit.Builder() .addConverterFactory(MoshiConverterFactory.create(moshi)) .baseUrl(BASE_URL) .build() interface TeamsApiService { @Headers("X-Api-Key: 437ce6edb8474cab8728c5e32a9dfd9a") @GET("Name") suspend fun getTeamNames(@Query("nameType") nameType: String, @Query("quantity") quantity: String): List<String> } object TeamsApi { val RETROFIT_SERVICE : TeamsApiService by lazy { retrofit.create(TeamsApiService::class.java) } }
0
Kotlin
0
0
3fbfb998ee08ba3a5c78e0c9279c578d0fb9e182
981
league-organizer
Apache License 2.0
app/src/main/java/com/emrekose/videogames/common/SimpleTextWatcher.kt
emrekose26
329,276,392
false
null
package com.emrekose.videogames.common import android.text.Editable import android.text.TextWatcher abstract class SimpleTextWatcher: TextWatcher { override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) { } override fun afterTextChanged(s: Editable?) { } }
0
Kotlin
0
2
9ff281a07df645bf8477f91f6350fed8bc6e8bb9
296
video-games-app
Apache License 2.0
user-agent/user-agent-store/src/test/java/com/duckduckgo/user/agent/store/RealUserAgentFeatureToggleRepositoryTest.kt
duckduckgo
78,869,127
false
{"Kotlin": 14333964, "HTML": 63593, "Ruby": 20564, "C++": 10312, "JavaScript": 8463, "CMake": 1992, "C": 1076, "Shell": 784}
/* * Copyright (c) 2024 DuckDuckGo * * 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.duckduckgo.user.agent.store import org.junit.Before import org.junit.Test import org.mockito.kotlin.mock import org.mockito.kotlin.verify class RealUserAgentFeatureToggleRepositoryTest { lateinit var testee: RealUserAgentFeatureToggleRepository private val mockPrivacyFeatureTogglesStore: UserAgentFeatureToggleStore = mock() @Before fun before() { testee = RealUserAgentFeatureToggleRepository(mockPrivacyFeatureTogglesStore) } @Test fun whenDeleteAllThenDeleteAllCalled() { testee.deleteAll() verify(mockPrivacyFeatureTogglesStore).deleteAll() } @Test fun whenGetThenGetCalled() { testee.get(UserAgentFeatureName.UserAgent, true) verify(mockPrivacyFeatureTogglesStore).get(UserAgentFeatureName.UserAgent, true) } @Test fun whenInsertThenInsertCalled() { val privacyFeatureToggle = UserAgentFeatureToggle(UserAgentFeatureName.UserAgent.value, true, null) testee.insert(privacyFeatureToggle) verify(mockPrivacyFeatureTogglesStore).insert(privacyFeatureToggle) } }
67
Kotlin
901
3,823
6415f0f087a11a51c0a0f15faad5cce9c790417c
1,706
Android
Apache License 2.0
src/test/kotlin/pages/Page.kt
diego-alves
110,293,831
false
null
package pages import org.openqa.selenium.WebDriver import org.openqa.selenium.support.PageFactory abstract class Page(val driver: WebDriver, val url: String) { init { PageFactory.initElements(driver, this) } fun open() = this.driver.get(url) fun close() = this.driver.close() fun title() = this.driver.title }
0
Kotlin
0
0
df21fff0d9b9b760cb0d7dca0ae815a76cf24aeb
343
kotlin-cucumber
Apache License 2.0
app/src/main/java/com/xda/nachonotch/components/TitleBar.kt
zacharee
127,220,159
false
null
package com.xda.nachonotch.components import androidx.activity.compose.LocalOnBackPressedDispatcherOwner import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.draw.shadow import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import androidx.compose.ui.zIndex import com.xda.nachonotch.R @OptIn(ExperimentalMaterial3Api::class) @Composable fun TitleBar( title: String, modifier: Modifier = Modifier ) { val backPressedDispatcher = LocalOnBackPressedDispatcherOwner.current?.onBackPressedDispatcher TopAppBar( title = { Text(text = title) }, navigationIcon = { IconButton( onClick = { backPressedDispatcher?.onBackPressed() }, ) { Icon( painter = painterResource(id = R.drawable.arrow_left), contentDescription = stringResource(id = R.string.back) ) } }, modifier = modifier.shadow(4.dp).zIndex(2f) ) }
4
null
21
78
cbea9323fd43d5f84f39c7999bb2318ddcfedfe1
1,352
NachoNotch
MIT License
app/src/main/java/inovex/ad/multiar/polyViewerModule/poly/UseCasePolyApi.kt
FloriJann
194,672,867
false
null
package inovex.ad.multiar.polyViewerModule.poly import inovex.ad.multiar.polyViewerModule.AssetRepository import okhttp3.ResponseBody import retrofit2.Call class UseCasePolyApi(private val polyApi: PolyApi) { private val TAG = this.javaClass.name private val FORMAT = "GLTF2" private val FIELDS = "assets(authorName%2Cdescription%2CdisplayName%2Cformats%2Cname%2Cthumbnail)" // determine the necessary fields private val API_KEY = "Insert Your Key Here" private val PAGESIZE = "50" private val queryMap = mutableMapOf( "format" to FORMAT, "fields" to FIELDS, "key" to API_KEY, "pageSize" to PAGESIZE ) fun getAssetList( category: AssetRepository.AssetCategory = AssetRepository.AssetCategory.none, keywords: String? = null ): Call<Assets> { if (category.name != "none") { queryMap["category"] = category.name } if (keywords != null) { queryMap["keywords"] = keywords } return polyApi.getAssetList(queryMap) } fun getFile(fileUrl: String): Call<ResponseBody> { return polyApi.get3DModel(fileUrl) } }
0
Kotlin
0
1
e7cfb04163b5fe9d0367837e0b9d497241ea025c
1,188
MultiAR
Apache License 2.0
app/src/main/java/com/example/workoutcompanion/activities/chat/ChatActivity.kt
ambeche
298,065,226
false
null
package com.example.workoutcompanion.activities.chat import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import com.example.workoutcompanion.BottomNavListener import com.example.workoutcompanion.R import com.example.workoutcompanion.activities.home.MainActivity import kotlinx.android.synthetic.main.activity_main.* class ChatActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_chat) title = getString(R.string.activity_title_chat) bottom_navigation.apply { selectedItemId = R.id.chat setOnNavigationItemSelectedListener( BottomNavListener(this@ChatActivity, ChatActivity::class.java ) ) } } }
0
Kotlin
1
5
deddc42809288fad8310ce8e0a6ad25faf21d0cb
819
WorkoutCompanion
MIT License
client/src/ktorMain/kotlin/br/com/devsrsouza/mcheads/client/HeadApiService.kt
DevSrSouza
207,658,750
false
null
package br.com.devsrsouza.mcheads.client import br.com.devsrsouza.mcheads.common.API_URL import br.com.devsrsouza.mcheads.common.Head import br.com.devsrsouza.mcheads.common.HeadCategory import io.ktor.client.HttpClient import io.ktor.client.features.json.JsonFeature import io.ktor.client.features.json.serializer.KotlinxSerializer import io.ktor.client.request.get class KtorHeadApi(private val http: HttpClient) : IHeadApiService { override suspend fun search( search: String ): List<Head> { return http.get("${API_URL}/search/${search}") } override suspend fun get( category: HeadCategory?, page: Int, limit: Int ): List<Head> { return http.get( "${API_URL}/heads?page=$page&limit=$limit${if(category != null) "&category=${category.name}" else ""}" ) } } actual object HeadApi { actual val service: IHeadApiService by lazy { KtorHeadApi(HttpClient(){ install(JsonFeature) { serializer = KotlinxSerializer() } }) } }
0
Kotlin
0
5
48947b6e6951f4900127665ff7cd7e94d9241ba4
1,082
MCHeads
Apache License 2.0
app/src/main/java/com/valhalla/lolchampviewer/repository/RepositoriesModule.kt
zed13
264,632,149
false
null
package com.valhalla.lolchampviewer.repository import org.koin.dsl.module val repositoriesModule = module { single<ChampionsRepository> { DragonChampionsRepository(get()) } }
0
Kotlin
0
0
796e875693caff8c965878a326cae4d4e3b15d50
180
TheGreenDragon
Apache License 2.0
composeApp/src/commonMain/kotlin/dev/anvith/binanceninja/core/ui/theme/ColorExtensions.kt
humblerookie
734,842,239
false
{"Kotlin": 157941, "Swift": 4768}
package dev.anvith.binanceninja.core.ui.theme import androidx.compose.ui.graphics.Color fun Color.alpha87() = copy(alpha = 0.87f) fun Color.alpha60() = copy(alpha = 0.60f) fun Color.alpha38() = copy(alpha = 0.38f) fun Color.alpha12() = copy(alpha = 0.12f)
1
Kotlin
1
1
351e3924e3333663d2b43fe3b8e97139c97a7a6c
260
binance-ninja
Apache License 2.0
sdk/src/main/kotlin/com/processout/sdk/di/ContextGraph.kt
processout
545,434,353
false
null
package com.processout.sdk.di import android.app.Application import android.os.Build import com.processout.sdk.api.model.request.PODeviceData import java.util.* internal interface ContextGraph { val deviceData: PODeviceData } internal class ContextGraphImpl(private val application: Application) : ContextGraph { private fun provideDeviceData(): PODeviceData { // fetch timezone offset val calendar = Calendar.getInstance() val timeZoneOffSet = -(calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)) / (1000 * 60) val displayMetrics = application.resources.displayMetrics val locale = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { application.resources.configuration.locales[0] } else { @Suppress("DEPRECATION") application.resources.configuration.locale } return PODeviceData( locale.language, displayMetrics.widthPixels, displayMetrics.heightPixels, timeZoneOffSet ) } override val deviceData: PODeviceData get() = provideDeviceData() }
0
Kotlin
0
1
df3ad13923a21d3a920ce2e61bb3fde8e834da47
1,169
android-v2
MIT License
src/main/kotlin/no/nav/arbeidsplassen/emailer/azure/impl/SendMailException.kt
navikt
344,235,170
false
{"Kotlin": 12780, "Dockerfile": 196, "Shell": 49}
package no.nav.arbeidsplassen.emailer.azure.impl import io.micronaut.http.HttpStatus class SendMailException(message: String?, val status : HttpStatus = HttpStatus.INTERNAL_SERVER_ERROR, e: Throwable? = null) : Throwable(message,e)
0
Kotlin
0
0
ab576197ca63067744924d15625330b6a8532876
282
pam-emailer
MIT License
app/src/main/java/cn/xxt/kotlinapplication/data/server/ForecastByZipCodeRequest.kt
Martin-zhq
156,842,627
false
null
package cn.xxt.kotlinapplication.data.server import com.google.gson.Gson class ForecastByZipCodeRequest(private val zipCode: Long, val gson: Gson = Gson()) { companion object { private val APP_ID = "15646a06818f61f7b8d7823ca833e1ce" private val URL = "http://api.openweathermap.org/data/2.5/" + "forecast/daily?mode=json&units=metric&cnt=7" private val COMPLETE_URL = "$URL&APPID=$APP_ID&q=" } fun execute(): ForecastResult { val forecastJsonStr = java.net.URL(COMPLETE_URL + zipCode).readText() return gson.fromJson(forecastJsonStr, ForecastResult::class.java) } }
0
Kotlin
0
0
4d63c9a643d47313724e22c631df6ea437fab8a9
653
KotlinApplication
Apache License 2.0
app/src/main/kotlin/com/simplemobiletools/notes/pro/services/WidgetService.kt
herou
193,502,512
true
{"Kotlin": 117492}
package com.simplemobiletools.notes.pro.services import android.content.Intent import android.widget.RemoteViewsService import com.simplemobiletools.notes.pro.adapters.WidgetAdapter class WidgetService : RemoteViewsService() { override fun onGetViewFactory(intent: Intent) = WidgetAdapter(applicationContext, intent) }
0
Kotlin
0
1
4d220d4d178bb1d945ae26bd4828bbc69d130551
325
Simple-Notes
Apache License 2.0
app/src/main/java/com/konradszewczuk/weatherapp/data/room/WeatherEntities.kt
ashish-andev
117,521,020
false
null
package com.konradszewczuk.weatherapp.data.room import android.arch.persistence.room.Entity import android.arch.persistence.room.PrimaryKey @Entity(tableName = RoomConfig.TABLE_CITIES) data class CityEntity( @PrimaryKey(autoGenerate = true) val id: Int = 0, var cityName: String )
0
Kotlin
33
2
8943d0ef12b6c3b2c04c145f880185bb7810198e
298
WeatherApp
Apache License 2.0
src/main/kotlin/components/imageWithCaption.kt
Cottand
324,835,406
false
null
package components import com.ccfraser.muirwik.components.MTypographyAlign import com.ccfraser.muirwik.components.MTypographyVariant.subtitle2 import com.ccfraser.muirwik.components.mTypography import com.ccfraser.muirwik.components.spacingUnits import kotlinx.css.CSSBuilder import kotlinx.css.FontStyle import kotlinx.css.LinearDimension.Companion import kotlinx.css.fontStyle import kotlinx.css.paddingBottom import kotlinx.css.paddingTop import kotlinx.css.width import react.RBuilder import style.BaseStyle import style.globalTheme import styled.css import styled.styledDiv import styled.styledImg import util.times fun RBuilder.imgWithCaption( src: String, caption: String = "", centered: Boolean = true, imgCss: CSSBuilder.() -> Unit = {} ) { styledDiv { css { if (centered) +BaseStyle.centered width = Companion.fitContent paddingTop = 2.spacingUnits paddingBottom = 1.spacingUnits } styledImg(src = src, alt = caption) { css { if (centered) +BaseStyle.centered +BaseStyle.borderRadius imgCss() } } if (caption.isNotBlank()) mTypography( caption, variant = subtitle2, align = MTypographyAlign.center ) { css { fontStyle = FontStyle.italic paddingTop = globalTheme.spacing * 1 } } } }
0
Kotlin
0
1
8ea04a869819cad38346e64bbf2bfb0c71eef6aa
1,486
kotlin-js-portfolio
Apache License 2.0
jetbrains-core/src/software/aws/toolkits/jetbrains/services/lambda/execution/sam/SamDebugSupport.kt
renwickman
346,482,587
true
{"Kotlin": 3334105, "C#": 96716, "Java": 9601, "Dockerfile": 2622}
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 package software.aws.toolkits.jetbrains.services.lambda.execution.sam import com.intellij.execution.runners.ExecutionEnvironment import com.intellij.openapi.application.ExpirableExecutor import com.intellij.openapi.application.impl.coroutineDispatchingContext import com.intellij.openapi.application.runInEdt import com.intellij.util.concurrency.AppExecutorUtil import com.intellij.xdebugger.XDebugProcessStarter import kotlinx.coroutines.launch import org.jetbrains.concurrency.AsyncPromise import org.jetbrains.concurrency.Promise import software.aws.toolkits.core.utils.getLogger import software.aws.toolkits.core.utils.warn import software.aws.toolkits.jetbrains.utils.ApplicationThreadPoolScope import software.aws.toolkits.resources.message import java.util.Timer import kotlin.concurrent.schedule interface SamDebugSupport { fun numberOfDebugPorts(): Int = 1 /** * SAM arguments added to the execution of `sam local invoke`. These include --debugger-path and --debug-args * for debugging, and anything else that is needed on a per-runtime basis * @param debugPorts The list of debugger ports. Some runtimes (dotnet) require more than one */ fun samArguments(debugPorts: List<Int>): List<String> = emptyList() fun createDebugProcessAsync( environment: ExecutionEnvironment, state: SamRunningState, debugHost: String, debugPorts: List<Int> ): Promise<XDebugProcessStarter?> { val promise = AsyncPromise<XDebugProcessStarter?>() val bgContext = ExpirableExecutor.on(AppExecutorUtil.getAppExecutorService()).expireWith(environment).coroutineDispatchingContext() val timerTask = Timer("Debugger Worker launch timer", true).schedule(SamDebugger.debuggerConnectTimeoutMs()) { if (!promise.isDone) { runInEdt { promise.setError(message("lambda.debug.process.start.timeout")) } } } ApplicationThreadPoolScope(environment.runProfile.name).launch(bgContext) { try { val debugProcess = createDebugProcess(environment, state, debugHost, debugPorts) runInEdt { promise.setResult(debugProcess) } } catch (t: Throwable) { LOG.warn(t) { "Failed to start debugger" } runInEdt { promise.setError(t) } } finally { timerTask.cancel() } } return promise } suspend fun createDebugProcess( environment: ExecutionEnvironment, state: SamRunningState, debugHost: String, debugPorts: List<Int> ): XDebugProcessStarter? private companion object { val LOG = getLogger<SamDebugSupport>() } }
0
null
0
0
d820241fdea36bbc0612a24be5cc7e267c3411b7
2,957
aws-toolkit-jetbrains
Apache License 2.0
app/src/main/java/com/example/final_project/join.kt
KoEunseong
570,469,006
false
null
package com.example.final_project import android.content.Context import android.database.sqlite.SQLiteDatabase import android.database.sqlite.SQLiteOpenHelper import android.os.Bundle import android.widget.Button import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import kotlinx.android.synthetic.main.join.* class join : AppCompatActivity() { lateinit var name : EditText lateinit var email : EditText lateinit var btnEmailCheck :Button lateinit var passWord : EditText lateinit var passWordCheck : EditText lateinit var joinBtn : Button lateinit var cancelBtn : Button lateinit var myHelper: MemberDBHelper lateinit var sqlDB: SQLiteDatabase override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.join) name = findViewById(R.id.join_name) email = findViewById(R.id.join_email) btnEmailCheck = findViewById(R.id.check_button) passWord = findViewById(R.id.join_password) passWordCheck = findViewById(R.id.join_pwck) joinBtn = findViewById(R.id.join_button) cancelBtn = findViewById(R.id.delete) myHelper = MemberDBHelper(this) var isValidEmail = false // var isValidPassWord = false var tmpbutton : Button = findViewById(R.id.tmpbutton) tmpbutton.setOnClickListener { sqlDB = myHelper.writableDatabase myHelper!!.onUpgrade(sqlDB, 1, 2) // 인수는 아무거나 입력하면 됨. sqlDB.close() Toast.makeText(applicationContext,"초기화.", Toast.LENGTH_SHORT).show() } btnEmailCheck.setOnClickListener { isValidEmail = true isValidEmail = myHelper!!.checkEmail(email.text.toString()) if(!isValidEmail){ Toast.makeText(applicationContext,"이미 가입된 이메일 입니다.", Toast.LENGTH_SHORT).show() } else{ Toast.makeText(applicationContext,"가능한 이메일", Toast.LENGTH_SHORT).show() } } joinBtn.setOnClickListener { var readyForJoin = true if(isValidEmail == false){ Toast.makeText(applicationContext,"이메일 확인을 다시하세요", Toast.LENGTH_SHORT).show() readyForJoin = false; } if(!passWord.text.toString().equals(passWordCheck.text.toString())){ Toast.makeText(applicationContext,"비밀번호가 일치하지 않습니다.", Toast.LENGTH_SHORT).show() readyForJoin = false; } // 후에 정규식을 통해 비밀번호 형식 지정해 주기, 메서드로 묶어서 처리하게 할것 if(readyForJoin == true){ myHelper!!.insertData(email.text.toString(),name.text.toString(),passWord.text.toString()) //데이터 베이스 회원가입된 회원정보 저장 Toast.makeText(applicationContext,"회원가입이 완료됐습니다.", Toast.LENGTH_SHORT).show() sqlDB.close() finish() } } cancelBtn.setOnClickListener { finish() } } }
0
Kotlin
0
0
9d38d10070fa2845adbfcc451311091829d88b79
3,078
Final_term_android
MIT License
src/me/anno/ecs/components/camera/control/FirstPersonController.kt
AntonioNoack
456,513,348
false
null
package me.anno.ecs.components.camera.control import me.anno.ecs.Transform import me.anno.ecs.components.camera.Camera open class FirstPersonController : CameraController() { override fun computeTransform(baseTransform: Transform, camTransform: Transform, camera: Camera) { lastWarning = "hasn't been implemented yet" } override fun clone(): FirstPersonController { val clone = FirstPersonController() copy(clone) return clone } override val className get() = "FirstPersonControls" }
0
Kotlin
0
7
bacd7c79b8b34765d157012a08d728008c4b2d9a
541
RemsEngine
Apache License 2.0
app/src/main/java/io/github/gusriil/moviemagnet/paging/search/tvshow/SearchTVShowPageKeyedDataSource.kt
superosystem
479,150,681
false
{"Kotlin": 225959, "Java": 7644}
package io.github.gusriil.moviemagnet.paging.search.tvshow import android.content.Context import io.github.gusriil.moviemagnet.data.network.TVShowApi import io.github.gusriil.moviemagnet.data.response.asTVShowDomainModel import io.github.gusriil.moviemagnet.domain.model.TVShow import io.github.gusriil.moviemagnet.paging.BasePageKeyedDataSource import io.reactivex.Observable import java.util.concurrent.Executor class SearchTVShowPageKeyedDataSource( private val api: TVShowApi, private val query: String, retryExecutor: Executor, context: Context ) : BasePageKeyedDataSource<TVShow>(retryExecutor, context) { override fun fetchItems(page: Int): Observable<List<TVShow>> = api.searchItems(page, query).map { it.items.asTVShowDomainModel() } }
0
Kotlin
0
3
91a2d005aab478bb5c864210fe0cbd2286daf2ad
775
MovieMagnet
MIT License
app/src/main/java/jp/co/yumemi/droidtraining/WeatherCase.kt
daikiumehara
703,830,643
false
{"Kotlin": 16404}
package jp.co.yumemi.droidtraining enum class WeatherCase(val value: Int) { SUNNY(value = R.drawable.baseline_wb_sunny_24), CLOUDY(value = R.drawable.baseline_cloud_24), RAINY(value = R.drawable.baseline_umbrella_24), SNOW(value = R.drawable.baseline_ac_unit_24), } class WeatherCaseConvertor() { companion object { fun convert(weatherString: String): WeatherCase { println(weatherString) return when (weatherString) { "sunny" -> WeatherCase.SUNNY "cloudy" -> WeatherCase.CLOUDY "rainy" -> WeatherCase.RAINY "snow" -> WeatherCase.SNOW else -> WeatherCase.SUNNY } } } }
20
Kotlin
0
0
c7cac8c29653d80253769c2ac13e333a03905298
727
android-training
Apache License 2.0
app-main/src/main/kotlin/com/github/francescojo/endpoint/v1/user/GetUserController.kt
FrancescoJo
534,724,231
false
null
/* * kopringboot-multimodule-template * Distributed under MIT licence */ package com.github.francescojo.endpoint.v1.user import com.github.francescojo.endpoint.v1.ApiPathsV1 import com.github.francescojo.endpoint.v1.ApiVariableV1 import com.github.francescojo.endpoint.v1.user.common.UserResponse import com.github.francescojo.endpoint.v1.user.create.CreateUserRequest import org.springframework.http.MediaType import org.springframework.web.bind.annotation.PathVariable import org.springframework.web.bind.annotation.RequestBody import org.springframework.web.bind.annotation.RequestMapping import org.springframework.web.bind.annotation.RequestMethod import java.util.UUID import javax.validation.Valid /** * ``` * GET /v1/users/{id} * * Content-Type: application/json * ``` * * @since 2021-08-10 */ @RequestMapping( produces = [MediaType.APPLICATION_JSON_VALUE] ) interface GetUserController { @RequestMapping( path = [ApiPathsV1.USERS_ID], method = [RequestMethod.GET] ) fun get(@PathVariable(ApiVariableV1.ID) id: UUID): UserResponse }
0
Kotlin
0
7
681bc732cc4424475f4d52b77f5e12c7ac4df742
1,086
kopringboot-multimodule-template
MIT License
SKIE/runtime/kotlin/impl/src/commonMain/kotlin/co/touchlab/skie/runtime/coroutines/suspend/Skie_SuspendHandler.kt
touchlab
685,579,240
false
{"Kotlin": 1644009, "Swift": 6029, "Shell": 1040}
package co.touchlab.skie.runtime.coroutines.suspend import co.touchlab.skie.runtime.coroutines.suspend.internal.CoroutineDispatcherWithDelegate import co.touchlab.skie.runtime.coroutines.suspend.internal.toNSError import kotlinx.coroutines.CancellationException import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.cancel import kotlinx.coroutines.launch import kotlin.reflect.KClass @Suppress("ClassName") class Skie_SuspendHandler( private val cancellationHandler: Skie_CancellationHandler, dispatcherDelegate: Skie_DispatcherDelegate, private val onResult: (Skie_SuspendResult) -> Unit, ) { private val dispatcher = CoroutineDispatcherWithDelegate(dispatcherDelegate) internal fun launch(checkedExceptions: Array<KClass<out Throwable>>, coroutine: suspend () -> Any?) { CoroutineScope(dispatcher).launch { cancellationHandler.setCancellationCallback { cancel() } try { val result = coroutine.invoke() onResult(Skie_SuspendResult.Success(result)) } catch (_: CancellationException) { onResult(Skie_SuspendResult.Canceled) } catch (e: Throwable) { if (e.isCheckedException(checkedExceptions)) { throwSwiftException(e) } else { throw e } } } } private fun Throwable.isCheckedException(checkedExceptions: Array<out KClass<out Throwable>>): Boolean = checkedExceptions.any { it.isInstance(this) } private fun throwSwiftException(e: Throwable) { val error = e.toNSError() onResult(Skie_SuspendResult.Error(error)) } }
9
Kotlin
8
735
b96044d4dec91e4b85c5b310226c6f56e3bfa2b5
1,739
SKIE
Apache License 2.0
simulator/api/src/main/kotlin/net/corda/simulator/SimulatorConfiguration.kt
corda
346,070,752
false
{"Kotlin": 18686067, "Java": 321931, "Smarty": 79539, "Shell": 56594, "Groovy": 28415, "TypeScript": 5826, "PowerShell": 4985, "Solidity": 2024}
package net.corda.simulator import net.corda.simulator.factories.ServiceOverrideBuilder import net.corda.v5.application.marshalling.json.JsonDeserializer import net.corda.v5.application.marshalling.json.JsonSerializer import net.corda.v5.serialization.SerializationCustomSerializer import java.time.Clock import java.time.Duration /** * Configuration for Simulator. This interface may be implemented directly or built using a * [net.corda.simulator.factories.SimulatorConfigurationBuilder]. */ interface SimulatorConfiguration { /** * The interval at which to check responder flow health. */ val pollInterval: Duration /** * The maximum length of time to wait for a responder flow to respond. */ val timeout: Duration /** * The clock to use for time-related functions in Simulator. */ val clock : Clock /** * A map of services to be overridden against the builders for the new services. */ val serviceOverrides: Map<Class<*>, ServiceOverrideBuilder<*>> /** * A list of custom serializers registered with Simulator */ val customSerializers : List<SerializationCustomSerializer<*, *>> /** * A map of custom JsonSerializer to its type registered with Simulator */ val customJsonSerializers : Map<JsonSerializer<*>, Class<*>> /** * A map of custom JsonDeserializer to its type registered with Simulator */ val customJsonDeserializers : Map<JsonDeserializer<*>, Class<*>> }
130
Kotlin
15
42
6ef36ce2d679a07abf7a5d95a832e98bd4d4d763
1,508
corda-runtime-os
Apache License 2.0
totaladapters/src/test/java/pl/arturborowy/adapters/AdapterTest.kt
ArturBorowy
188,580,962
false
null
package pl.arturborowy.adapters import org.junit.After import org.junit.Before import org.junit.runner.RunWith import org.koin.core.context.stopKoin import org.koin.dsl.module import org.mockito.Mock import org.mockito.MockitoAnnotations import org.robolectric.RobolectricTestRunner import pl.arturborowy.TestServiceLocator import pl.arturborowy.util.TestData import pl.arturborowy.util.ViewInflater @RunWith(RobolectricTestRunner::class) internal abstract class AdapterTest { protected val context = TestData.getContext() @Mock protected lateinit var mockViewInflater: ViewInflater protected val givenStrings = TestData.STRING_LIST @Before open fun setUp() { TestServiceLocator.init(context, module { single { mockViewInflater } }) MockitoAnnotations.initMocks(this) } @After fun tearDown() = stopKoin() }
0
Kotlin
0
5
d2090995f767d1c10fc8cdb1eca6cbc1df031ed6
865
total-adapters
MIT License
app/src/main/java/com/justnik/mosplace/presentation/registration/RegistrationFormEvent.kt
JustNik8
460,106,261
false
{"Kotlin": 160815}
package com.justnik.mosplace.presentation.registration sealed class RegistrationFormEvent { data class EmailChanged(val email: String) : RegistrationFormEvent() data class UsernameChanged(val username: String) : RegistrationFormEvent() data class PasswordChanged(val password: String) : RegistrationFormEvent() data class RepeatedPasswordChanged(val repeatedPassword: String) : RegistrationFormEvent() object Submit : RegistrationFormEvent() }
0
Kotlin
1
1
8ae2a811c895c6b4d75f8e31139dd4d15c425561
466
MosPlace
Apache License 2.0
app/src/main/java/ru/ozh/android/recycler/decorator/sample/chat/decor/ChatDecorOffset.kt
ozh-dev
193,144,003
false
{"Kotlin": 84727}
package ru.ozh.android.recycler.decorator.sample.chat.decor import android.graphics.Rect import android.view.View import androidx.recyclerview.widget.RecyclerView import ru.ozh.android.recycler.decorator.lib.Decorator import ru.ozh.android.recycler.decorator.sample.chat.controller.ChatMessageController import ru.ozh.android.recycler.decorator.sample.px class ChatDecorOffset : Decorator.OffsetDecor { override fun getItemOffsets( outRect: Rect, view: View, recyclerView: RecyclerView, state: RecyclerView.State ) { val vh = recyclerView.getChildViewHolder(view) if(vh !is ChatMessageController.Holder) { return } outRect.set(0, 8.px, 0, 0) } }
1
Kotlin
19
92
c3718d6a58a5712933d4e92ce333b4fb57e262b2
753
recycler-decorator-library-sample
Apache License 2.0
app/src/androidTest/java/com/jraska/dagger/codelab/app/TestDaggerApp.kt
jraska
245,893,320
false
null
package com.jraska.dagger.codelab.app import android.content.Context import androidx.test.rule.ActivityTestRule import com.jraska.dagger.codelab.app.di.AppComponent import com.jraska.dagger.codelab.config.di.ConfigModule import com.jraska.dagger.codelab.core.analytics.AnalyticsEvent import com.jraska.dagger.codelab.core.analytics.EventAnalytics import dagger.BindsInstance import dagger.Component import dagger.Module import dagger.Provides import javax.inject.Singleton class TestDaggerApp : DaggerApp() { val fakeAnalytics = (appComponent() as TestAppComponent).fakeEventAnalytics() override fun createDaggerComponent(): AppComponent { return DaggerTestAppComponent.factory().create(this) } } fun ActivityTestRule<*>.reportedAnalytics(): List<AnalyticsEvent> { return (activity.application as TestDaggerApp).fakeAnalytics.reportedAnalytics } @Singleton @Component(modules = [ConfigModule::class, FakeAnalyticsModule::class]) interface TestAppComponent : AppComponent { fun fakeEventAnalytics(): FakeEventAnalytics @Component.Factory interface Factory { fun create(@BindsInstance context: Context): TestAppComponent } } @Module object FakeAnalyticsModule { @Provides @Singleton fun fakeEventAnalytics(): FakeEventAnalytics = FakeEventAnalytics() @Provides fun eventAnalytics(fakeEventAnalytics: FakeEventAnalytics): EventAnalytics = fakeEventAnalytics }
0
Kotlin
4
9
5012c7d6f2af9e1c3bfc9a97f170f54b6d0f276b
1,401
Dagger-Codelab
Apache License 2.0
src/main/kotlin/nl/jhvh/sudoku/grid/event/cellvalue/CellRemoveCandidatesEvent.kt
JanHendrikVanHeusden
305,492,630
false
null
package nl.jhvh.sudoku.grid.event.cellvalue /* Copyright 2020 <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. */ import nl.jhvh.sudoku.grid.event.ValueEvent import nl.jhvh.sudoku.grid.event.ValueEventType import nl.jhvh.sudoku.grid.event.ValueEventType.CELL_REMOVE_CANDIDATES import nl.jhvh.sudoku.grid.model.cell.CellValue.NonFixedValue /** [ValueEvent] to inform interested listeners of removal of value(s) from the [NonFixedValue.valueCandidates] */ class CellRemoveCandidatesEvent(override val eventSource: NonFixedValue, val removedValues: Set<Int>): ValueEvent { override val type: ValueEventType = CELL_REMOVE_CANDIDATES override fun toString(): String { return "${this.javaClass.simpleName}: (eventSource=$eventSource, removedValues=$removedValues)" } }
0
Kotlin
0
1
5a487a594600edc28b46067b12ed9a5ac610bea2
1,300
Sudoku
Apache License 2.0
container-tasks-gradle-plugin/src/main/kotlin/util/toCamelCase.kt
mpetuska
482,828,109
false
null
package dev.petuska.container.util import java.util.Locale import java.util.regex.Pattern private val WORD_SEPARATOR = Pattern.compile("\\W+") internal fun String.toCamelCase(lower: Boolean = false): String { val builder = StringBuilder() val matcher = WORD_SEPARATOR.matcher(this) var pos = 0 var first = true while (matcher.find()) { var chunk: String = subSequence(pos, matcher.start()).toString() pos = matcher.end() if (chunk.isEmpty()) { continue } chunk = chunk.replaceFirstChar { when { first && lower -> it.lowercase(Locale.getDefault()).also { first = false } it.isLowerCase() -> it.titlecase(Locale.getDefault()) else -> it.toString() } } builder.append(chunk) } var rest: String = subSequence(pos, length).toString() rest = rest.replaceFirstChar { when { first && lower -> it.lowercase(Locale.getDefault()).also { first = false } it.isLowerCase() -> it.titlecase(Locale.getDefault()) else -> it.toString() } } builder.append(rest) return builder.toString() }
10
Kotlin
0
2
05265b4ec9dd977c863fd86c11991648aa1990a2
1,092
container-tasks-gradle
Apache License 2.0
app/src/main/java/com/chatspring/appsetting/ApiIkeyFragment.kt
goatpang
642,752,766
false
{"Kotlin": 134006}
package com.chatspring.appsetting import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ArrayAdapter import android.widget.Button import android.widget.EditText import android.widget.Spinner import androidx.fragment.app.Fragment import androidx.fragment.app.FragmentManager import com.chatspring.R class ApiIkeyFragment : Fragment() { private lateinit var sharedPreferences: SharedPreferences //private lateinit var apiurlEditText: EditText private lateinit var apikeyEditText: EditText override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { val view = inflater.inflate(R.layout.fragment_apikey, container, false) // 初始化 SharedPreferences sharedPreferences = requireContext().getSharedPreferences("MyPrefs", Context.MODE_PRIVATE) // 找到 EditText 视图 //apiurlEditText = view.findViewById(R.id.apiurl_edit_text) apikeyEditText = view.findViewById(R.id.apikey_edit_text) // 从 SharedPreferences 中获取已存储的值 //val storedApiUrl = sharedPreferences.getString("apiUrl", "") val storedApiKey = sharedPreferences.getString("apiKey", "") // 如果已存储的值不为空,则设置 EditText 的文本 // if (storedApiUrl!=null) { // apiurlEditText.setText(storedApiUrl) // } if (storedApiKey!=null) { apikeyEditText.setText(storedApiKey) } // 找到 Spinner 视图 val spinner: Spinner = view.findViewById(R.id.spinner) // 从 SharedPreferences 中获取已存储的选项值 val storedSelectedValue = sharedPreferences.getString("gpt_version", "") // 如果已存储的选项值不为空,则设置 Spinner 的选中项 if (storedSelectedValue != null) { val adapter = ArrayAdapter.createFromResource(requireContext(), R.array.gpt_versions, android.R.layout.simple_spinner_item) adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) spinner.adapter = adapter val position = adapter.getPosition(storedSelectedValue) spinner.setSelection(position) } // 获取保存按钮并添加点击事件 val saveButton: Button = view.findViewById(R.id.save_button) saveButton.setOnClickListener { // 获取输入框的值 //val apiUrl = apiurlEditText.text.toString() val apiKey = apikeyEditText.text.toString() // 获取Spinner选中的内容 val spinner: Spinner = view.findViewById(R.id.spinner) val selectvalue = spinner.selectedItem.toString() // 使用 SharedPreferences 存储输入框的值 val editor = sharedPreferences.edit() //editor.putString("apiUrl", apiUrl) editor.putString("apiKey", apiKey) editor.putString("gpt_version", selectvalue) editor.apply() // 根据登录状态导航到 MainAfterFragment 或 MainFragment val transaction = activity?.supportFragmentManager?.beginTransaction() transaction?.setCustomAnimations(R.anim.slide_in_right, R.anim.slide_out_left) val fragment = if (LoginState.isLoggedIn) MainAfterFragment() else MainFragment() transaction?.replace(R.id.fragment_main, fragment)?.commit() } val back_button: Button = view.findViewById(R.id.back_button) back_button.setOnClickListener { val transaction = activity?.supportFragmentManager?.beginTransaction() transaction?.setCustomAnimations(R.anim.slide_in_left, R.anim.slide_out_right) val fragment = if (LoginState.isLoggedIn) MainAfterFragment() else MainFragment() transaction?.replace(R.id.fragment_main, fragment)?.commit() } return view } }
0
Kotlin
1
1
23f41e7014704d6298d683b1904b884faddb1a8c
3,856
ChatSpring
Apache License 2.0
StartKotlin/app/src/main/java/com/muzi/startkotlin/LearnExtensionInKotlin.kt
lj20082
243,641,769
false
null
/* * * * * Created by Li.jianzhong on 3/5/20 4:43 PM * * Copyright (c) 2020 . All rights reserved. * * Last modified 3/5/20 4:43 PM * */ package com.muzi.startkotlin class Example { companion object {} fun printFunctionType() { LogHelper().logInfo("Class function") } } fun Example.printFunctionType(i: Int) { LogHelper().logInfo("Extension function") } fun Example.Companion.printCompanion() { LogHelper().logInfo("companion") } fun Any?.toString(): String { if (this == null) return "null" return toString() } fun List<String>.getLongestString(){ LogHelper.log("fetch longest string") } class Host(val hostname: String) { fun printHostname() { LogHelper.log(hostname) } } class Connection(val host: Host, val port: Int) { fun printPort() { LogHelper.log(port) } fun Host.printConnectionString() { printHostname() LogHelper.log(":") printPort() LogHelper.log(toString()) LogHelper.log(this@Connection.toString()) } fun connect() { host.printConnectionString() } } open class BaseObj{} class DerivedObj : BaseObj() {}
0
Kotlin
0
0
70c54410fb66ef96183279d85c45efe402878238
1,170
StartAndroid
Apache License 2.0
solar/src/main/java/com/chiksmedina/solar/broken/essentionalui/MinusCircle.kt
CMFerrer
689,442,321
false
{"Kotlin": 36591890}
package com.chiksmedina.solar.broken.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.Round 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.broken.EssentionalUiGroup val EssentionalUiGroup.MinusCircle: ImageVector get() { if (_minusCircle != null) { return _minusCircle!! } _minusCircle = Builder( name = "MinusCircle", defaultWidth = 24.0.dp, defaultHeight = 24.0.dp, viewportWidth = 24.0f, viewportHeight = 24.0f ).apply { path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(15.0f, 12.0f) horizontalLineTo(9.0f) } path( fill = SolidColor(Color(0x00000000)), stroke = SolidColor(Color(0xFF000000)), strokeLineWidth = 1.5f, strokeLineCap = Round, strokeLineJoin = Miter, strokeLineMiter = 4.0f, pathFillType = NonZero ) { moveTo(7.0f, 3.3378f) curveTo(8.4709f, 2.487f, 10.1786f, 2.0f, 12.0f, 2.0f) curveTo(17.5228f, 2.0f, 22.0f, 6.4771f, 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, 10.1786f, 2.487f, 8.4709f, 3.3378f, 7.0f) } } .build() return _minusCircle!! } private var _minusCircle: ImageVector? = null
0
Kotlin
0
0
3414a20650d644afac2581ad87a8525971222678
2,086
SolarIconSetAndroid
MIT License
src/android/MapsGisFullActivity.kt
pcamilojunior
639,631,841
false
null
package com.outsystems.plugin.urbimaps import android.Manifest import android.annotation.SuppressLint import android.content.Intent import android.content.pm.PackageManager import android.graphics.Color import android.location.Location import android.os.Bundle import android.view.Gravity import android.view.View import android.view.ViewGroup import android.view.WindowManager import android.widget.AdapterView import android.widget.ArrayAdapter import android.widget.Button import android.widget.PopupMenu import android.widget.Spinner import android.widget.TextView import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.lifecycle.lifecycleScope import com.google.android.gms.location.FusedLocationProviderClient import com.google.android.gms.location.LocationRequest import com.google.android.gms.location.LocationServices import com.google.android.gms.tasks.CancellationToken import com.google.android.gms.tasks.CancellationTokenSource import com.google.android.gms.tasks.OnTokenCanceledListener import com.google.android.material.switchmaterial.SwitchMaterial import com.outsystems.experts.neom.R import ru.dgis.sdk.map.Gesture import ru.dgis.sdk.map.GestureManager import ru.dgis.sdk.map.Map import ru.dgis.sdk.map.MapView import ru.dgis.sdk.map.MyLocationDirectionBehaviour import ru.dgis.sdk.map.MyLocationMapObjectSource import ru.dgis.sdk.map.ScreenPoint import ru.dgis.sdk.map.TouchEventsObserver import ru.dgis.sdk.map.createSmoothMyLocationController import ru.dgis.sdk.navigation.DefaultNavigationControls import ru.dgis.sdk.navigation.NavigationView import java.util.Calendar class MapsGisFullActivity : AppCompatActivity(), TouchEventsObserver { private lateinit var mapSource: MyLocationMapObjectSource private var map: Map? = null private lateinit var mapView: MapView private lateinit var contentSearchNavigation: View // Navigation Context private lateinit var navigationView: NavigationView private lateinit var routeTypeSpinner: Spinner private lateinit var startNavigationButton: Button private var viewModel: NavigationViewModel? = null private lateinit var routeEditorView: View private lateinit var textClose: TextView private var fuseClient: FusedLocationProviderClient? = null private lateinit var simulationSwitch: SwitchMaterial override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_maps_full) prepareViews() mapView = findViewById<MapView>(R.id.mapView).also { lifecycle.addObserver(it) it.setTouchEventsObserver(this@MapsGisFullActivity) it.getMapAsync(this::onMapReady) it.showApiVersionInCopyrightView = true } setupListeners() } private fun onMapReady(map: Map) { this.map = map val gestureManager = checkNotNull(mapView.gestureManager) subscribeGestureSwitches(gestureManager) mapSource = MyLocationMapObjectSource( SdkContext.context, MyLocationDirectionBehaviour.FOLLOW_MAGNETIC_HEADING, createSmoothMyLocationController() ) map.addSource(mapSource) initViewModel(map) } private fun initViewModel(map: Map) { val activity = this viewModel = NavigationViewModel(SdkContext.context, map, lifecycleScope).also { viewModel -> viewModel.messageCallback = { Toast.makeText(activity, it, Toast.LENGTH_LONG).show() } lifecycleScope.launchWhenStarted { viewModel.state.collect { navigationView.removeAllViews() when (it) { NavigationViewModel.State.ROUTE_EDITING -> { routeEditorView.visibility = View.VISIBLE navigationView.navigationManager = null } NavigationViewModel.State.NAVIGATION -> { routeEditorView.visibility = View.INVISIBLE navigationView.navigationManager = viewModel.navigationManager navigationView.addView(DefaultNavigationControls(navigationView.context).apply { defaultState = viewModel.navigationType onFinishClicked = { viewModel.stopNavigation() } }) } } } } lifecycleScope.launchWhenStarted { viewModel.canStartNavigation.collect { startNavigationButton.isEnabled = it } } } // setupFuseClientLocation() } private fun setupFuseClientLocation() { if (checkPermission()) { // todo: request here return } fuseClient = LocationServices.getFusedLocationProviderClient(applicationContext) fuseClient?.getCurrentLocation(LocationRequest.PRIORITY_HIGH_ACCURACY, object : CancellationToken() { override fun onCanceledRequested(p0: OnTokenCanceledListener) = CancellationTokenSource().token override fun isCancellationRequested() = false }) ?.addOnSuccessListener { location: Location? -> if (location == null) Toast.makeText(this, "Cannot get location.", Toast.LENGTH_SHORT).show() else { val lat = location.latitude val lon = location.longitude viewModel?.onMenuAction( ScreenPoint(lat.toFloat(), lon.toFloat()), NavigationViewModel.MenuAction.SELECT_START_POINT ) } } } private fun showMenu(point: ScreenPoint) { val anchorView = View(this).apply { x = point.x y = point.y layoutParams = ViewGroup.LayoutParams(1, 1) mapView.addView(this) } PopupMenu(this, anchorView, Gravity.CENTER).apply { inflate(R.menu.route_points_menu) setOnMenuItemClickListener { val action = when (it.itemId) { R.id.menuStartPoint -> NavigationViewModel.MenuAction.SELECT_START_POINT R.id.menuFinishPoint -> NavigationViewModel.MenuAction.SELECT_FINISH_POINT R.id.menuClearPoints -> NavigationViewModel.MenuAction.CLEAR_POINTS else -> null } if (action != null) { viewModel?.onMenuAction(point, action) } mapView.removeView(anchorView) true } setOnDismissListener { mapView.removeView(anchorView) } }.show() } override fun onLongTouch(point: ScreenPoint) { val viewModel = viewModel ?: return if (viewModel.state.value != NavigationViewModel.State.ROUTE_EDITING) { return } showMenu(point) } override fun onTap(point: ScreenPoint) { viewModel?.onTap(point) } override fun onBackPressed() { viewModel?.let { if (it.state.value == NavigationViewModel.State.NAVIGATION) { it.stopNavigation() return } } super.onBackPressed() } override fun onDestroy() { super.onDestroy() viewModel?.close() } private fun subscribeGestureSwitches(gm: GestureManager) { gm.enableGesture(Gesture.ROTATION) gm.enableGesture(Gesture.SHIFT) gm.enableGesture(Gesture.SCALING) gm.enableGesture(Gesture.TILT) } private fun setupListeners() { //Hide keyboard window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN) textClose.setOnClickListener { finish() } startNavigationButton.setOnClickListener { viewModel?.startNavigation() } simulationSwitch.setOnCheckedChangeListener { _, isChecked -> viewModel?.useSimulation = isChecked } } private fun prepareViews() { contentSearchNavigation = findViewById(R.id.contentSearchNavigation) startNavigationButton = findViewById(R.id.startButton) navigationView = findViewById(R.id.navigationView) routeTypeSpinner = findViewById(R.id.routeTypeSpinner) routeEditorView = findViewById(R.id.routeEditorView) textClose = findViewById(R.id.textClose) simulationSwitch = findViewById(R.id.simulationSwitch) val longTapText = findViewById<TextView>(R.id.availabilityTextView) textClose.setTextColor(getColorText()) longTapText.setTextColor(getColorText()) setupSpinnerRouteType() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) if (resultCode == SearchActivity.SEARCH_RESULT_CODE && data != null) { val resultData = data.extras?.getSerializable(SearchActivity.SEARCH_RESULT) as? SearchActivity.SearchResult? if (resultData?.title != null && resultData.subtitle != null) { setSearchResultOnPoints(resultData) } } } @SuppressLint("SetTextI18n") private fun setSearchResultOnPoints(result: SearchActivity.SearchResult) { when(result.searchType) { SearchType.START_POINT -> { viewModel?.onMenuAction(ScreenPoint(result.lat.toFloat(), result.long.toFloat()), NavigationViewModel.MenuAction.SELECT_START_POINT) } SearchType.END_POINT -> { viewModel?.onMenuAction(ScreenPoint(result.lat.toFloat(), result.long.toFloat()), NavigationViewModel.MenuAction.SELECT_FINISH_POINT) } else -> {} } } private fun getColorText(): Int { val c = Calendar.getInstance() return when (c.get(Calendar.HOUR_OF_DAY)) { in 0..11 -> Color.parseColor("#1182fd") in 12..15 -> Color.parseColor("#1182fd") in 16..20 -> Color.parseColor("#1182fd") in 21..23 -> Color.parseColor("#ffffff") else -> Color.parseColor("#ffffff") } } private fun setupSpinnerRouteType() { routeTypeSpinner.apply { adapter = ArrayAdapter.createFromResource( context, R.array.route_search_types, android.R.layout.simple_spinner_item ).apply { setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item) } onItemSelectedListener = object : AdapterView.OnItemSelectedListener { override fun onNothingSelected(parent: AdapterView<*>?) {} override fun onItemSelected( parent: AdapterView<*>?, view: View?, pos: Int, id: Long ) { (parent?.getChildAt(0) as? TextView)?.setTextColor(Color.BLACK) viewModel?.routeType = when (pos) { 1 -> NavigationViewModel.RouteType.PEDESTRIAN 2 -> NavigationViewModel.RouteType.BICYCLE else -> NavigationViewModel.RouteType.CAR } } } } } private fun checkPermission(): Boolean = ActivityCompat.checkSelfPermission( applicationContext, Manifest.permission.ACCESS_FINE_LOCATION ) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission( applicationContext, Manifest.permission.ACCESS_COARSE_LOCATION ) != PackageManager.PERMISSION_GRANTED }
0
Kotlin
0
0
b190aa3cdeaa95339a1f7fad8cdade678e9a227a
12,113
outsystems-plugin-urbimaps
MIT License
app/shared/state-machine/ui/public/src/commonMain/kotlin/build/wallet/statemachine/settings/full/notifications/NotificationsSettingsUiStateMachine.kt
proto-at-block
761,306,853
false
{"C": 10424094, "Kotlin": 7156393, "Rust": 2046237, "Swift": 700307, "Python": 331492, "HCL": 271992, "Shell": 111209, "TypeScript": 102700, "C++": 64770, "Meson": 64234, "JavaScript": 36227, "Just": 28071, "Ruby": 9428, "Dockerfile": 5731, "Makefile": 3839, "Open Policy Agent": 1552, "Procfile": 80}
package build.wallet.statemachine.settings.full.notifications import build.wallet.statemachine.core.ScreenModel import build.wallet.statemachine.core.StateMachine import build.wallet.statemachine.data.keybox.AccountData.HasActiveFullAccountData.ActiveFullAccountLoadedData /** * State machine for the settings screen that displays the currently set * notification touchpoints for the account */ interface NotificationsSettingsUiStateMachine : StateMachine<NotificationsSettingsProps, ScreenModel> data class NotificationsSettingsProps( val accountData: ActiveFullAccountLoadedData, val onBack: () -> Unit, )
0
C
10
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
618
bitkey
MIT License
ui-kit-lib/src/main/kotlin/com/linkedplanet/uikit/wrapper/atlaskit/taggroup/Imports.kt
linked-planet
427,161,616
false
{"Kotlin": 317837, "JavaScript": 1646, "HTML": 940, "SCSS": 653}
/** * Copyright 2022 linked-planet GmbH. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ @file:JsModule("@atlaskit/tag-group") package com.linkedplanet.uikit.wrapper.atlaskit.taggroup import react.ComponentClass import react.Props @JsName("default") external val TagGroup: ComponentClass<TagGroupProps> external interface TagGroupProps : Props
0
Kotlin
0
2
9328c3032a8eff76767e19bb28e9b71973f49125
865
ui-kit
Apache License 2.0
src/main/kotlin/com/kotcrab/xgbc/io/IO.kt
kotcrab
52,388,562
false
null
package com.kotcrab.xgbc.io import com.kotcrab.xgbc.Emulator /** @author Kotcrab */ class IO(private val emulator: Emulator) { val ioMem: ByteArray = ByteArray(0x4C) val devicesMap = arrayOfNulls<IODevice>(0x4C) val serialPort = SerialPort(emulator) val div = Div(emulator) val timer = Timer(emulator) val lcd = Lcd(emulator) val joypad = Joypad(emulator) val devices = arrayOf(serialPort, timer, div, lcd, joypad) var cyclesSynced = 0 init { for (device in devices) { device.register({ addr -> devicesMap[addr - 0xFF00] = device }) } } fun reset() { ioMem.fill(0) for (device in devices) { device.reset() } cyclesSynced = 0 } fun tick(cyclesElapsed: Int) { for (device in devices) { device.tick(cyclesElapsed) } } fun sync(cycles: Int) { cyclesSynced += cycles tick(cycles) } fun getAndClearSyncedCycles(): Int { val cyclesTmp = cyclesSynced cyclesSynced = 0 return cyclesTmp } fun read(addr: Int): Byte { val relAddr = addr - 0xFF00 val device = devicesMap[relAddr] device?.onRead(addr) return ioMem[relAddr] } fun write(addr: Int, value: Byte) { val relAddr = addr - 0xFF00 ioMem[relAddr] = value val device = devicesMap[relAddr] device?.onWrite(addr, value) } fun directWrite(addr: Int, value: Byte) { ioMem[addr - 0xFF00] = value } } interface IODevice { fun reset() fun tick(cyclesElapsed: Int) fun register(registrar: (addr: Int) -> Unit) fun onRead(addr: Int) fun onWrite(addr: Int, value: Byte) }
0
Kotlin
4
49
25d2623acf0f1e87cb7a2db61c26af4d2d74f735
1,756
xgbc
Apache License 2.0
vector/src/main/java/im/vector/app/features/settings/passwordmanagement/changepassword/VectorSettingsChangePasswordViewEvents.kt
FaradayApp
732,727,396
false
{"Kotlin": 15889711, "Java": 250183, "Shell": 102807, "HTML": 28529, "Python": 25379, "FreeMarker": 7662, "JavaScript": 7070, "Ruby": 3420, "Gherkin": 58}
/* * Copyright (c) 2023 New Vector Ltd * * 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 im.vector.app.features.settings.passwordmanagement.changepassword import im.vector.app.core.platform.VectorViewEvents sealed class VectorSettingsChangePasswordViewEvents : VectorViewEvents { object OnPasswordReset: VectorSettingsChangePasswordViewEvents() data class RestorePasswords(val oldPassword: String, val newPassword: String, val repeatPassword: String): VectorSettingsChangePasswordViewEvents() data class ShowError(val message: String, val location: ErrorLocation) : VectorSettingsChangePasswordViewEvents() } enum class ErrorLocation { OLD_PASSWORD, GENERAL }
0
Kotlin
2
0
d765bc66c3dc1ee2ab2e54f3d1f7bc09896b3708
1,205
Faraday-android
Apache License 2.0
app/src/main/java/com/egorhoot/chomba/di/DomainModule.kt
HootEgor
676,993,231
false
{"Kotlin": 268578}
package com.egorhoot.chomba.di import android.content.Context import androidx.compose.runtime.MutableState import androidx.compose.runtime.mutableStateOf import com.egorhoot.chomba.pages.PageState import com.egorhoot.chomba.pages.onlinegame.OnLineGameUiState import com.egorhoot.chomba.pages.user.ProfileScreenUiState import com.egorhoot.chomba.utils.IdConverter import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.ktx.firestore import com.google.firebase.ktx.Firebase import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.android.qualifiers.ApplicationContext import dagger.hilt.components.SingletonComponent import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object DomainModule { @Provides fun provideIdConverter(@ApplicationContext context: Context): IdConverter { return IdConverter(context) } @Provides @Singleton fun provideProfileUiState(): ProfileScreenUiState { return ProfileScreenUiState() } @Provides @Singleton fun provideMutableProfileUiState(): MutableState<ProfileScreenUiState> { return mutableStateOf(ProfileScreenUiState()) } @Provides @Singleton fun providePageState(): PageState { return PageState() } @Provides @Singleton fun provideMutablePageState(): MutableState<PageState> { return mutableStateOf(PageState()) } @Provides @Singleton fun provideMutableOnLineGameUiState(): MutableState<OnLineGameUiState> { return mutableStateOf(OnLineGameUiState()) } @Provides @Singleton fun provideContext(@ApplicationContext context: Context): Context { return context } @Provides @Singleton fun provideFirebaseAuth(): FirebaseAuth { return FirebaseAuth.getInstance() } @Provides @Singleton fun providesFirebaseFirestore(): FirebaseFirestore { return Firebase.firestore } }
0
Kotlin
0
0
0a80eedd48a90a0097ed7350037c09fa1ba567e4
2,056
Chomba
MIT License