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
store/src/test/java/com/nytimes/android/external/store3/pipeline/PipelineStoreTest.kt
sabarirangan
217,744,247
true
{"Kotlin": 60156, "Shell": 1020}
package com.nytimes.android.external.store3.pipeline import com.nytimes.android.external.store3.pipeline.ResponseOrigin.Cache import com.nytimes.android.external.store3.pipeline.ResponseOrigin.Fetcher import com.nytimes.android.external.store3.pipeline.ResponseOrigin.Persister import com.nytimes.android.external.store3.pipeline.StoreResponse.Data import com.nytimes.android.external.store3.pipeline.StoreResponse.Loading import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.delay import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.take import kotlinx.coroutines.flow.toList import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import kotlinx.coroutines.test.TestCoroutineScope import kotlinx.coroutines.test.runBlockingTest import org.assertj.core.api.Assertions.assertThat import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.JUnit4 @ExperimentalCoroutinesApi @RunWith(JUnit4::class) class PipelineStoreTest { private val testScope = TestCoroutineScope() @Test fun getAndFresh() = testScope.runBlockingTest { val fetcher = FakeFetcher( 3 to "three-1", 3 to "three-2" ) val pipeline = beginNonFlowingPipeline(fetcher::fetch) .withCache() pipeline.stream(StoreRequest.cached(3, refresh = false)) .assertCompleteStream( Loading( origin = Fetcher ), Data( value = "three-1", origin = Fetcher ) ) pipeline.stream(StoreRequest.cached(3, refresh = false)) .assertCompleteStream( Data( value = "three-1", origin = Cache ) ) pipeline.stream(StoreRequest.fresh(3)) .assertItems( Loading( origin = Fetcher ), Data( value = "three-2", origin = Fetcher ) ) pipeline.stream(StoreRequest.cached(3, refresh = false)) .assertItems( Data( value = "three-2", origin = Cache ) ) } @Test fun getAndFresh_withPersister() = runBlocking<Unit> { val fetcher = FakeFetcher( 3 to "three-1", 3 to "three-2" ) val persister = InMemoryPersister<Int, String>() val pipeline = beginNonFlowingPipeline(fetcher::fetch) .withNonFlowPersister( reader = persister::read, writer = persister::write ) .withCache() pipeline.stream(StoreRequest.cached(3, refresh = false)) .assertItems( Loading( origin = Fetcher ), Data( value = "three-1", origin = Fetcher ) ) pipeline.stream(StoreRequest.cached(3, refresh = false)) .assertItems( Data( value = "three-1", origin = Cache ) ) pipeline.stream(StoreRequest.fresh(3)) .assertItems( Loading( origin = Fetcher ), Data( value = "three-2", origin = Fetcher ) ) pipeline.stream(StoreRequest.cached(3, refresh = false)) .assertItems( Data( value = "three-2", origin = Cache ) ) } @Test fun streamAndFresh_withPersister() = testScope.runBlockingTest { val fetcher = FakeFetcher( 3 to "three-1", 3 to "three-2" ) val persister = InMemoryPersister<Int, String>() val pipeline = beginNonFlowingPipeline(fetcher::fetch) .withNonFlowPersister( reader = persister::read, writer = persister::write ) .withCache() pipeline.stream(StoreRequest.cached(3, refresh = true)) .assertItems( Loading( origin = Fetcher ), Data( value = "three-1", origin = Fetcher ) ) pipeline.stream(StoreRequest.cached(3, refresh = true)) .assertItems( Data( value = "three-1", origin = Cache ), Data( value = "three-1", origin = Persister ), Loading( origin = Fetcher ), Data( value = "three-2", origin = Fetcher ) ) } @Test fun streamAndFresh() = testScope.runBlockingTest { val fetcher = FakeFetcher( 3 to "three-1", 3 to "three-2" ) val pipeline = beginNonFlowingPipeline(fetcher::fetch) .withCache() pipeline.stream(StoreRequest.cached(3, refresh = true)) .assertCompleteStream( Loading( origin = Fetcher ), Data( value = "three-1", origin = Fetcher ) ) pipeline.stream(StoreRequest.cached(3, refresh = true)) .assertCompleteStream( Data( value = "three-1", origin = Cache ), Loading( origin = Fetcher ), Data( value = "three-2", origin = Fetcher ) ) } @Test fun skipCache() = testScope.runBlockingTest { val fetcher = FakeFetcher( 3 to "three-1", 3 to "three-2" ) val pipeline = beginNonFlowingPipeline(fetcher::fetch) .withCache() pipeline.stream(StoreRequest.skipMemory(3, refresh = false)) .assertCompleteStream( Loading( origin = Fetcher ), Data( value = "three-1", origin = Fetcher ) ) pipeline.stream(StoreRequest.skipMemory(3, refresh = false)) .assertCompleteStream( Loading( origin = Fetcher ), Data( value = "three-2", origin = Fetcher ) ) } @Test fun flowingFetcher() = testScope.runBlockingTest { val fetcher = FlowingFakeFetcher( 3 to "three-1", 3 to "three-2" ) val persister = InMemoryPersister<Int, String>() val pipeline = beginPipeline(fetcher::createFlow) .withNonFlowPersister( reader = persister::read, writer = persister::write ) pipeline.stream(StoreRequest.fresh(3)) .assertItems( Loading( origin = Fetcher ), Data( value = "three-1", origin = Fetcher ), Data( value = "three-2", origin = Fetcher ) ) pipeline.stream(StoreRequest.cached(3, refresh = true)).assertItems( Data( value = "three-2", origin = Persister ), Loading( origin = Fetcher ), Data( value = "three-1", origin = Fetcher ), Data( value = "three-2", origin = Fetcher ) ) } @Test fun diskChangeWhileNetworkIsFlowing_simple() = testScope.runBlockingTest { val persister = InMemoryPersister<Int, String>().asObservable() val pipeline = beginPipeline<Int, String> { flow { // never emit } }.withPersister( reader = persister::flowReader, writer = persister::flowWriter ) launch { delay(10) persister.flowWriter(3, "local-1") } pipeline .stream(StoreRequest.cached(3, refresh = true)) .assertItems( Loading( origin = Fetcher ), Data( value = "local-1", origin = Persister ) ) } @Test fun diskChangeWhileNetworkIsFlowing_overwrite() = testScope.runBlockingTest { val persister = InMemoryPersister<Int, String>().asObservable() val pipeline = beginPipeline<Int, String> { flow { delay(10) emit("three-1") delay(10) emit("three-2") } }.withPersister( reader = persister::flowReader, writer = persister::flowWriter ) launch { delay(5) persister.flowWriter(3, "local-1") delay(10) // go in between two server requests persister.flowWriter(3, "local-2") } pipeline .stream(StoreRequest.cached(3, refresh = true)) .assertItems( Loading( origin = Fetcher ), Data( value = "local-1", origin = Persister ), Data( value = "three-1", origin = Fetcher ), Data( value = "local-2", origin = Persister ), Data( value = "three-2", origin = Fetcher ) ) } @Test fun errorTest() = testScope.runBlockingTest { val exception = IllegalArgumentException("wow") val persister = InMemoryPersister<Int, String>().asObservable() val pipeline = beginNonFlowingPipeline<Int, String> { key: Int -> throw exception }.withPersister( reader = persister::flowReader, writer = persister::flowWriter ) launch { delay(10) persister.flowWriter(3, "local-1") } pipeline.stream(StoreRequest.cached(key = 3, refresh = true)) .assertItems( Loading( origin = Fetcher ), StoreResponse.Error( error = exception, origin = Fetcher ), Data( value = "local-1", origin = Persister ) ) pipeline.stream(StoreRequest.cached(key = 3, refresh = true)) .assertItems( Data( value = "local-1", origin = Persister ), Loading( origin = Fetcher ), StoreResponse.Error( error = exception, origin = Fetcher ) ) } suspend fun PipelineStore<Int, String>.get(request: StoreRequest<Int>) = this.stream(request).filter { it.dataOrNull() != null }.first() suspend fun PipelineStore<Int, String>.get(key: Int) = get( StoreRequest.cached( key = key, refresh = false ) ) suspend fun PipelineStore<Int, String>.fresh(key: Int) = get( StoreRequest.fresh( key = key ) ) private class FlowingFakeFetcher<Key, Output>( vararg val responses: Pair<Key, Output> ) { fun createFlow(key: Key) = flow { responses.filter { it.first == key }.forEach { emit(it.second) delay(1) } } } private class FakeFetcher<Key, Output>( vararg val responses: Pair<Key, Output> ) { private var index = 0 @Suppress("RedundantSuspendModifier") // needed for function reference suspend fun fetch(key: Key): Output { if (index >= responses.size) { throw AssertionError("unexpected fetch request") } val pair = responses[index++] assertThat(pair.first).isEqualTo(key) return pair.second } } private class InMemoryPersister<Key, Output> { private val data = mutableMapOf<Key, Output>() @Suppress("RedundantSuspendModifier")// for function reference suspend fun read(key: Key) = data[key] @Suppress("RedundantSuspendModifier") // for function reference suspend fun write(key: Key, output: Output) { data[key] = output } suspend fun asObservable() = SimplePersisterAsFlowable( reader = this::read, writer = this::write ) } /** * Asserts only the [expected] items by just taking that many from the stream * * Use this when Pipeline has an infinite part (e.g. Persister or a never ending fetcher) */ private suspend fun <T> Flow<T>.assertItems(vararg expected: T) { assertThat(this.take(expected.size).toList()) .isEqualTo(expected.toList()) } /** * Takes all elements from the stream and asserts them. * Use this if test does not have an infinite flow (e.g. no persister or no infinite fetcher) */ private suspend fun <T> Flow<T>.assertCompleteStream(vararg expected: T) { assertThat(this.toList()) .isEqualTo(expected.toList()) } }
0
null
0
0
e9d6a91d838727740e0f59628e6c88b6226c3c4f
14,510
Core
Apache License 2.0
1277.Count Square Submatrices with All Ones.kt
sarvex
842,260,390
false
{"Kotlin": 1775678, "PowerShell": 418}
internal class Solution { fun countSquares(matrix: Array<IntArray>): Int { val m = matrix.size val n = matrix[0].size val f = Array(m) { IntArray(n) } var ans = 0 for (i in 0 until m) { for (j in 0 until n) { if (matrix[i][j] == 0) { continue } if (i == 0 || j == 0) { f[i][j] = 1 } else { f[i][j] = min(f[i - 1][j - 1], min(f[i - 1][j], f[i][j - 1])) + 1 } ans += f[i][j] } } return ans } }
0
Kotlin
0
0
71f5d03abd6ae1cd397ec4f1d5ba04f792dd1b48
514
kotlin-leetcode
MIT License
Framework/src/main/kotlin/net/milosvasic/factory/application/ArgumentsValidator.kt
Server-Factory
326,063,014
true
{"Kotlin": 470923, "Shell": 188}
package net.milosvasic.factory.application import net.milosvasic.factory.common.exception.EmptyDataException import net.milosvasic.factory.common.validation.Validation import net.milosvasic.factory.validation.Validator class ArgumentsValidator : Validation<Array<String>> { @Throws(EmptyDataException::class, IllegalArgumentException::class) override fun validate(vararg what: Array<String>): Boolean { Validator.Arguments.validateSingle(what) val args = what[0] if (args.isEmpty()) { throw EmptyDataException() } return true } }
0
Kotlin
0
1
7c9a48ac22541c01d56cb7ed404348f9dbcf6d6d
598
Core-Framework
Apache License 2.0
feature/favorite/src/test/kotlin/io/github/shinhyo/brba/feature/favorite/FavoriteViewModelTest.kt
shinhyo
347,642,471
false
{"Kotlin": 171169, "Shell": 587}
/* * Copyright 2024 shinhyo * * 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. */ import app.cash.turbine.test import io.github.shinhyo.brba.core.model.BrbaCharacter import io.github.shinhyo.brba.core.testing.BaseViewModelTest import io.github.shinhyo.brba.feature.favorate.FavoriteUiState import io.github.shinhyo.brba.feature.favorate.FavoriteViewModel import io.mockk.coEvery import io.mockk.coVerify import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.flow.flow import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runTest import org.junit.Assert.assertEquals import org.junit.Assert.assertTrue import org.junit.Test @ExperimentalCoroutinesApi class FavoriteViewModelTest : BaseViewModelTest<FavoriteViewModel>() { override fun makeViewModel(): FavoriteViewModel = FavoriteViewModel( getFavoriteListUseCase = getFavoriteListUseCase, updateFavoriteUseCase = updateFavoriteUseCase, ) @Test fun `Given ViewModel is initialized, When observed, Then initial state should be Loading`() = runTest { // When val initialState = viewModel.uiState.value // Then assertTrue(initialState is FavoriteUiState.Loading) } @Test fun `Given favorites exist, When uiState is observed, Then it should emit Success with data`() = runTest { // Given val testData = listOf( BrbaCharacter( charId = 2770, name = "<NAME>", birthday = "iaculis", img = "ullamcorper", status = "netus", nickname = "<NAME>", portrayed = "epicuri", category = listOf(), description = "oratio", ), ) coEvery { charactersRepository.getDatabaseList() } returns flowOf(testData) val viewModel = makeViewModel() // Then viewModel.uiState.test { val uiState = awaitItem() assertTrue(uiState is FavoriteUiState.Success) assertEquals(testData, (uiState as FavoriteUiState.Success).list) } } @Test fun `Given getFavoriteListUseCase throws an exception, When uiState is observed, Then it should emit Error`() = runTest { // Given coEvery { charactersRepository.getDatabaseList() } returns flow { throw RuntimeException() } // When viewModel = makeViewModel() // Then viewModel.uiState.test { val uiState = awaitItem() assertTrue(uiState is FavoriteUiState.Error) } } @Test fun `Given no favorites exist, When uiState is observed, Then it should emit Empty`() = runTest { // Given coEvery { charactersRepository.getDatabaseList() } returns flowOf(emptyList()) // When viewModel = makeViewModel() // Then viewModel.uiState.test { val uiState = awaitItem() assertTrue(uiState is FavoriteUiState.Empty) } } @Test fun `Given a character, When onFavoriteClick is called, Then updateFavoriteUseCase should be invoked`() = runTest { // Given coEvery { charactersRepository.updateFavorite(any()) } returns flowOf(true) val character = BrbaCharacter( charId = 3906, name = "<NAME>", birthday = "finibus", img = "nunc", nickname = "<NAME>", isFavorite = false, ) // When viewModel.onFavoriteClick(character) // Then coVerify { updateFavoriteUseCase(character) } } }
0
Kotlin
15
76
8f9c6abc813b778a16d2f93c0c3aa2e0666df1bd
4,469
Compose-BreakingBad
Apache License 2.0
build-logic/convention/src/main/kotlin/com/civciv/app/GitHooks.kt
fatih-ozturk
638,702,981
false
null
package com.civciv.app import com.civciv.app.utils.GitHooksTask import org.gradle.api.Project fun Project.registerPrePushTask() { tasks.register("installGitHooks", GitHooksTask::class.java) { group = "git-hooks" val projectDirectory = rootProject.layout.projectDirectory hookSource.set(projectDirectory.file("scripts/pre-push.sh")) hookOutput.set(projectDirectory.file(".git/hooks/pre-push")) } }
5
Kotlin
0
1
08fff8a03e93d6472a3752c19d0dc7c7515f217a
439
Civciv
Apache License 2.0
kotlin-antd/src/main/kotlin/antd/grid/RowContext.kt
oxiadenine
206,398,615
false
{"Kotlin": 1619835, "HTML": 1515}
package antd.grid import react.Context external val rowContext: Context<RowContextState> external interface RowContextState { var gutter: Array<Number>? var wrap: Boolean? }
1
Kotlin
8
50
e0017a108b36025630c354c7663256347e867251
185
kotlin-js-wrappers
Apache License 2.0
graphql/src/main/kotlin/com/trib3/graphql/resources/GraphQLResource.kt
trib3
191,460,324
false
null
package com.trib3.graphql.resources import com.codahale.metrics.annotation.Timed import com.expediagroup.graphql.server.execution.GraphQLRequestHandler import com.expediagroup.graphql.server.types.GraphQLBatchResponse import com.expediagroup.graphql.server.types.GraphQLRequest import com.expediagroup.graphql.server.types.GraphQLResponse import com.expediagroup.graphql.server.types.GraphQLServerRequest import com.trib3.graphql.GraphQLConfig import com.trib3.graphql.modules.KotlinDataLoaderRegistryFactoryProvider import com.trib3.graphql.websocket.GraphQLContextWebSocketCreatorFactory import com.trib3.server.config.TribeApplicationConfig import com.trib3.server.coroutine.AsyncDispatcher import com.trib3.server.filters.RequestIdFilter import graphql.GraphQL import graphql.GraphQLContext import io.dropwizard.auth.Auth import io.swagger.v3.oas.annotations.Hidden import io.swagger.v3.oas.annotations.Parameter import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.cancelChildren import kotlinx.coroutines.supervisorScope import mu.KotlinLogging import org.eclipse.jetty.http.HttpStatus import org.eclipse.jetty.websocket.server.WebSocketServerFactory import java.security.Principal import java.util.Optional import java.util.concurrent.ConcurrentHashMap import javax.annotation.Nullable import javax.inject.Inject import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse import javax.ws.rs.DELETE import javax.ws.rs.GET import javax.ws.rs.POST import javax.ws.rs.Path import javax.ws.rs.Produces import javax.ws.rs.QueryParam import javax.ws.rs.container.ContainerRequestContext import javax.ws.rs.core.Context import javax.ws.rs.core.MediaType import javax.ws.rs.core.Response import kotlin.collections.set private val log = KotlinLogging.logger {} /** * Helper method for null-safe context map construction */ inline fun <reified T> contextMap(value: T?): Map<*, Any> { return value?.let { mapOf(T::class to value) }.orEmpty() } /** * Helper method to construct a [GraphQLContext]'s underlying [Map] from a [CoroutineScope] and optional [Principal]. */ fun getGraphQLContextMap( scope: CoroutineScope, principal: Principal? = null, ): Map<*, Any> { return contextMap(scope) + contextMap(principal) } /** * Returns a response telling the browser that basic authorization is required */ internal fun unauthorizedResponse(): Response { return Response.status(HttpStatus.UNAUTHORIZED_401).header( "WWW-Authenticate", "Basic realm=\"realm\"", ).build() } /** * Jersey Resource entry point to GraphQL execution. Configures the graphql schemas at * injection time and then executes a [GraphQLRequest] specified query when requested. */ @Path("/graphql") @Produces(MediaType.APPLICATION_JSON) open class GraphQLResource @Inject constructor( private val graphQL: GraphQL, private val graphQLConfig: GraphQLConfig, private val creatorFactory: GraphQLContextWebSocketCreatorFactory, @Nullable val dataLoaderRegistryFactoryProvider: KotlinDataLoaderRegistryFactoryProvider? = null, appConfig: TribeApplicationConfig, ) { // Using the CrossOriginFilter directly is tricky because it avoids setting // CORS headers on websocket requests, so mimic its regex and evaluate that // when doing CORS checking of websockets private val corsRegex = Regex( appConfig.corsDomains.joinToString("|") { "https?://*.?$it|" + "https?://*.?$it:${appConfig.appPort}" }.replace(".", "\\.").replace("*", ".*"), ) internal val runningFutures = ConcurrentHashMap<String, CoroutineScope>() @get:Hidden internal val webSocketFactory = WebSocketServerFactory().apply { if (graphQLConfig.idleTimeout != null) { this.policy.idleTimeout = graphQLConfig.idleTimeout } if (graphQLConfig.maxBinaryMessageSize != null) { this.policy.maxBinaryMessageSize = graphQLConfig.maxBinaryMessageSize } if (graphQLConfig.maxTextMessageSize != null) { this.policy.maxTextMessageSize = graphQLConfig.maxTextMessageSize } this.start() } /** * Execute the query specified by the [GraphQLRequest] */ @POST @Timed @AsyncDispatcher("IO") open suspend fun graphQL( @Parameter(hidden = true) @Auth principal: Optional<Principal>, query: GraphQLServerRequest, @Context requestContext: ContainerRequestContext? = null, ): Response = supervisorScope { val responseBuilder = Response.ok() val contextMap = getGraphQLContextMap(this, principal.orElse(null)) + contextMap(responseBuilder) + contextMap(requestContext) val requestId = RequestIdFilter.getRequestId() if (requestId != null) { runningFutures[requestId] = this } try { val factory = dataLoaderRegistryFactoryProvider?.invoke(query, contextMap) val response = GraphQLRequestHandler(graphQL, factory).executeRequest(query, graphQLContext = contextMap) log.debug("$requestId finished with $response") val responses = when (response) { is GraphQLResponse<*> -> listOf(response) is GraphQLBatchResponse -> response.responses } if ( responses.all { r -> r.data == null } && responses.all { r -> val errors = r.errors errors != null && errors.all { it.message == "HTTP 401 Unauthorized" } } ) { unauthorizedResponse() } else { responseBuilder.entity(response).build() } } finally { if (requestId != null) { runningFutures.remove(requestId) } } } /** * Allow cancellation of running queries by [requestId]. */ @DELETE fun cancel( @Parameter(hidden = true) @Auth principal: Optional<Principal>, @QueryParam("id") requestId: String, ): Response { if (graphQLConfig.checkAuthorization && !principal.isPresent) { return unauthorizedResponse() } val running = runningFutures[requestId] if (running != null) { running.coroutineContext[Job]?.cancelChildren() } return Response.status(HttpStatus.NO_CONTENT_204).build() } /** * For websocket subscriptions, support upgrading from GET to a websocket */ @GET @Timed open fun graphQLUpgrade( @Parameter(hidden = true) @Auth principal: Optional<Principal>, @Context request: HttpServletRequest, @Context response: HttpServletResponse, @Context containerRequestContext: ContainerRequestContext, ): Response { val origin = request.getHeader("Origin") if (origin != null) { if (!origin.matches(corsRegex)) { return unauthorizedResponse() } } // Create a new WebSocketCreator for each request bound to an optional authorized principal val creator = creatorFactory.getCreator(containerRequestContext) return if (webSocketFactory.isUpgradeRequest(request, response) && webSocketFactory.acceptWebSocket(creator, request, response) ) { Response.status(HttpStatus.SWITCHING_PROTOCOLS_101).build() } else { Response.status(HttpStatus.METHOD_NOT_ALLOWED_405).build() } } }
6
Kotlin
2
7
233aa30c2ebe69c019692c69c3f1934e21f78cea
7,662
leakycauldron
Apache License 2.0
src/main/kotlin/me/nobaboy/nobaaddons/commands/subcommands/HelpCommand.kt
nobaboy
778,328,806
false
{"Kotlin": 147079}
package me.nobaboy.nobaaddons.commands.subcommands import me.nobaboy.nobaaddons.NobaAddons import me.nobaboy.nobaaddons.commands.ISubCommand import me.nobaboy.nobaaddons.util.ChatUtils class HelpCommand : ISubCommand { fun getHelpMessage(type: String): String { return when (type.lowercase()) { "dmcommands" -> """ #§7§m-----------------§r§7[ §9DM Commands §7]§m----------------- # §3Prefixes: §r! ? . # # §3help §7» §rSends all usable commands. # §3warpme §7» §rWarp user to your lobby. # §3partyme (Alias: !pme) §7» §rInvite user to party. #§7§m----------------------------------------------- """.trimMargin("#") "partycommands" -> """ #§7§m-----------------§r§7[ §9Party Commands §7]§m----------------- # §3Prefixes: §r! ? . # # §3help §7» §rSends all usable commands. # §3ptme (Alias: !transfer or !pt) §7» §rTransfer party to the player who ran the command." # §3allinvite (Alias: !allinv) §7» §rTurns on all invite party setting. # §3warp [optional: seconds] §7» §rRequests party warp with an optional warp delay. # §3cancel §7» §rStop the current delayed warp. # §3warpme §7» §rWarp user to your lobby. # §3coords §7» §rSends current location of user. #§7§m-------------------------------------------------- """.trimMargin("#") "guildcommands" -> """ #§7§m-----------------§r§7[ §9Guild Commands §7]§m----------------- # §3Prefixes: §r! ? . # # §3help §7» §rSends all usable commands. # §3warpout [username] §7» §rWarp out a player. #§7§m------------------------------------------------- """.trimMargin("#") else -> """ #§7§m-----------------§r§7[ §9NobaAddons §7]§m----------------- # §3§l◆ §3Mod Version: §b${NobaAddons.MOD_VERSION} # # §9§l➜ Commands and Info: # §3/nobaaddons (Alias: /noba) §7» §rOpens the mod Config GUI. # §3/noba help §7» §rSends this help message. # §9§l➜ Chat Commands: # §3/noba help dmCommands §7» §rSends usable DM Commands. # §3/noba help partyCommands §7» §rSends usable Party Commands. # §3/noba help guildCommands §7» §rSends usable Guild Commands. # §9§l➜ Dungeons: # §3/noba ssPB §7» §rGet SS PB time. # §3/noba ssAverage §7» §rSend average time taken to complete SS Device. # §3/noba ssRemoveLast §7» §rRemove the last SS time. # §3/noba ssClearTimes §7» §rClear SS Times. # §3/noba refillPearls §7» §rRefills you with pearls up to 16. # §9§l➜ Debug: # §3/noba debugParty §7» Sends a debug response of the users party #§7§m----------------------------------------------- """.trimMargin("#") } } override val name: String = "help" override fun run(args: Array<String>) { val helpMessage = getHelpMessage((if (args.isNotEmpty()) args[0] else "")) ChatUtils.addMessage(false, helpMessage) } }
0
Kotlin
0
1
cebdef91337207fe8289c978e2cc878fc3bfd63f
3,752
NobaAddons-old
The Unlicense
src/main/kotlin/ph/mcmod/csd/item/BowlFoodItem.kt
Phoupraw
523,310,408
false
null
package ph.mcmod.csd.item import net.minecraft.advancement.criterion.Criteria import net.minecraft.entity.LivingEntity import net.minecraft.entity.player.PlayerEntity import net.minecraft.item.Item import net.minecraft.item.ItemStack import net.minecraft.item.ItemUsage import net.minecraft.item.PotionItem import net.minecraft.item.Items import net.minecraft.server.network.ServerPlayerEntity import net.minecraft.stat.Stats import net.minecraft.util.Hand import net.minecraft.util.TypedActionResult import net.minecraft.util.UseAction import net.minecraft.world.World import net.minecraft.world.event.GameEvent class BowlFoodItem(settings: Settings) : Item(settings) { override fun finishUsing(stack: ItemStack, world: World, user: LivingEntity): ItemStack { user.eatFood(world,stack) if (user is PlayerEntity) { if (user is ServerPlayerEntity) { Criteria.CONSUME_ITEM.trigger(user, stack) } user.incrementStat(Stats.USED.getOrCreateStat(this)) ItemUsage.exchangeStack(stack, user, Items.BOWL.defaultStack) } world.emitGameEvent(user, GameEvent.EAT, user.cameraBlockPos) return stack } override fun use(world: World?, user: PlayerEntity?, hand: Hand?): TypedActionResult<ItemStack?>? { return ItemUsage.consumeHeldItem(world, user, hand) } }
1
Kotlin
2
4
3d6870faea3f44d97523431fc6b7ee0b371c67fb
1,374
CreateSDelight
The Unlicense
tempo/src/main/java/io/tempo/internal/tempo_event_utils.kt
AllanHasegawa
96,262,686
false
null
package io.tempo.internal import io.tempo.TempoEvent import io.tempo.internal.data.TempoEventLogger internal fun TempoEvent.log(logger: TempoEventLogger) = logger.log(this)
1
Kotlin
13
62
e915139accff22e7b4b10a4d5bcf967c30805823
174
Tempo
Apache License 2.0
idea/testData/refactoring/renameMultiModule/headersAndImplsByImplFun/before/Common/src/test/test.kt
gigliovale
89,726,097
false
null
package test header fun foo() header fun foo(n: Int) header fun bar(n: Int) fun test() { foo() foo(1) bar(1) }
0
null
4
6
ce145c015d6461c840050934f2200dbc11cb3d92
124
kotlin
Apache License 2.0
app/src/main/java/com/rogertalk/roger/event/success/SmsTokenAnswerSuccessEvent.kt
rogertalk
207,123,525
false
{"C": 1446968, "Kotlin": 1051662, "C++": 79853, "Objective-C": 32032, "Java": 22252, "Makefile": 1047}
package com.rogertalk.roger.event.success import com.rogertalk.roger.models.json.SmsTokenAnswer data class SmsTokenAnswerSuccessEvent(val smsTokenAnswer: SmsTokenAnswer)
0
C
0
1
55c9922947311d9d8a1e930463b9ac2a1332e006
172
roger-android
MIT License
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/covidcertificate/person/model/SettingsMap.kt
corona-warn-app
268,027,139
false
null
package de.rki.coronawarnapp.covidcertificate.person.model import com.fasterxml.jackson.core.JsonGenerator import com.fasterxml.jackson.core.JsonProcessingException import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonSerializer import com.fasterxml.jackson.databind.KeyDeserializer import com.fasterxml.jackson.databind.SerializerProvider import com.fasterxml.jackson.databind.annotation.JsonDeserialize import com.fasterxml.jackson.databind.annotation.JsonSerialize import com.fasterxml.jackson.module.kotlin.readValue import de.rki.coronawarnapp.covidcertificate.common.certificate.CertificatePersonIdentifier import de.rki.coronawarnapp.util.serialization.SerializationModule import java.io.IOException class PersonIdentifierSerializer : JsonSerializer<CertificatePersonIdentifier>() { @Throws(IOException::class, JsonProcessingException::class) override fun serialize( value: CertificatePersonIdentifier?, gen: JsonGenerator?, serializers: SerializerProvider? ) { gen?.let { jGen -> value?.let { id -> jGen.writeFieldName(SerializationModule.jacksonBaseMapper.writeValueAsString(id)) } ?: jGen.writeNull() } } } class PersonIdentifierDeserializer : KeyDeserializer() { @Throws(IOException::class, JsonProcessingException::class) override fun deserializeKey(key: String?, ctxt: DeserializationContext?): CertificatePersonIdentifier? { return key?.let { SerializationModule.jacksonBaseMapper.readValue<CertificatePersonIdentifier>(key) } } } data class SettingsMap( @JsonSerialize(keyUsing = PersonIdentifierSerializer::class) @JsonDeserialize(keyUsing = PersonIdentifierDeserializer::class) val settings: Map<CertificatePersonIdentifier, PersonSettings> )
6
null
514
2,495
d3833a212bd4c84e38a1fad23b282836d70ab8d5
1,842
cwa-app-android
Apache License 2.0
app/src/main/java/com/immimu/pm/db/converter/StatusConverter.kt
immimu
154,905,332
false
null
package com.immimu.pm.db.converter import android.arch.persistence.room.TypeConverter import com.immimu.pm.entity.Status /** * Created by root on 01/10/17. */ class StatusConverter { @TypeConverter fun toStatus(code: Int): Status { return when (code) { 1 -> Status.IN_PROGRESS 2 -> Status.DONE else -> Status.TODO } } @TypeConverter fun toInt(status: Status): Int { return when (status) { Status.IN_PROGRESS -> 1 Status.DONE -> 2 else -> 0 } } }
0
Kotlin
0
0
94101b4292eb000e5287e5beb770b762e86a2173
516
project-manager
Apache License 2.0
lcds/src/main/java/com/v5ent/xiubit/data/recylerapter/MemberInvestRecordAdapter.kt
wuhanligong110
148,960,988
false
{"Java": 5585019, "Kotlin": 539029}
package com.v5ent.xiubit.data.recylerapter import android.view.View import android.widget.ImageView import com.chad.library.adapter.base.BaseQuickAdapter import com.chad.library.adapter.base.BaseViewHolder import com.toobei.common.TopBaseActivity import com.toobei.common.entity.CustomerInvestRecordData import com.toobei.common.utils.PhotoUtil import com.v5ent.xiubit.R import com.v5ent.xiubit.activity.WebActivityCommon import com.v5ent.xiubit.util.C /** * 公司: tophlc * 类说明: * * @author hasee-pc * @time 2017/10/18 */ class MemberInvestRecordAdapter : BaseQuickAdapter<CustomerInvestRecordData, BaseViewHolder> { var memberType: Int = 0 companion object { val MEMBERTYPE_CUSTOMER = 1 val MEMBERTYPE_CFG = 2 } var titleList = ArrayList<String>() val titlePostion = ArrayList<Int>() var leveltags = listOf<Int>( R.drawable.ic_customer_tag , R.drawable.ic_direct_cfg_tag , R.drawable.ic_two_cfg_tag , R.drawable.ic_three_cfg_tag) constructor(memberType: Int) : super(R.layout.item_member_invest) { this.memberType = memberType } override fun convert(helper: BaseViewHolder, item: CustomerInvestRecordData) { val position = helper.adapterPosition if (!titleList.contains(item.investTime)) { titleList.add(item.investTime) titlePostion.add(position) } if (titlePostion.contains(position)) { helper.setText(R.id.dateTv, item.investTime) helper.getView<View>(R.id.dateTv).visibility = View.VISIBLE helper.getView<View>(R.id.divideV).visibility = if (position == 1) View.GONE else View.VISIBLE } else { helper.getView<View>(R.id.dateTv).visibility = View.GONE helper.getView<View>(R.id.divideV).visibility = View.GONE } PhotoUtil.loadImageByGlide(mContext, item.headImage, helper.getView<ImageView>(R.id.headIv), C.DefaultResId.HEADER_IMG) if (memberType != MEMBERTYPE_CUSTOMER) { helper.setImageResource(R.id.cfgTypeTagIv, leveltags[item.userType]) } var nameSuffix = when (item.userType) { 0, 1 -> "" 2 -> "的直推理财师" 3 -> "的二级理财师" else -> "" } helper.setText(R.id.nameTv, item.userName) .setText(R.id.nameSuffixTv, nameSuffix) .setText(R.id.platformNameTv, item.orgName) .setText(R.id.issueAmountTv, item.investAmt) .setText(R.id.commissionTv, item.feeAmount) .setText(R.id.platformTypeTv, if (item.userType == 0) "投资平台" else "出单平台") .setText(R.id.issueTypeTv, if (item.userType == 0) "投资金额" else "出单金额(元)") helper.getView<View>(R.id.rootView).setOnClickListener { WebActivityCommon.showThisActivity(mContext as TopBaseActivity, "${C.INVEST_DETIAL}${item.investId}&canJumpNative=0", "") } } override fun setNewData(data: MutableList<CustomerInvestRecordData>?) { super.setNewData(data) titleList.clear() titlePostion.clear() } }
0
Java
1
1
5723b5a8187a14909f605605b42fb3e7a8c3d768
3,155
xiubit-android
MIT License
game/plugin/cmd/src/debug-cmd.plugin.kts
stevesoltys
140,373,082
false
{"Java": 873190, "Ruby": 227078, "Kotlin": 222820, "Groovy": 2503}
import org.apollo.game.message.impl.* import org.apollo.game.model.entity.attr.* import org.apollo.game.model.entity.setting.PrivilegeLevel AttributeMap.define("debug_mode", AttributeDefinition(false, AttributePersistence.PERSISTENT, AttributeType.BOOLEAN)) on_command("debug", PrivilegeLevel.ADMINISTRATOR) .then { player -> val debugMode = ((player.attributes["debug_mode"]?.value ?: false) as Boolean).not() player.setAttribute("debug_mode", BooleanAttribute(debugMode)) player.sendMessage("Debug mode is now ${if (debugMode) "enabled" else "disabled"}.") } on { ButtonMessage::class } .then { player -> val debugMode = (player.attributes["debug_mode"]?.value ?: false) as Boolean if (debugMode) { player.sendMessage("ButtonMessage -> { Index: $index, Interface: $interfaceId, Button: $button, " + "Child button: $childButton, I Item: $itemId }") } } on { ObjectActionMessage::class } .then { player -> val debugMode = (player.attributes["debug_mode"]?.value ?: false) as Boolean if (debugMode) { player.sendMessage("ObjectActionMessage -> { Object: $id, Option: $option, Position: " + "(${position.x}, ${position.y}, ${position.height}) }") } } on { ItemOptionMessage::class } .then { player -> val debugMode = (player.attributes["debug_mode"]?.value ?: false) as Boolean if (debugMode) { player.sendMessage("ItemOptionMessage -> { Interface: $interfaceId, Slot: $slot, Item: $id, " + "Option: $option }") } } on { ItemOnItemMessage::class } .then { player -> val debugMode = (player.attributes["debug_mode"]?.value ?: false) as Boolean if (debugMode) { player.sendMessage("ItemOnItemMessage -> { Interface: $interfaceId -> $targetInterfaceId, " + "Slot: $slot -> $targetSlot, Item: $id -> $targetId }") } } on { NpcActionMessage::class } .then { player -> val debugMode = (player.attributes["debug_mode"]?.value ?: false) as Boolean if (debugMode) { val npc = player.world.npcRepository.get(index) player.sendMessage("NpcActionMessage -> { NPC: ${npc.id}, Option: $option }") } }
18
null
1
1
3818a83fd2b437c3bd878d147fd6aff2374ee3fb
2,502
apollo-osrs
ISC License
app/src/main/java/com/eokoe/sagui/services/Retry.kt
AppCivico
99,857,442
false
{"Gradle": 3, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 2, "Batchfile": 1, "Proguard": 1, "Java": 5, "XML": 160, "JSON": 1, "Kotlin": 152}
package com.eokoe.sagui.services import android.content.Context /** * Created by pedroabinajm on 08/08/17. */ interface Retry { fun schedule(context: Context) fun cancel(context: Context) }
0
Kotlin
0
2
6d55559aeb81b6917bc13364765b14d4d832b753
202
sagui-android
MIT License
core/src/main/java/com/sha/formvalidator/textview/validator/LengthRangeValidator.kt
ShabanKamell
110,319,898
false
null
package com.sha.formvalidator.textview.validator /** * A validator that returns true only if the text is within the given range. * */ class LengthRangeValidator(errorMessage: String, private val min: Int, private val max: Int) : TextValidator(errorMessage) { override fun isValid(text: String): Boolean { val length = text.length return length in min..max } }
1
Kotlin
12
89
eaa1dd1714353e2b57f3f58f4bf579407bba36a0
389
FormValidator
Apache License 2.0
server/cache/src/main/kotlin/io/rsbox/server/cache/GameCache.kt
rsbox
704,702,007
false
{"Java": 2428938, "Kotlin": 633136}
package io.rsbox.server.cache import io.netty.buffer.UnpooledByteBufAllocator import io.rsbox.server.cache.model.Archive import io.rsbox.server.common.get import org.openrs2.cache.Cache import org.openrs2.cache.Js5MasterIndex import org.openrs2.cache.Store import java.io.File class GameCache { private val archives = mutableMapOf<Int, Archive>() lateinit var store: Store private set lateinit var cache: Cache private set lateinit var masterIndex: Js5MasterIndex private set lateinit var configArchive: ConfigArchive private set lateinit var mapArchive: MapArchive private set fun load() { store = Store.open(CACHE_DIR.toPath(), UnpooledByteBufAllocator.DEFAULT) cache = Cache.open(store, UnpooledByteBufAllocator.DEFAULT) masterIndex = Js5MasterIndex.create(store) /* * Load all game model archives. */ configArchive = ConfigArchive.load(readArchive(ConfigArchive.id)) mapArchive = MapArchive() } fun readArchive(archiveId: Int): Archive { return if(archives.containsKey(archiveId)) archives[archiveId]!! else { val archive = Archive(archiveId) archives[archiveId] = archive archive } } companion object { private val CACHE_DIR = File("data/cache/") val cache by lazy { get<GameCache>().cache } val store by lazy { get<GameCache>().store } } }
1
null
1
1
58d6086e3318170a069c9a4985d06e068b853535
1,455
rsbox
Apache License 2.0
app/src/main/java/com/petitsraids/yunbiandialer/support/MyUtils.kt
PetitsRaids
222,222,345
false
null
package com.petitsraids.yunbiandialer.support import android.content.Context object MyUtils { const val TAG = "YunBianDialer" const val REQUEST_CODE_CALL = 0 const val SHARED_NAME = "font_size" const val SHARED_KEY = "font_size_key" const val FONT_SIZE_SMALL = 1 const val FONT_SIZE_MEDIUM = 2 const val FONT_SIZE_LARGE = 3 const val FONT_SIZE_XLARGE = 4 const val FONT_SIZE_XXLARGE = 5 fun dp2px(context: Context, value: Float): Int { val scale = context.resources.displayMetrics.density return (scale * value + 0.5f).toInt() } fun theme2dp(theme: Int): Float { var dpSize = 0 when (theme) { FONT_SIZE_SMALL -> dpSize = 36 FONT_SIZE_MEDIUM -> dpSize = 41 FONT_SIZE_LARGE -> dpSize = 46 FONT_SIZE_XLARGE -> dpSize = 51 FONT_SIZE_XXLARGE -> dpSize = 56 } return dpSize.toFloat() } fun theme2sp(theme: Int): Float { var dpSize = 0 when (theme) { FONT_SIZE_SMALL -> dpSize = 18 FONT_SIZE_MEDIUM -> dpSize = 22 FONT_SIZE_LARGE -> dpSize = 26 FONT_SIZE_XLARGE -> dpSize = 30 FONT_SIZE_XXLARGE -> dpSize = 34 } return dpSize.toFloat() } }
1
null
1
1
1fe75b92f2e78cf0077369aae37b2c8171a4bfb9
1,300
YunBianDialer
Apache License 2.0
modules/gclib/src/main/kotlin/com/github/guqt178/utils/ext/DensityExt.kt
nakupenda178
246,516,496
false
{"Java": 4888326, "Kotlin": 281154}
package com.github.guqt178.utils.ext import android.content.Context import android.util.TypedValue fun Context.px2dp(px: Number) = TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, px.toFloat(), this.resources.displayMetrics )
1
Java
1
2
d35e7758dab47776290e86b9306d0a8530be1a16
260
gclib
Apache License 2.0
bbfgradle/tmp/results/diffCompile/ipwngbc.kt
DaniilStepanov
346,008,310
false
null
// Different compile happens on:JVM ,JVM -Xnew-inference interface BK { fun foo() fun bar() } interface K : BK { override fun foo() = TODO() } class A : K { override fun bar() = TODO() class B : K { fun box(): String { var aInt: Int var bInt: Int var bFloat: Float = TODO() if (aInt != null) throw RuntimeException() if (aInt != bInt) return "" 1+ bInt++ } override fun bar() = TODO() } }
1
null
1
1
e772ef1f8f951873ebe7d8f6d73cf19aead480fa
420
kotlinWithFuzzer
Apache License 2.0
freight-processor/src/main/kotlin/io/dwak/freight/processor/extension/StringExt.kt
dinosaurwithakatana
56,482,482
false
{"Kotlin": 139081, "Java": 19129}
package io.dwak.freight.processor.extension fun String.capitalizeFirst() : String { return "${this[0].toUpperCase()}${this.substring(1, this.length)}" } fun String.ifEmpty(default: String) : String { return if(isEmpty()) default else this }
2
Kotlin
1
11
47bf2a016f16734a3000d44d53c7716e0f4389de
249
freight
Apache License 2.0
actorsystem-servicecontract/src/main/kotlin/org/actorlang/actorsystem/exception/DoesNotReferenceALocalActorException.kt
422404
371,440,848
false
{"Java": 174885, "Kotlin": 156913, "ANTLR": 3771, "Shell": 991}
package org.actorlang.actorsystem.exception import org.actorlang.actorsystem.messaging.RemoteActorRef class DoesNotReferenceALocalActorException(actorRef: RemoteActorRef) : ActorSystemRuntimeException( "The actor ref $actorRef does not represent a known local actor" )
23
Java
1
3
bccf9c554e2dc2ad9c946cf8f38cacdd7002b555
275
ActorLang
MIT License
app/src/main/java/net/yslibrary/monotweety/appdata/local/LocalModule.kt
yshrsmz
69,078,478
false
{"Kotlin": 444779}
package net.yslibrary.monotweety.appdata.local import android.content.Context import android.database.sqlite.SQLiteOpenHelper import com.pushtorefresh.storio3.sqlite.StorIOSQLite import com.pushtorefresh.storio3.sqlite.impl.DefaultStorIOSQLite import dagger.Module import dagger.Provides import net.yslibrary.monotweety.appdata.user.User import net.yslibrary.monotweety.appdata.user.local.resolver.UserSQLiteTypeMapping import javax.inject.Singleton @Module class LocalModule { @Singleton @Provides fun provideDbOpenHelper(context: Context): SQLiteOpenHelper { return DbOpenHelper(context) } @Singleton @Provides fun provideStorIOSQLite(sqLiteOpenHelper: SQLiteOpenHelper): StorIOSQLite { return DefaultStorIOSQLite.builder() .sqliteOpenHelper(sqLiteOpenHelper) .addTypeMapping(User::class.java, UserSQLiteTypeMapping()) .build() } }
10
Kotlin
25
113
7b5b5fe9e0b1dd4667a024d5e22947132b01c426
922
monotweety
Apache License 2.0
Corona-Warn-App/src/main/java/de/rki/coronawarnapp/http/WebRequestBuilder.kt
activesince93
269,008,182
false
null
/****************************************************************************** * Corona-Warn-App * * * * SAP SE and all other contributors / * * copyright owners license this file to you 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 de.rki.coronawarnapp.http import KeyExportFormat import android.util.Log import com.android.volley.DefaultRetryPolicy import com.android.volley.Response import com.android.volley.VolleyError import com.android.volley.toolbox.JsonArrayRequest import com.android.volley.toolbox.StringRequest import de.rki.coronawarnapp.BuildConfig import de.rki.coronawarnapp.exception.WebRequestException import de.rki.coronawarnapp.exception.report import de.rki.coronawarnapp.http.request.ApplicationConfigurationRequest import de.rki.coronawarnapp.http.request.KeyFileRequest import de.rki.coronawarnapp.http.request.KeySubmissionRequest import de.rki.coronawarnapp.http.request.RegistrationTokenRequest import de.rki.coronawarnapp.http.request.TanRequest import de.rki.coronawarnapp.http.request.TestResultRequest import de.rki.coronawarnapp.risk.TimeVariables import de.rki.coronawarnapp.server.protocols.ApplicationConfigurationOuterClass.ApplicationConfiguration import de.rki.coronawarnapp.util.IndexHelper.convertToIndex import org.json.JSONArray import java.io.File import java.util.ArrayList import java.util.UUID import kotlin.coroutines.Continuation import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException import kotlin.coroutines.suspendCoroutine object WebRequestBuilder { private val TAG: String? = WebRequestBuilder::class.simpleName private const val MAX_RETRIES = 3 private const val BACKOFF_MULTIPLIER = 2F private val standardRetryPolicy by lazy { DefaultRetryPolicy( TimeVariables.getTransactionTimeout().toInt(), MAX_RETRIES, BACKOFF_MULTIPLIER ) } suspend fun <T> asyncGetArrayListFromGenericRequest( url: String, parser: (JSONArray) -> ArrayList<T> ) = suspendCoroutine<ArrayList<T>> { cont -> val requestID = UUID.randomUUID() val getArrayListRequest = JsonArrayRequest( url, Response.Listener { response -> Log.d(TAG, "$requestID: Response is $response") cont.resume(parser(response)) }, RequestErrorListener(requestID, cont) ) RequestQueueHolder.addToRequestQueue(getArrayListRequest) Log.d(TAG, "$requestID: Added $url to queue.") } suspend fun asyncGetIndexBasedQueryURLsFromServer(url: String) = suspendCoroutine<Map<Long, String>> { cont -> val requestID = UUID.randomUUID() val getArrayListRequest = StringRequest( url, Response.Listener { response -> if (BuildConfig.DEBUG) Log.d(TAG, "$requestID: Response is $response") cont.resume(response.convertToIndex()) }, RequestErrorListener(requestID, cont) ) RequestQueueHolder.addToRequestQueue(getArrayListRequest) Log.d(TAG, "$requestID: Added $url to queue.") } /** * Retrieves Key Files from the Server based on a URL * * @param url the given URL */ suspend fun asyncGetKeyFilesFromServer(url: String) = suspendCoroutine<File> { cont -> val requestID = UUID.randomUUID() val request = KeyFileRequest( url, requestID, null, Response.Listener { response -> Log.v(requestID.toString(), "key file request successful. (${response.length()}B)") cont.resume(response) }, RequestErrorListener(requestID, cont) ).also { keyFileRequest -> keyFileRequest.retryPolicy = standardRetryPolicy keyFileRequest.setShouldCache(false) keyFileRequest.setShouldRetryServerErrors(true) } RequestQueueHolder.addToRequestQueue(request) Log.v(requestID.toString(), "Added $url to queue.") } suspend fun asyncGetApplicationConfigurationFromServer(url: String) = suspendCoroutine<ApplicationConfiguration> { cont -> val requestID = UUID.randomUUID() val getKeyBucketRequest = ApplicationConfigurationRequest( url, requestID, null, Response.Listener { response -> cont.resume(response) }, RequestErrorListener(requestID, cont) ) RequestQueueHolder.addToRequestQueue(getKeyBucketRequest) Log.d(TAG, "$requestID: Added $url to queue.") } suspend fun asyncGetRegistrationToken( url: String, key: String, keyType: String ) = suspendCoroutine<String> { cont -> val requestID = UUID.randomUUID() val getRegistrationTokenRequest = RegistrationTokenRequest( url, requestID, keyType, key, false, standardRetryPolicy, Response.Listener { response -> Log.d( TAG, "$requestID: Registration Token Request successful" ) cont.resume(response) }, RequestErrorListener(requestID, cont) ) RequestQueueHolder.addToRequestQueue(getRegistrationTokenRequest) Log.d(TAG, "$requestID: Added $url to queue.") } suspend fun asyncGetTestResult( url: String, registrationToken: String ) = suspendCoroutine<Int> { cont -> val requestID = UUID.randomUUID() val getTestResultRequest = TestResultRequest( url, requestID, registrationToken, false, standardRetryPolicy, Response.Listener { response -> Log.d( TAG, "$requestID: Test Result Request successful" ) cont.resume(response) }, RequestErrorListener(requestID, cont) ) RequestQueueHolder.addToRequestQueue(getTestResultRequest) Log.d(TAG, "$requestID: Added $url to queue.") } suspend fun asyncGetTan( url: String, registrationToken: String ) = suspendCoroutine<String> { cont -> val requestID = UUID.randomUUID() val getTestResultRequest = TanRequest( url, requestID, registrationToken, false, standardRetryPolicy, Response.Listener { response -> Log.d( TAG, "$requestID: TAN Request successful" ) cont.resume(response) }, RequestErrorListener(requestID, cont) ) RequestQueueHolder.addToRequestQueue(getTestResultRequest) Log.d(TAG, "$requestID: Added $url to queue.") } suspend fun asyncSubmitKeysToServer( url: String, authCode: String, faked: Boolean, keyList: List<KeyExportFormat.TemporaryExposureKey> ) = suspendCoroutine<Int> { cont -> val requestID = UUID.randomUUID() Log.d(TAG, "Writing ${keyList.size} Keys to the Submission Payload.") val submissionPayload = KeyExportFormat.SubmissionPayload.newBuilder() .addAllKeys(keyList) .build() .toByteArray() val submitKeysRequest = KeySubmissionRequest( url, requestID, submissionPayload, authCode, faked, standardRetryPolicy, Response.Listener { response -> Log.d( TAG, "$requestID: Key Submission Request successful." ) cont.resume(response) }, RequestErrorListener(requestID, cont) ) RequestQueueHolder.addToRequestQueue(submitKeysRequest) Log.d(TAG, "$requestID: Added $url to queue.") } private class RequestErrorListener<T>( private val requestID: UUID, private val cont: Continuation<T> ) : Response.ErrorListener { override fun onErrorResponse(error: VolleyError?) { if (error != null) { val webRequestException = WebRequestException("an error occured during a webrequest", error) webRequestException.report(de.rki.coronawarnapp.exception.ExceptionCategory.HTTP) cont.resumeWithException(webRequestException) } else { cont.resumeWithException(NullPointerException("the provided exception from volley was null")) } } } }
0
null
0
1
36921e586e653ad0fc2fc4e67fd5d52dbbfe9618
10,847
cwa-app-android
Apache License 2.0
web-utils/src/main/kotlin/com/icerockdev/exception/ForbiddenException.kt
icerockdev
241,792,535
false
null
/* * Copyright 2020 IceRock MAG Inc. Use of this source code is governed by the Apache 2.0 license. */ package com.icerockdev.exception import io.ktor.http.HttpStatusCode class ForbiddenException(message: String = HttpStatusCode.Forbidden.description) : UserException(HttpStatusCode.Forbidden.value, message)
3
Kotlin
0
2
c3fa6aa5cb777b11bc2ad87e22efa249dab9eb5a
318
web-utils
Apache License 2.0
app/src/main/java/io/github/amirisback/todolist/TodoListApp.kt
amirisback
673,618,440
false
null
package io.github.amirisback.todolist import android.app.Application import android.content.Context import io.github.amirisback.todolist.common.ext.APP_IS_DEBUG import io.github.amirisback.todolist.di.delegateModule import io.github.amirisback.todolist.di.repositoryModule import io.github.amirisback.todolist.di.viewModelModule import org.koin.android.ext.koin.androidContext import org.koin.android.ext.koin.androidLogger import org.koin.core.KoinApplication import org.koin.core.context.startKoin import org.koin.core.logger.Level /** * Created by Amir on 08/02/23 * todolist Source Code * ----------------------------------------- * Name : Muhammad Faisal Amir * E-mail : [email protected] * Github : github.com/amirisback * ----------------------------------------- * Copyright (C) 2023 FrogoBox Inc. * All rights reserved * */ class TodoListApp : Application() { companion object { val TAG: String = TodoListApp::class.java.simpleName lateinit var instance: TodoListApp fun getContext(): Context = instance.applicationContext } override fun onCreate() { super.onCreate() startKoin { androidContext(this@TodoListApp) androidLogger( if (APP_IS_DEBUG) { Level.DEBUG } else { Level.ERROR } ) setupKoinModule(this) } instance = this } private fun setupKoinModule(koinApplication: KoinApplication) { koinApplication.modules( listOf( delegateModule, repositoryModule, viewModelModule ) ) } }
0
Kotlin
0
0
087f4240a4890f40f0a5cb7d8b9917ed101900be
1,728
todolist-jetpack-compose
Apache License 2.0
src/test/kotlin/uk/gov/justice/digital/hmpps/calculatereleasedatesapi/config/CalculationParamsTestConfigHelper.kt
ministryofjustice
387,841,000
false
{"Kotlin": 1306622, "Shell": 7185, "Dockerfile": 1397}
package uk.gov.justice.digital.hmpps.calculatereleasedatesapi.config import org.springframework.beans.factory.config.YamlPropertiesFactoryBean import org.springframework.boot.context.properties.bind.Binder import org.springframework.boot.context.properties.source.MapConfigurationPropertySource import org.springframework.core.io.ClassPathResource object CalculationParamsTestConfigHelper { fun releasePointMultiplierConfigurationForTests(): ReleasePointMultipliersConfiguration { return Binder(propertySource()).bind("release-point-multipliers", ReleasePointMultipliersConfiguration::class.java).get() } fun hdcedConfigurationForTests(): HdcedConfiguration { return Binder(propertySource()).bind("hdced", HdcedConfiguration::class.java).get() } fun ersedConfigurationForTests(): ErsedConfiguration { return Binder(propertySource()).bind("ersed", ErsedConfiguration::class.java).get() } private fun propertySource() = MapConfigurationPropertySource(YamlPropertiesFactoryBean().apply { setResources(ClassPathResource("application-calculation-params.yml")) }.getObject()) }
5
Kotlin
0
4
8e8bb8ec68d743d91c523a8bc08b9a974ba73527
1,102
calculate-release-dates-api
MIT License
ui-compose/src/main/java/cl/tiocomegfas/lib/uicompose/color/BlueberryColor.kt
TioComeGfas
708,796,414
false
{"Kotlin": 146161}
package cl.tiocomegfas.lib.uicompose.color import androidx.compose.ui.graphics.Color class BlueberryColor: AndroidColor { override fun get5Percent(): Color { return Color(0xFFF3F5FC) } override fun get10Percent(): Color { return Color(0xFFD4DCF4) } override fun get20Percent(): Color { return Color(0xFFB5C5ED) } override fun get30Percent(): Color { return Color(0xFF95AEE5) } override fun get40Percent(): Color { return Color(0xFF6E95DC) } override fun get50Percent(): Color { return Color(0xFF4782D4) } override fun get60Percent(): Color { return Color(0xFF096DC4) } override fun get70Percent(): Color { return Color(0xFF19589C) } override fun get80Percent(): Color { return Color(0xFF1C4476) } override fun get90Percent(): Color { return Color(0xFF1B3052) } }
0
Kotlin
0
0
9b923b3f013f2fd19df45659c340caf361387c0a
933
Android-Libraries
Apache License 2.0
src/commonTest/kotlin/io/github/hansanto/kault/engine/kv/v2/response/KvV2ReadResponseTest.kt
Hansanto
712,104,593
false
{"Kotlin": 436555, "Shell": 427}
package io.github.hansanto.kault.engine.kv.v2.response import io.github.hansanto.kault.common.Metadata import io.github.hansanto.kault.compose.JsonDecoderComposer import io.github.hansanto.kault.util.ComplexSerializableClass import io.github.hansanto.kault.util.randomBoolean import io.kotest.core.spec.style.ShouldSpec import io.kotest.matchers.shouldBe import kotlinx.datetime.Instant import kotlinx.serialization.json.JsonObject class KvV2ReadResponseTest : ShouldSpec({ should("check is deleted return true when data is null and metadata is not destroyed") { val response = KvV2ReadResponse(null, createResponse(false)) response.isDeleted() shouldBe true } should("check is deleted return false when data is not null") { val response = KvV2ReadResponse( JsonObject(emptyMap()), createResponse(randomBoolean()) ) response.isDeleted() shouldBe false } should("check is deleted return false when metadata is destroyed") { val response = KvV2ReadResponse(null, createResponse(true)) response.isDeleted() shouldBe false } should("check is destroyed return true when metadata is destroyed") { val response = KvV2ReadResponse(null, createResponse(true)) response.isDestroyed() shouldBe true } should("check is destroyed return false when metadata is not destroyed") { val response = KvV2ReadResponse( JsonObject(emptyMap()), createResponse(false) ) response.isDestroyed() shouldBe false } JsonDecoderComposer.composeSerialFieldTest(this) { val response = createResponse(it) response.data<ComplexSerializableClass>() } }) private fun createResponse(data: JsonObject?) = KvV2ReadResponse( data = data, metadata = createResponse(randomBoolean()) ) private fun createResponse(destroyed: Boolean) = Metadata( createdTime = Instant.DISTANT_PAST, deletionTime = Instant.DISTANT_PAST, customMetadata = null, destroyed = destroyed, version = 1 )
2
Kotlin
0
3
be25c2e7c585ed053e1b4f03ed5a4089b26dafb7
2,080
kault
Apache License 2.0
finance/src/main/java/com/scitrader/finance/state/FinanceChartState.kt
ABTSoftware
468,421,926
false
{"Kotlin": 296559, "Java": 3061}
package com.scitrader.finance.state data class FinanceChartState( val chartState: PropertyState = PropertyState(), val paneStates: MutableMap<String, PropertyState> = HashMap(), )
3
Kotlin
0
2
00245ef7ee93ee79b1b5a1e8a6a77bce0f02777b
189
Finance.Android
Apache License 2.0
chart_server/src/main/kotlin/io/madrona/njord/db/FeatureDao.kt
manimaul
213,533,249
false
{"Kotlin": 319145, "TypeScript": 74099, "Python": 12720, "PLpgSQL": 5294, "HTML": 3275, "Shell": 3043, "Dockerfile": 2008, "CSS": 1315}
package io.madrona.njord.db import com.fasterxml.jackson.module.kotlin.readValue import io.madrona.njord.layers.TopmarData import io.madrona.njord.model.FeatureRecord import io.madrona.njord.model.LayerQueryResult import io.madrona.njord.model.LayerQueryResultPage import org.locationtech.jts.io.WKTReader import java.sql.Connection import java.sql.ResultSet import kotlin.math.max class FeatureDao : Dao() { suspend fun findLayerPositionsPage(layer: String, startId: Long): LayerQueryResultPage? = sqlOpAsync { conn -> conn.prepareStatement( """SELECT features.id, ST_AsText(ST_Centroid(geom)), ST_GeometryType(geom), props, charts.name, charts.zoom FROM features JOIN charts ON features.chart_id = charts.id WHERE features.id > ? AND features.layer = ? ORDER BY features.id LIMIT 5; """.trimIndent() ).apply { setLong(1, startId) setString(2, layer) }.executeQuery().use { val result = mutableListOf<LayerQueryResult>() var lastId = 0L while (it.next()) { val id = it.getLong(1) lastId = max(lastId, id) val wkt = it.getString(2) val coord = WKTReader().read(wkt).coordinate val props: Map<String, Any?> = if (layer == "TOPMAR") { objectMapper.readValue<Map<String, Any?>>(it.getString(4)).toMutableMap().apply { val assoc = findAssociatedLayerNames(this["LNAM"].toString()) TopmarData.fromAssoc(assoc).addTo(this) } } else { objectMapper.readValue(it.getString(4)) } result.add( LayerQueryResult( id = id, lat = coord.y, lng = coord.x, zoom = it.getFloat(6), props = props, chartName = it.getString(5), geomType = it.getString(3).replace("ST_", ""), ) ) } LayerQueryResultPage( lastId = lastId, items = result ) } } suspend fun findAssociatedLayerNames(lnam: String): List<String> = sqlOpAsync { conn -> conn.prepareStatement("SELECT DISTINCT layer FROM features WHERE ?=ANY(lnam_refs);").apply { setString(1, lnam) }.executeQuery().use { generateSequence { if (it.next()) { it.getString(1) } else null }.toList() } } ?: emptyList() /** * Find feature using its LNAM . * * LNAM Long name. An encoding of AGEN, FIDN and FIDS used to uniquely identify this features within an S-57 file. */ suspend fun findFeature(lnam: String): FeatureRecord? = sqlOpAsync { conn -> conn.prepareStatement( """ SELECT id, layer, ST_AsGeoJSON(geom)::JSON as geo, props, chart_id, lower(z_range), upper(z_range) FROM features WHERE props->'LNAM' = to_jsonb(?::text);""".trimIndent() ).apply { setString(1, lnam) }.executeQuery().use { it.featureRecord().firstOrNull() } } fun featureCount(conn: Connection, chartId: Long): Int { return conn.prepareStatement("SELECT COUNT(id) FROM features WHERE chart_id = ?;").apply { setLong(1, chartId) }.executeQuery().use { if (it.next()) it.getInt(1) else 0 } } private fun ResultSet.featureRecord(): Sequence<FeatureRecord> { return generateSequence { if (next()) { var i = 0 FeatureRecord( id = getLong(++i), layer = getString(++i), geom = objectMapper.readValue(getString(++i)), props = objectMapper.readValue(getString(++i)), chartId = getLong(++i), zoomMax = getInt(++i), zoomMin = getInt(++i), ) } else null } } }
18
Kotlin
4
19
3061cc466bd9deecf8c238740870439b2849ffcf
4,229
njord
Apache License 2.0
data/src/main/java/io/homeassistant/companion/android/data/wifi/WifiHelper.kt
grote
250,287,852
true
null
package io.homeassistant.companion.android.data.wifi interface WifiHelper { fun getWifiSsid(): String }
0
null
0
12
f6618527d4f5f1233e7e0515f9816eb3ac282e5b
109
home-assistant-android
Apache License 2.0
core/src/main/kotlin/org/eduardoleolim/organizadorpec660/core/statisticType/application/create/StatisticTypeCreator.kt
eduardoleolim
673,214,659
false
{"Kotlin": 811069}
package org.eduardoleolim.organizadorpec660.core.statisticType.application.create import org.eduardoleolim.organizadorpec660.core.shared.domain.Either import org.eduardoleolim.organizadorpec660.core.shared.domain.Left import org.eduardoleolim.organizadorpec660.core.shared.domain.Right import org.eduardoleolim.organizadorpec660.core.statisticType.domain.* import java.util.* class StatisticTypeCreator(private val statisticTypeRepository: StatisticTypeRepository) { fun create(keyCode: String, name: String): Either<StatisticTypeError, UUID> { try { if (existsStatisticType(keyCode)) return Left(StatisticTypeAlreadyExistsError(keyCode)) StatisticType.create(keyCode, name).let { statisticTypeRepository.save(it) return Right(it.id()) } } catch (e: InvalidArgumentStatisticTypeException) { return Left(CanNotSaveStatisticTypeError(e)) } } private fun existsStatisticType(keyCode: String) = StatisticTypeCriteria.keyCodeCriteria(keyCode).let { statisticTypeRepository.count(it) > 0 } }
0
Kotlin
0
0
bfe0cdaa736579f86d96e77503bdb8dca57685e8
1,134
organizador-pec-660
Creative Commons Attribution 4.0 International
app/src/main/java/com/gmail/shtukarrv/dogbreedsapp/data/ApiConstants.kt
shtukar
348,483,748
false
null
package com.gmail.shtukarrv.dogbreedsapp.data object ApiConstants { const val CONNECT_TIMEOUT = 15L const val READ_TIMEOUT = 30L const val BASE_URL = "https://dog.ceo/api/" const val SUCCESS_STATUS = "success" }
0
Kotlin
0
0
9d97166df0cc611144fb544fbdc0f74484191572
230
Dog-Breeds-App
Apache License 2.0
src/main/kotlin/br/com/iliachallenge/punchtheclock/dto/RegisterRequestDTO.kt
gabrielmaximo
382,696,410
false
null
package br.com.iliachallenge.punchtheclock.dto import java.time.LocalDateTime data class RegisterRequestDTO( val moment: LocalDateTime )
0
Kotlin
0
0
e60866f842c6ec5c681b26d7d89914de41d2505e
144
ilia-challenge
Apache License 2.0
kbomberx-io/src/main/kotlin/kbomberx/io/j2k/MappedBufferedWriterChannelWrapper.kt
LM-96
517,382,094
false
{"Kotlin": 253830}
package kbomberx.io.j2k import kbomberx.io.IoScope import kotlinx.coroutines.* import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ClosedReceiveChannelException import kotlinx.coroutines.channels.SendChannel import java.io.* /** * A wrapper class for [BufferedWriter] that *wraps* the standard *Java* buffered writer * to a new *Kotlin* [Channel]. The [sendChannel] can be used to send data that will be * written on the old writer. The object sent to the [sendChannel] are mapped into strings * using [mapper] function. * After the creation of the object, the old writer **must no longer be used** and * will be automatically closed with the new channel. * The default capacity of the new channel is [Channel.UNLIMITED] and the default scope * for the coroutine that listen from the channel and writes to the writer is [IoScope] * @param writer the writer to be wrapped * @param capacity the capacity of the channel (default [Channel.UNLIMITED]) * @param scope the scope of the internal listening job (default [IoScope]) * @param mapper the transformation function from [T] to [String] */ class MappedBufferedWriterChannelWrapper<T>( private val writer: BufferedWriter, private val capacity : Int = Channel.UNLIMITED, private val scope : CoroutineScope = IoScope, private val mapper : (T) -> String ) : Closeable, AutoCloseable { constructor(outputStream: OutputStream, capacity: Int = Channel.UNLIMITED, scope : CoroutineScope = IoScope, mapper: (T) -> String) : this(outputStream.bufferedWriter(), capacity, scope, mapper) private val channel = Channel<T>(capacity) /** * The new [Channel] that can be used instead of the old [BufferedWriter] */ val sendChannel : SendChannel<T> = channel private val job = scope.launch(Dispatchers.IO) { var obj : T try { while(true) { obj = channel.receive() writer.write("${mapper(obj)}\n") writer.flush() } } catch (crce : ClosedReceiveChannelException) { //Channel has been closed -> writer must be closed writer.close() } catch (ioe : IOException) { //Writer has been closed -> channel must be closed channel.close(ioe) } catch (ce : CancellationException) { //Channel has been cancelled -> writer must be closed writer.close() } //Ensure channel is closed at the end if(!channel.isClosedForReceive) { channel.close() } } /** * Closes the internal channel and waits for the listening * job end. The closure of the channel also causes the closure * of the internal [BufferedWriter] */ override fun close() { if(!channel.isClosedForReceive) channel.close() runBlocking { job.join() } } }
0
Kotlin
0
2
f5c087635ffcb4cea4fea71a4738adf9d3dbfc74
2,941
KBomber
MIT License
src/main/kotlin/com/cloudcontactai/smsreceiver/model/dto/RequeueRequestDto.kt
CloudContactAI
373,333,949
false
null
/* Copyright 2021 Cloud Contact AI, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 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.cloudcontactai.smsreceiver.model.dto import java.time.LocalDateTime data class RequeueRequestDto( val ids: List<String>? = null, val to: String? = null, val since: LocalDateTime? = null, val until: LocalDateTime? = null, val limit: Int? = null, val queue: Boolean = true )
0
Kotlin
0
0
d2cd021400014413c3c9dd88e110d68bc967699f
977
SMSReceiver
Apache License 2.0
central-server/src/main/kotlin/net/dodian/central/web/routes/GameClientRoutes.kt
dodian-community
457,389,140
false
{"Kotlin": 532088}
package net.dodian.central.web.routes import io.ktor.application.* import io.ktor.response.* import io.ktor.routing.* import net.dodian.central.services.WorldService import net.dodian.common.util.rsEncoded import java.io.File fun Application.routesGameClient(worldService: WorldService) { routing { get("/gamepack.jar") { call.respondBytes { File("./data/game-client-data/gamepack.jar").readBytes() } } get("/jav_config.ws") { call.respondBytes { File("./data/game-client-data/jav_config.ws").readBytes() } } get("/world_list.ws") { call.respondBytes { worldService.worlds.rsEncoded() } } } }
6
Kotlin
3
3
f3b341a724016c699e620dd75db121b364261e41
687
osrs-ub3r-monorepo
ISC License
app/src/main/java/me/ykrank/s1next/view/activity/HelpActivity.kt
UFR6cRY9xufLKtx2idrc
853,383,380
false
{"Kotlin": 1174002, "Java": 356564, "HTML": 20430}
package me.ykrank.s1next.view.activity import android.content.Context import android.content.Intent import android.os.Bundle import android.view.MenuItem import android.view.View import androidx.annotation.StyleRes import androidx.appcompat.app.AppCompatActivity import androidx.appcompat.widget.Toolbar import me.ykrank.s1next.App.Companion.get import me.ykrank.s1next.R import me.ykrank.s1next.view.fragment.HelpFragment import me.ykrank.s1next.view.internal.ToolbarDelegate import me.ykrank.s1next.widget.track.event.ViewHelpTrackEvent /** * An Activity shows a help page. */ class HelpActivity : AppCompatActivity() { private var mToolbarDelegate: ToolbarDelegate? = null private var mHelpFragment: HelpFragment? = null override fun onCreate(savedInstanceState: Bundle?) { val styleId = intent.getIntExtra(ARG_STYLE, -1) if (styleId != -1) { setTheme(styleId) } super.onCreate(savedInstanceState) setContentView(R.layout.activity_base_without_drawer_and_scrolling_effect) setupToolbar() if (savedInstanceState == null) { val instance = HelpFragment.instance mHelpFragment = instance supportFragmentManager.beginTransaction().add( R.id.frame_layout, instance, HelpFragment.TAG ).commit() } else { mHelpFragment = supportFragmentManager.findFragmentByTag( HelpFragment.TAG ) as HelpFragment? } } override fun onOptionsItemSelected(item: MenuItem): Boolean { return when (item.itemId) { android.R.id.home -> { onBackPressed() true } else -> super.onOptionsItemSelected(item) } } override fun onBackPressed() { val webView = mHelpFragment?.webView if (webView?.canGoBack() == true) { webView.goBack() } else { super.onBackPressed() } } private fun setupToolbar() { val toolbar = findViewById<View>(R.id.toolbar) as Toolbar? if (toolbar != null) { mToolbarDelegate = ToolbarDelegate(this, toolbar) } } companion object { private const val ARG_STYLE = "style" fun startHelpActivity(context: Context, @StyleRes styleId: Int) { get().trackAgent.post(ViewHelpTrackEvent()) val intent = Intent(context, HelpActivity::class.java) intent.putExtra(ARG_STYLE, styleId) context.startActivity(intent) } } }
0
Kotlin
0
0
7cfc58523207dc5ed5df4525c2e3de087cf9e8b9
2,604
test24
Apache License 2.0
fluent-icons-extended/src/commonMain/kotlin/com/konyaco/fluent/icons/regular/ReadingList.kt
Konyaco
574,321,009
false
null
package com.konyaco.fluent.icons.regular import androidx.compose.ui.graphics.vector.ImageVector import com.konyaco.fluent.icons.Icons import com.konyaco.fluent.icons.fluentIcon import com.konyaco.fluent.icons.fluentPath public val Icons.Regular.ReadingList: ImageVector get() { if (_readingList != null) { return _readingList!! } _readingList = fluentIcon(name = "Regular.ReadingList") { fluentPath { moveTo(7.0f, 18.0f) horizontalLineToRelative(13.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.1f, 1.5f) lineTo(7.0f, 19.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.1f, -1.5f) lineTo(7.0f, 18.0f) close() moveTo(17.0f, 15.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.1f, 1.5f) lineTo(4.0f, 16.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.1f, -1.5f) lineTo(17.0f, 15.0f) close() moveTo(20.0f, 12.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.1f, 1.5f) lineTo(7.0f, 13.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.1f, -1.5f) lineTo(20.0f, 12.0f) close() moveTo(6.0f, 5.0f) curveToRelative(1.13f, 0.0f, 2.13f, 0.69f, 2.55f, 1.72f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -1.35f, 0.65f) lineToRelative(-0.04f, -0.09f) arcTo(1.25f, 1.25f, 0.0f, true, false, 6.0f, 9.0f) horizontalLineToRelative(11.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.1f, 1.5f) lineTo(6.0f, 10.5f) arcTo(2.75f, 2.75f, 0.0f, false, true, 6.0f, 5.0f) close() moveTo(20.0f, 6.0f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, 0.1f, 1.5f) lineTo(11.0f, 7.5f) arcToRelative(0.75f, 0.75f, 0.0f, false, true, -0.1f, -1.5f) lineTo(20.0f, 6.0f) close() } } return _readingList!! } private var _readingList: ImageVector? = null
1
Kotlin
3
83
9e86d93bf1f9ca63a93a913c990e95f13d8ede5a
2,302
compose-fluent-ui
Apache License 2.0
chat-persistence-cassandra/src/test/kotlin/com/demo/chat/test/persistence/mock/TextMessageServiceTests.kt
marios-code-path
181,180,043
false
{"Kotlin": 924762, "Shell": 36602, "C": 3160, "HTML": 2714, "Starlark": 278}
package com.demo.chat.test.persistence.mock import com.demo.chat.domain.Message import com.demo.chat.domain.MessageKey import com.demo.chat.persistence.cassandra.domain.ChatMessageById import com.demo.chat.persistence.cassandra.domain.ChatMessageByIdKey import com.demo.chat.persistence.cassandra.repository.ChatMessageRepository import com.demo.chat.service.core.IKeyService import com.demo.chat.persistence.cassandra.impl.MessagePersistenceCassandra import com.demo.chat.test.TestBase import com.demo.chat.test.TestUUIDKeyService import org.hamcrest.MatcherAssert import org.hamcrest.Matchers import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertNotNull import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import org.junit.jupiter.api.assertAll import org.junit.jupiter.api.extension.ExtendWith import org.mockito.BDDMockito import org.mockito.Mockito import org.slf4j.LoggerFactory import org.springframework.boot.test.mock.mockito.MockBean import org.springframework.test.context.junit.jupiter.SpringExtension import reactor.core.publisher.Flux import reactor.core.publisher.Mono import reactor.test.StepVerifier import java.time.Instant import java.util.* @TestInstance(TestInstance.Lifecycle.PER_CLASS) @ExtendWith(SpringExtension::class) class TextMessageServiceTests { val logger = LoggerFactory.getLogger(this::class.simpleName) private val MSGTEXT = "SUP TEST" lateinit var persistence: MessagePersistenceCassandra<UUID> @MockBean lateinit var msgRepo: ChatMessageRepository<UUID> private val keyService: IKeyService<UUID> = TestUUIDKeyService() private val rid: UUID = UUID.randomUUID() private val uid: UUID = UUID.randomUUID() @BeforeEach fun setUp() { val newMessage = ChatMessageById(ChatMessageByIdKey(UUID.randomUUID(), rid, uid, Instant.now()), MSGTEXT, true) Mockito.`when`(msgRepo.add(TestBase.anyObject())) .thenReturn(Mono.empty()) BDDMockito .given(msgRepo.findAll()) .willReturn(Flux.just(newMessage)) persistence = MessagePersistenceCassandra(keyService, msgRepo) } @Test fun `should find all messages`() { val messages = persistence.all() .doOnNext { logger.info("A message found: ${it}") } StepVerifier .create(messages) .assertNext { org.assertj.core.api.Assertions .assertThat(it) .isNotNull .hasNoNullFieldsOrProperties() } .verifyComplete() } @Test fun `should send to room and receive messages from room`() { val roomId = UUID.randomUUID() val userId = UUID.randomUUID() val messages = keyService.key(Message::class.java) .flatMap { persistence.add( Message.create( MessageKey.create(it.id, roomId, userId), MSGTEXT, true ) ) } .thenMany(persistence.all().collectList()) StepVerifier .create(messages) .expectSubscription() .assertNext { assertAll("messages", { assertNotNull(it) }, { MatcherAssert .assertThat(it, Matchers .not((Matchers.emptyCollectionOf(Message::class.java))) ) }, { assertAll("message", { assertEquals(MSGTEXT, it.first().data) }) } ) } .verifyComplete() } }
2
Kotlin
1
9
2ae59375cd44e8fb58093b0f24596fc3111fd447
4,200
demo-chat
MIT License
src/main/kotlin/frc/team449/robot2024/constants/subsystem/PivotConstants.kt
blair-robot-project
736,410,238
false
{"Kotlin": 256507}
package frc.team449.robot2024.constants.subsystem import edu.wpi.first.math.util.Units import edu.wpi.first.wpilibj.Encoder import frc.team449.robot2024.constants.MotorConstants import kotlin.math.PI object PivotConstants { const val MOTOR_ID = 11 const val INVERTED = false const val CURRENT_LIM = 40 const val FOLLOWER_ID = 12 const val FOLLOWER_INVERTED = false /** Encoder stuff */ const val ENC_CHANNEL = 0 const val GEARING = 1.0 / 75.0 const val UPR = 2.0 * PI * (25.0 / 36.0) const val OFFSET = -0.2125 + (0.150882 / UPR) + (0.829237 / UPR) - (0.012295 / UPR) + (0.020301 / UPR) + (0.339 / UPR) const val ENC_INVERTED = true val QUAD_ENCODER = Encoder(1, 2) val CPR = 2048 val SAMPLES_TO_AVERAGE = 127 const val NUM_MOTORS = 2 /** Moment of inertia in m^2 kg given from CAD with a 0.035 m^2kg cushion for unmodeled objects */ const val MOMENT_OF_INERTIA = 0.570869 + 0.035 const val EFFICIENCY = 0.95 const val ARM_LENGTH = 1.0 const val KS = 0.0 /** Deviations for Kalman filter in units of radians or radians / seconds */ val MODEL_POS_DEVIATION = Units.degreesToRadians(10.0) val MODEL_VEL_DEVIATION = Units.degreesToRadians(20.0) const val MODEL_ERROR_DEVIATION = 0.10 val ENCODER_POS_DEVIATION = Units.degreesToRadians(0.25) /** LQR Position and Velocity tolerances */ val POS_TOLERANCE = Units.degreesToRadians(2.0) val VEL_TOLERANCE = Units.degreesToRadians(15.0) const val CONTROL_EFFORT_VOLTS = 12.0 val MAX_POS_ERROR = 2.5 val MAX_VEL_ERROR = Units.degreesToRadians(30.0) const val MAX_VOLTAGE = 12.0 /** Profile Constraints */ val MAX_VELOCITY = MotorConstants.FREE_SPEED * GEARING // Max at 40A should be 10.567679154992222 const val MAX_ACCEL = 8.0 const val SLOW_ACCEL = 3.0 val MIN_ANGLE = Units.degreesToRadians(0.0) val MAX_ANGLE = Units.degreesToRadians(105.0) val AMP_ANGLE = Units.degreesToRadians(95.0) val ANYWHERE_ANGLE = Units.degreesToRadians(20.0) val CLIMB_ANGLE = Units.degreesToRadians(65.0) val STOW_ANGLE = Units.degreesToRadians(-2.0) // IS THIS CORRECT??? val AUTO_ANGLE = 0.350 }
0
Kotlin
1
2
ffb56fa26bb18ca7a7b6cf38b11560972fb8529c
2,134
robot2024
MIT License
kotlin-node/src/jsMain/generated/node/util/isStringContract.kt
JetBrains
93,250,841
false
{"Kotlin": 12809812, "JavaScript": 280674}
// Generated by Karakum - do not modify it manually! package node.util @Suppress("NOTHING_TO_INLINE", "CANNOT_CHECK_FOR_EXTERNAL_INTERFACE") inline fun isString(`object`: Any?): Boolean /* object is string */ { kotlin.contracts.contract { returns(true) implies (`object` is String) } return isStringRaw(`object`) }
30
Kotlin
175
1,275
e5d911cc5705e4c52f21fc676329c6e733fff3f3
339
kotlin-wrappers
Apache License 2.0
codegen/smithy-kotlin-codegen/src/main/kotlin/software/amazon/smithy/kotlin/codegen/rendering/auth/AuthSchemeProviderAdapterGenerator.kt
awslabs
294,823,838
false
{"Kotlin": 3484792, "Smithy": 113286, "Python": 1215}
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0 */ package software.amazon.smithy.kotlin.codegen.rendering.auth import software.amazon.smithy.codegen.core.Symbol import software.amazon.smithy.kotlin.codegen.KotlinSettings import software.amazon.smithy.kotlin.codegen.core.RuntimeTypes import software.amazon.smithy.kotlin.codegen.core.clientName import software.amazon.smithy.kotlin.codegen.core.withBlock import software.amazon.smithy.kotlin.codegen.model.buildSymbol import software.amazon.smithy.kotlin.codegen.rendering.protocol.ProtocolGenerator /** * Generates the adapter from the service type specific auth scheme provider and the generic one used to execute * a request. */ class AuthSchemeProviderAdapterGenerator { companion object { fun getSymbol(settings: KotlinSettings): Symbol = buildSymbol { val prefix = clientName(settings.sdkId) name = "${prefix}AuthSchemeProviderAdapter" namespace = "${settings.pkg.name}.auth" definitionFile = "$name.kt" } } fun render(ctx: ProtocolGenerator.GenerationContext) { val symbol = getSymbol(ctx.settings) ctx.delegator.useSymbolWriter(symbol) { writer -> writer.dokka("Adapts the service specific auth scheme resolver to the agnostic runtime interface and binds the auth parameters") writer.withBlock( "internal class #T(private val delegate: #T): #T {", "}", symbol, AuthSchemeProviderGenerator.getSymbol(ctx.settings), RuntimeTypes.HttpClient.Operation.AuthSchemeResolver, ) { withBlock( "override suspend fun resolve(request: #T): List<#T> {", "}", RuntimeTypes.HttpClient.Operation.SdkHttpRequest, RuntimeTypes.Auth.Identity.AuthOption, ) { withBlock("val params = #T {", "}", AuthSchemeParametersGenerator.getImplementationSymbol(ctx.settings)) { addImport(RuntimeTypes.Core.Utils.get) write("operationName = request.context[#T.OperationName]", RuntimeTypes.SmithyClient.SdkClientOption) } write("return delegate.resolveAuthScheme(params)") } } } } }
33
Kotlin
18
33
ad34f2ae3a9c9619317f6df9569d649bdb8c09a8
2,449
smithy-kotlin
Apache License 2.0
src/main/kotlin/com/github/moole100/management/Eventmanage.kt
moole100
312,189,943
false
null
package com.github.moole100.management import com.destroystokyo.paper.event.server.PaperServerListPingEvent import org.bukkit.Bukkit import org.bukkit.ChatColor import org.bukkit.event.EventHandler import org.bukkit.event.Listener import org.bukkit.event.entity.PlayerDeathEvent import org.bukkit.event.player.PlayerJoinEvent import org.bukkit.event.player.PlayerQuitEvent import org.bukkit.event.player.PlayerRespawnEvent import java.awt.Color import java.util.Calendar import kotlin.random.Random class Eventmanage : Listener{ @EventHandler fun onPaperServerListPing(event: PaperServerListPingEvent) { val c = Calendar.getInstance() event.numPlayers = c.get(Calendar.YEAR) * 7 + (c.get(Calendar.MONTH) + 5) * 26 + c.get(Calendar.DAY_OF_MONTH) event.maxPlayers = c.get(Calendar.HOUR) * 7 + c.get(Calendar.MINUTE) * 5 + c.get(Calendar.SECOND) + 26 event.motd = "${net.md_5.bungee.api.ChatColor.of(Color(Random.nextInt(0x92ddc8)))}${net.md_5.bungee.api.ChatColor.BOLD}${Bukkit.getServer().motd}" event.playerSample.clear() } @EventHandler fun onQuit(event:PlayerQuitEvent){ event.quitMessage = "${ChatColor.YELLOW}Bye Bye. ${event.player.name} See you again soon." } @EventHandler fun onDead(event: PlayerDeathEvent){ event.deathMessage = "${ChatColor.AQUA}${event.entity.name} is Dead." } @EventHandler fun onJoin(event:PlayerJoinEvent){ event.joinMessage = "${net.md_5.bungee.api.ChatColor.of(Color(Random.nextInt(0x92ddc8)))}${net.md_5.bungee.api.ChatColor.BOLD}Welcome to the ${Bukkit.getServer().name}" } }
0
Kotlin
0
0
e75bc818030bc7f5b7aa07ca625d0b12d2edef76
1,627
minecraft-server-management-plugin
MIT License
compiler/testData/codegen/box/inference/pcla/issues/kt48633.kt
JetBrains
3,432,266
false
null
// DONT_TARGET_EXACT_BACKEND: WASM // WITH_RUNTIME class TowerDataElementsForName() { @OptIn(ExperimentalStdlibApi::class) val reversedFilteredLocalScopes = buildList { class Foo { val reversedFilteredLocalScopes = { add("OK") } } Foo().reversedFilteredLocalScopes() } } fun box(): String { return TowerDataElementsForName().reversedFilteredLocalScopes[0] }
34
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
439
kotlin
Apache License 2.0
app/src/main/java/com/maff/planetshandbook/ui/details/ParameterDialogContract.kt
maff91
110,017,500
false
{"Kotlin": 49207}
package com.maff.planetshandbook.ui.details import com.maff.planetshandbook.data.Parameter import com.maff.planetshandbook.data.Planet import com.maff.planetshandbook.ui.BasePresenter import com.maff.planetshandbook.ui.PresenterView /** * Created by maff on 11/26/2017. */ interface ParameterDialogContract { interface View : PresenterView<com.maff.planetshandbook.ui.details.ProbeDialogContract.Presenter> { fun setPresenter(presenter: Presenter) fun showPlanet(planet: Planet) fun showParameterInfo(parameter: Parameter, valsByPlanet: Collection<Pair<Planet, Double>>) fun close() } interface Presenter : BasePresenter { fun planetSelected(planet: Planet) fun okClicked() } }
0
Kotlin
0
1
a9db430764ed0e836ddf523445c770b3caf47e9c
755
planets-handbook
MIT License
store/src/commonMain/kotlin/org/mobilenativefoundation/store/store5/UpdaterResult.kt
MobileNativeFoundation
226,169,258
false
null
package org.mobilenativefoundation.store.store5 sealed class UpdaterResult { sealed class Success : UpdaterResult() { data class Typed<Response : Any>(val value: Response) : Success() data class Untyped(val value: Any) : Success() } sealed class Error : UpdaterResult() { data class Exception(val error: Throwable) : Error() data class Message(val message: String) : Error() } }
57
null
202
3,174
f9072fc59cc8bfe95cfe008cc8a9ce999301b242
430
Store
Apache License 2.0
src/main/kotlin/io/github/recipestore/domain/RecipeStep.kt
AahzBrut
302,587,602
false
null
package io.github.recipestore.domain import com.fasterxml.jackson.annotation.JsonIgnore import org.springframework.data.annotation.Id import org.springframework.data.annotation.Transient import org.springframework.data.relational.core.mapping.Column import org.springframework.data.relational.core.mapping.Table import java.time.LocalDateTime @Table("RECIPE_STEP") data class RecipeStep( @Id @Column("RECIPE_STEP_ID") var id: Long? = null, @Column("NAME") var name: String, @Column("DESCRIPTION") var description: String, @Column("ORDINAL") var ordinal: Int, @JsonIgnore @Column("RECIPE_ID") var recipeId: Long, @JsonIgnore @Column("USER_ID") var userId: Long, @Column("CREATED") var created: LocalDateTime = LocalDateTime.now(), @Column("MODIFIED") var modified: LocalDateTime = LocalDateTime.now(), ) { @Transient var user: User? = null @Transient var ingredients: List<RecipeStepIngredient> = mutableListOf() }
0
Kotlin
0
1
47b29469c48f7caa5813e20b92d7fb460299125d
1,017
recipestore
MIT License
app/src/main/java/io/twinkle/unreal/ui/viewmodel/AppsPageViewModel.kt
sumonnic
870,812,278
false
{"Kotlin": 237415, "Java": 14968}
package io.twinkle.unreal.ui.viewmodel import android.content.pm.PackageInfo import android.content.pm.PackageManager import androidx.datastore.preferences.core.edit import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import io.twinkle.unreal.data.EnableMap import io.twinkle.unreal.ui.state.AppSort import io.twinkle.unreal.ui.state.AppsUiState import io.twinkle.unreal.util.Settings import io.twinkle.unreal.util.settings import io.twinkle.unreal.vcampApp import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.serialization.json.Json import java.io.File import java.text.Collator import java.util.Locale class AppsPageViewModel : ViewModel() { private val _uiState = MutableStateFlow(AppsUiState()) val uiState: StateFlow<AppsUiState> = _uiState.asStateFlow() fun update(_update: (AppsUiState) -> AppsUiState) { _uiState.update(_update) } fun sortBy(way: AppSort) { val apps = if (uiState.value.showCameraApps) uiState.value.cameraApps else uiState.value.apps val sortedResult = when (way) { AppSort.APP_NAME -> apps.sortedWith(Comparators.byLabel) AppSort.INSTALL_TIME -> apps.sortedWith(Comparators.byInstallTime) AppSort.UPDATE_TIME -> apps.sortedWith(Comparators.byUpdateTime) AppSort.PACKAGE_NAME -> apps.sortedWith(Comparators.byPackageName) } viewModelScope.launch { vcampApp.settings.edit { it[Settings.APPS_SORT] = way.name } } update { it.copy( appsShowed = sortedResult.sortedWith(Comparators.byEnabled(uiState.value.enableMap)), sortBy = way, dropDownMenuExpanded = false ) } } fun reversed() { val apps = uiState.value.appsShowed update { it.copy(appsShowed = apps.reversed(), dropDownMenuExpanded = false) } } fun showDropDownMenu() { update { it.copy(dropDownMenuExpanded = true) } } fun closeDropDownMenu() { update { it.copy(dropDownMenuExpanded = false) } } fun refresh() { update { it.copy(isRefreshing = true) } val apps = vcampApp.packageManager.getInstalledPackages( PackageManager.GET_PERMISSIONS or PackageManager.GET_CONFIGURATIONS ) val cameraApps = apps.filter { if (it.requestedPermissions != null) it.requestedPermissions.contains( android.Manifest.permission.CAMERA ) else false } val jsonFile = File(vcampApp.filesDir.path + "/enable_list.json") val enableMap = if (jsonFile.exists()) Json.decodeFromString<EnableMap>(jsonFile.readText()) else EnableMap() viewModelScope.launch { vcampApp.settings.data.collect { pref -> update { it.copy( apps = apps, cameraApps = cameraApps, appsShowed = apps, showSystemApp = pref[Settings.SHOW_SYSTEM_APPS] ?: false, showCameraApps = pref[Settings.SHOW_CAMERA_APPS] ?: false, enableMap = enableMap, isRefreshing = false ) } sortBy( AppSort.valueOf( pref[Settings.APPS_SORT] ?: AppSort.UPDATE_TIME.name ) ) } } } private object Comparators { private val pm: PackageManager = vcampApp.packageManager val byLabel = Comparator<PackageInfo> { o1, o2 -> val n1 = o1.applicationInfo.loadLabel(pm).toString().lowercase(Locale.getDefault()) val n2 = o2.applicationInfo.loadLabel(pm).toString().lowercase(Locale.getDefault()) Collator.getInstance(Locale.getDefault()).compare(n1, n2) } val byPackageName = Comparator<PackageInfo> { o1, o2 -> val n1 = o1.packageName.lowercase(Locale.getDefault()) val n2 = o2.packageName.lowercase(Locale.getDefault()) Collator.getInstance(Locale.getDefault()).compare(n1, n2) } val byInstallTime = Comparator<PackageInfo> { o1, o2 -> val n1 = o1.firstInstallTime val n2 = o2.firstInstallTime n2.compareTo(n1) } val byUpdateTime = Comparator<PackageInfo> { o1, o2 -> val n1 = o1.lastUpdateTime val n2 = o2.lastUpdateTime n2.compareTo(n1) } fun byEnabled(enableMap: EnableMap) = Comparator<PackageInfo> { o1, o2 -> val n1 = enableMap.map[o1.applicationInfo.packageName] ?: false val n2 = enableMap.map[o2.applicationInfo.packageName] ?: false n2.compareTo(n1) } } }
0
Kotlin
0
0
dfadfd73f57ecccaa2b10cebbcb1d5538ad7e071
5,021
sumonnic
MIT License
app/src/main/java/com/rayadev/jetpackcomposedisney/presentation/ui/theme/Color.kt
AlexRaya25
823,675,973
false
{"Kotlin": 62170}
package com.rayadev.jetpackcomposedisney.presentation.ui.theme import androidx.compose.ui.graphics.Color val Purple80 = Color(0xFFD0BCFF) val PurpleGrey80 = Color(0xFFCCC2DC) val Pink80 = Color(0xFFEFB8C8) val Purple40 = Color(0xFF6650a4) val PurpleGrey40 = Color(0xFF625b71) val Pink40 = Color(0xFF7D5260) val White = Color(0xFFFFFFFF) val LightGray = Color(0xFFF5F5F5) val DarkGray = Color(0xFF333333) val Black = Color(0xFF000000) val Red = Color(0xFFE53935)
0
Kotlin
0
2
824399e0cff525c2877ff280b9a1c1b6b600c4d4
465
JetpackComposeDisney
MIT License
src/Day00.kt
fasfsfgs
573,562,215
false
{"Kotlin": 52546}
fun main() { fun part1(input: List<String>): Int { return input.size } fun part2(input: List<String>): Int { return input.size } val testInput = readInput("Day00_test") check(part1(testInput) == 0) check(part2(testInput) == 0) val input = readInput("Day00") println(part1(input)) println(part2(input)) }
0
Kotlin
0
0
17cfd7ff4c1c48295021213e5a53cf09607b7144
363
advent-of-code-2022
Apache License 2.0
feature/search/presentation/src/main/java/com/gigauri/reptiledb/module/feature/search/presentation/event/SearchEvent.kt
george-gigauri
758,816,993
false
{"Kotlin": 331680}
package com.gigauri.reptiledb.module.feature.search.presentation.event sealed class SearchEvent { data class KeywordChange(val keyword: String) : SearchEvent() }
0
Kotlin
0
2
f256dcd2ba9e4d88135a5399c5b2a71ddff454d0
166
herpi-android
Apache License 2.0
feature/search/presentation/src/main/java/com/gigauri/reptiledb/module/feature/search/presentation/event/SearchEvent.kt
george-gigauri
758,816,993
false
{"Kotlin": 331680}
package com.gigauri.reptiledb.module.feature.search.presentation.event sealed class SearchEvent { data class KeywordChange(val keyword: String) : SearchEvent() }
0
Kotlin
0
2
f256dcd2ba9e4d88135a5399c5b2a71ddff454d0
166
herpi-android
Apache License 2.0
src/jvmTest/kotlin/com/sunnychung/application/multiplatform/hellohttp/test/DataBackwardCompatibilityTest.kt
sunny-chung
711,387,879
false
{"Kotlin": 1426494, "Shell": 3020}
package com.sunnychung.application.multiplatform.hellohttp.test import com.sunnychung.application.multiplatform.hellohttp.AppContext import com.sunnychung.application.multiplatform.hellohttp.document.ApiSpecDI import com.sunnychung.application.multiplatform.hellohttp.document.OperationalDI import com.sunnychung.application.multiplatform.hellohttp.document.ProjectAndEnvironmentsDI import com.sunnychung.application.multiplatform.hellohttp.document.RequestsDI import com.sunnychung.application.multiplatform.hellohttp.document.ResponsesDI import com.sunnychung.application.multiplatform.hellohttp.document.UserPreferenceDI import com.sunnychung.application.multiplatform.hellohttp.importer.DataDumpImporter import com.sunnychung.application.multiplatform.hellohttp.model.ContentType import com.sunnychung.application.multiplatform.hellohttp.model.FieldValueType import com.sunnychung.application.multiplatform.hellohttp.model.FormUrlEncodedBody import com.sunnychung.application.multiplatform.hellohttp.model.GraphqlBody import com.sunnychung.application.multiplatform.hellohttp.model.HttpConfig import com.sunnychung.application.multiplatform.hellohttp.model.MultipartBody import com.sunnychung.application.multiplatform.hellohttp.model.ProtocolApplication import com.sunnychung.application.multiplatform.hellohttp.model.StringBody import com.sunnychung.application.multiplatform.hellohttp.model.UserKeyValuePair import com.sunnychung.application.multiplatform.hellohttp.model.UserResponse import com.sunnychung.lib.multiplatform.kdatetime.KZoneOffset import com.sunnychung.lib.multiplatform.kdatetime.KZonedDateTime import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Order import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.ParameterizedTest.ARGUMENTS_PLACEHOLDER import org.junit.jupiter.params.ParameterizedTest.DISPLAY_NAME_PLACEHOLDER import org.junit.jupiter.params.provider.MethodSource import org.junit.jupiter.params.provider.ValueSource import java.io.File import java.io.FileNotFoundException import java.util.UUID import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotEquals class DataBackwardCompatibilityTest { companion object { @JvmStatic fun appVersionsHavingTestData(): List<String> = listOf("1.5.2", "1.6.0", "1.7.0") // sorted by versions ascending } internal fun currentAppVersionExcludingLabel(): String = AppContext.MetadataManager.version.substringBefore("-") internal fun testDataBaseDirOfAppVersion(version: String) = File("test-data-archive", version) internal fun isCurrentAppVersionDev() = AppContext.MetadataManager.version.endsWith("-snapshot", ignoreCase = true) /** * This method assumes tests are NOT executed in parallel. */ fun copyDataFilesAndTest( inputDataDir: File?, isThrowExceptionIfMissingInput: Boolean = !isCurrentAppVersionDev(), testContent: suspend (tempBaseDataDir: File) -> Unit, ) { val dataFiles = if (inputDataDir != null) { if (!inputDataDir.exists() || !inputDataDir.isDirectory) { if (isThrowExceptionIfMissingInput) { throw FileNotFoundException("Input data files directory is missing") } return } val dataFiles = inputDataDir.list() if (dataFiles.isNullOrEmpty()) { if (isThrowExceptionIfMissingInput) { throw FileNotFoundException("Input data files directory is empty") } return } dataFiles } else { emptyArray() } // copy all data files to a temporary build directory val tempBaseDataDir = File("build", "temp-test-run-${UUID.randomUUID()}") if (tempBaseDataDir.exists()) { tempBaseDataDir.deleteRecursively() } val previousAppContext = AppContext.instance try { tempBaseDataDir.mkdirs() dataFiles.forEach { File(inputDataDir, it).copyRecursively(File(tempBaseDataDir, it)) } AppContext.instance = AppContext() // use a new context AppContext.dataDir = tempBaseDataDir runBlocking { testContent(tempBaseDataDir) } } finally { tempBaseDataDir.deleteRecursively() AppContext.instance = previousAppContext } } /** * Import the backup dump generated by last release version into current context, * and then copy current context into the `test-data-archive` folder. */ @Test @Order(-200) // highest priority fun `generate data files for current app version if missing`() { val currentVersion = currentAppVersionExcludingLabel() val baseArchiveDataDir = testDataBaseDirOfAppVersion(currentVersion) val outputDataDir = File(baseArchiveDataDir, "app-data") if (outputDataDir.isDirectory && outputDataDir.list().isNotEmpty()) { return } val allVersions = appVersionsHavingTestData() val index = allVersions.indexOfFirst { it == currentVersion } val appVersionToCopyDataFrom = allVersions[index - 1] val sourceBackupFile = File(testDataBaseDirOfAppVersion(appVersionToCopyDataFrom), "app-data-backup.dump") copyDataFilesAndTest(null) { tempBaseDataDir -> coroutineScope { emulateAppInitIO() DataDumpImporter().importAsProjects(sourceBackupFile) AppContext.allRepositories.forEach { it.awaitAllUpdates() } } tempBaseDataDir.copyRecursively(outputDataDir, overwrite = true) } } /** * Read data files from $projectDir/test-data-archive/$version/app-data/, * and generate a backup file to $projectDir/test-data-archive/$version/app-data-backup.dump. * * Other test cases in this test depend on the execution product of this test case. */ @Test @Order(-100) // high priority fun `data files for current app version can be read successfully, and can be converted to backup dump file`() { val baseArchiveDataDir = testDataBaseDirOfAppVersion(currentAppVersionExcludingLabel()) val inputDataDir = File(baseArchiveDataDir, "app-data") copyDataFilesAndTest(inputDataDir) { val backupDestination = File(baseArchiveDataDir, "app-data-backup.dump") AppContext.AutoBackupManager.backupNow(backupDestination) if (!backupDestination.isFile) { throw RuntimeException("Backup file cannot be created") } } } private suspend fun assertCurrentDataAreCorrectTestData() { val projectCollection = AppContext.ProjectCollectionRepository.read(ProjectAndEnvironmentsDI())!! val projects = projectCollection.projects assertEquals(2, projects.size) projects.first { it.name == "Empty Project" }.let { assert(it.subprojects.isEmpty()) } projects.first { it.name == "Test Server" }.let { project -> assertEquals(5, project.subprojects.size) project.subprojects.first { it.name == "HTTP only" }.let { subproject -> assertEquals(4, subproject.environments.size) subproject.environments.first { it.name == "HTTP Cleartext" }.let { env -> env.variables.first { it.key == "prefix" }.let { assertEquals("http://testserver.net:18081", it.value) assertEquals(true, it.isEnabled) } assertEquals(null, env.httpConfig.protocolVersion) assertEquals(null, env.sslConfig.isInsecure) assertEquals(0, env.sslConfig.trustedCaCertificates.size) assertEquals(null, env.sslConfig.isDisableSystemCaCertificates) assertEquals(0, env.sslConfig.clientCertificateKeyPairs.size) } subproject.environments.first { it.name == "HTTP/2 Cleartext" }.let { env -> env.variables.first { it.key == "prefix2" }.let { assertEquals("http://testserver.net:18081", it.value) assertEquals(true, it.isEnabled) } assertEquals(HttpConfig.HttpProtocolVersion.Http2Only, env.httpConfig.protocolVersion) assertEquals(null, env.sslConfig.isInsecure) assertEquals(0, env.sslConfig.trustedCaCertificates.size) assertEquals(null, env.sslConfig.isDisableSystemCaCertificates) assertEquals(0, env.sslConfig.clientCertificateKeyPairs.size) } subproject.environments.first { it.name == "HTTP/1 SSL Insecure" }.let { env -> env.variables.first { it.key == "prefix" }.let { assertEquals("https://testserver.net:18084", it.value) assertEquals(true, it.isEnabled) } assertEquals(HttpConfig.HttpProtocolVersion.Http1Only, env.httpConfig.protocolVersion) assertEquals(true, env.sslConfig.isInsecure) assertEquals(0, env.sslConfig.trustedCaCertificates.size) assertEquals(null, env.sslConfig.isDisableSystemCaCertificates) assertEquals(0, env.sslConfig.clientCertificateKeyPairs.size) } subproject.environments.first { it.name == "HTTP/2 SSL Trust" }.let { env -> env.variables.first { it.key == "prefix2" }.let { assertEquals("https://testserver.net:18084", it.value) assertEquals(true, it.isEnabled) } assertEquals(HttpConfig.HttpProtocolVersion.Negotiate, env.httpConfig.protocolVersion) assertEquals(true, env.sslConfig.isInsecure) assertEquals(1, env.sslConfig.trustedCaCertificates.size) assert(env.sslConfig.trustedCaCertificates.first().name.contains("CN=Test Server CA")) assert( env.sslConfig.trustedCaCertificates.first().createdWhen > KZonedDateTime( year = 2024, month = 1, day = 1, hour = 0, minute = 0, second = 0, zoneOffset = KZoneOffset.local() ).toKInstant() ) assertEquals(null, env.sslConfig.isDisableSystemCaCertificates) assertEquals(0, env.sslConfig.clientCertificateKeyPairs.size) } val requests = AppContext.RequestCollectionRepository .read(RequestsDI(subprojectId = subproject.id))!! .requests assertEquals(7, requests.size) val responses = AppContext.PersistResponseManager .loadResponseCollection(ResponsesDI(subprojectId = subproject.id)) .responsesByRequestExampleId assert(responses.isNotEmpty()) requests.first { it.name == "Only Base Example" }.let { assertEquals(ProtocolApplication.Http, it.application) assertEquals("GET", it.method) assertEquals("\${{prefix}}/rest/echo", it.url) assertEquals(1, it.examples.size) it.examples.first().let { ex -> assertEquals(ContentType.None, ex.contentType) assertEquals(2, ex.queryParameters.size) assertEquals("value1", ex.queryParameters.first { it.key == "key1" }.value) assertEquals(true, ex.queryParameters.first { it.key == "key1" }.isEnabled) assertEquals("test value 2", ex.queryParameters.first { it.key == "key2" }.value) assertEquals(true, ex.queryParameters.first { it.key == "key2" }.isEnabled) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) responses[ex.id]!!.assertHttpStatus200WithContent() } } requests.first { it.name == "New Request" }.let { assertEquals(ProtocolApplication.Http, it.application) assertEquals("PATCH", it.method) assertEquals("\${{prefix}}/rest/echo", it.url) assertEquals(1, it.examples.size) it.examples.first().let { ex -> assertEquals(ContentType.None, ex.contentType) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.id !in responses) } } requests.first { it.name == "HTTP/2 GET" }.let { assertEquals(ProtocolApplication.Http, it.application) assertEquals("GET", it.method) assertEquals("\${{prefix2}}/rest/echo", it.url) assertEquals(4, it.examples.size) var i = 0 it.examples[i++].let { ex -> // Base Example assertEquals(ContentType.None, ex.contentType) assertEquals(2, ex.queryParameters.size) assertEquals("v1", ex.queryParameters.first { it.key == "key_inherited1" }.value) assertEquals(true, ex.queryParameters.first { it.key == "key_inherited1" }.isEnabled) assertEquals("value2", ex.queryParameters.first { it.key == "key_inherited2" }.value) assertEquals(true, ex.queryParameters.first { it.key == "key_inherited2" }.isEnabled) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.id !in responses) } it.examples[i++].let { ex -> assertEquals("Ex1", ex.name) assertEquals(ContentType.None, ex.contentType) assertEquals(2, ex.queryParameters.size) assertEquals("this+value+1", ex.queryParameters.first { it.key == "key_example1" }.value) assertEquals(true, ex.queryParameters.first { it.key == "key_example1" }.isEnabled) assertEquals("value 2", ex.queryParameters.first { it.key == "key_new2" }.value) assertEquals(true, ex.queryParameters.first { it.key == "key_new2" }.isEnabled) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assertEquals(true, ex.overrides?.hasNoDisable() ?: true) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("Example 2", ex.name) assertEquals(ContentType.None, ex.contentType) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assertEquals(true, ex.overrides?.hasNoDisable() ?: true) assert(ex.id !in responses) } it.examples[i++].let { ex -> assertEquals("Example3", ex.name) assertEquals(ContentType.None, ex.contentType) assertEquals(1, ex.queryParameters.size) assertEquals("value3", ex.queryParameters.first { it.key == "ex3" }.value) assertEquals(true, ex.queryParameters.first { it.key == "ex3" }.isEnabled) assertEquals(1, ex.headers.size) assertEquals("H1", ex.headers.first { it.key == "custom-header" }.value) assertEquals(true, ex.headers.first { it.key == "custom-header" }.isEnabled) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assertEquals(true, ex.overrides?.hasNoDisable() ?: true) responses[ex.id]!!.assertHttpStatus200WithContent() } } requests.first { it.name == "Mixed GET" }.let { assertEquals(ProtocolApplication.Http, it.application) assertEquals("GET", it.method) assertEquals("\${{prefix}}/rest/echo", it.url) assertEquals(4, it.examples.size) var i = 0 it.examples[i++].let { ex -> // Base Example assertEquals(ContentType.None, ex.contentType) assertEquals(2, ex.queryParameters.size) assertEquals("v1", ex.queryParameters.first { it.key == "key_inherited1" }.value) assertEquals(true, ex.queryParameters.first { it.key == "key_inherited1" }.isEnabled) assertEquals("value2", ex.queryParameters.first { it.key == "key_inherited2" }.value) assertEquals(true, ex.queryParameters.first { it.key == "key_inherited2" }.isEnabled) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.id !in responses) } it.examples[i++].let { ex -> assertEquals("Ex1", ex.name) assertEquals(ContentType.None, ex.contentType) assertEquals(2, ex.queryParameters.size) assertEquals("this+value+1", ex.queryParameters.first { it.key == "key_example1" }.value) assertEquals(true, ex.queryParameters.first { it.key == "key_example1" }.isEnabled) assertEquals("value 2", ex.queryParameters.first { it.key == "key_new2" }.value) assertEquals(true, ex.queryParameters.first { it.key == "key_new2" }.isEnabled) assertEquals(1, ex.headers.size) assertEquals("valuevalue", ex.headers.first { it.key == "header" }.value) assertEquals(true, ex.headers.first { it.key == "header" }.isEnabled) assertEquals(1, ex.postFlight.updateVariablesFromHeader.size) ex.postFlight.updateVariablesFromHeader.first { it.key == "length" }.let { assertEquals("Content-Length", it.value) assertEquals(true, it.isEnabled) } assertEquals(1, ex.postFlight.updateVariablesFromBody.size) ex.postFlight.updateVariablesFromBody.first { it.key == "method" }.let { assertEquals("\$.method", it.value) assertEquals(true, it.isEnabled) } assertEquals(true, ex.overrides?.hasNoDisable() ?: true) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("Example 2", ex.name) assertEquals(ContentType.None, ex.contentType) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assertEquals(true, ex.overrides?.hasNoDisable() ?: true) assert(ex.id !in responses) } it.examples[i++].let { ex -> assertEquals("Example3", ex.name) assertEquals(ContentType.None, ex.contentType) assertEquals(1, ex.queryParameters.size) assertEquals("value3", ex.queryParameters.first { it.key == "ex3" }.value) assertEquals(true, ex.queryParameters.first { it.key == "ex3" }.isEnabled) assertEquals(1, ex.headers.size) assertEquals("H1", ex.headers.first { it.key == "custom-header" }.value) assertEquals(true, ex.headers.first { it.key == "custom-header" }.isEnabled) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assertEquals(true, ex.overrides?.hasNoDisable() ?: true) responses[ex.id]!!.assertHttpStatus200WithContent() } } requests.first { it.name == "Post" }.let { assertEquals(ProtocolApplication.Http, it.application) assertEquals("POST", it.method) assertEquals("\${{prefix}}/rest/echo", it.url) assertEquals(7, it.examples.size) val baseEx = it.examples.first() var i = 0 it.examples[i++].let { ex -> // Base Example assertEquals(ContentType.Json, ex.contentType) assert(ex.body is StringBody) assert((ex.body as StringBody).value.isNotEmpty()) assertEquals(0, ex.queryParameters.size) assertEquals(1, ex.headers.size) ex.headers.first { it.key == "my-Header" }.let { assertEquals("header", it.value) assertEquals(true, it.isEnabled) } assertEquals(1, ex.postFlight.updateVariablesFromHeader.size) ex.postFlight.updateVariablesFromHeader.first { it.key == "len" }.let { assertEquals("Content-Length", it.value) assertEquals(true, it.isEnabled) } assertEquals(1, ex.postFlight.updateVariablesFromBody.size) ex.postFlight.updateVariablesFromBody.first { it.key == "met" }.let { assertEquals("\$.method", it.value) assertEquals(true, it.isEnabled) } responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("Directly inherited from BASE", ex.name) assertEquals(ContentType.Json, ex.contentType) assert(!ex.overrides!!.isOverrideBody) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.overrides!!.hasNoDisable()) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("Different Body", ex.name) assertEquals(ContentType.Json, ex.contentType) assert(ex.overrides!!.isOverrideBody) assert((ex.body as StringBody).value.isNotEmpty()) assertNotEquals(it.examples.first().body, ex.body) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.overrides!!.hasNoDisable()) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("Form", ex.name) assertEquals(ContentType.FormUrlEncoded, ex.contentType) (ex.body as FormUrlEncodedBody).value.let { form -> assertEquals(2, form.size) var j = 0 form[j++].let { assertEquals("k1", it.key) assertEquals("v1", it.value) assertEquals(true, it.isEnabled) } form[j++].let { assertEquals("k2", it.key) assertEquals("v2", it.value) assertEquals(true, it.isEnabled) } } assertEquals(1, ex.queryParameters.size) ex.queryParameters.first().let { assertEquals("q1", it.key) assertEquals("v1", it.value) assertEquals(true, it.isEnabled) } assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.overrides!!.hasNoDisable()) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("Remove all inherited", ex.name) assertEquals(ContentType.None, ex.contentType) assertEquals(1, ex.queryParameters.size) ex.queryParameters.first().let { assertEquals("qq", it.key) assertEquals("Q", it.value) assertEquals(true, it.isEnabled) } assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.overrides!!.disabledHeaderIds.containsAll(baseEx.headers.map { it.id })) assert(ex.overrides!!.disablePostFlightUpdateVarIds.containsAll(baseEx.postFlight.updateVariablesFromHeader.map { it.id })) assert(ex.overrides!!.disablePostFlightUpdateVarIds.containsAll(baseEx.postFlight.updateVariablesFromBody.map { it.id })) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("Multipart Text-only", ex.name) assertEquals(ContentType.Multipart, ex.contentType) (ex.body as MultipartBody).value.let { form -> assertEquals(4, form.size) form.first { it.key == "form1" }.assert("value1", true) form.first { it.key == "form2" }.assert("value2 disabled", false) form.first { it.key == "key3" }.assert("enabled value 3", true) form.first { it.key == "unicode" }.assert("中文字元", true) } assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(1, ex.postFlight.updateVariablesFromHeader.size) ex.postFlight.updateVariablesFromHeader.first() .assert("type", "Content-Type", true) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.overrides!!.disabledHeaderIds.isEmpty()) assert(ex.overrides!!.disablePostFlightUpdateVarIds == baseEx.postFlight.updateVariablesFromHeader.map { it.id }.toSet()) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("Multipart File", ex.name) assertEquals(ContentType.Multipart, ex.contentType) (ex.body as MultipartBody).value.let { form -> assertEquals(2, form.size) form.first { it.key == "file1" }.assert("C:\\Users\\S\\Documents\\中文檔名.txt", true, FieldValueType.File) form.first { it.key == "text2" }.assert("value2", true) } assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.overrides!!.hasNoDisable()) responses[ex.id]!!.assertHttpStatus200WithContent() } } requests.first { it.name == "HTTP/2 Inherited Form" }.let { assertEquals(ProtocolApplication.Http, it.application) assertEquals("POST", it.method) assertEquals("\${{prefix2}}/rest/echo", it.url) assertEquals(5, it.examples.size) val baseEx = it.examples.first() var i = 0 it.examples[i++].let { ex -> // Base Example assertEquals(ContentType.Multipart, ex.contentType) (ex.body as MultipartBody).value.let { form -> assertEquals(2, form.size) form.first { it.key == "key1" }.assert("val1", true) form.first { it.key == "fil2" }.assert("C:\\Users\\S\\Documents\\中文檔名.txt", true, FieldValueType.File) } assertEquals(0, ex.queryParameters.size) assertEquals(1, ex.headers.size) ex.headers.first().assert("auth", "abcDEF", true) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("Inherited", ex.name) assertEquals(ContentType.Multipart, ex.contentType) val body = (ex.body as MultipartBody).value assertEquals(0, body.size) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.overrides!!.hasNoDisable()) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("Inherited with overrides", ex.name) assertEquals(ContentType.Multipart, ex.contentType) assert(ex.overrides!!.disabledBodyKeyValueIds == (baseEx.body as MultipartBody) .value.filter { it.key == "fil2" }.map { it.id }.toSet()) (ex.body as MultipartBody).value.let { form -> assertEquals(1, form.size) form.first { it.key == "file2" }.assert("C:\\Users\\S\\Downloads\\serverCACert.pem", true, FieldValueType.File) } assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.overrides!!.disabledHeaderIds.isEmpty()) assert(ex.overrides!!.disabledQueryParameterIds.isEmpty()) assert(ex.overrides!!.disablePostFlightUpdateVarIds.isEmpty()) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("Form (different type cannot inherit)", ex.name) assertEquals(ContentType.FormUrlEncoded, ex.contentType) (ex.body as FormUrlEncodedBody).value.let { form -> assertEquals(1, form.size) form.first { it.key == "abc" }.assert("def", true) } assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.overrides!!.hasNoDisable()) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("json", ex.name) assertEquals(ContentType.Json, ex.contentType) assertEquals("{\"abc\": \"de\"}", (ex.body as StringBody).value) assertEquals(true, ex.overrides!!.isOverrideBody) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.overrides!!.hasNoDisable()) responses[ex.id]!!.assertHttpStatus200WithContent() } } requests.first { it.name == "Custom Method" }.let { assertEquals(ProtocolApplication.Http, it.application) assertEquals("CUS", it.method) assertEquals("\${{prefix2}}/rest/echo", it.url) assertEquals(1, it.examples.size) it.examples.first().let { ex -> assertEquals(ContentType.None, ex.contentType) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) responses[ex.id]!!.assertHttpStatus200WithContent() } } } project.subprojects.first { it.name == "gRPC only" }.let { subproject -> assertEquals(1, subproject.environments.size) subproject.environments.first { it.name == "Insecure" }.let { env -> env.variables.first { it.key == "grpc" }.let { assertEquals("grpc://testserver.net:18082/", it.value) assertEquals(true, it.isEnabled) } assertEquals(null, env.httpConfig.protocolVersion) assertEquals(null, env.sslConfig.isInsecure) assertEquals(0, env.sslConfig.trustedCaCertificates.size) assertEquals(null, env.sslConfig.isDisableSystemCaCertificates) assertEquals(0, env.sslConfig.clientCertificateKeyPairs.size) } val requests = AppContext.RequestCollectionRepository .read(RequestsDI(subprojectId = subproject.id))!! .requests assertEquals(7, requests.size) val responses = AppContext.PersistResponseManager .loadResponseCollection(ResponsesDI(subprojectId = subproject.id)) .responsesByRequestExampleId assert(responses.isNotEmpty()) val apiSpecs = AppContext.ApiSpecificationCollectionRepository.read(ApiSpecDI(project.id))!! .grpcApiSpecs .filter { it.id in subproject.grpcApiSpecIds } assertEquals(1, apiSpecs.size) val apiSpec = apiSpecs.first() assertEquals("testserver.net:18082", apiSpec.name) assertEquals(true, apiSpec.isActive) requests.first { it.name == "Health" }.let { assertEquals(ProtocolApplication.Grpc, it.application) assertEquals("\${{grpc}}", it.url) assertEquals(apiSpec.id, it.grpc!!.apiSpecId) assertEquals("grpc.health.v1.Health", it.grpc!!.service) assertEquals("Check", it.grpc!!.method) assertEquals(1, it.examples.size) it.examples.first().let { ex -> assertEquals(ContentType.Json, ex.contentType) assertEquals("{}", (ex.body as StringBody).value) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) responses[ex.id]!!.assertGrpcOKWithContent() } } requests.first { it.name == "Unary" }.let { assertEquals(ProtocolApplication.Grpc, it.application) assertEquals("\${{grpc}}", it.url) assertEquals(apiSpec.id, it.grpc!!.apiSpecId) assertEquals("sunnychung.grpc.services.MyService", it.grpc!!.service) assertEquals("SayHello", it.grpc!!.method) assertEquals(1, it.examples.size) it.examples.first().let { ex -> assertEquals(ContentType.Json, ex.contentType) assertEquals("{\n \"name\": \"123\"\n}\n", (ex.body as StringBody).value) assertEquals(0, ex.queryParameters.size) assertEquals(1, ex.headers.size) ex.headers.first { it.key == "extraheader" }.assert("Extra!", true) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) responses[ex.id]!!.assertGrpcOKWithContent() } } requests.first { it.name == "Server Stream" }.let { assertEquals(ProtocolApplication.Grpc, it.application) assertEquals("\${{grpc}}", it.url) assertEquals(apiSpec.id, it.grpc!!.apiSpecId) assertEquals("sunnychung.grpc.services.MyService", it.grpc!!.service) assertEquals("ServerStream", it.grpc!!.method) assertEquals(1, it.examples.size) it.examples.first().let { ex -> assertEquals(ContentType.Json, ex.contentType) assertEquals("{\"data\":4}", (ex.body as StringBody).value) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) responses[ex.id]!!.let { response -> assertEquals(0, response.statusCode) assert(response.headers!!.isNotEmpty()) assertEquals(5, response.payloadExchanges!!.size) assert(response.rawExchange.exchanges.size > response.payloadExchanges!!.size) } } } requests.first { it.name == "Server Stream (Cancel midway)" }.let { assertEquals(ProtocolApplication.Grpc, it.application) assertEquals("\${{grpc}}", it.url) assertEquals(apiSpec.id, it.grpc!!.apiSpecId) assertEquals("sunnychung.grpc.services.MyService", it.grpc!!.service) assertEquals("ServerStream", it.grpc!!.method) assertEquals(1, it.examples.size) it.examples.first().let { ex -> assertEquals(ContentType.Json, ex.contentType) assertEquals("{\"data\":4}", (ex.body as StringBody).value) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) responses[ex.id]!!.let { response -> assertEquals(null, response.statusCode) assert(response.headers!!.isNotEmpty()) assertEquals(3, response.payloadExchanges!!.size) assert(response.rawExchange.exchanges.size > response.payloadExchanges!!.size) } } } requests.first { it.name == "Client Stream" }.let { assertEquals(ProtocolApplication.Grpc, it.application) assertEquals("\${{grpc}}", it.url) assertEquals(apiSpec.id, it.grpc!!.apiSpecId) assertEquals("sunnychung.grpc.services.MyService", it.grpc!!.service) assertEquals("ClientStream", it.grpc!!.method) assertEquals(1, it.examples.size) it.examples.first().let { ex -> assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) responses[ex.id]!!.let { response -> assertEquals(0, response.statusCode) assert(response.headers!!.isNotEmpty()) assertEquals(5, response.payloadExchanges!!.size) assert(response.rawExchange.exchanges.size > response.payloadExchanges!!.size) } } assertEquals(3, it.payloadExamples!!.size) it.payloadExamples!!.forEachIndexed { index, it -> when (index) { 0 -> { assertEquals("New Payload", it.name) assertEquals("{\"data\":12}", it.body) } 1 -> { assertEquals("7", it.name) assertEquals("{\"data\": 7}", it.body) } 2 -> { assertEquals("10", it.name) assertEquals("{\n \"data\": 10\n}", it.body) } else -> throw NotImplementedError() } } } requests.first { it.name == "Bi-stream" }.let { assertEquals(ProtocolApplication.Grpc, it.application) assertEquals("\${{grpc}}", it.url) assertEquals(apiSpec.id, it.grpc!!.apiSpecId) assertEquals("sunnychung.grpc.services.MyService", it.grpc!!.service) assertEquals("BiStream", it.grpc!!.method) assertEquals(1, it.examples.size) it.examples.first().let { ex -> assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) responses[ex.id]!!.let { response -> assertEquals(0, response.statusCode) assert(response.headers!!.isNotEmpty()) assertEquals(5, response.payloadExchanges!!.size) assert(response.rawExchange.exchanges.size > response.payloadExchanges!!.size) } } assertEquals(3, it.payloadExamples!!.size) it.payloadExamples!!.forEachIndexed { index, it -> when (index) { 0 -> { assertEquals("New Payload", it.name) assertEquals("{\"data\":12}", it.body) } 1 -> { assertEquals("7", it.name) assertEquals("{\"data\": 7}", it.body) } 2 -> { assertEquals("10", it.name) assertEquals("{\n \"data\": 10\n}", it.body) } else -> throw NotImplementedError() } } } requests.first { it.name == "error" }.let { assertEquals(ProtocolApplication.Grpc, it.application) assertEquals("\${{grpc}}", it.url) assertEquals(apiSpec.id, it.grpc!!.apiSpecId) assertEquals("sunnychung.grpc.services.MyService", it.grpc!!.service) assertEquals("Error", it.grpc!!.method) assertEquals(1, it.examples.size) it.examples.first().let { ex -> assertEquals(ContentType.Json, ex.contentType) assertEquals("{\"data\": 9}", (ex.body as StringBody).value) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) responses[ex.id]!!.let { response -> assertEquals(9, response.statusCode) assert(response.headers!!.isNotEmpty()) assert(response.rawExchange.exchanges.isNotEmpty()) } } } } project.subprojects.first { it.name == "Without Env" }.let { subproject -> assertEquals(0, subproject.environments.size) val requests = AppContext.RequestCollectionRepository .read(RequestsDI(subprojectId = subproject.id))!! .requests assertEquals(1, requests.size) val responses = AppContext.PersistResponseManager .loadResponseCollection(ResponsesDI(subprojectId = subproject.id)) .responsesByRequestExampleId assert(responses.isNotEmpty()) requests.first { it.name == "New Request" }.let { assertEquals(ProtocolApplication.Http, it.application) assertEquals("POST", it.method) assertEquals("http://testserver.net:18081/rest/echo", it.url) assertEquals(2, it.examples.size) var i = 0 it.examples[i++].let { ex -> // Base Example assertEquals(ContentType.Json, ex.contentType) assertEquals("{\n \"data\": 123\n}", (ex.body as StringBody).value) assertEquals(0, ex.queryParameters.size) assertEquals(1, ex.headers.size) ex.headers.first { it.key == "a" }.assert("va", true) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("Override", ex.name) assertEquals(ContentType.Json, ex.contentType) assertEquals("{\n \"def\": \"gh\" \n}", (ex.body as StringBody).value) assertEquals(true, ex.overrides!!.isOverrideBody) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assertEquals(true, ex.overrides?.hasNoDisable() ?: true) responses[ex.id]!!.assertHttpStatus200WithContent() } } } project.subprojects.first { it.name == "Without Requests" }.let { subproject -> assertEquals(0, subproject.environments.size) val requests = AppContext.RequestCollectionRepository .read(RequestsDI(subprojectId = subproject.id))!! .requests assertEquals(0, requests.size) val responses = AppContext.PersistResponseManager .loadResponseCollection(ResponsesDI(subprojectId = subproject.id)) .responsesByRequestExampleId assert(responses.isEmpty()) } project.subprojects.first { it.name == "Mixed Request Types" }.let { subproject -> assertEquals(1, subproject.environments.size) subproject.environments.first { it.name == "Cleartext" }.let { env -> env.variables.first { it.key == "prefix" } .assert("http://testserver.net:18081", true) env.variables.first { it.key == "ws" } .assert("ws://testserver.net:18081/ws", true) env.variables.first { it.key == "grpc" } .assert("grpc://testserver.net:18082", true) assertEquals(null, env.httpConfig.protocolVersion) assertEquals(null, env.sslConfig.isInsecure) assertEquals(0, env.sslConfig.trustedCaCertificates.size) assertEquals(null, env.sslConfig.isDisableSystemCaCertificates) assertEquals(0, env.sslConfig.clientCertificateKeyPairs.size) } val requests = AppContext.RequestCollectionRepository .read(RequestsDI(subprojectId = subproject.id))!! .requests assertEquals(7, requests.size) val responses = AppContext.PersistResponseManager .loadResponseCollection(ResponsesDI(subprojectId = subproject.id)) .responsesByRequestExampleId assert(responses.isNotEmpty()) val apiSpecs = AppContext.ApiSpecificationCollectionRepository.read(ApiSpecDI(project.id))!! .grpcApiSpecs .filter { it.id in subproject.grpcApiSpecIds } assertEquals(1, apiSpecs.size) val apiSpec = apiSpecs.first() assertEquals("testserver.net:18082", apiSpec.name) assertEquals(true, apiSpec.isActive) requests.first { it.name == "REST API" }.let { assertEquals(ProtocolApplication.Http, it.application) assertEquals("PUT", it.method) assertEquals("\${{prefix}}/rest/echo", it.url) assertEquals(4, it.examples.size) var i = 0 it.examples[i++].let { ex -> // Base Example assertEquals(ContentType.Json, ex.contentType) assertEquals("{\"id\":1234}", (ex.body as StringBody).value) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("1235", ex.name) assertEquals(ContentType.Json, ex.contentType) assertEquals("{\"id\":1235}", (ex.body as StringBody).value) assertEquals(true, ex.overrides!!.isOverrideBody) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assertEquals(true, ex.overrides?.hasNoDisable() ?: true) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("1236", ex.name) assertEquals(ContentType.Json, ex.contentType) assertEquals("{\"id\": 1236}", (ex.body as StringBody).value) assertEquals(true, ex.overrides!!.isOverrideBody) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assertEquals(true, ex.overrides?.hasNoDisable() ?: true) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("Raw", ex.name) assertEquals(ContentType.Raw, ex.contentType) assertEquals("1237", (ex.body as StringBody).value) assertEquals(true, ex.overrides!!.isOverrideBody) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assertEquals(true, ex.overrides?.hasNoDisable() ?: true) responses[ex.id]!!.assertHttpStatus200WithContent() } } requests.first { it.name == "GraphQL Query - Sum" }.let { assertEquals(ProtocolApplication.Graphql, it.application) assertEquals("\${{prefix}}/graphql", it.url) assertEquals(3, it.examples.size) var i = 0 it.examples[i++].let { ex -> // Base Example assertEquals(ContentType.Graphql, ex.contentType) (ex.body as GraphqlBody).let { body -> assert(body.operationName.isNullOrEmpty()) assertEquals("", body.document) assertEquals("", body.variables) } assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.id !in responses) } it.examples[i++].let { ex -> assertEquals("Anonymous Op", ex.name) assertEquals(ContentType.Graphql, ex.contentType) (ex.body as GraphqlBody).let { body -> assert(body.operationName.isNullOrEmpty()) assert(body.document.isNotEmpty()) assertEquals("", body.variables) } assertEquals(true, ex.overrides!!.isOverrideBodyContent) assertEquals(true, ex.overrides!!.isOverrideBodyVariables) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.overrides!!.hasNoDisable()) responses[ex.id]!!.assertHttpStatus200WithContent() } it.examples[i++].let { ex -> assertEquals("Variable", ex.name) assertEquals(ContentType.Graphql, ex.contentType) (ex.body as GraphqlBody).let { body -> assertEquals("GetSum", body.operationName) assert(body.document.isNotEmpty()) assert(body.variables.isNotEmpty()) } assertEquals(true, ex.overrides!!.isOverrideBodyContent) assertEquals(true, ex.overrides!!.isOverrideBodyVariables) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.overrides!!.hasNoDisable()) responses[ex.id]!!.assertHttpStatus200WithContent() } } requests.first { it.name == "GraphQL Subscription" }.let { assertEquals(ProtocolApplication.Graphql, it.application) assertEquals("\${{prefix}}/graphql", it.url) assertEquals(4, it.examples.size) var i = 0 it.examples[i++].let { ex -> // Base Example assertEquals(ContentType.Graphql, ex.contentType) (ex.body as GraphqlBody).let { body -> assert(body.operationName.isNullOrEmpty()) assert(body.document.isNotEmpty()) assertEquals("", body.variables) } assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.id !in responses) } it.examples[i++].let { ex -> assertEquals("Normal", ex.name) assertEquals(ContentType.Graphql, ex.contentType) (ex.body as GraphqlBody).let { body -> assert(body.operationName.isNullOrEmpty()) assertEquals("{\"seconds\": 2, \"stopAt\": 5}", body.variables) } assertEquals(false, ex.overrides!!.isOverrideBodyContent) assertEquals(true, ex.overrides!!.isOverrideBodyVariables) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.overrides!!.hasNoDisable()) responses[ex.id]!!.let { response -> assertEquals(101, response.statusCode) assert(response.headers!!.isNotEmpty()) assertEquals(8, response.payloadExchanges!!.size) assert(response.rawExchange.exchanges.size > response.payloadExchanges!!.size) } } it.examples[i++].let { ex -> assertEquals("Cancel midway", ex.name) assertEquals(ContentType.Graphql, ex.contentType) (ex.body as GraphqlBody).let { body -> assert(body.operationName.isNullOrEmpty()) assertEquals("{\"seconds\": 2, \"stopAt\": 5}", body.variables) } assertEquals(false, ex.overrides!!.isOverrideBodyContent) assertEquals(true, ex.overrides!!.isOverrideBodyVariables) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.overrides!!.hasNoDisable()) responses[ex.id]!!.let { response -> assertEquals(101, response.statusCode) assert(response.headers!!.isNotEmpty()) assertEquals(5, response.payloadExchanges!!.size) assert(response.rawExchange.exchanges.size > response.payloadExchanges!!.size) } } it.examples[i++].let { ex -> assertEquals("Error", ex.name) assertEquals(ContentType.Graphql, ex.contentType) (ex.body as GraphqlBody).let { body -> assert(body.operationName.isNullOrEmpty()) assertEquals("{\"seconds\": 1, \"stopAt\": 5, \"errorAt\": 3}", body.variables) } assertEquals(false, ex.overrides!!.isOverrideBodyContent) assertEquals(true, ex.overrides!!.isOverrideBodyVariables) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assert(ex.overrides!!.hasNoDisable()) responses[ex.id]!!.let { response -> assertEquals(101, response.statusCode) assert(response.headers!!.isNotEmpty()) assertEquals(7, response.payloadExchanges!!.size) assert(response.rawExchange.exchanges.size > response.payloadExchanges!!.size) } } } requests.first { it.name == "WebSocket" }.let { assertEquals(ProtocolApplication.WebSocket, it.application) assertEquals("\${{ws}}", it.url) assertEquals(1, it.examples.size) it.examples.first().let { ex -> // Base Example assertEquals(2, ex.queryParameters.size) ex.queryParameters.first { it.key == "q1" }.assert("abc", true) ex.queryParameters.first { it.key == "q2" }.assert("bcd", true) assertEquals(1, ex.headers.size) ex.headers.first { it.key == "h1" }.assert("hv1", true) responses[ex.id]!!.let { response -> assertEquals(101, response.statusCode) assert(response.headers!!.isNotEmpty()) assertEquals(10, response.payloadExchanges!!.size) assert(response.rawExchange.exchanges.size > response.payloadExchanges!!.size) } } assertEquals(3, it.payloadExamples!!.size) it.payloadExamples!!.forEachIndexed { index, it -> when (index) { 0 -> { assertEquals("Echo", it.name) assertEquals("!echo", it.body) } 1 -> { assertEquals("123", it.name) assertEquals("123", it.body) } 2 -> { assertEquals("2345", it.name) assertEquals("2345", it.body) } else -> throw NotImplementedError() } } } requests.first { it.name == "Unary" }.let { assertEquals(ProtocolApplication.Grpc, it.application) assertEquals("\${{grpc}}", it.url) assertEquals(apiSpec.id, it.grpc!!.apiSpecId) assertEquals("sunnychung.grpc.services.MyService", it.grpc!!.service) assertEquals("Hi", it.grpc!!.method) assertEquals(1, it.examples.size) it.examples.first().let { ex -> assertEquals(ContentType.Json, ex.contentType) assertEquals("{}", (ex.body as StringBody).value) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) responses[ex.id]!!.assertGrpcOKWithContent() } } requests.first { it.name == "Bi-stream" }.let { assertEquals(ProtocolApplication.Grpc, it.application) assertEquals("\${{grpc}}", it.url) assertEquals(apiSpec.id, it.grpc!!.apiSpecId) assertEquals("sunnychung.grpc.services.MyService", it.grpc!!.service) assertEquals("BiStream", it.grpc!!.method) assertEquals(1, it.examples.size) it.examples.first().let { ex -> assertEquals(0, ex.queryParameters.size) assertEquals(1, ex.headers.size) ex.headers.first { it.key == "header1" }.assert("val1", true) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) responses[ex.id]!!.let { response -> assertEquals(0, response.statusCode) assert(response.headers!!.isNotEmpty()) assertEquals(7, response.payloadExchanges!!.size) assert(response.rawExchange.exchanges.size > response.payloadExchanges!!.size) } } assertEquals(2, it.payloadExamples!!.size) it.payloadExamples!!.forEachIndexed { index, it -> when (index) { 0 -> { assertEquals("20", it.name) assertEquals("{\"data\":20}", it.body) } 1 -> { assertEquals("123", it.name) assertEquals("{\"data\":123}", it.body) } else -> throw NotImplementedError() } } } requests.first { it.name == "Empty Request" }.let { assertEquals(ProtocolApplication.Http, it.application) assertEquals("GET", it.method) assertEquals("", it.url) assertEquals(1, it.examples.size) it.examples.first().let { ex -> // Base Example assertEquals(ContentType.None, ex.contentType) assertEquals(0, ex.queryParameters.size) assertEquals(0, ex.headers.size) assertEquals(0, ex.postFlight.updateVariablesFromHeader.size) assertEquals(0, ex.postFlight.updateVariablesFromBody.size) assertEquals(true, ex.overrides?.hasNoDisable() ?: true) assert(ex.id !in responses) } } } } } @ParameterizedTest(name = "$DISPLAY_NAME_PLACEHOLDER [$ARGUMENTS_PLACEHOLDER]") @MethodSource("appVersionsHavingTestData") fun `correctly load and convert data files generated from app version`(version: String) { val inputDataDir = File(testDataBaseDirOfAppVersion(version), "app-data") copyDataFilesAndTest(inputDataDir, isThrowExceptionIfMissingInput = version != currentAppVersionExcludingLabel()) { // perform the I/O steps implemented in `main()` emulateAppInitIO() // data verification assertCurrentDataAreCorrectTestData() } } @ParameterizedTest(name = "$DISPLAY_NAME_PLACEHOLDER [$ARGUMENTS_PLACEHOLDER]") @MethodSource("appVersionsHavingTestData") fun `correctly load backup dump generated from app version`(version: String) { val backupFile = File(testDataBaseDirOfAppVersion(version), "app-data-backup.dump") if (!backupFile.isFile) { if (version != currentAppVersionExcludingLabel()) { throw FileNotFoundException("Test backup dump file '${backupFile.absolutePath}' not found") } return } copyDataFilesAndTest(inputDataDir = null, isThrowExceptionIfMissingInput = false) { // perform the I/O steps implemented in `main()` emulateAppInitIO() // load backup dump into current context DataDumpImporter().importAsProjects(backupFile) // data verification assertCurrentDataAreCorrectTestData() } } } private suspend fun emulateAppInitIO() { // perform the I/O steps implemented in `main()` AppContext.PersistenceManager.initialize() AppContext.AutoBackupManager.backupNow() AppContext.OperationalRepository.read(OperationalDI()) val preference = AppContext.UserPreferenceRepository.read(UserPreferenceDI())!!.preference AppContext.UserPreferenceViewModel.setColorTheme(preference.colourTheme) } private fun UserResponse.assertHttpStatus200WithContent() { assertEquals(200, statusCode) assert(headers!!.isNotEmpty()) assert(body!!.isNotEmpty()) assert(rawExchange.exchanges.isNotEmpty()) } private fun UserResponse.assertGrpcOKWithContent() { assertEquals(0, statusCode) assert(headers!!.isNotEmpty()) assert(body!!.isNotEmpty()) assert(rawExchange.exchanges.isNotEmpty()) } private fun UserKeyValuePair.assert(value: String, isEnabled: Boolean, valueType: FieldValueType = FieldValueType.String) { assertEquals(value, this.value) assertEquals(valueType, this.valueType) assertEquals(isEnabled, this.isEnabled) } private fun UserKeyValuePair.assert(key: String, value: String, isEnabled: Boolean, valueType: FieldValueType = FieldValueType.String) { assertEquals(key, this.key) assert(value = value, isEnabled = isEnabled, valueType = valueType) }
0
Kotlin
0
72
a71b1bab930be2ecbf533c702ee44ef8c549a287
75,495
hello-http
Apache License 2.0
Chess4Android/app/src/main/java/pt/isel/pdm/chess4android/common/ChessMovesLocal.kt
TiagoCebola
744,256,826
false
{"Kotlin": 133661}
package pt.isel.pdm.chess4android.common import kotlin.math.abs // Variable that checks if the King hasn't moved private var ROQUE_REQUIREMENT = true /** * Generates a random number that corresponds to a piece to switch a Pawn to another Piece */ private fun randPiece() : model.Piece { val piece = (0..39).random() return when(piece) { 0, 4, 16, 2, 37, 15, 13, 18, 1, 35 -> model.Piece.ROOK 3, 24, 26, 32, 19, 21, 14, 9, 33, 39 -> model.Piece.KNIGHT 36, 31, 20, 28, 25, 11, 10, 6, 34, 7 -> model.Piece.BISHOP else -> model.Piece.QUEEN } } /** * Makes the movements for the KNIGHT piece */ fun knightMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>>{ // Initial position of the piece var initialY = move.get(1).digitToInt() var initialX = move.get(2).digitToInt() // Final position for the piece var destinyY = move.get(3).digitToInt() var destinyX = move.get(4).digitToInt() // Checks if the sum of the modules between the final coordinates and initial coordinates corresponds to the horse move L = (3 squares) if( (abs(destinyX-initialX) + abs(destinyY-initialY)) == 3 ){ // Removes the piece from the previous position board[initialX][initialY] = null // Puts the piece in the new position board[destinyX][destinyY] = pieceId } return board; } /** * Makes the movements for the ROOK piece */ fun towerMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>>{ // Initial position of the piece var initialY = move.get(1).digitToInt() var initialX = move.get(2).digitToInt() // Final position for the piece var destinyY = move.get(3).digitToInt() var destinyX = move.get(4).digitToInt() // Flag that indicates if there is any piece that may interrupt the movement var validator = 0 // Coordinate used to move in the tile and interrupt movement if we are in the same tile were we began var position : Int // Checks if we are in the same row if(initialX == destinyX){ if(initialY < destinyY) { position = initialY + 1 // Avoid starting in initial position while(position < destinyY && validator == 0){ if(board[destinyX][position] != null) validator = 1 // Checks if there is any piece on the way position++ } } else { position = initialY - 1 while (position > destinyY && validator == 0) { if (board[destinyX][position] != null) validator = 1 position-- } } } // Checks if we are in the same column else if(initialY == destinyY){ if(initialX < destinyX){ position = initialX + 1 while(position < destinyX && validator == 0){ if(board[position][destinyY] != null) validator = 1 position++ } } else { position = initialX - 1 while (position > destinyX && validator == 0) { if (board[position][destinyY] != null) validator = 1 position-- } } } // If we aren't in the same row or column it's an invalid move else validator = 1 // If there isn't any piece on the way and it was a valid move, // remove the piece from the previous location and put it on the destiny if(validator == 0){ board[initialX][initialY] = null board[destinyX][destinyY] = pieceId } return board; } /** * Makes the movements for the QUEEN piece */ fun queenMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>> { // Initial position of the piece var initialY = move.get(1).digitToInt() var initialX = move.get(2).digitToInt() // Final position for the piece var destinyY = move.get(3).digitToInt() var destinyX = move.get(4).digitToInt() // Flag that indicates if there is any piece that may interrupt the movement var validator = 0 // Coordinate used to move in the tile and interrupt movement if we are in the same tile were we began var position : Int // Coordinate used to move in the tile and interrupt movement if we there is any other piece in the diagonal var positionX: Int var positionY: Int // Checks if we are in the same row if(initialX == destinyX){ if(initialY < destinyY) { position = initialY + 1 // Avoid starting in initial position while(position < destinyY && validator == 0){ if(board[destinyX][position] != null) validator = 1 // Checks if there is any piece on the way position++ } } else { position = initialY - 1 while (position > destinyY && validator == 0) { if (board[destinyX][position] != null) validator = 1 position-- } } } // Checks if we are in the same column else if(initialY == destinyY){ if(initialX < destinyX){ position = initialX + 1 while(position < destinyX && validator == 0){ if(board[position][destinyY] != null) validator = 1 position++ } } else { position = initialX - 1 while (position > destinyX && validator == 0) { if (board[position][destinyY] != null) validator = 1 position-- } } } // Checks if the modules between the final coordinates and initial coordinates are equal // ( Ex: 4 moves in diagonal = 4 moves in row + 4 moves in column ) else if( abs(destinyX-initialX) == abs(destinyY-initialY) ) { // Left side bottom movement if (destinyX < initialX && destinyY < initialY) { // Change coordinates to check if there is any piece on the diagonal positionX = initialX - 1 positionY = initialY - 1 while (positionX > destinyX && positionY > destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX-- positionY-- } } // Right side top movement else if (destinyX > initialX && destinyY > initialY) { positionX = initialX + 1 positionY = initialY + 1 while (positionX < destinyX && positionY < destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX++ positionY++ } } // Right side bottom movement else if (destinyX > initialX && destinyY < initialY) { positionX = initialX + 1 positionY = initialY - 1 while (positionX < destinyX && positionY > destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX++ positionY-- } } // Left side top movement else if (destinyX < initialX && destinyY > initialY) { positionX = initialX - 1 positionY = initialY + 1 while (positionX > destinyX && positionY < destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX-- positionY++ } } } // If the other movements failed it's an invalid move else validator = 1 // If there isn't any piece on the way and it was a valid move, // remove the piece from the previous location and put it on the destiny if(validator == 0){ board[initialX][initialY] = null board[destinyX][destinyY] = pieceId } return board; } /** * Makes the movements for the KING piece */ fun kingMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>> { // Initial position of the piece var initialY = move.get(1).digitToInt() var initialX = move.get(2).digitToInt() // Final position for the piece var destinyX = move.get(4).digitToInt() var destinyY = move.get(3).digitToInt() // Checks if we are in the same row or column if(initialX == destinyX || initialY == destinyY){ // Verify if there is one tile movement in the row or in the column direction if( (abs(destinyX-initialX) + abs(destinyY-initialY)) == 1 ){ ROQUE_REQUIREMENT = false // If the king moved from the initial position he can't make the ROQUE anymore board[initialX][initialY] = null board[destinyX][destinyY] = pieceId } } // Verify if is one tile movement in the diagonal // ( Ex: 1 diagonal = 1 row + 1 column ) else if( (abs(destinyX-initialX) + abs(destinyY-initialY)) == 2 ){ ROQUE_REQUIREMENT = false board[initialX][initialY] = null board[destinyX][destinyY] = pieceId } return board; } /** * Makes the movements for the BISHOP piece */ fun bishopMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>>{ // Initial position of the piece var initialY = move.get(1).digitToInt() var initialX = move.get(2).digitToInt() // Final position for the piece var destinyY = move.get(3).digitToInt() var destinyX = move.get(4).digitToInt() // Flag that indicates if there is any piece that may interrupt the movement var validator = 0 // Coordinate used to move in the tile and interrupt movement if we there is any other piece in the diagonal var positionX: Int var positionY: Int // Checks if the modules between the final coordinates and initial coordinates are equal // ( Ex: 4 moves in diagonal = 4 moves in row + 4 moves in column ) if( abs(destinyX-initialX) == abs(destinyY-initialY) ) { // Left side bottom movement if (destinyX < initialX && destinyY < initialY) { // Change coordinates to check if there is any piece on the diagonal positionX = initialX - 1 positionY = initialY - 1 while (positionX > destinyX && positionY > destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX-- positionY-- } } // Right side top movement else if (destinyX > initialX && destinyY > initialY) { positionX = initialX + 1 positionY = initialY + 1 while (positionX < destinyX && positionY < destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX++ positionY++ } } // Right side bottom movement else if (destinyX > initialX && destinyY < initialY) { positionX = initialX + 1 positionY = initialY - 1 while (positionX < destinyX && positionY > destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX++ positionY-- } } // Left side top movement else if (destinyX < initialX && destinyY > initialY) { positionX = initialX - 1 positionY = initialY + 1 while (positionX > destinyX && positionY < destinyY) { if (board[positionX][positionY] != null) validator = 1 positionX-- positionY++ } } } // If the other movements failed it's an invalid move else validator = 1 // If there isn't any piece on the way and it was a valid move, // remove the piece from the previous location and put it on the destiny if(validator == 0){ board[initialX][initialY] = null board[destinyX][destinyY] = pieceId } return board; } /** * Makes the movements for the ROQUE */ fun swapMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId1: Pair<model.Army, model.Piece>, pieceId2: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>>{ // Initial position of the piece var initialY = move.get(1).digitToInt() var initialX = move.get(2).digitToInt() // Final position for the piece var destinyX = move.get(4).digitToInt() var destinyY = move.get(3).digitToInt() // Flag that indicates if there is any piece that may interrupt the movement var validator = 0 // Coordinate used to move in the tile and interrupt movement if we are in the same tile were we began var position : Int // Checks if we are in the first row/column or the last row/column, if its the king, // if the destiny row is the same and the initial and if the king hasn't moved. if( (initialX == 0 || initialX == 7) && (destinyY == 0 || destinyY == 7) && initialY == 4 && (initialX == destinyX) && ROQUE_REQUIREMENT) { // Left side movement if(destinyY < initialY) { position = initialY - 1 // Avoid starting in the initial position while (position > destinyY) { if (board[destinyX][position] != null) validator = 1 // Checks if there is any piece on the way position-- } // Makes the swap if(validator == 0) { board[destinyX][3] = pieceId2 board[destinyX][2] = pieceId1 board[destinyX][0] = null board[destinyX][4] = null } } // Right side movement else { position = initialY + 1 while (position < destinyX) { if (board[destinyX][position] != null) validator = 1 position++ } // Makes the swap if(validator == 0) { board[destinyX][5] = pieceId2 board[destinyX][6] = pieceId1 board[destinyX][7] = null board[destinyX][4] = null } } } return board; } /** * Makes the movements for the black PAWN */ fun blackPawnMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>> { // Initial position of the piece var initialY = move.get(0).digitToInt() var initialX = move.get(1).digitToInt() // Final position for the piece var destinyX = move.get(3).digitToInt() var destinyY = move.get(2).digitToInt() // Flag that indicates if there is any piece that may interrupt the movement var validator = 1 // Checks if the pawn movement is on the final row var piece = pieceId if(destinyX == 7) { piece = Pair(pieceId.first, randPiece()) // Swaps the pawn to a random piece } // Movement in the same column if( abs(initialY-destinyY) == 0 ) { // First move if(initialX == 1 && (destinyX - initialX == 1 || destinyX-initialX == 2) && board[destinyX][destinyY] == null) validator = 0 else if(destinyX-initialX == 1 && board[destinyX][destinyY] == null) validator = 0 } // Movement in the diagonal else if( abs(initialY-destinyY) == 1 ){ if(destinyX-initialX == 1 && board[destinyX][destinyY] != null) validator = 0 } if(validator == 0){ board[initialX][initialY] = null board[destinyX][destinyY] = piece } return board; } /** * Makes the movements for the white PAWN */ fun whitePawnMoveLocal(board: Array<Array<Pair<model.Army, model.Piece>?>>, move: String, pieceId: Pair<model.Army, model.Piece>) : Array<Array<Pair<model.Army, model.Piece>?>> { // Initial position of the piece var initialY = move.get(0).digitToInt() var initialX = move.get(1).digitToInt() // Final position for the piece var destinyX = move.get(3).digitToInt() var destinyY = move.get(2).digitToInt() // Flag that indicates if there is any piece that may interrupt the movement var validator = 1 // Checks if the pawn movement is on the final row var piece = pieceId if(destinyX == 0) { piece = Pair(pieceId.first, randPiece()) // Swaps the pawn to a random piece } // Movement in the same column if( abs(initialY-destinyY) == 0 ) { // First move if(initialX == 6 && (initialX - destinyX == 1 || initialX - destinyX== 2) && board[destinyX][destinyY] == null) validator = 0 else if(initialX-destinyX == 1 && board[destinyX][destinyY] == null) validator = 0 } // Movement in the diagonal else if(abs(initialY-destinyY) == 1){ if(initialX-destinyX == 1 && board[destinyX][destinyY] != null) validator = 0 } if(validator == 0){ board[initialX][initialY] = null board[destinyX][destinyY] = piece } return board; }
0
Kotlin
0
0
fb88fce1a00cc00233f50cc1d93649f05cee0061
19,022
ISEL-Chess4Android
MIT License
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/autoscalingplans/CfnScalingPlanPredefinedScalingMetricSpecificationPropertyDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.autoscalingplans import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.autoscalingplans.CfnScalingPlan /** * `PredefinedScalingMetricSpecification` is a subproperty of * [TargetTrackingConfiguration](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscalingplans-scalingplan-targettrackingconfiguration.html) * that specifies a customized scaling metric for a target tracking configuration to use with AWS Auto * Scaling ( Auto Scaling Plans ). * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.autoscalingplans.*; * PredefinedScalingMetricSpecificationProperty predefinedScalingMetricSpecificationProperty = * PredefinedScalingMetricSpecificationProperty.builder() * .predefinedScalingMetricType("predefinedScalingMetricType") * // the properties below are optional * .resourceLabel("resourceLabel") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-autoscalingplans-scalingplan-predefinedscalingmetricspecification.html) */ @CdkDslMarker public class CfnScalingPlanPredefinedScalingMetricSpecificationPropertyDsl { private val cdkBuilder: CfnScalingPlan.PredefinedScalingMetricSpecificationProperty.Builder = CfnScalingPlan.PredefinedScalingMetricSpecificationProperty.builder() /** * @param predefinedScalingMetricType The metric type. * The `ALBRequestCountPerTarget` metric type applies only to Auto Scaling groups, Spot Fleet * requests, and ECS services. */ public fun predefinedScalingMetricType(predefinedScalingMetricType: String) { cdkBuilder.predefinedScalingMetricType(predefinedScalingMetricType) } /** * @param resourceLabel Identifies the resource associated with the metric type. * You can't specify a resource label unless the metric type is `ALBRequestCountPerTarget` and * there is a target group for an Application Load Balancer attached to the Auto Scaling group, Spot * Fleet request, or ECS service. * * You create the resource label by appending the final portion of the load balancer ARN and the * final portion of the target group ARN into a single value, separated by a forward slash (/). The * format is * app/<load-balancer-name>/<load-balancer-id>/targetgroup/<target-group-name>/<target-group-id>, * where: * * * app/<load-balancer-name>/<load-balancer-id> is the final portion of the load balancer ARN * * targetgroup/<target-group-name>/<target-group-id> is the final portion of the target group * ARN. * * This is an example: * app/EC2Co-EcsEl-1TKLTMITMM0EO/f37c06a68c1748aa/targetgroup/EC2Co-Defau-LDNM7Q3ZH1ZN/6d4ea56ca2d6a18d. * * To find the ARN for an Application Load Balancer, use the * [DescribeLoadBalancers](https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_DescribeLoadBalancers.html) * API operation. To find the ARN for the target group, use the * [DescribeTargetGroups](https://docs.aws.amazon.com/elasticloadbalancing/latest/APIReference/API_DescribeTargetGroups.html) * API operation. */ public fun resourceLabel(resourceLabel: String) { cdkBuilder.resourceLabel(resourceLabel) } public fun build(): CfnScalingPlan.PredefinedScalingMetricSpecificationProperty = cdkBuilder.build() }
1
Kotlin
0
0
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
3,702
awscdk-dsl-kotlin
Apache License 2.0
backend/security-oauth/src/main/kotlin/io/featurehub/web/security/oauth/providers/GoogleProvider.kt
nashjain
427,612,281
true
{"Dart": 807678, "Java": 590572, "TypeScript": 405372, "Groovy": 245705, "Kotlin": 134946, "Gherkin": 76789, "Shell": 10214, "JavaScript": 4738, "TSQL": 4373, "Dockerfile": 3036, "C#": 1519, "HTML": 616}
package io.featurehub.web.security.oauth.providers import cd.connect.app.config.ConfigKey import cd.connect.app.config.DeclaredConfigResolver import io.featurehub.web.security.oauth.AuthClientResult import java.net.URLEncoder import java.nio.charset.StandardCharsets class GoogleProvider : OAuth2Provider { @ConfigKey("oauth2.providers.google.secret") override var clientSecret: String? = null protected set @ConfigKey("oauth2.providers.google.id") override var clientId: String? = null protected set @ConfigKey("oauth2.redirectUrl") protected var redirectUrl: String? = null private val actualAuthUrl: String private val tokenUrl: String override fun discoverProviderUser(authed: AuthClientResult): ProviderUser? { val idInfo = Jwt.decodeJwt(authed.idToken) ?: return null return ProviderUser.Builder().email(idInfo["email"].toString()) .name(idInfo["given_name"].toString() + " " + idInfo["family_name"]).build() } override fun providerName(): String { return PROVIDER_NAME } override fun requestTokenUrl(): String { return tokenUrl } override fun requestAuthorizationUrl(): String { return actualAuthUrl } companion object { const val PROVIDER_NAME = "oauth2-google" } init { DeclaredConfigResolver.resolve(this) actualAuthUrl = "https://accounts.google.com/o/oauth2/v2/auth?&scope=profile%20email&access_type=online" + "&include_granted_scopes=true&response_type=code&client_id=" + clientId + "&redirect_uri=" + URLEncoder.encode(redirectUrl, StandardCharsets.UTF_8) tokenUrl = "https://oauth2.googleapis.com/token" } }
5
null
0
0
d0dd173a814bf1184a7aa671f49b669701e91314
1,636
featurehub
Apache License 2.0
platform/src/main/kotlin/researchstack/backend/adapter/outgoing/mongo/education/DeleteEducationalContentMongoAdapter.kt
S-ResearchStack
520,365,362
false
{"Kotlin": 1297198, "Dockerfile": 202, "Shell": 59}
package researchstack.backend.adapter.outgoing.mongo.education import kotlinx.coroutines.reactive.awaitFirstOrDefault import org.springframework.stereotype.Component import researchstack.backend.adapter.outgoing.mongo.repository.EducationalContentRepository import researchstack.backend.application.port.outgoing.education.DeleteEducationalContentOutPort @Component class DeleteEducationalContentMongoAdapter( private val educationalContentRepository: EducationalContentRepository ) : DeleteEducationalContentOutPort { override suspend fun deleteEducationalContent(contentId: String) { educationalContentRepository.deleteById(contentId).awaitFirstOrDefault(null) } }
1
Kotlin
9
29
214dc84476e2de6948c3fc5225cebca0707bfb91
689
backend-system
Apache License 2.0
app/src/main/java/com/example/cadastro/CadastroApplication.kt
daniel6rufino
861,467,385
false
{"Kotlin": 17196}
package com.example.cadastro import android.app.Application import com.example.cadastro.data.AppDatabase class CadastroApplication : Application() { val database: AppDatabase by lazy { AppDatabase.getDatabase(this) } }
0
Kotlin
0
0
6b85e650472cc7e5ab4a48a5f32c42c395956121
225
APP_Cadastro_Pessoa
Apache License 2.0
code/2146. Subjects, Part 2 1-009-subjects-2/1-009-subjects-2/pre-recording/end/src/main/kotlin/main.kt
iOSDevLog
186,328,282
false
null
import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.subscribeBy import io.reactivex.subjects.BehaviorSubject import io.reactivex.subjects.PublishSubject import io.reactivex.subjects.ReplaySubject fun main(args: Array<String>) { exampleOf("PublishSubject") { val quotes = PublishSubject.create<String>() quotes.onNext(itsNotMyFault) val subscriptionOne = quotes.subscribeBy( onNext = { printWithLabel("1)", it) }, onComplete = { printWithLabel("1)", "Complete") } ) quotes.onNext(doOrDoNot) val subscriptionTwo = quotes.subscribeBy( onNext = { printWithLabel("2)", it) }, onComplete = { printWithLabel("2)", "Complete") } ) quotes.onNext(lackOfFaith) subscriptionOne.dispose() quotes.onNext(eyesCanDeceive) quotes.onComplete() val subscriptionThree = quotes.subscribeBy( onNext = { printWithLabel("3)", it) }, onComplete = { printWithLabel("3)", "Complete") } ) quotes.onNext(stayOnTarget) subscriptionTwo.dispose() subscriptionThree.dispose() } exampleOf("BehaviorSubject") { val subscriptions = CompositeDisposable() val quotes = BehaviorSubject.createDefault(iAmYourFather) val subscriptionOne = quotes.subscribeBy( onNext = { printWithLabel("1)", it) }, onError = { printWithLabel("1)", it) }, onComplete = { printWithLabel("1)", "Complete") } ) subscriptions.add(subscriptionOne) quotes.onError(Quote.NeverSaidThat()) subscriptions.add(quotes.subscribeBy( onNext = { printWithLabel("2)", it) }, onError = { printWithLabel("2)", it) }, onComplete = { printWithLabel("2)", "Complete") } )) } exampleOf("BehaviorSubject State") { val subscriptions = CompositeDisposable() val quotes = BehaviorSubject.createDefault(mayTheForceBeWithYou) println(quotes.value) subscriptions.add(quotes.subscribeBy { printWithLabel("1)", it) }) quotes.onNext(mayThe4thBeWithYou) println(quotes.value) } exampleOf("ReplaySubject") { val subscriptions = CompositeDisposable() val subject = ReplaySubject.createWithSize<String>(2) subject.onNext(useTheForce) subscriptions.add(subject.subscribeBy( onNext = { printWithLabel("1)", it) }, onError = { printWithLabel("1)", it) }, onComplete = { printWithLabel("1)", "Complete") } )) subject.onNext(theForceIsStrong) subscriptions.add(subject.subscribeBy( onNext = { printWithLabel("2)", it) }, onError = { printWithLabel("2)", it) }, onComplete = { printWithLabel("2)", "Complete") } )) } }
0
null
1
4
8b81fbeb046abfeda95f9870c3c29b4998dbb12d
2,707
raywenderlich
MIT License
plugins/github/src/org/jetbrains/plugins/github/ui/cloneDialog/GHCloneDialogLoginPanel.kt
ahaddad91
270,487,787
true
null
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.github.ui.cloneDialog import com.intellij.CommonBundle import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.actionSystem.CommonShortcuts.ENTER import com.intellij.openapi.actionSystem.PlatformDataKeys.CONTEXT_COMPONENT import com.intellij.openapi.application.ModalityState import com.intellij.openapi.progress.EmptyProgressIndicator import com.intellij.openapi.project.DumbAwareAction import com.intellij.ui.SimpleColoredComponent import com.intellij.ui.SimpleTextAttributes import com.intellij.ui.components.panels.VerticalLayout import com.intellij.ui.layout.* import com.intellij.util.ui.components.BorderLayoutPanel import org.jetbrains.plugins.github.api.GithubApiRequestExecutor import org.jetbrains.plugins.github.authentication.GithubAuthenticationManager import org.jetbrains.plugins.github.authentication.accounts.GithubAccount import org.jetbrains.plugins.github.authentication.ui.GithubLoginPanel import org.jetbrains.plugins.github.i18n.GithubBundle import org.jetbrains.plugins.github.util.completionOnEdt import org.jetbrains.plugins.github.util.errorOnEdt import org.jetbrains.plugins.github.util.successOnEdt import javax.swing.JButton import javax.swing.JPanel internal class GHCloneDialogLoginPanel(private val account: GithubAccount?) : BorderLayoutPanel() { private val authenticationManager get() = GithubAuthenticationManager.getInstance() private val errorPanel = JPanel(VerticalLayout(10)) private val loginPanel = GithubLoginPanel( GithubApiRequestExecutor.Factory.getInstance(), { name, server -> if (account == null) authenticationManager.isAccountUnique(name, server) else true }, false ) private val loginButton = JButton(GithubBundle.message("button.login.mnemonic")) private val cancelButton = JButton(CommonBundle.message("button.cancel.c")) init { loginPanel.footer = { buttonPanel() } // footer is used to put buttons in 2-nd column - align under text boxes addToTop(loginPanel) addToCenter(errorPanel) if (account != null) { loginPanel.setCredentials(account.name, null, false) loginPanel.setServer(account.server.toUrl(), false) } cancelButton.isVisible = authenticationManager.hasAccounts() loginButton.addActionListener { login() } LoginAction().registerCustomShortcutSet(ENTER, loginPanel) } fun setCancelHandler(listener: () -> Unit) = cancelButton.addActionListener { listener() } private fun LayoutBuilder.buttonPanel() = row("") { cell { loginButton() cancelButton() } } private fun login() { val modalityState = ModalityState.stateForComponent(this) loginPanel.acquireLoginAndToken(EmptyProgressIndicator(modalityState)) .completionOnEdt(modalityState) { errorPanel.removeAll() } .errorOnEdt(modalityState) { for (validationInfo in loginPanel.doValidateAll()) { val component = SimpleColoredComponent() component.append(validationInfo.message, SimpleTextAttributes.ERROR_ATTRIBUTES) errorPanel.add(component) errorPanel.revalidate() } errorPanel.repaint() } .successOnEdt(modalityState) { (login, token) -> if (account != null) { authenticationManager.updateAccountToken(account, token) } else { authenticationManager.registerAccount(login, loginPanel.getServer().host, token) } } } private inner class LoginAction : DumbAwareAction() { override fun update(e: AnActionEvent) { e.presentation.isEnabledAndVisible = e.getData(CONTEXT_COMPONENT) != cancelButton } override fun actionPerformed(e: AnActionEvent) = login() } }
0
null
0
0
89873c8d4fe856cc79fa2fd4eeef28db29732772
3,871
intellij-community
Apache License 2.0
dsl/src/main/kotlin/com/faendir/awscdkkt/generated/services/omics/CfnRunGroupDsl.kt
F43nd1r
643,016,506
false
null
package com.faendir.awscdkkt.generated.services.omics import com.faendir.awscdkkt.AwsCdkDsl import javax.`annotation`.Generated import kotlin.String import kotlin.Unit import software.amazon.awscdk.services.omics.CfnRunGroup import software.amazon.awscdk.services.omics.CfnRunGroupProps import software.constructs.Construct @Generated public fun Construct.cfnRunGroup(id: String): CfnRunGroup = CfnRunGroup(this, id) @Generated public fun Construct.cfnRunGroup(id: String, initializer: @AwsCdkDsl CfnRunGroup.() -> Unit): CfnRunGroup = CfnRunGroup(this, id).apply(initializer) @Generated public fun Construct.cfnRunGroup(id: String, props: CfnRunGroupProps): CfnRunGroup = CfnRunGroup(this, id, props) @Generated public fun Construct.cfnRunGroup( id: String, props: CfnRunGroupProps, initializer: @AwsCdkDsl CfnRunGroup.() -> Unit, ): CfnRunGroup = CfnRunGroup(this, id, props).apply(initializer) @Generated public fun Construct.buildCfnRunGroup(id: String, initializer: @AwsCdkDsl CfnRunGroup.Builder.() -> Unit): CfnRunGroup = CfnRunGroup.Builder.create(this, id).apply(initializer).build()
1
Kotlin
0
0
a1cf8fbfdfef9550b3936de2f864543edb76348b
1,121
aws-cdk-kt
Apache License 2.0
kotlin-typescript/src/jsMain/generated/typescript/isParameter.kt
JetBrains
93,250,841
false
{"Kotlin": 12635434, "JavaScript": 423801}
// Automatically generated - do not modify! @file:JsModule("typescript") package typescript @JsName("isParameter") external fun isParameterRaw(node: Node): Boolean /* node is ParameterDeclaration */
38
Kotlin
162
1,347
997ed3902482883db4a9657585426f6ca167d556
203
kotlin-wrappers
Apache License 2.0
failgood/src/test/kotlin/failgood/internal/ContextExecutorTest.kt
failgood
323,114,755
false
null
package failgood.internal import failgood.Failure import failgood.RootContext import failgood.Success import failgood.Test import failgood.describe import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.awaitAll import kotlinx.coroutines.cancel import kotlinx.coroutines.coroutineScope import kotlinx.coroutines.delay import kotlinx.coroutines.withTimeout import strikt.api.expectThat import strikt.assertions.* import java.util.concurrent.ConcurrentHashMap @Suppress("NAME_SHADOWING") @Test class ContextExecutorTest { private var assertionError: AssertionError? = null val context = describe(ContextExecutor::class) { describe("with a valid root context") { val ctx = RootContext("root context") { test("test 1") {} test("test 2") {} test("failed test") { assertionError = AssertionError("failed") throw assertionError!! } context("context 1") { context("context 2") { test("test 3") {} } } context("context 4") { test("test 4") {} } } describe("executing all the tests") { val contextResult = execute(ctx) val contextInfo = expectThat(contextResult).isA<ContextInfo>().subject it("returns tests in the same order as they are declared in the file") { expectThat(contextInfo).get { tests.keys }.map { it.testName } .containsExactly("test 1", "test 2", "failed test", "test 3", "test 4") } it("returns deferred test results") { val testResults = contextInfo.tests.values.awaitAll() val successful = testResults.filter { it.isSuccess } val failed = testResults - successful.toSet() expectThat(successful.map { it.test.testName }).containsExactly( "test 1", "test 2", "test 3", "test 4" ) expectThat(failed).map { it.test.testName }.containsExactly("failed test") } it("returns contexts in the same order as they appear in the file") { expectThat(contextInfo.contexts).map { it.name } .containsExactly("root context", "context 1", "context 2", "context 4") } it("reports time of successful tests") { expectThat( contextInfo.tests.values.awaitAll().map { it.result } .filterIsInstance<Success>() ).isNotEmpty().all { get { timeMicro }.isGreaterThanOrEqualTo(1) } } describe("reports failed tests") { val failure = contextInfo.tests.values.awaitAll().map { it.result }.filterIsInstance<Failure>().single() it("reports exception for failed tests") { expectThat(assertionError).isNotNull() val assertionError = assertionError!! expectThat(failure.failure) { get { stackTraceToString() }.isEqualTo(assertionError.stackTraceToString()) } } } } describe("executing a subset of tests") { it("can execute a subset of tests") { val contextResult = coroutineScope { ContextExecutor( ctx, this, testFilter = StringListTestFilter(listOf("root context", "test 1")) ).execute() } val contextInfo = expectThat(contextResult).isA<ContextInfo>().subject expectThat(contextInfo) { get { tests.keys }.map { it.testName }.containsExactly("test 1") get { contexts }.map { it.name }.containsExactly("root context") } } it("does not execute the context at all if the root name does not match") { val contextResult = coroutineScope { ContextExecutor( ctx, this, testFilter = StringListTestFilter(listOf("other root context", "test 1")) ).execute() } val contextInfo = expectThat(contextResult).isA<ContextInfo>().subject expectThat(contextInfo) { get { tests }.isEmpty() get { contexts }.isEmpty() } } } describe("reports line numbers") { var rootContextLine = 0 var context1Line = 0 var context2Line = 0 var test1Line = 0 var test2Line = 0 val ctx = RootContext("root context") { rootContextLine = RuntimeException().stackTrace.first().lineNumber - 1 describe("context 1") { context1Line = RuntimeException().stackTrace.first().lineNumber - 1 it("test1") { test1Line = RuntimeException().stackTrace.first().lineNumber - 1 } } describe("context 2") { context2Line = RuntimeException().stackTrace.first().lineNumber - 1 it("test2") { test2Line = RuntimeException().stackTrace.first().lineNumber - 1 } } } val contextResult = execute(ctx) expectThat(contextResult).isA<ContextInfo>() val contextInfo = contextResult as ContextInfo it("returns file info for all subcontexts") { expectThat(contextInfo.contexts).all { get { sourceInfo }.isNotNull().and { get { fileName }.isEqualTo("ContextExecutorTest.kt") } } } it("returns line number for contexts") { expectThat(contextInfo.contexts) { get(0).get { sourceInfo }.isNotNull().get { lineNumber }.isEqualTo(rootContextLine) get(1).get { sourceInfo }.isNotNull().get { lineNumber }.isEqualTo(context1Line) get(2).get { sourceInfo }.isNotNull().get { lineNumber }.isEqualTo(context2Line) } } it("reports file name for all tests") { expectThat(contextInfo.tests.keys).all { get { sourceInfo }.and { get { fileName }.isEqualTo("ContextExecutorTest.kt") } } } it("reports line number for all tests") { expectThat(contextInfo.tests.keys.toList()) { get(0).get { sourceInfo }.get { lineNumber }.isEqualTo(test1Line) get(1).get { sourceInfo }.get { lineNumber }.isEqualTo(test2Line) } } } } describe("supports lazy execution") { it("postpones test execution until the deferred is awaited when lazy is set to true") { var testExecuted = false val ctx = RootContext("root context") { test("test 1") { testExecuted = true } } coroutineScope { val contextInfo = ContextExecutor( ctx, this, lazy = true, testFilter = ExecuteAllTests ).execute() expectThat(testExecuted).isEqualTo(false) expectThat(contextInfo).isA<ContextInfo>() val deferred = (contextInfo as ContextInfo).tests.values.single() expectThat(deferred.await().result).isA<Success>() expectThat(testExecuted).isEqualTo(true) } } } describe("timing") { it("reports context structure before tests finish") { val ctx = RootContext("root context") { repeat(10) { test("test $it") { delay(1000) } } } val scope = CoroutineScope(Dispatchers.Unconfined) withTimeout(100) { expectThat(ContextExecutor(ctx, scope).execute()).isA<ContextInfo>() } scope.cancel() } } describe("when an exception happeins inside a subcontext") { var error: Throwable? = null val ctx = RootContext("root context") { test("test 1") {} test("test 2") {} context("context 1") { error = NotImplementedError("") throw error!! } context("context 4") { test("test 4") {} } } val results = expectThat(execute(ctx)).isA<ContextInfo>().subject it("it is reported as a failing test inside that context") { expectThat(results.tests.values.awaitAll().filter { it.isFailure }).single().and { get { test }.and { get { testName }.isEqualTo("error in context") get { container.name }.isEqualTo("context 1") get { sourceInfo }.and { get { lineNumber }.isEqualTo(getLineNumber(error) - 1) get { className }.contains("ContextExecutorTest") } } } } it("reports the context as a context") { expectThat(results.contexts).map { it.name }.contains("context 1") } } it("handles failing root contexts") { val ctx = RootContext("root context") { throw RuntimeException("root context failed") } val result = execute(ctx) expectThat(result).isA<FailedRootContext>() } describe("detects duplicated tests") { it("fails with duplicate tests in one context") { val ctx = RootContext { test("dup test name") {} test("dup test name") {} } val result = execute(ctx) assert( result is FailedRootContext && result.failure.message!!.contains("duplicate name \"dup test name\" in context \"root\"") ) } it("does not fail when the tests with the same name are in different contexts") { val ctx = RootContext { test("duplicate test name") {} context("context") { test("duplicate test name") {} } } coroutineScope { ContextExecutor( ctx, this, testFilter = ExecuteAllTests ).execute() } } } describe("detects duplicate contexts") { it("fails with duplicate contexts in one context") { val ctx = RootContext { context("dup ctx") {} context("dup ctx") {} } val result = execute(ctx) expectThat(result).isA<FailedRootContext>().get { failure }.message.isNotNull() .contains("duplicate name \"dup ctx\" in context \"root\"") } it("does not fail when the contexts with the same name are in different contexts") { val ctx = RootContext { test("same context name") {} context("context") { test("same context name") {} } } coroutineScope { ContextExecutor( ctx, this, testFilter = ExecuteAllTests ).execute() } } it("fails when a context has the same name as a test in the same contexts") { val ctx = RootContext { test("same name") {} context("same name") {} } val result = execute(ctx) expectThat(result).isA<FailedRootContext>().get { failure }.message.isNotNull() .contains("duplicate name \"same name\" in context \"root\"") } } describe("filtering by tag") { val events = ConcurrentHashMap.newKeySet<String>() // start with the easy version it("can filter contexts in the root context by tag") { val context = RootContext { describe("context without the tag") { events.add("context without tag") } describe("context with the tag", tags = setOf("single")) { events.add("context with tag") it("should be executed") { events.add("test in context with tag") } describe("subcontext of the context with the tag") { events.add("context in context with tag") it("should also be executed") { events.add("test in context in context with tag") } } } test("test that should also not be executed") { events.add("test in root context without tag") } } val contextResult = execute(context, "single") expectSuccess(contextResult) expectThat(events).containsExactlyInAnyOrder( "context with tag", "test in context with tag", "context in context with tag", "test in context in context with tag" ) } it("can filter tests in the root context by tag") { val context = RootContext { describe("context without the tag") { events.add("context without tag") } test("test with the tag", tags = setOf("single")) { events.add("test in root context with tag") } it("other test with the tag", tags = setOf("single")) { events.add("other test with the tag") } test("test that should also not be executed") { events.add("test in root context without tag") } } val contextResult = execute(context, tag = "single") expectSuccess(contextResult) expectThat(events).containsExactlyInAnyOrder( "test in root context with tag", "other test with the tag" ) } pending("can filter tests in a subcontext") { val context = RootContext { describe("context without the tag") { events.add("context without tag") it("test in context without the tag") { events.add("test in context without the tag") } } describe("context without the tag that contains the test with the tag") { events.add("context without the tag that contains the test with the tag") test("test with the tag", tags = setOf("single")) { events.add("test with the tag") } } test("test in root context without tag") { events.add("test in root context without tag") } } val contextResult = execute(context, "single") expectSuccess(contextResult) expectThat(events).containsExactlyInAnyOrder( "context without the tag that contains the test with the tag", "test with the tag" ) } } describe("handles strange contexts correctly") { it("a context with only one pending test") { val context = RootContext { describe("context") { pending("pending") {} } test("test") {} } val contextResult = execute(context) expectSuccess(contextResult) } test("tests can not contain nested contexts") { // context("this does not even compile") {} } } } private suspend fun expectSuccess(contextResult: ContextResult) { expectThat(contextResult).isA<ContextInfo>().subject.tests.values.awaitAll() } private suspend fun execute(context: RootContext, tag: String? = null): ContextResult { return coroutineScope { ContextExecutor(context, this, onlyTag = tag).execute() } } private fun getLineNumber(runtimeException: Throwable?): Int = runtimeException!!.stackTrace.first().lineNumber }
18
null
4
12
ee51afa22d6451d3b5be4312d87860f09c9a841b
18,207
failgood
MIT License
testing-tools/app/src/main/kotlin/net/consensys/zkevm/load/LineaEstimateGasResponse.kt
Consensys
681,656,806
false
{"Go": 3732756, "Kotlin": 2036043, "TypeScript": 1677629, "Solidity": 1011831, "Java": 190613, "Shell": 25336, "Python": 25050, "Jupyter Notebook": 14509, "Makefile": 13574, "Dockerfile": 8023, "JavaScript": 7341, "C": 5181, "Groovy": 2557, "CSS": 787, "Nix": 315, "Batchfile": 117}
package net.consensys.zkevm.load import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.core.JsonToken import com.fasterxml.jackson.databind.DeserializationContext import com.fasterxml.jackson.databind.JsonDeserializer import com.fasterxml.jackson.databind.ObjectReader import com.fasterxml.jackson.databind.annotation.JsonDeserialize import net.consensys.linea.bigIntFromPrefixedHex import org.web3j.protocol.ObjectMapperFactory import org.web3j.protocol.core.Response import java.io.IOException import java.math.BigInteger /** eth_feeHistory. */ class LineaEstimateGasResponse : Response<LineaEstimateGasResponse.GasEstimationSerialized?>() { @JsonDeserialize(using = GasEstimationSerialized.Companion.ResponseDeserialiser::class) override fun setResult(result: GasEstimationSerialized?) { super.setResult(result) } fun getGasEstimation(): GasEstimation? { return if (result != null) { GasEstimation( baseFeePerGas = result!!.baseFeePerGas.bigIntFromPrefixedHex(), gasLimit = result!!.gasLimit.bigIntFromPrefixedHex(), priorityFeePerGas = result!!.priorityFeePerGas.bigIntFromPrefixedHex() ) } else { null } } data class GasEstimation(val baseFeePerGas: BigInteger, val gasLimit: BigInteger, val priorityFeePerGas: BigInteger) data class GasEstimationSerialized(val baseFeePerGas: String, val gasLimit: String, val priorityFeePerGas: String) { constructor() : this("", "", "") companion object { class ResponseDeserialiser : JsonDeserializer<GasEstimationSerialized?>() { private val objectReader: ObjectReader = ObjectMapperFactory.getObjectReader() @Throws(IOException::class) override fun deserialize( jsonParser: JsonParser, deserializationContext: DeserializationContext ): GasEstimationSerialized? { return if (jsonParser.currentToken != JsonToken.VALUE_NULL) { objectReader.readValue(jsonParser, GasEstimationSerialized::class.java) } else { null // null is wrapped by Optional in above getter } } } } } }
27
Go
2
26
48547c9f3fb21e9003d990c9f62930f4facee0dd
2,153
linea-monorepo
Apache License 2.0
domain/src/main/java/com/example/domain/usecases/register/GetRegisterUseCase.kt
meghdadya
776,918,286
false
{"Kotlin": 85745}
package com.example.domain.usecases.register import com.example.domain.models.GeneralError import com.example.domain.models.ListDomainModel import com.example.domain.models.Resource import com.example.domain.models.register.RegisterDomainModel import com.example.domain.repositories.register.RegisterRepository import com.example.domain.usecases.base.BaseUseCase import javax.inject.Inject class GetRegisterUseCase @Inject constructor(private val registerRepository: RegisterRepository) : BaseUseCase<Unit, Resource<ListDomainModel<RegisterDomainModel>, GeneralError>>() { override suspend fun execute(param: Unit): Resource<ListDomainModel<RegisterDomainModel>, GeneralError> = registerRepository.getRegister() }
0
Kotlin
0
0
a0b7cd489ee3e85e1197b90d8b08eb94a9c7901c
731
OryAuthentication
Apache License 2.0
app/src/main/java/com/ismynr/githubuserlist/adapter/FollowingAdapter.kt
ismynr
301,744,290
false
null
package com.ismynr.githubuserlist.adapter import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.bumptech.glide.Glide import com.bumptech.glide.request.RequestOptions import com.ismynr.githubuserlist.R import com.ismynr.githubuserlist.databinding.ItemUserBinding import com.ismynr.githubuserlist.model.Following class FollowingAdapter(private val listUser: ArrayList<Following>) : RecyclerView.Adapter<FollowingAdapter.FollowingViewHolder>() { fun setData(items: ArrayList<Following>) { listUser.clear() notifyDataSetChanged() listUser.addAll(items) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): FollowingViewHolder { val view = LayoutInflater.from(parent.context).inflate(R.layout.item_user, parent, false) return FollowingViewHolder(view) } override fun onBindViewHolder(holder: FollowingViewHolder, position: Int) { holder.bind(listUser[position]) } override fun getItemCount(): Int = listUser.size inner class FollowingViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val binding = ItemUserBinding.bind(itemView) fun bind(user: Following) { with(binding){ Glide.with(itemView.context) .load(user.avatar) .apply(RequestOptions().override(72, 72)) .into(imgAvatar) tvName.text = user.name tvUsername.text = itemView.context.getString(R.string.github_username, user.username) tvRepositories.text = itemView.context.getString(R.string.repositories_100, user.repository) tvFollowers.text = itemView.context.getString(R.string.followers_1000, user.followers) tvFollowing.text = itemView.context.getString(R.string.following_100, user.following) } } } }
0
Kotlin
0
0
165a414752034fa1287a1703d6d917825ab7901a
1,989
DC-ListGIthubUser-Android
MIT License
app/src/main/java/com/matiasmandelbaum/alejandriaapp/domain/model/book/components/ImageLinks.kt
mandelbaummatias
696,924,886
false
{"Kotlin": 218948}
package com.matiasmandelbaum.alejandriaapp.domain.model.book.components data class ImageLinks( val smallThumbnail: String? )
0
Kotlin
0
0
82f90a11529a20489e8beb1dfa7a0d958874c6e8
129
AlejandriaApp
Apache License 2.0
src/test/kotlin/ga/fundamental/integrationadapter/dsl/DslTest.kt
alexe13
198,091,188
false
null
package ga.fundamental.integrationadapter.dsl import ga.fundamental.integrationadapter.components.Message import ga.fundamental.integrationadapter.components.processor.SimpleMapper import ga.fundamental.integrationadapter.components.processor.splitter.ConditionalSplitter import ga.fundamental.integrationadapter.components.sink.StdErrWriter import ga.fundamental.integrationadapter.components.sink.StdOutWriter import ga.fundamental.integrationadapter.components.source.RandomNumberGenerator import ga.fundamental.integrationadapter.components.source.StdOutReader import org.assertj.core.api.Assertions.assertThat import org.junit.jupiter.api.AfterAll import org.junit.jupiter.api.BeforeAll import org.junit.jupiter.api.Test import org.junit.jupiter.api.TestInstance import reactor.core.publisher.ReplayProcessor import reactor.core.scheduler.Schedulers import java.time.Duration @TestInstance(TestInstance.Lifecycle.PER_CLASS) class DslTest { private val replayProcessor = ReplayProcessor.create<Message>() private val reader1 = StdOutReader() private val mapper1 = SimpleMapper { it } private val writer1 = StdOutWriter() private val numberGenerator = RandomNumberGenerator(Duration.ofSeconds(5)) private val okWriter = StdOutWriter() private val errWriter = StdErrWriter() private val splitter = ConditionalSplitter { { m: Message -> m.payload is Number } > okWriter { m: Message -> m.payload !is Number } > errWriter } private lateinit var router: Router @BeforeAll private fun initRouter() { router = Router { pipeline("Pipeline1") { eventBus(replayProcessor) components { link(reader1 to mapper1) link(mapper1 to writer1) } } pipeline("Pipeline2") { scheduler(Schedulers.boundedElastic()) components { link(numberGenerator to splitter) } } } } @AfterAll private fun cleanUp() { router.destroy() } @Test fun `verify basic structure`() { assertThat(router).isNotNull assertThat(router.pipelines).hasSize(2) assertThat(router.pipelines.keys).contains("Pipeline1") assertThat(router.pipelines.keys).contains("Pipeline2") } @Test fun `verify first pipeline`() { val pipeline1 = router.pipelines["Pipeline1"] assertThat(pipeline1).extracting { it?.eventBus }.isInstanceOf(ReplayProcessor::class.java) assertThat(pipeline1).extracting { it?.eventBus }.isSameAs(replayProcessor) assertThat(pipeline1).extracting { it?.scheduler }.isSameAs(Schedulers.single()) val components1 = pipeline1?.components assertThat(components1).hasSize(2) assertThat(components1?.flatMap { it.pair.toList() }).containsAll(listOf(reader1, mapper1, writer1)) } @Test fun `verify second pipeline`() { val pipeline2 = router.pipelines["Pipeline2"] assertThat(pipeline2).extracting { it?.eventBus }.isInstanceOf(ReplayProcessor::class.java) assertThat(pipeline2).extracting { it?.eventBus }.isNotSameAs(replayProcessor) assertThat(pipeline2).extracting { it?.scheduler }.isSameAs(Schedulers.boundedElastic()) val components2 = pipeline2?.components assertThat(components2).hasSize(1) assertThat(components2?.flatMap { it.pair.toList() }).containsAll(listOf(numberGenerator, splitter)) } }
0
Kotlin
0
2
d7229784e9a4269fbe003fb782a8ce8c1be5f7f0
3,557
integration-adapter-dsl
Apache License 2.0
app/src/main/java/com/marvelapp/marvelcomics/br/sdk/response/comic/Result.kt
Erasmojf
356,364,056
false
null
package com.marvelapp.br.sdk.response.comic import com.marvelapp.br.sdk.response.Stories import com.marvelapp.br.sdk.response.Thumbnail import com.marvelapp.br.sdk.response.Url import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Result( val characters: Characters, val collectedIssues: List<Any>, val collections: List<Any>, val creators: Creators, val dates: List<Date>, val description: String?, val diamondCode: String, val digitalId: Int, val ean: String, val events: Events, val format: String, val id: Int, val images: List<Image>, val isbn: String, val issn: String, val issueNumber: Int, val modified: String, val pageCount: Int, val prices: List<Price>, val resourceURI: String, val series: Series, val stories: Stories, val textObjects: List<TextObject>, val thumbnail: Thumbnail, val title: String, val upc: String, val urls: List<Url>, val variantDescription: String, val variants: List<Variant> )
0
Kotlin
0
2
6c360c1b2a88a74f50bf67a31203eeaa04ae6323
1,057
MarvelComicsApp
MIT License
SharedCode/src/commonMain/kotlin/net/compoza/deactivator/mpp/model/PluginViewModel.kt
Diy2210
302,059,309
false
null
package net.compoza.deactivator.mpp.model import dev.icerock.moko.mvvm.livedata.MutableLiveData import dev.icerock.moko.mvvm.viewmodel.ViewModel import kotlinx.coroutines.launch import kotlinx.serialization.json.Json import net.compoza.deactivator.db.Server import net.compoza.deactivator.mpp.api.PluginDeactivatorApi class PluginViewModel : ViewModel() { private val client = PluginDeactivatorApi() lateinit var resp: PluginResponseModel var list: List<PluginModel> = emptyList() val _plugins: MutableLiveData<List<PluginModel>> = MutableLiveData(list) var status: String = "Loading" val _status: MutableLiveData<String> = MutableLiveData(status) private val _pluginsMutableLiveData: MutableLiveData<List<PluginModel>> = MutableLiveData(initialValue = List(1) { PluginModel( "Loading", "Loading", false ) }) val pluginList: MutableLiveData<List<PluginModel>> = _pluginsMutableLiveData fun getInitList(): MutableLiveData<List<PluginModel>> { _plugins.value = list return _plugins } fun launchAsyncRequest(server: Server) { viewModelScope.launch { try { client.getPluginsList(server) .also { response -> resp = Json.decodeFromString(PluginResponseModel.serializer(), response) if (resp.success) { pluginList.value = resp.data _status.value = "Success" } else { _status.value = "Error" } } } catch (e: Exception) { println("Server Error: $e") _status.value = "Error" } } } fun getStatus(): MutableLiveData<String> { return _status } fun setStatus(server: Server, model: PluginModel, state: Boolean) { viewModelScope.launch { try { client.updatePluginStatus(server, model, state) } catch (e: Exception) { println("Server Error: $e") } } } }
0
Kotlin
0
0
4a8d3739c7cde9cafb14e75fc11a02c4ec055d71
2,228
com.rompos.deactivator2
Apache License 2.0
src/main/kotlin/cn/net/polyglot/verticle/community/WebServerVerticle.kt
liqianjie
189,933,377
true
{"Kotlin": 104201, "HTML": 11314, "Java": 4023, "Groovy": 3471, "CSS": 296}
package cn.net.polyglot.verticle.community import cn.net.polyglot.verticle.im.IMServletVerticle import cn.net.polyglot.verticle.web.DispatchVerticle import io.vertx.core.http.HttpMethod class WebServerVerticle: DispatchVerticle() { //设置http方法为put时候,http请求体缺省为application/json,但是flutter中以及需要设置Content-Type为application/json,否则会自动设为text/plain override fun getDefaultContentTypeByHttpMethod(httpMethod: HttpMethod):String{ return when(httpMethod){ HttpMethod.PUT -> "application/json" else -> super.getDefaultContentTypeByHttpMethod(httpMethod) } } override suspend fun getVerticleAddressByPath(httpMethod: HttpMethod, path: String): String { return when(httpMethod){ HttpMethod.GET, HttpMethod.POST -> when(path){ "/login","/profile","/register","/update","/portrait" -> LoginVerticle::class.java.name "/prepareArticle", "/submitArticle","/prepareModifyArticle","/modifyArticle","/deleteArticle","/prepareSearchArticle","/searchArticle","/article", "/community","/uploadPortrait" -> CommunityVerticle::class.java.name else -> "" } HttpMethod.PUT -> IMServletVerticle::class.java.name else -> "" } } }
0
Kotlin
0
0
1736611e0c7f55234a01173ff8858d365b265e2d
1,188
social-vertex
MIT License
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/cloudwatch/CfnDashboardDsl.kt
cloudshiftinc
667,063,030
false
null
@file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION") package cloudshift.awscdk.dsl.services.cloudwatch import cloudshift.awscdk.common.CdkDslMarker import kotlin.String import software.amazon.awscdk.services.cloudwatch.CfnDashboard import software.constructs.Construct /** * The `AWS::CloudWatch::Dashboard` resource specifies an Amazon CloudWatch dashboard. * * A dashboard is a customizable home page in the CloudWatch console that you can use to monitor * your AWS resources in a single view. * * All dashboards in your account are global, not region-specific. * * Example: * * ``` * // The code below shows an example of how to instantiate this type. * // The values are placeholders you should change. * import software.amazon.awscdk.services.cloudwatch.*; * CfnDashboard cfnDashboard = CfnDashboard.Builder.create(this, "MyCfnDashboard") * .dashboardBody("dashboardBody") * // the properties below are optional * .dashboardName("dashboardName") * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudwatch-dashboard.html) */ @CdkDslMarker public class CfnDashboardDsl( scope: Construct, id: String, ) { private val cdkBuilder: CfnDashboard.Builder = CfnDashboard.Builder.create(scope, id) /** * The detailed information about the dashboard in JSON format, including the widgets to include * and their location on the dashboard. * * * * For more information about the syntax, see [Dashboard Body Structure and * Syntax](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/CloudWatch-Dashboard-Body-Structure.html) * . * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudwatch-dashboard.html#cfn-cloudwatch-dashboard-dashboardbody) * @param dashboardBody The detailed information about the dashboard in JSON format, including the * widgets to include and their location on the dashboard. */ public fun dashboardBody(dashboardBody: String) { cdkBuilder.dashboardBody(dashboardBody) } /** * The name of the dashboard. * * The name must be between 1 and 255 characters. If you do not specify a name, one will be * generated automatically. * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-cloudwatch-dashboard.html#cfn-cloudwatch-dashboard-dashboardname) * @param dashboardName The name of the dashboard. */ public fun dashboardName(dashboardName: String) { cdkBuilder.dashboardName(dashboardName) } public fun build(): CfnDashboard = cdkBuilder.build() }
1
Kotlin
0
0
17c41bdaffb2e10d31b32eb2282b73dd18be09fa
2,770
awscdk-dsl-kotlin
Apache License 2.0
app/src/main/java/io/github/gmathi/novellibrary/activity/ReaderDBPagerActivity.kt
TechnoJo4
249,806,029
true
{"Kotlin": 649350, "Java": 33921}
package io.github.gmathi.novellibrary.activity import android.animation.ObjectAnimator import android.app.Activity import android.content.Intent import android.graphics.Typeface import android.graphics.drawable.Drawable import android.os.Bundle import android.os.Handler import android.os.Looper import android.view.KeyEvent import android.view.View import android.view.View.* import android.view.WindowManager import android.webkit.MimeTypeMap import android.webkit.WebView import android.widget.CompoundButton import androidx.core.content.ContextCompat import androidx.documentfile.provider.DocumentFile import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import androidx.recyclerview.widget.RecyclerView.LayoutParams.MATCH_PARENT import androidx.recyclerview.widget.RecyclerView.LayoutParams.WRAP_CONTENT import androidx.viewpager.widget.ViewPager import com.afollestad.materialdialogs.DialogAction import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.Theme import com.yarolegovich.slidingrootnav.SlideGravity import com.yarolegovich.slidingrootnav.SlidingRootNav import com.yarolegovich.slidingrootnav.SlidingRootNavBuilder import io.github.gmathi.novellibrary.R import io.github.gmathi.novellibrary.adapter.DrawerAdapter import io.github.gmathi.novellibrary.adapter.GenericFragmentStatePagerAdapter import io.github.gmathi.novellibrary.adapter.WebPageFragmentPageListener import io.github.gmathi.novellibrary.dataCenter import io.github.gmathi.novellibrary.database.* import io.github.gmathi.novellibrary.dbHelper import io.github.gmathi.novellibrary.extensions.* import io.github.gmathi.novellibrary.fragment.WebPageDBFragment import io.github.gmathi.novellibrary.model.* import io.github.gmathi.novellibrary.util.Constants import io.github.gmathi.novellibrary.util.Constants.VOLUME_SCROLL_LENGTH_STEP import io.github.gmathi.novellibrary.util.Utils import io.github.gmathi.novellibrary.view.TwoWaySeekBar import kotlinx.android.synthetic.main.activity_reader_pager.* import kotlinx.android.synthetic.main.item_option.view.* import kotlinx.android.synthetic.main.menu_left_drawer.* import org.greenrobot.eventbus.EventBus import java.io.File class ReaderDBPagerActivity : BaseActivity(), ViewPager.OnPageChangeListener, DrawerAdapter.OnItemSelectedListener, SimpleItem.Listener<ReaderMenu> { companion object { private const val READER_MODE = 0 private const val NIGHT_MODE = 1 private const val JAVA_SCRIPT = 2 private const val FONTS = 3 private const val FONT_SIZE = 4 private const val REPORT_PAGE = 5 private const val OPEN_IN_BROWSER = 6 private const val SHARE_CHAPTER = 7 private const val MORE_SETTINGS = 8 private const val READ_ALOUD = 9 private val FONT_MIME_TYPES = arrayOf( MimeTypeMap.getSingleton().getMimeTypeFromExtension("ttf") ?: "application/x-font-ttf", "fonts/ttf", MimeTypeMap.getSingleton().getMimeTypeFromExtension("otf") ?: "application/x-font-opentype", "fonts/otf", "application/octet-stream" ) private val AVAILABLE_FONTS = linkedMapOf<String, String>() } private lateinit var slidingRootNav: SlidingRootNav private lateinit var screenTitles: Array<String> private lateinit var screenIcons: Array<Drawable?> private lateinit var recyclerView: RecyclerView private lateinit var novel: Novel private lateinit var adapter: GenericFragmentStatePagerAdapter private var sourceId: Long = -1L private var webPages: List<WebPage> = ArrayList() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_reader_pager) if (dataCenter.keepScreenOn) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) //Read Intent Extras sourceId = intent.getLongExtra("sourceId", -1L) val tempNovel = intent.getSerializableExtra("novel") as Novel? //Check if it is Valid Novel if (tempNovel == null || tempNovel.chaptersCount.toInt() == 0) { finish() return } else novel = tempNovel //Get all WebPages & set view pager webPages = dbHelper.getAllWebPages(novel.id, sourceId) if (dataCenter.japSwipe) webPages = webPages.reversed() adapter = GenericFragmentStatePagerAdapter(supportFragmentManager, null, webPages.size, WebPageFragmentPageListener(novel, webPages)) viewPager.addOnPageChangeListener(this) viewPager.adapter = adapter //Set the current page to the bookmarked webPage novel.currentWebPageUrl?.let { bookmarkUrl -> val index = webPages.indexOfFirst { it.url == bookmarkUrl } if (index != -1) viewPager.currentItem = index if (index == 0) updateBookmark(webPages[0]) } //Set up the Slide-Out Reader Menu. slideMenuSetup(savedInstanceState) screenIcons = loadScreenIcons() screenTitles = loadScreenTitles() slideMenuAdapterSetup() menuNav.setOnClickListener { toggleSlideRootNab() } // Easy access to open reader menu button if (!dataCenter.isReaderModeButtonVisible) menuNav.visibility = INVISIBLE } private fun updateBookmark(webPage: WebPage) { dbHelper.updateBookmarkCurrentWebPageUrl(novel.id, webPage.url) val webPageSettings = dbHelper.getWebPageSettings(webPage.url) if (webPageSettings != null) { dbHelper.updateWebPageSettingsReadStatus(webPageSettings.url, 1, webPageSettings.metaData) } } override fun onWindowFocusChanged(hasFocus: Boolean) { super.onWindowFocusChanged(hasFocus) if (hasFocus && dataCenter.enableImmersiveMode) { main_content.fitsSystemWindows = false window.decorView.systemUiVisibility = Constants.IMMERSIVE_MODE_FLAGS } } override fun onPageSelected(position: Int) { updateBookmark(webPage = webPages[position]) } override fun onPageScrollStateChanged(position: Int) { //Do Nothing } override fun onPageScrolled(p0: Int, p1: Float, p2: Int) { //Do Nothing } private fun changeTextSize() { val dialog = MaterialDialog.Builder(this) .title(R.string.text_size) .customView(R.layout.dialog_slider, true) .build() dialog.show() dialog.customView?.findViewById<TwoWaySeekBar>(R.id.seekBar)?.setOnSeekBarChangedListener { _, progress -> dataCenter.textSize = progress.toInt() EventBus.getDefault().post(ReaderSettingsEvent(ReaderSettingsEvent.TEXT_SIZE)) } dialog.customView?.findViewById<TwoWaySeekBar>(R.id.seekBar)?.setProgress(dataCenter.textSize.toDouble()) } private fun reportPage() { MaterialDialog.Builder(this) .content("Please use discord to report a bug.") .positiveText("Ok") .onPositive { dialog, _ -> dialog.dismiss() } .show() } private fun inBrowser() { val url = (viewPager.adapter?.instantiateItem(viewPager, viewPager.currentItem) as WebPageDBFragment?)?.getUrl() if (url != null) openInBrowser(url) } private fun share() { val url = (viewPager.adapter?.instantiateItem(viewPager, viewPager.currentItem) as WebPageDBFragment?)?.getUrl() if (url != null) { shareUrl(url) } } override fun dispatchKeyEvent(event: KeyEvent): Boolean { val action = event.action val keyCode = event.keyCode val webView = (viewPager.adapter?.instantiateItem(viewPager, viewPager.currentItem) as WebPageDBFragment?)?.view?.findViewById<WebView>(R.id.readerWebView) return when (keyCode) { KeyEvent.KEYCODE_VOLUME_UP -> { if (action == KeyEvent.ACTION_DOWN && dataCenter.volumeScroll) { val anim = ObjectAnimator.ofInt( webView, "scrollY", webView?.scrollY ?: 0, (webView?.scrollY ?: 0) - dataCenter.scrollLength * VOLUME_SCROLL_LENGTH_STEP ) anim.setDuration(500).start() } dataCenter.volumeScroll } KeyEvent.KEYCODE_VOLUME_DOWN -> { if (action == KeyEvent.ACTION_DOWN && dataCenter.volumeScroll) { val anim = ObjectAnimator.ofInt( webView, "scrollY", webView?.scrollY ?: 0, (webView?.scrollY ?: 0) + dataCenter.scrollLength * VOLUME_SCROLL_LENGTH_STEP ) anim.setDuration(500).start() } dataCenter.volumeScroll } else -> super.dispatchKeyEvent(event) } } override fun onBackPressed() { val currentFrag = (viewPager.adapter?.instantiateItem(viewPager, viewPager.currentItem) as WebPageDBFragment) when { currentFrag.history.isNotEmpty() -> currentFrag.goBack() //currentFrag.readerWebView.canGoBack() -> currentFrag.readerWebView.goBack() else -> super.onBackPressed() } } fun checkUrl(url: String): Boolean { val webPageSettings = dbHelper.getWebPageSettingsByRedirectedUrl(url) ?: return false val webPage = dbHelper.getWebPage(webPageSettings.url) ?: return false val index = dbHelper.getAllWebPages(novel.id, sourceId).indexOf(webPage) return if (index == -1) false else { viewPager.currentItem = index updateBookmark(webPage) true } } private fun slideMenuSetup(savedInstanceState: Bundle?) { slidingRootNav = SlidingRootNavBuilder(this) .withMenuOpened(false) .withContentClickableWhenMenuOpened(true) .withSavedState(savedInstanceState) .withGravity(SlideGravity.RIGHT) .withMenuLayout(R.layout.menu_left_drawer) .inject() } private fun slideMenuAdapterSetup() { @Suppress("UNCHECKED_CAST") val adapter = DrawerAdapter( listOf( createItemFor(READER_MODE).setSwitchOn(true), createItemFor(NIGHT_MODE).setSwitchOn(true), createItemFor(JAVA_SCRIPT).setSwitchOn(true), createItemFor(FONTS), createItemFor(FONT_SIZE), createItemFor(REPORT_PAGE), createItemFor(OPEN_IN_BROWSER), createItemFor(SHARE_CHAPTER), createItemFor(MORE_SETTINGS), createItemFor(READ_ALOUD) ) as List<DrawerItem<DrawerAdapter.ViewHolder>> ) adapter.setListener(this) list.isNestedScrollingEnabled = false list.layoutManager = LinearLayoutManager(this) list.adapter = adapter } private fun createItemFor(position: Int): DrawerItem<SimpleItem.ViewHolder> { return SimpleItem(ReaderMenu(screenIcons[position]!!, screenTitles[position]), this) } private fun toggleSlideRootNab() { if (slidingRootNav.isMenuOpened) slidingRootNav.closeMenu() else slidingRootNav.openMenu() } private fun loadScreenTitles(): Array<String> { return resources.getStringArray(R.array.reader_mode_menu_titles_list) } private fun loadScreenIcons(): Array<Drawable?> { val ta = resources.obtainTypedArray(R.array.reader_mode_menu_icons_list) val icons = arrayOfNulls<Drawable>(ta.length()) for (i in 0 until ta.length()) { val id = ta.getResourceId(i, 0) if (id != 0) { icons[i] = ContextCompat.getDrawable(this, id) } } ta.recycle() return icons } private fun createTypeface(path: String = dataCenter.fontPath): Typeface { return if (path.startsWith("/android_asset")) Typeface.createFromAsset(assets, path.substringAfter('/').substringAfter('/')) else Typeface.createFromFile(path) } /** * Handle Slide Menu Nav Options */ override fun onItemSelected(position: Int) { slidingRootNav.closeMenu() when (position) { FONTS -> { if (AVAILABLE_FONTS.isEmpty()) getAvailableFonts() var selectedFont = dataCenter.fontPath.substringAfterLast('/') .substringBeforeLast('.') .replace('_', ' ') var typeFace = createTypeface() val dialog = MaterialDialog.Builder(this) .theme(Theme.DARK) .title(getString(R.string.title_fonts)) .items(AVAILABLE_FONTS.keys) .alwaysCallSingleChoiceCallback() .itemsCallbackSingleChoice(AVAILABLE_FONTS.keys.indexOf(selectedFont)) { dialog, _, which, font -> if (which == 0) { addFont() dialog.dismiss() } else { val fontPath = AVAILABLE_FONTS[font.toString()] if (fontPath != null) { selectedFont = font.toString() typeFace = createTypeface(fontPath) dialog.setTypeface(dialog.titleView, typeFace) } else { dialog.selectedIndex = AVAILABLE_FONTS.keys.indexOf(selectedFont) dialog.notifyItemsChanged() } } true } .onPositive { _, which -> if (which == DialogAction.POSITIVE) { dataCenter.fontPath = AVAILABLE_FONTS[selectedFont] ?: "" EventBus.getDefault().post(ReaderSettingsEvent(ReaderSettingsEvent.FONT)) } } .positiveText(R.string.okay) .show() dialog.setTypeface(dialog.titleView, typeFace) } FONT_SIZE -> changeTextSize() REPORT_PAGE -> reportPage() OPEN_IN_BROWSER -> inBrowser() SHARE_CHAPTER -> share() MORE_SETTINGS -> startReaderSettingsActivity() READ_ALOUD -> { if (dataCenter.readerMode) { val webPageDBFragment = (viewPager.adapter?.instantiateItem(viewPager, viewPager.currentItem) as? WebPageDBFragment) val audioText = webPageDBFragment?.doc?.text() ?: return val title = webPageDBFragment.doc?.title() ?: "" startTTSService(audioText, title, novel.id, sourceId) } else { showAlertDialog(title = "Read Aloud", message = "Only supported in Reader Mode!") } } } } /** * For Reader Mode & Night Mode toggle */ override fun bind(item: ReaderMenu, itemView: View, position: Int, simpleItem: SimpleItem) { if (itemView.visibility == GONE) { itemView.visibility = VISIBLE itemView.layoutParams = RecyclerView.LayoutParams(MATCH_PARENT, WRAP_CONTENT) } itemView.title.text = item.title itemView.icon.setImageDrawable(item.icon) itemView.itemSwitch.setOnCheckedChangeListener(null) if (simpleItem.isSwitchOn() && position == READER_MODE) { itemView.itemSwitch.visibility = VISIBLE itemView.itemSwitch.isChecked = dataCenter.readerMode } else if (simpleItem.isSwitchOn() && position == NIGHT_MODE) { if (!dataCenter.readerMode) { itemView.visibility = GONE itemView.layoutParams = RecyclerView.LayoutParams(0, 0) } else { itemView.itemSwitch.visibility = VISIBLE itemView.itemSwitch.isChecked = dataCenter.isDarkTheme } } else if (simpleItem.isSwitchOn() && position == JAVA_SCRIPT) { if (dataCenter.readerMode) { itemView.visibility = GONE itemView.layoutParams = RecyclerView.LayoutParams(0, 0) } else { itemView.itemSwitch.visibility = VISIBLE itemView.itemSwitch.isChecked = !dataCenter.javascriptDisabled } } else itemView.itemSwitch.visibility = GONE itemView.itemSwitch.setOnCheckedChangeListener { _: CompoundButton, isChecked: Boolean -> when (position) { READER_MODE -> { dataCenter.readerMode = isChecked if (isChecked && !dataCenter.javascriptDisabled) dataCenter.javascriptDisabled = true list.adapter?.notifyItemRangeChanged(NIGHT_MODE, 2) EventBus.getDefault().post(ReaderSettingsEvent(ReaderSettingsEvent.READER_MODE)) } NIGHT_MODE -> { dataCenter.isDarkTheme = isChecked EventBus.getDefault().post(ReaderSettingsEvent(ReaderSettingsEvent.NIGHT_MODE)) } JAVA_SCRIPT -> { dataCenter.javascriptDisabled = !isChecked if (!dataCenter.javascriptDisabled && dataCenter.readerMode) dataCenter.readerMode = false EventBus.getDefault().post(ReaderSettingsEvent(ReaderSettingsEvent.JAVA_SCRIPT)) } } } } @Synchronized private fun getAvailableFonts() { if (AVAILABLE_FONTS.isNotEmpty()) return AVAILABLE_FONTS[getString(R.string.add_font)] = "" assets.list("fonts")?.filter { it.endsWith(".ttf") || it.endsWith(".otf") }?.forEach { AVAILABLE_FONTS[it.substringBeforeLast('.').replace('_', ' ')] = "/android_asset/fonts/$it" } val appFontsDir = File(getExternalFilesDir(null) ?: filesDir, "Fonts") if (!appFontsDir.exists()) appFontsDir.mkdir() appFontsDir.listFiles()?.forEach { AVAILABLE_FONTS[it.nameWithoutExtension.replace('_', ' ')] = it.path } } private fun addFont() { val intent = Intent(Intent.ACTION_OPEN_DOCUMENT) .addCategory(Intent.CATEGORY_OPENABLE) .setType("*/*") .putExtra(Intent.EXTRA_MIME_TYPES, FONT_MIME_TYPES) .addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) .addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION) // .addFlags(Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION) startActivityForResult(intent, Constants.ADD_FONT_REQUEST_CODE) } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) when (requestCode) { Constants.IWV_ACT_REQ_CODE -> { Handler(Looper.getMainLooper()).post { EventBus.getDefault().post(ReaderSettingsEvent(ReaderSettingsEvent.READER_MODE)) } } Constants.ADD_FONT_REQUEST_CODE -> { if (resultCode == Activity.RESULT_OK) { val uri = data?.data if (uri != null) { val document = DocumentFile.fromSingleUri(baseContext, uri) if (document != null && document.isFile) { val fontsDir = File(getExternalFilesDir(null) ?: filesDir, "Fonts/") if (!fontsDir.exists()) fontsDir.mkdir() val file = File(fontsDir, document.name!!) Utils.copyFile(contentResolver, document, file) AVAILABLE_FONTS[file.nameWithoutExtension.replace('_', ' ')] = file.path dataCenter.fontPath = file.path EventBus.getDefault().post(ReaderSettingsEvent(ReaderSettingsEvent.FONT)) } } } } Constants.READER_SETTINGS_ACT_REQ_CODE -> { EventBus.getDefault().post(ReaderSettingsEvent(ReaderSettingsEvent.NIGHT_MODE)) } } } override fun onResume() { super.onResume() novel.metaData[Constants.MetaDataKeys.LAST_READ_DATE] = Utils.getCurrentFormattedDate() dbHelper.updateNovelMetaData(novel) } }
0
Kotlin
0
1
343f1afd469f4556668c785b2df8e5356fee6f28
21,056
NovelLibrary
Apache License 2.0
src/main/kotlin/adventofcode/year2020/Day21AllergenAssessment.kt
pfolta
573,956,675
false
{"Kotlin": 199554, "Dockerfile": 214}
package adventofcode.year2020 import adventofcode.Puzzle import adventofcode.PuzzleInput class Day21AllergenAssessment(customInput: PuzzleInput? = null) : Puzzle(customInput) { private val foods by lazy { input.lines().map(Food::invoke) } override fun partOne(): Int { val ingredientsToAllergens = foods.ingredientsAllergensMap() return foods.flatMap(Food::ingredients).filter { !ingredientsToAllergens.contains(it) }.size } override fun partTwo() = foods.ingredientsAllergensMap().entries.sortedBy { it.value }.joinToString(",") { it.key } companion object { private data class Food( val ingredients: List<String>, val allergens: List<String> ) { companion object { operator fun invoke(input: String): Food { val ingredients = input.split("(").first().trim().split(" ") val allergens = when { input.contains("(") -> input.split("(").last().replace("contains ", "").replace(")", "").split(", ") else -> emptyList() } return Food(ingredients, allergens) } } } private fun List<Food>.ingredientsAllergensMap() = flatMap { food -> food.allergens.map { allergen -> food.ingredients.last { ingredient -> filter { it.allergens.contains(allergen) }.all { it.ingredients.contains(ingredient) } } to allergen } }.toMap() } }
0
Kotlin
0
0
c20489304c3ced82a67fc290f5046e631b4bf9c9
1,588
AdventOfCode
MIT License
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Cream.kt
localhostov
808,861,591
false
{"Kotlin": 79430321, "HTML": 331, "CSS": 102}
package me.localx.icons.straight.outline import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.PathFillType.Companion.NonZero import androidx.compose.ui.graphics.SolidColor import androidx.compose.ui.graphics.StrokeCap.Companion.Butt import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.graphics.vector.ImageVector.Builder import androidx.compose.ui.graphics.vector.path import androidx.compose.ui.unit.dp import me.localx.icons.straight.Icons public val Icons.Outline.Cream: ImageVector get() { if (_cream != null) { return _cream!! } _cream = Builder(name = "Cream", 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(22.0f, 12.184f) lineTo(22.0f, 8.0f) lineTo(20.0f, 8.0f) curveTo(20.0f, 2.56f, 17.028f, 0.291f, 16.9f, 0.2f) lineTo(16.637f, 0.0f) lineTo(15.0f, 0.0f) lineTo(15.0f, 1.0f) arcToRelative(1.883f, 1.883f, 0.0f, false, true, -2.0f, 2.0f) lineTo(10.0f, 3.0f) arcTo(5.648f, 5.648f, 0.0f, false, false, 4.089f, 8.0f) lineTo(2.0f, 8.0f) verticalLineToRelative(4.184f) arcTo(3.0f, 3.0f, 0.0f, false, false, 0.0f, 15.0f) verticalLineToRelative(9.0f) lineTo(24.0f, 24.0f) lineTo(24.0f, 15.0f) arcTo(3.0f, 3.0f, 0.0f, false, false, 22.0f, 12.184f) close() moveTo(10.0f, 5.0f) horizontalLineToRelative(3.0f) arcToRelative(4.026f, 4.026f, 0.0f, false, false, 3.613f, -2.162f) arcTo(9.083f, 9.083f, 0.0f, false, true, 18.0f, 8.0f) lineTo(6.131f, 8.0f) arcTo(3.658f, 3.658f, 0.0f, false, true, 10.0f, 5.0f) close() moveTo(20.0f, 10.0f) verticalLineToRelative(2.0f) lineTo(4.0f, 12.0f) lineTo(4.0f, 10.0f) close() moveTo(22.0f, 22.0f) lineTo(2.0f, 22.0f) lineTo(2.0f, 15.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, -1.0f) lineTo(21.0f, 14.0f) arcToRelative(1.0f, 1.0f, 0.0f, false, true, 1.0f, 1.0f) close() } } .build() return _cream!! } private var _cream: ImageVector? = null
1
Kotlin
0
5
cbd8b510fca0e5e40e95498834f23ec73cc8f245
2,890
icons
MIT License
app/src/main/java/org/nekomanga/presentation/components/HeaderCard.kt
CarlosEsco
182,704,531
false
null
package org.nekomanga.presentation.components import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.Card import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.text.font.FontWeight import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import org.nekomanga.presentation.theme.Shapes import org.nekomanga.presentation.theme.Typefaces @Composable fun HeaderCard(text: String) { Card( shape = RoundedCornerShape(Shapes.coverRadius), modifier = Modifier .fillMaxWidth() .padding(8.dp), elevation = 8.dp, backgroundColor = MaterialTheme.colorScheme.secondary, ) { Text( text = text, fontSize = MaterialTheme.typography.titleMedium.fontSize, fontFamily = Typefaces.montserrat, fontWeight = FontWeight.Normal, textAlign = TextAlign.Center, color = MaterialTheme.colorScheme.onSecondary, modifier = Modifier.padding(all = 12.dp), ) } } @Preview @Composable private fun HeaderCardPreview() { HeaderCard(text = "My Test header") }
84
Kotlin
73
1,173
b5765ea27eb5826aa98f1cb6c9906802ac994c9a
1,457
Neko
Apache License 2.0
skyline/src/main/java/io/trubi/skyline/cross/dcfw/FloatWindow.kt
trubi-io
205,840,541
false
null
package io.trubi.skyline.cross.dcfw import android.graphics.Canvas import android.graphics.Typeface /** * author : <NAME> * created on : 17/12/2018 15:09 * description : */ abstract class FloatWindow { var x: Float = 0f var y: Float = 0f var digitalTypeface: Typeface? = null var width: Float = 0f var height: Float = 0f var leftPadding: Float = 0f var topPadding: Float = 0f var rightPadding: Float = 0f var bottomPadding: Float = 0f var leftMargin: Float = 0f var rightMargin: Float = 0f var topMargin: Float = 0f var bottomMargin: Float = 0f var alignment: FloatWindowAlign = FloatWindowAlign.Left abstract fun draw(canvas: Canvas?) fun setPadding(padding: Float){ leftPadding = padding topPadding = padding rightPadding = padding bottomPadding = padding } }
0
Kotlin
3
16
80adab7c3a9bb13c4aee378f7c0bfcc2131d3602
893
skyline
MIT License
app/src/main/java/io/eugenethedev/taigamobile/ui/screens/kanban/KanbanViewModel.kt
cypper
379,608,374
true
{"Kotlin": 317219}
package io.eugenethedev.taigamobile.ui.screens.kanban import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import io.eugenethedev.taigamobile.R import io.eugenethedev.taigamobile.Session import io.eugenethedev.taigamobile.TaigaApp import io.eugenethedev.taigamobile.domain.entities.CommonTaskExtended import io.eugenethedev.taigamobile.domain.entities.CommonTaskType import io.eugenethedev.taigamobile.domain.entities.Status import io.eugenethedev.taigamobile.domain.entities.User import io.eugenethedev.taigamobile.domain.repositories.ITasksRepository import io.eugenethedev.taigamobile.domain.repositories.IUsersRepository import io.eugenethedev.taigamobile.ui.commons.MutableLiveResult import io.eugenethedev.taigamobile.ui.commons.Result import io.eugenethedev.taigamobile.ui.commons.ResultStatus import io.eugenethedev.taigamobile.ui.commons.ScreensState import kotlinx.coroutines.launch import timber.log.Timber import javax.inject.Inject class KanbanViewModel : ViewModel() { @Inject lateinit var tasksRepository: ITasksRepository @Inject lateinit var usersRepository: IUsersRepository @Inject lateinit var screensState: ScreensState @Inject lateinit var session: Session val projectName: String get() = session.currentProjectName val statuses = MutableLiveResult<List<Status>>() val team = MutableLiveResult<List<User>>() val stories = MutableLiveResult<List<CommonTaskExtended>>() init { TaigaApp.appComponent.inject(this) } fun start() { if (screensState.shouldReloadKanbanScreen) { reset() } if (team.value == null || stories.value == null) { loadTeam() loadStories() loadStatuses() } } private fun loadStatuses() = viewModelScope.launch { statuses.value = Result(ResultStatus.Loading) statuses.value = try { Result(ResultStatus.Success, tasksRepository.getStatuses(CommonTaskType.UserStory)) } catch (e: Exception) { Timber.w(e) Result(ResultStatus.Error, message = R.string.common_error_message) } } private fun loadTeam() = viewModelScope.launch { team.value = Result(ResultStatus.Loading) team.value = try { Result(ResultStatus.Success, usersRepository.getTeam().map { it.toUser() }) } catch (e: Exception) { Timber.w(e) Result(ResultStatus.Error, message = R.string.common_error_message) } } private fun loadStories() = viewModelScope.launch { stories.value = Result(ResultStatus.Loading) stories.value = try { Result(ResultStatus.Success, tasksRepository.getAllUserStories()) } catch (e: Exception) { Timber.w(e) Result(ResultStatus.Error, message = R.string.common_error_message) } } fun reset() { statuses.value = null team.value = null stories.value = null } }
0
null
0
0
9a54bc3a92239a67e0c3665bb2d24868374184cf
3,016
TaigaMobile
Apache License 2.0
src/main/kotlin/com/turbomates/kotlin/lsports/sdk/api/request/Request.kt
turbomates
447,160,415
false
{"Kotlin": 82756}
package com.turbomates.kotlin.lsports.sdk.api.request import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable open class Request { @SerialName("UserName") lateinit var username: String @SerialName("Password") lateinit var password: String @SerialName("PackageId") lateinit var packageId: String }
1
Kotlin
0
2
8e7287ae18c82a47aae3767ad793f0bc3161c500
366
lsports-sdk-kotlin
MIT License
questDomain/src/main/java/ru/nekit/android/qls/domain/model/resources/ChildrenToysVisualResourceCollection.kt
ru-nekit-android
126,668,350
false
null
package ru.nekit.android.qls.domain.model.resources import ru.nekit.android.qls.domain.model.resources.ResourceGroupCollection.* import ru.nekit.android.qls.domain.model.resources.common.IVisualResourceWithGroupHolder enum class ChildrenToysVisualResourceCollection(vararg groups: ResourceGroupCollection) : IVisualResourceWithGroupHolder { CAR(BOY, CHILDREN_TOY), DOLL_BOOTS(GIRL, CHILDREN_TOY), DOLL_SKIRT(GIRL, CHILDREN_TOY), DOLL_BLOUSE(GIRL, CHILDREN_TOY); override val groups: List<ResourceGroupCollection> = groups.toList() override val id: Int get() = ordinal //override val collection: List<ChildrenToysVisualResourceCollection> = values().toList() companion object { fun getById(id: Int): SimpleVisualResourceCollection { return SimpleVisualResourceCollection.values()[id] } } }
0
Kotlin
0
1
37a2037be2ecdbe19607b5fbb9e5f7852320a5a0
879
QuestLockScreen
Apache License 2.0
tools/common-kt-utils/src/main/java/com/zaiming/android/common_kt_utils/utils/ReleasableVar.kt
qiuzaiming
456,448,337
false
{"Kotlin": 285018}
package com.zaiming.android.common_kt_utils.utils import kotlin.properties.ReadWriteProperty import kotlin.reflect.KProperty import kotlin.reflect.KProperty0 import kotlin.reflect.jvm.isAccessible /** * adapter var not null, null when is release */ fun <T : Any> releasableNotNull() = ReleasableNotNull<T>() class ReleasableNotNull<T : Any> : ReadWriteProperty<Any, T> { private var value: T? = null override fun getValue(thisRef: Any, property: KProperty<*>): T { return value ?: error("ReleasableNotNull value is null or already released") } override fun setValue(thisRef: Any, property: KProperty<*>, value: T) { this.value = value } fun release() { value = null } val isInitialized: Boolean get() = value != null } fun KProperty0<*>.release() { isAccessible = true (getDelegate() as? ReleasableNotNull<*>)?.release() ?: error("ReleasableNotNull value is null") } val KProperty0<*>.isInitialized: Boolean get() { isAccessible = true return (getDelegate() as? ReleasableNotNull<*>)?.isInitialized ?: error("Delegate is not ReleasableNotNull instance or is null") }
1
Kotlin
0
1
09b2a8512e46c24926515bfd9011db1bd8b09453
1,126
gallery
Apache License 2.0
apps/android/src/main/kotlin/dev/eduayuso/cgkotlin/components/ui/CGListRecyclerAdapter.kt
eduayuso
353,986,267
false
null
package dev.eduayuso.cgkotlin.components.ui import androidx.recyclerview.widget.RecyclerView import dev.eduayuso.cgkotlin.shared.domain.entities.IEntity abstract class CGListRecyclerAdapter<EntityType: IEntity, VH: CGViewHolder>: RecyclerView.Adapter<VH>() { private var dataList: MutableList<EntityType> = mutableListOf() val items: List<EntityType> get() = dataList override fun onBindViewHolder(viewHolder: VH, i: Int) { viewHolder.onBind(i) } override fun getItemCount(): Int { return dataList.size } fun addItems(data: List<EntityType>) { dataList.clear() dataList.addAll(data) notifyDataSetChanged() } }
0
Kotlin
0
0
4e1b5272088b77353a87073255dddbb6487318f7
694
compose-computational-geometry
Apache License 2.0
app/src/main/java/ca/josuelubaki/mealzapp/ui/meals/MealsCategoriesScreen.kt
josue-lubaki
584,532,496
false
null
package ca.josuelubaki.mealzapp.ui.meals import androidx.compose.animation.animateContentSize import androidx.compose.foundation.Image import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.KeyboardArrowDown import androidx.compose.material.icons.filled.KeyboardArrowUp import androidx.compose.runtime.* import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.lifecycle.viewmodel.compose.viewModel import ca.josuelubaki.mealzapp.ui.theme.MealzAppTheme import ca.josuelubaki.model.response.MealResponse import coil.compose.rememberAsyncImagePainter @Composable fun MealsCategoriesScreen(navigationCallback : (String) -> Unit) { val viewModel : MealCategoriesViewModel = viewModel() val meals = viewModel.mealsState.value LazyColumn( contentPadding = PaddingValues(16.dp), ) { items(meals) { meal -> MealCategory(meal, navigationCallback) } } } @Composable fun MealCategory(meal : MealResponse, navigationCallback : (String) -> Unit) { var isExpanded by remember { mutableStateOf(false) } Card( shape = RoundedCornerShape(8.dp), elevation = 2.dp, modifier = Modifier .fillMaxWidth() .padding(top = 16.dp) .clickable { navigationCallback(meal.id) } ) { Row( modifier = Modifier.animateContentSize() ) { Image( painter = rememberAsyncImagePainter(meal.imageUrl), contentDescription = "Meal Picture", modifier = Modifier .size(88.dp) .padding(4.dp) .align(Alignment.CenterVertically), contentScale = ContentScale.Inside, ) Column( modifier = Modifier .align(Alignment.CenterVertically) .fillMaxWidth(0.8f) .padding(16.dp) ) { Text( text = meal.name, style = MaterialTheme.typography.h6 ) CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.medium) { Text( text = meal.description, textAlign = TextAlign.Start, style = MaterialTheme.typography.subtitle2, overflow = TextOverflow.Ellipsis, maxLines = if(isExpanded) 10 else 4 ) } } Icon( imageVector = if(isExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown, contentDescription = "Expand row icon", modifier = Modifier .padding(16.dp) .align(if(isExpanded) Alignment.Bottom else Alignment.CenterVertically) .clickable { isExpanded = !isExpanded } ) } } } @Preview(showBackground = true) @Composable fun DefaultPreview() { MealzAppTheme { MealsCategoriesScreen {} } }
0
Kotlin
0
2
983240f24f5adbe142fbaa40be934bcb14c73362
3,680
Mealz
MIT License
app/src/main/kotlin/gradle/kotlin/latest/payments/application/Pay.kt
code-sherpas-academy
563,007,234
false
{"Kotlin": 4032}
package gradle.kotlin.latest.payments.application class Pay { }
0
Kotlin
0
0
7c12f0053c75abbfc87c5f899245e54aede95313
64
code-retreat-22-kotlin-starter-codesherpasrocks
MIT License
src/main/kotlin/org/kotrix/utils/Stringify.kt
JarnaChao09
285,169,397
false
null
package org.kotrix.utils interface Stringify { fun stringify(): String }
0
Kotlin
1
5
7d05b5b3a36208d0026c016cb24d6360479e754e
78
Kotrix
MIT License
app/src/main/java/by/bsuir/luckymushroom/app/ui/fragments/RecognitionResultFragment.kt
AlexX333BY
176,341,456
false
null
package by.bsuir.luckymushroom.app.ui.fragments import android.net.Uri import android.os.Bundle import android.support.v4.app.Fragment import android.util.Base64 import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import by.bsuir.luckymushroom.R import by.bsuir.luckymushroom.app.App import by.bsuir.luckymushroom.app.dto.recognitionRequests.EdibleStatus import by.bsuir.luckymushroom.app.dto.recognitionRequests.RecognitionRequest import by.bsuir.luckymushroom.app.dto.recognitionRequests.RecognitionStatus import by.bsuir.luckymushroom.app.dto.recognitionRequests.RequestPhoto import by.bsuir.luckymushroom.app.ui.activities.MainActivity import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.io.File import java.util.* class RecognitionResultFragment : Fragment() { val REQ_RESULTS = mapOf( "edible" to "съедобный", "non-edible" to "несъедобный", "partial-edible" to "условно-съедобный", "not-a-mushroom" to "не гриб", "not-recognized" to "не распознан" ) override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate( R.layout.fragment_recognition_result, container, false ).apply { val photoUri: Uri? = arguments?.getParcelable( MainActivity.EXTRA_IMAGE) val recognitionResultText: String = arguments!!.getString( MainActivity.EXTRA_TEXT) val imageView = findViewById<ImageView>(R.id.imageView).apply { setImageBitmap(null) setImageURI( photoUri ) } findViewById<TextView>(R.id.textView).text = REQ_RESULTS[recognitionResultText] val edibleStatus: EdibleStatus? = if (recognitionResultText == "not-recognized") null else EdibleStatus( recognitionResultText ) val recognitionStatus: RecognitionStatus = if (recognitionResultText != "not-recognized") RecognitionStatus( "recognized" ) else RecognitionStatus(recognitionResultText) App.cookie?.let { cookie -> photoUri?.let { photoUri -> File(photoUri.path).also { val base64Image = Base64.encodeToString( it.readBytes(), Base64.DEFAULT ) App.addRecognitionRequestService.addRecognitionRequest( RecognitionRequest( null, Date(System.currentTimeMillis()), edibleStatus, recognitionStatus, RequestPhoto("jpg", base64Image) ), cookie ) .enqueue(object : Callback<RecognitionRequest> { override fun onFailure( call: Call<RecognitionRequest>, t: Throwable ) { t.message } override fun onResponse( call: Call<RecognitionRequest>, response: Response<RecognitionRequest> ) { response.body() } }) } } } } } }
3
Kotlin
1
1
a3e4e53b9251ab23c61ad5a7f5a4a40a7c91eef8
3,917
lucky-mushroom-android
MIT License
jetpack/src/main/java/org/zhiwei/jetpack/components/room/StudentRepo.kt
iOrchid
156,658,695
false
{"Kotlin": 1005931, "Java": 2777}
package org.zhiwei.jetpack.components.room import kotlinx.coroutines.flow.Flow import org.zhiwei.jetpack.components.paging.TeacherPagingSource /** * 定义数据层的管理类,上接viewModel,下承数据库或网络 */ class StudentRepo( private val studentDao: StudentDao, // private val networkSource:NetworkSource,//这里就是模拟说有个网络加载数据的方式,在MVVM或MVI等设计架构中, // 上层UI的数据源是统一收口管理的。网络数据先落地数据库,通过liveData/flow来让UI感知更新 ) { fun loadAllStudents(): Flow<List<Student>> { return studentDao.queryAllStudents() } /** * 创建一些模拟的数据 */ fun mockStudents(dao: StudentDao) { repeat(100) { val student = Student( name = "🧑‍🎓学生 $it", age = 10 + (it % 30), sex = it % 2, height = 80 + it, school = "实验中学 $it 班级", address = "人民路 $it 号" ) dao.insertStudent(student = student) } } } class TeacherRepo { fun loadPagingTeachers() = TeacherPagingSource() }
0
Kotlin
111
627
2c24cb98da0b1731279fd9c1473c1aa229198fa7
1,001
android-jetpack-demo
Apache License 2.0
samples/urlshortener/src/main/kotlin/app/cash/tempest/urlshortener/RealUrlShortener.kt
cashapp
270,829,467
false
{"Kotlin": 487620, "Shell": 2116, "Java": 2108}
/* * Copyright 2021 Square 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 app.cash.tempest.urlshortener import com.amazonaws.services.dynamodbv2.datamodeling.DynamoDBSaveExpression import com.amazonaws.services.dynamodbv2.model.ConditionalCheckFailedException import com.amazonaws.services.dynamodbv2.model.ExpectedAttributeValue class RealUrlShortener( private val table: AliasTable ) : UrlShortener { override fun shorten(shortUrl: String, destinationUrl: String): Boolean { val item = Alias(shortUrl, destinationUrl) val ifNotExist = DynamoDBSaveExpression() .withExpectedEntry( "short_url", ExpectedAttributeValue() .withExists(false) ) return try { table.aliases.save(item, ifNotExist) true } catch (e: ConditionalCheckFailedException) { println("Failed to shorten $shortUrl because it already exists!") false } } override fun redirect(shortUrl: String): String? { val key = Alias.Key(shortUrl) return table.aliases.load(key)?.destination_url } }
17
Kotlin
33
83
8430cf3ad4be5f1e6786dd927bcc494fe0ea7baf
1,582
tempest
Apache License 2.0
app/src/main/java/com/example/loginsesame/factories/CreateViewModelFactory.kt
sw21-tug
350,454,499
false
{"Kotlin": 112493}
package com.example.loginsesame.factories import androidx.lifecycle.ViewModel import androidx.lifecycle.ViewModelProvider import com.example.loginsesame.CreateViewModel import com.example.loginsesame.data.UserRepository class CreateViewModelFactory(val userRepository: UserRepository) : ViewModelProvider.NewInstanceFactory() { override fun <T : ViewModel?> create(modelClass: Class<T>): T { return CreateViewModel(userRepository) as T } }
19
Kotlin
5
1
684325336e50fad9482073faf56596f70732739f
462
Team_17
MIT License
mock-server-junit4/src/main/kotlin/io/github/infeez/kotlinmockserver/junit4/rule/MockServerRule.kt
infeez
176,031,247
false
null
package io.github.infeez.kotlinmockserver.junit4.rule import io.github.infeez.kotlinmockserver.server.Server import org.junit.rules.ExternalResource class MockServerRule internal constructor( private val server: Server ) : ExternalResource() { override fun before() { server.start() } override fun after() { server.stop() } }
0
Kotlin
0
7
770c99e25310e91763e586080d33fa1e4d363713
366
kotlin-mock-server
Apache License 2.0
app/shared/database/public/src/commonMain/kotlin/build/wallet/database/adapters/PublicKeyColumnAdapter.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.database.adapters import app.cash.sqldelight.ColumnAdapter import build.wallet.crypto.KeyPurpose import build.wallet.crypto.PublicKey class PublicKeyColumnAdapter<T : KeyPurpose> : ColumnAdapter<PublicKey<T>, String> { override fun decode(databaseValue: String) = PublicKey<T>(databaseValue) override fun encode(value: PublicKey<T>) = value.value }
0
C
10
98
1f9f2298919dac77e6791aa3f1dbfd67efe7f83c
377
bitkey
MIT License
domene/src/main/kotlin/no/nav/tiltakspenger/saksbehandling/domene/saksopplysning/Kilde.kt
navikt
487,246,438
false
{"Kotlin": 876281, "Shell": 1309, "Dockerfile": 495, "HTML": 45}
package no.nav.tiltakspenger.saksbehandling.domene.saksopplysning enum class Kilde(val navn: String) { ARENA("Arena"), PDL("Pdl"), EF("EF"), FPSAK("FPSAK"), K9SAK("K9SAK"), PESYS("pesys"), SØKNAD("Søknad"), SAKSB("Saksbehandler"), }
8
Kotlin
0
1
e125e2953c16c4bb2c99e6d36075c553b51ed794
266
tiltakspenger-vedtak
MIT License
object-adapter-kotlin/src/test/java/de/pfaffenrodt/adapter/NoPresenterTest.kt
mi-sch-ka
301,521,310
true
{"Kotlin": 44214, "Java": 38747}
package de.pfaffenrodt.adapter import android.view.View import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.nhaarman.mockito_kotlin.mock import org.junit.jupiter.api.Assertions.* import org.spekframework.spek2.Spek import org.spekframework.spek2.style.gherkin.Feature object NoPresenterTest : Spek({ Feature("NoPresenter") { val noPresenter = NoPresenter() var viewHolder : RecyclerView.ViewHolder? = null Scenario("Default") { Given("A NoPresenter") { noPresenter } Then("should return id of no_presenter_layout") { assertEquals(R.layout.no_presenter_layout, noPresenter.layoutId) } When("create a ViewHolder") { val mockedView: View = mock() val mockedContainer: ViewGroup = mock() viewHolder = noPresenter.onCreateViewHolder(mockedView, mockedContainer) } Then(" it should have reference to NoPresenter") { assertTrue(viewHolder is PresenterProvider) val presenterProvider : PresenterProvider = viewHolder as PresenterProvider assertEquals(noPresenter, presenterProvider.presenter) } } } })
0
null
0
0
b9aa1abee7f21f48c736237073b32943a26cc9fc
1,300
android-object-adapter
Apache License 2.0
src/main/kotlin/com/alwa/testhub/repository/VolumeBasedReportRepository.kt
alexwatts
450,846,737
false
{"Kotlin": 50215, "Dockerfile": 152, "Shell": 104}
package com.alwa.testhub.repository import com.alwa.testhub.domain.ReportData import org.springframework.beans.factory.annotation.Value import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty import org.springframework.stereotype.Repository import java.io.File import java.nio.file.Files import java.nio.file.Path import java.time.Instant import java.util.stream.Collectors import kotlin.text.Charsets.UTF_8 @Repository @ConditionalOnProperty("storage.volume", havingValue="true") class VolumeBasedReportRepository: ReportRepository { @Value("\${storage.rootPath}") lateinit var rootPath: String override fun create(reportData: ReportData) { writeReportToPath(reportData.report, createReportFilePath(reportData)) } override fun getBefore(before: Instant) = getReportsFiltered { it.time.isBefore(before) } override fun getAfter(after: Instant) = getReportsFiltered { it.time.isAfter(after) } override fun delete(group: String) = Files.walk(Path.of("$rootPath/$group")) .sorted(Comparator.reverseOrder()) .map(Path::toFile) .forEach(File::delete) private fun createReportFilePath(reportData: ReportData) = Path.of( getReportDirectory(reportData), reportData.time.toString() ) private fun getReportDirectory(reportData: ReportData) = createReportDirectory(reportDirectory(reportData)).toAbsolutePath().toString() private fun reportDirectory(reportData: ReportData) = "$rootPath/${reportData.group}" private fun getReportsFiltered(filter: (ReportData) -> (Boolean)) = Files.walk(Path.of(rootPath)) .filter { !Files.isDirectory(it) } .map { it.toFile().toReport() } .filter { filter(it) } .collect(Collectors.toList()) .groupBy { it.group } private fun createReportDirectory(directory: String) = Files.createDirectories(Path.of(directory)) private fun writeReportToPath(report: String, reportDirectoryPath: Path) { Files.write( reportDirectoryPath, report.toByteArray() ) } private fun File.toReport() = ReportData( Instant.parse(this.name), this.readText(UTF_8), this.parent.substringAfterLast(File.separatorChar) ) }
0
Kotlin
0
0
18a61149525ecadef8f1c773a1318cf5cfb0e8d5
2,395
TestHub
MIT License
idea/tests/testData/refactoring/inline/namedFunction/methodReference.kt
JetBrains
278,369,660
false
null
class Wrapper(val f: () -> String) class Test { fun f(): String = "Hello" val reference = ::f val foo = Wrapper(referen<caret>ce) }
0
Kotlin
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
144
intellij-kotlin
Apache License 2.0
templates/release-0.26/src/main/java/com/badoo/ribs/template/node_dagger/foo_bar/mapper/StateToViewModel.kt
d1m0nh
217,258,646
true
{"Kotlin": 1703850}
package com.badoo.ribs.template.node_dagger.foo_bar.mapper import com.badoo.ribs.template.node_dagger.foo_bar.FooBarView.ViewModel import com.badoo.ribs.template.node_dagger.foo_bar.feature.FooBarFeature.State internal object StateToViewModel : (State) -> ViewModel { override fun invoke(state: State): ViewModel = ViewModel() }
0
Kotlin
0
0
fb4331298bfcebcb7ddd8a8e5066f838c62118b9
344
RIBs
Apache License 2.0