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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
hazelnet-community/src/main/kotlin/io/hazelnet/community/controllers/DiscordServerController.kt | nilscodes | 446,203,879 | false | {"TypeScript": 1045486, "Kotlin": 810416, "Dockerfile": 4476, "Shell": 1830, "JavaScript": 1384} | package io.hazelnet.community.controllers
import io.hazelnet.community.data.EmbeddableSetting
import io.hazelnet.community.data.claim.PhysicalOrder
import io.hazelnet.community.data.discord.DiscordMember
import io.hazelnet.community.data.discord.DiscordMemberPartial
import io.hazelnet.community.data.discord.DiscordServer
import io.hazelnet.community.data.discord.DiscordServerPartial
import io.hazelnet.community.data.premium.IncomingDiscordPayment
import io.hazelnet.community.data.premium.IncomingDiscordPaymentRequest
import io.hazelnet.community.services.BillingService
import io.hazelnet.community.services.DiscordServerRetriever
import io.hazelnet.community.services.DiscordServerService
import io.hazelnet.community.services.IncomingPaymentService
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.*
import org.springframework.web.servlet.support.ServletUriComponentsBuilder
import javax.validation.Valid
@RestController
@RequestMapping("/discord/servers")
class DiscordServerController(
private val discordServerService: DiscordServerService,
private val discordServerRetriever: DiscordServerRetriever,
private val billingService: BillingService,
private val incomingPaymentService: IncomingPaymentService,
) {
@PostMapping("")
@ResponseStatus(HttpStatus.CREATED)
fun addDiscordServer(@RequestBody @Valid discordServer: DiscordServer): ResponseEntity<DiscordServer> {
val newDiscordServer = discordServerService.addDiscordServer(discordServer)
return ResponseEntity
.created(ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{guildId}")
.buildAndExpand(newDiscordServer.guildId)
.toUri())
.body(newDiscordServer)
}
@GetMapping("")
@ResponseStatus(HttpStatus.OK)
fun listDiscordServers() = discordServerRetriever.getDiscordServers()
@GetMapping(value = ["/{guildId}"], params = ["!byId"])
@ResponseStatus(HttpStatus.OK)
fun getDiscordServer(@PathVariable guildId: Long) = discordServerRetriever.getDiscordServer(guildId)
@GetMapping(value = ["/{serverId}"], params = ["byId"])
@ResponseStatus(HttpStatus.OK)
fun getDiscordServerByInternalId(@PathVariable serverId: Int) = discordServerRetriever.getDiscordServerByInternalId(serverId)
@PatchMapping("/{guildId}")
@ResponseStatus(HttpStatus.OK)
fun updateDiscordServer(@PathVariable guildId: Long, @RequestBody @Valid discordServerPartial: DiscordServerPartial) = discordServerService.updateDiscordServer(guildId, discordServerPartial)
@PostMapping("/{guildId}/members")
@ResponseStatus(HttpStatus.CREATED)
fun connectExternalAccount(@PathVariable guildId: Long, @RequestBody @Valid discordMember: DiscordMember) = discordServerService.addMember(guildId, discordMember)
@GetMapping("/{guildId}/members/{externalAccountId}")
@ResponseStatus(HttpStatus.OK)
fun getExternalAccountOnDiscord(@PathVariable guildId: Long, @PathVariable externalAccountId: Long) = discordServerService.getMember(guildId, externalAccountId)
@PatchMapping("/{guildId}/members/{externalAccountId}")
@ResponseStatus(HttpStatus.OK)
fun updateExternalAccountOnDiscord(@PathVariable guildId: Long, @PathVariable externalAccountId: Long, @RequestBody @Valid discordMemberPartial: DiscordMemberPartial) = discordServerService.updateMember(guildId, externalAccountId, discordMemberPartial)
@DeleteMapping("/{guildId}/members/{externalAccountId}")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun disconnectExternalAccount(
@PathVariable guildId: Long,
@PathVariable externalAccountId: Long,
@RequestParam(required = false, defaultValue = "false") skipRoleUpdates: Boolean,
) = discordServerService.removeMember(guildId, externalAccountId, skipRoleUpdates)
@PutMapping("/{guildId}/settings/{settingName}")
@ResponseStatus(HttpStatus.OK)
fun updateSetting(@PathVariable guildId: Long, @PathVariable settingName: String, @RequestBody @Valid embeddableSetting: EmbeddableSetting): EmbeddableSetting {
if (embeddableSetting.name != settingName) {
throw IllegalArgumentException("Discord server setting name in path $settingName did not match setting in request body ${embeddableSetting.name}.")
}
return discordServerService.updateSettings(guildId, embeddableSetting)
}
@DeleteMapping("/{guildId}/settings/{settingName}")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun deleteSetting(@PathVariable guildId: Long, @PathVariable settingName: String) = discordServerService.deleteSettings(guildId, settingName)
@GetMapping("/{guildId}/members")
@ResponseStatus(HttpStatus.OK)
fun getExternalAccounts(@PathVariable guildId: Long) = discordServerService.getMembers(guildId)
@GetMapping("/{guildId}/roleassignments/quizroles")
@ResponseStatus(HttpStatus.OK)
fun getCurrentQuizRoleAssignments(@PathVariable guildId: Long) = discordServerService.getAllCurrentQuizRoleAssignmentsForGuild(guildId)
@PostMapping("/{guildId}/accesstoken")
@ResponseStatus(HttpStatus.OK)
fun regenerateAccessToken(@PathVariable guildId: Long) = discordServerService.regenerateAccessToken(guildId)
@DeleteMapping("/{guildId}/accesstoken")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun deleteAccessToken(@PathVariable guildId: Long) = discordServerService.deleteAccessToken(guildId)
@GetMapping("/{guildId}/premium")
@ResponseStatus(HttpStatus.OK)
fun getPremiumInfo(@PathVariable guildId: Long) = billingService.getPremiumInfo(guildId)
@GetMapping("/{guildId}/payment")
@ResponseStatus(HttpStatus.OK)
fun getCurrentPayment(@PathVariable guildId: Long) = incomingPaymentService.getCurrentPayment(guildId)
@PostMapping("/{guildId}/payment")
@ResponseStatus(HttpStatus.CREATED)
fun requestIncomingPayment(@PathVariable guildId: Long, @RequestBody @Valid incomingDiscordPaymentRequest: IncomingDiscordPaymentRequest): ResponseEntity<IncomingDiscordPayment> {
val newIncomingDiscordPayment = incomingPaymentService.requestIncomingPayment(guildId, incomingDiscordPaymentRequest)
return ResponseEntity
.created(ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{incomingDiscordPaymentId}")
.buildAndExpand(newIncomingDiscordPayment.id)
.toUri())
.body(newIncomingDiscordPayment)
}
@DeleteMapping("/{guildId}/payment")
@ResponseStatus(HttpStatus.NO_CONTENT)
fun cancelIncomingPayment(@PathVariable guildId: Long) = incomingPaymentService.cancelIncomingPayment(guildId)
} | 0 | TypeScript | 4 | 13 | 79f8b096f599255acb03cc809464d0570a51d82c | 6,800 | hazelnet | Apache License 2.0 |
compiler/fir/resolve/src/org/jetbrains/kotlin/fir/resolve/providers/impl/FirProviderImpl.kt | android | 263,405,600 | false | null | /*
* Copyright 2010-2018 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.fir.resolve.impl
import org.jetbrains.annotations.TestOnly
import org.jetbrains.kotlin.fir.FirElement
import org.jetbrains.kotlin.fir.FirSession
import org.jetbrains.kotlin.fir.declarations.*
import org.jetbrains.kotlin.fir.resolve.FirProvider
import org.jetbrains.kotlin.fir.resolve.ScopeSession
import org.jetbrains.kotlin.fir.scopes.FirScope
import org.jetbrains.kotlin.fir.scopes.impl.FirClassDeclaredMemberScope
import org.jetbrains.kotlin.fir.symbols.CallableId
import org.jetbrains.kotlin.fir.symbols.ConeClassLikeLookupTag
import org.jetbrains.kotlin.fir.symbols.impl.*
import org.jetbrains.kotlin.fir.types.ConeLookupTagBasedType
import org.jetbrains.kotlin.fir.types.FirResolvedTypeRef
import org.jetbrains.kotlin.fir.visitors.FirDefaultVisitorVoid
import org.jetbrains.kotlin.name.ClassId
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
class FirProviderImpl(val session: FirSession) : FirProvider() {
override fun getFirCallableContainerFile(symbol: FirCallableSymbol<*>): FirFile? {
symbol.overriddenSymbol?.let {
return getFirCallableContainerFile(it)
}
return state.callableContainerMap[symbol]
}
override fun getClassLikeSymbolByFqName(classId: ClassId): FirClassLikeSymbol<*>? {
return getFirClassifierByFqName(classId)?.symbol
}
override fun getTopLevelCallableSymbols(packageFqName: FqName, name: Name): List<FirCallableSymbol<*>> {
return (state.callableMap[CallableId(packageFqName, null, name)] ?: emptyList())
}
override fun getClassDeclaredMemberScope(classId: ClassId) =
(getFirClassifierByFqName(classId) as? FirRegularClass)?.let(::FirClassDeclaredMemberScope)
override fun getFirClassifierContainerFile(fqName: ClassId): FirFile {
return state.classifierContainerFileMap[fqName] ?: error("Couldn't find container for $fqName")
}
override fun getFirClassifierContainerFileIfAny(fqName: ClassId): FirFile? {
return state.classifierContainerFileMap[fqName]
}
override fun getClassNamesInPackage(fqName: FqName): Set<Name> {
return state.classesInPackage[fqName] ?: emptySet()
}
fun recordFile(file: FirFile) {
recordFile(file, state)
}
private fun recordFile(file: FirFile, state: State) {
val packageName = file.packageFqName
state.fileMap.merge(packageName, listOf(file)) { a, b -> a + b }
file.acceptChildren(object : FirDefaultVisitorVoid() {
override fun visitElement(element: FirElement) {}
override fun visitRegularClass(regularClass: FirRegularClass) {
val classId = regularClass.symbol.classId
state.classifierMap[classId] = regularClass
state.classifierContainerFileMap[classId] = file
if (!classId.isNestedClass && !classId.isLocal) {
state.classesInPackage.getOrPut(classId.packageFqName, ::mutableSetOf).add(classId.shortClassName)
}
regularClass.acceptChildren(this)
}
override fun visitTypeAlias(typeAlias: FirTypeAlias) {
val classId = typeAlias.symbol.classId
state.classifierMap[classId] = typeAlias
state.classifierContainerFileMap[classId] = file
}
override fun <F : FirCallableDeclaration<F>> visitCallableDeclaration(callableDeclaration: FirCallableDeclaration<F>) {
val symbol = callableDeclaration.symbol
val callableId = symbol.callableId
state.callableMap.merge(callableId, listOf(symbol)) { a, b -> a + b }
state.callableContainerMap[symbol] = file
}
override fun visitConstructor(constructor: FirConstructor) {
visitCallableDeclaration(constructor)
}
override fun visitSimpleFunction(simpleFunction: FirSimpleFunction) {
visitCallableDeclaration(simpleFunction)
}
override fun visitProperty(property: FirProperty) {
visitCallableDeclaration(property)
}
})
}
private val state = State()
private class State {
val fileMap = mutableMapOf<FqName, List<FirFile>>()
val classifierMap = mutableMapOf<ClassId, FirClassLikeDeclaration<*>>()
val classifierContainerFileMap = mutableMapOf<ClassId, FirFile>()
val classesInPackage = mutableMapOf<FqName, MutableSet<Name>>()
val callableMap = mutableMapOf<CallableId, List<FirCallableSymbol<*>>>()
val callableContainerMap = mutableMapOf<FirCallableSymbol<*>, FirFile>()
fun setFrom(other: State) {
fileMap.clear()
classifierMap.clear()
classifierContainerFileMap.clear()
callableMap.clear()
callableContainerMap.clear()
fileMap.putAll(other.fileMap)
classifierMap.putAll(other.classifierMap)
classifierContainerFileMap.putAll(other.classifierContainerFileMap)
callableMap.putAll(other.callableMap)
callableContainerMap.putAll(other.callableContainerMap)
classesInPackage.putAll(other.classesInPackage)
}
}
override fun getFirFilesByPackage(fqName: FqName): List<FirFile> {
return state.fileMap[fqName].orEmpty()
}
override fun getFirClassifierByFqName(classId: ClassId): FirClassLikeDeclaration<*>? {
require(!classId.isLocal) {
"Local $classId should never be used to find its corresponding classifier"
}
return state.classifierMap[classId]
}
@TestOnly
fun ensureConsistent(files: List<FirFile>) {
val newState = State()
files.forEach { recordFile(it, newState) }
val failures = mutableListOf<String>()
fun <K, V> checkMapDiff(
title: String,
a: Map<K, V>,
b: Map<K, V>,
equal: (old: V?, new: V?) -> Boolean = { old, new -> old === new }
) {
var hasTitle = false
val unionKeys = a.keys + b.keys
for ((key, aValue, bValue) in unionKeys.map { Triple(it, a[it], b[it]) }) {
if (!equal(aValue, bValue)) {
if (!hasTitle) {
failures += title
hasTitle = true
}
failures += "diff at key = '$key': was: '$aValue', become: '$bValue'"
}
}
}
fun <K, V> checkMMapDiff(title: String, a: Map<K, List<V>>, b: Map<K, List<V>>) {
var hasTitle = false
val unionKeys = a.keys + b.keys
for ((key, aValue, bValue) in unionKeys.map { Triple(it, a[it], b[it]) }) {
if (aValue == null || bValue == null) {
if (!hasTitle) {
failures += title
hasTitle = true
}
failures += "diff at key = '$key': was: $aValue, become: $bValue"
} else {
val aSet = aValue.toSet()
val bSet = bValue.toSet()
val aLost = aSet - bSet
val bNew = bSet - aSet
if (aLost.isNotEmpty() || bNew.isNotEmpty()) {
failures += "diff at key = '$key':"
failures += " Lost:"
aLost.forEach { failures += " $it" }
failures += " New:"
bNew.forEach { failures += " $it" }
}
}
}
}
checkMMapDiff("fileMap", state.fileMap, newState.fileMap)
checkMapDiff("classifierMap", state.classifierMap, newState.classifierMap)
checkMapDiff("classifierContainerFileMap", state.classifierContainerFileMap, newState.classifierContainerFileMap)
checkMMapDiff("callableMap", state.callableMap, newState.callableMap)
checkMapDiff("callableContainerMap", state.callableContainerMap, newState.callableContainerMap)
if (!rebuildIndex) {
assert(failures.isEmpty()) {
failures.joinToString(separator = "\n")
}
} else {
state.setFrom(newState)
}
}
override fun getClassUseSiteMemberScope(
classId: ClassId,
useSiteSession: FirSession,
scopeSession: ScopeSession
): FirScope? {
return when (val symbol = this.getClassLikeSymbolByFqName(classId) ?: return null) {
is FirRegularClassSymbol -> buildDefaultUseSiteMemberScope(symbol.fir, useSiteSession, scopeSession)
is FirAnonymousObjectSymbol -> buildDefaultUseSiteMemberScope(symbol.fir, useSiteSession, scopeSession)
is FirTypeAliasSymbol -> {
val expandedTypeRef = symbol.fir.expandedTypeRef as FirResolvedTypeRef
val expandedType = expandedTypeRef.type as? ConeLookupTagBasedType ?: return null
val lookupTag = expandedType.lookupTag as? ConeClassLikeLookupTag ?: return null
getClassUseSiteMemberScope(lookupTag.classId, useSiteSession, scopeSession)
}
else -> throw IllegalArgumentException("Unexpected FIR symbol in getClassUseSiteMemberScope: $symbol")
}
}
}
private const val rebuildIndex = true
| 1 | null | 37 | 316 | 74126637a097f5e6b099a7b7a4263468ecfda144 | 9,714 | kotlin | Apache License 2.0 |
app/src/test/java/com/whisker/world/data/BreedRepositoryTest.kt | juyuky | 866,404,196 | false | {"Kotlin": 67848} | package com.whisker.world.data
import com.whisker.world.data.local.BreedDao
import com.whisker.world.data.local.entity.BreedEntity
import com.whisker.world.data.remote.BreedApi
import com.whisker.world.data.remote.dto.BreedDto
import com.whisker.world.data.repository.BreedRepositoryImpl
import com.whisker.world.domain.model.Breed
import com.whisker.world.domain.repository.BreedRepository
import kotlinx.coroutines.test.runTest
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.Mock
import org.mockito.junit.MockitoJUnitRunner
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import retrofit2.Call
import retrofit2.Response
import java.io.IOException
@RunWith(MockitoJUnitRunner::class)
class BreedRepositoryTest {
@Mock
private lateinit var breedApi: BreedApi
@Mock
private lateinit var breedDao: BreedDao
@Mock
private lateinit var breedRepository: BreedRepository
@Before
fun setUp() {
breedRepository = BreedRepositoryImpl(breedApi, breedDao)
}
@Test
fun getAllBreeds_available_in_local_storage_success() {
runTest {
val breedEntities = listOf(getFakeBreedEntity())
val breeds = breedEntities.map { it.toBreed() }
whenever(breedDao.getAll()).thenReturn(breedEntities)
val result = breedRepository.getAllBreeds()
assertTrue(result.isSuccess)
assertEquals(breeds, result.getOrNull())
}
}
@Test
fun getAllBreeds_remote_success() {
runTest {
val breedsDto = listOf(getFakeBreedDto())
val response = Response.success(breedsDto)
val breeds = breedsDto.map { it.toBreed() }
val mockCall: Call<List<BreedDto>> = mock()
whenever(breedDao.getAll()).thenReturn(emptyList())
whenever(breedApi.getAll()).thenReturn(mockCall)
whenever(breedApi.getAll().execute()).thenReturn(response)
val result = breedRepository.getAllBreeds()
assertTrue(result.isSuccess)
assertEquals(breeds, result.getOrNull())
verify(breedDao).getAll()
}
}
@Test
fun getAllBreeds_remote_not_success() {
runTest {
val mockCall: Call<List<BreedDto>> = mock()
whenever(breedDao.getAll()).thenReturn(emptyList())
whenever(breedApi.getAll()).thenReturn(mockCall)
whenever(breedApi.getAll().execute()).thenThrow(IOException::class.java)
val result = breedRepository.getAllBreeds()
assertTrue(result.isFailure)
}
}
@Test
fun getBreedById_success() {
runTest {
val id = "id"
val breedEntity = getFakeBreedEntity()
val breed = breedEntity.toBreed()
whenever(breedDao.getById(id)).thenReturn(breedEntity)
val result = breedRepository.getBreedById(id)
assertTrue(result.isSuccess)
assertEquals(breed, result.getOrNull())
}
}
@Test
fun getBreedById_error() {
runTest {
val id = "otherId"
whenever(breedDao.getById(id)).thenReturn(null)
val result = breedRepository.getBreedById(id)
assertTrue(result.isFailure)
}
}
@Test
fun getBreedsByName_success() {
runTest {
val name = "name"
val breedEntities = listOf(getFakeBreedEntity())
val breeds = breedEntities.map { it.toBreed() }
whenever(breedDao.getByName(name)).thenReturn(breedEntities)
val result = breedRepository.getBreedsByName(name)
assertTrue(result.isSuccess)
assertEquals(breeds, result.getOrNull())
}
}
@Test
fun getBreedsByName_empty() {
runTest {
val name = "otherName"
whenever(breedDao.getByName(name)).thenReturn(emptyList())
val result = breedRepository.getBreedsByName(name)
assertTrue(result.isSuccess)
assertEquals(emptyList<Breed>(), result.getOrNull())
}
}
@Test
fun getFavouriteBreeds_success() {
runTest {
val isFavourites = true
val breedEntities = listOf(getFakeBreedEntity())
val breeds = breedEntities.map { it.toBreed() }
whenever(breedDao.getByFavourite(isFavourites)).thenReturn(breedEntities)
val result = breedRepository.getFavouriteBreeds()
assertTrue(result.isSuccess)
assertEquals(breeds, result.getOrNull())
}
}
@Test
fun getFavouriteBreed_error() {
runTest {
whenever(breedDao.getByFavourite(true)).thenReturn(emptyList())
val result = breedRepository.getFavouriteBreeds()
assertTrue(result.isFailure)
}
}
@Test
fun updateBreeds_success() {
runTest {
val breedEntities = listOf(getFakeBreedEntity())
val breeds = breedEntities.map { it.toBreed() }
whenever(breedDao.getAll()).thenReturn(breedEntities)
val result = breedRepository.updateBreeds(breeds)
assertTrue(result.isSuccess)
}
}
@Test
fun updateBreeds_error() {
runTest {
whenever(breedDao.getAll()).thenReturn(emptyList())
val result = breedRepository.updateBreeds(emptyList())
assertTrue(result.isFailure)
}
}
private fun getFakeBreedEntity() = BreedEntity(
id = "id",
name = "name",
temperament = "temperament",
description = "description",
origin = "origin",
imageId = "imageId",
isFavourite = true
)
private fun getFakeBreedDto() = BreedDto(
id = "id",
name = "name",
temperament = "temperament",
description = "description",
origin = "origin",
imageId = "imageId"
)
} | 0 | Kotlin | 0 | 0 | 2b317ba625a88a1309805a3a23144b3b09ea3896 | 6,120 | WhiskerWorld | MIT License |
core-test/src/test/kotlin/io/github/lavenderses/aws_app_config_openfeature_provider/proxy/agent/AwsAppConfigAgentProxyTest.kt | lavenderses | 795,942,797 | false | {"Kotlin": 108089, "Java": 105311} | package io.github.lavenderses.aws_app_config_openfeature_provider.proxy.agent
import assertk.assertThat
import assertk.assertions.isEqualTo
import io.github.lavenderses.aws_app_config_openfeature_provider.AwsAppConfigClientOptions
import io.github.lavenderses.aws_app_config_openfeature_provider.proxy.AwsAppConfigProxyException
import io.github.lavenderses.aws_app_config_openfeature_provider.proxy.config.AwsAppConfigAgentProxyConfig
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import org.mockito.InjectMocks
import org.mockito.Mock
import org.mockito.Spy
import org.mockito.junit.jupiter.MockitoExtension
import org.mockito.kotlin.doReturn
import org.mockito.kotlin.doThrow
import org.mockito.kotlin.mock
import org.mockito.kotlin.whenever
import java.io.IOException
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.net.http.HttpResponse.BodyHandler
@ExtendWith(MockitoExtension::class)
class AwsAppConfigAgentProxyTest {
@InjectMocks
private lateinit var awsAppConfigAgentProxy: AwsAppConfigAgentProxy
@Spy
private val awsAppConfigAgentProxyConfig = AwsAppConfigAgentProxyConfig.builder()
.endpoint(URI("http://localhost:2772"))
.build()
@Spy
private val awsAppConfigClientOptions = AwsAppConfigClientOptions.builder()
.applicationName("app")
.environmentName("env")
.profile("profile")
.awsAppConfigProxyConfig(awsAppConfigAgentProxyConfig)
.build()
@Mock
private lateinit var httpClient: HttpClient
@Mock
private lateinit var handler: BodyHandler<String>
@Test
fun getRawFlagObject() {
// prepare
val key = "key"
val response = mock<HttpResponse<String>> {
on { body() } doReturn "{}"
}
val excepted = "{}"
doReturn(response)
.whenever(httpClient)
.send(
@Suppress("ktlint:standard:max-line-length")
/* request = */ HttpRequest.newBuilder()
.uri(URI("http://localhost:2772/applications/app/environments/env/configurations/profile?flag=key"))
.GET()
.build(),
/* responseBodyHandler = */ handler,
)
// do & verify
assertThat(
awsAppConfigAgentProxy.getRawFlagObject(
/* key = */ key,
),
).isEqualTo(excepted)
}
@Test
fun `getRawFlagObject failed to call API`() {
// prepare
val key = "key"
doThrow(IOException("error"))
.whenever(httpClient)
.send(
@Suppress("ktlint:standard:max-line-length")
/* request = */ HttpRequest.newBuilder()
.uri(URI("http://localhost:2772/applications/app/environments/env/configurations/profile?flag=key"))
.GET()
.build(),
/* responseBodyHandler = */ handler,
)
// do & verify
val e = assertThrows<AwsAppConfigProxyException> {
awsAppConfigAgentProxy.getRawFlagObject(
/* key = */ key,
)
}
@Suppress("ktlint:standard:max-line-length", "MaxLineLength")
assertThat(e.message).isEqualTo("Failed to call to AWS AppConfig agent: http://localhost:2772/applications/app/environments/env/configurations/profile?flag=key")
}
}
| 14 | Kotlin | 0 | 1 | 74b780d4b81302a7341f2b47208712050a0bb4c6 | 3,567 | aws-appconfig-openfeature-provider-java | Apache License 2.0 |
core/src/main/kotlin/org/archguard/core/task/TaskConfigure.kt | archguard | 565,163,416 | false | {"Kotlin": 212032, "TypeScript": 19660, "MDX": 5365, "CSS": 2612, "HTML": 1703, "JavaScript": 1360} | package org.archguard.core.task
class TaskConfigure {
} | 1 | Kotlin | 2 | 31 | 4c1f6a57568affeaab7771e83eb0665e934110a5 | 56 | codedb | MIT License |
app/src/main/java/com/example/hiltroomtest/di/AppModule.kt | burakselcuk1 | 468,541,632 | false | null | package com.example.hiltroomtest.di
import android.content.Context
import androidx.room.Room
import com.example.hiltroomtest.db.toDoDatabase
import com.example.hiltroomtest.model.toDo
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object AppModule {
@Singleton
@Provides
fun provideToDoDataBase(
@ApplicationContext context: Context
) = Room.databaseBuilder(
context, toDoDatabase::class.java,
"todo"
).build()
@Singleton
@Provides
fun provideToDoDao(
db: toDoDatabase
) = db.toDoDao()
} | 0 | Kotlin | 0 | 0 | b14ea736506fbae23fd5c629c2648eeba5a6854f | 768 | HiltRoomMvvmYT | The Unlicense |
app/src/main/java/com/gobinda/admob/nativetemplate/SmallAdActivity.kt | gobinda1547 | 685,210,506 | false | null | package com.gobinda.admob.nativetemplate
import android.annotation.SuppressLint
import android.graphics.drawable.ColorDrawable
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.google.android.gms.ads.AdLoader
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.nativead.NativeAd
import com.google.android.material.card.MaterialCardView
class MediumAdActivity : AppCompatActivity() {
private lateinit var adViewHolder: MaterialCardView
private lateinit var templateView: NativeTemplateView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_medium_ad)
adViewHolder = findViewById(R.id.ad_view_holder)
templateView = findViewById(R.id.template_view)
loadNativeAd()
}
override fun onDestroy() {
// As per admob document - we should destroy native ad when we are done showing
// our native ad, so that it could be properly garbage collected.
templateView.destroyNativeAd()
super.onDestroy()
}
/**
* While loading the new add, we first of all making the ad contain or ad view holder
* INVISIBLE cause before downloading the actual ad, it will be invalid.
*/
private fun loadNativeAd() {
adViewHolder.visibility = View.GONE
val adLoader = AdLoader.Builder(this, MyConst.AD_ID)
.forNativeAd { showNativeAdInTemplateView(it) }
.build()
adLoader.loadAd(AdRequest.Builder().build())
}
/**
* Here in this function we are setting the native ad to template view. The reason
* why I have used try-catch block here is, this function could get invoked when the
* activity is actually destroyed. In that case templateView & adViewHolder will be
* null and we will get an exception. Also before setting the newly downloaded native
* ad, we have to destroyed the previous native ad (If there is any). And finally
* making the ad view holder visible cause it contains a valid ad now.
*/
private fun showNativeAdInTemplateView(mNativeAd: NativeAd) {
try {
templateView.destroyNativeAd()
templateView.applyStyles(getStyleForNativeAd())
templateView.setNativeAd(mNativeAd)
adViewHolder.visibility = View.VISIBLE
} catch (e: Exception) {
e.printStackTrace()
}
}
/**
* Here we are creating a style object for native template view. I have taken all the
* colors from the ad view holder (MaterialCardView), so that the ad could look like
* similar with it's container or holder.
*/
@SuppressLint("ResourceType")
fun getStyleForNativeAd(): NativeTemplateStyle {
val mSurface = MyColorScanner.scanSurfaceColor(adViewHolder)
val mOnSurface = MyColorScanner.scanOnSurfaceColor(adViewHolder)
val mPrimary = MyColorScanner.scanPrimaryColor(adViewHolder)
val mOnPrimary = MyColorScanner.scanOnPrimaryColor(adViewHolder)
return NativeTemplateStyle.Builder()
.withMainBackgroundColor(ColorDrawable(mSurface))
.withPrimaryTextColor(mPrimary)
.withPrimaryTextBackgroundColor(ColorDrawable(mSurface))
.withSecondaryTextColor(mOnSurface)
.withCallToActionBackgroundColor(ColorDrawable(mPrimary))
.withCallToActionTextColor(mOnPrimary)
.build()
}
} | 0 | Kotlin | 0 | 0 | fed46dab9de0c9efd3206a0a0249df645e774ffc | 3,534 | AdmobNativeTemplate | Apache License 2.0 |
sample-http/src/test/kotlin/com/github/lemfi/kest/samplehttp/multiplescenarios/stepsextracted/Steps.kt | lemfi | 316,065,076 | false | null | package com.github.lemfi.kest.samplehttp.multiplescenarios.stepsextracted
import com.github.lemfi.kest.core.builder.ScenarioBuilder
import com.github.lemfi.kest.core.cli.assertThat
import com.github.lemfi.kest.core.cli.nestedScenario
import com.github.lemfi.kest.http.cli.givenHttpCall
import com.github.lemfi.kest.http.model.NoContent
import com.github.lemfi.kest.json.cli.json
import com.github.lemfi.kest.json.cli.matches
import com.github.lemfi.kest.json.cli.validator
import com.github.lemfi.kest.json.model.JsonMap
fun ScenarioBuilder.`say hello`(who: String) {
givenHttpCall<String>("$who says hello") {
url = "http://localhost:8080/hello"
method = "POST"
headers["Authorization"] = "Basic aGVsbG86d29ybGQ="
body = """
{
"who": "$who"
}
"""
} assertThat { stepResult ->
stepResult.status isEqualTo 201
stepResult.body isEqualTo "Hello $who!"
}
}
fun ScenarioBuilder.`get greeted`(vararg expectedGreeted: String) {
givenHttpCall<List<String>>("${expectedGreeted.joinToString(", ")} were greeted") {
url = "http://localhost:8080/hello"
method = "GET"
headers["Authorization"] = "Basic aGVsbG86d29ybGQ="
} assertThat { stepResult ->
stepResult.status isEqualTo 200
stepResult.body isEqualTo expectedGreeted.toList()
}
}
fun ScenarioBuilder.`get otp`() =
givenHttpCall<JsonMap>("generate OTP") {
url = "http://localhost:8080/otp"
method = "GET"
headers["Authorization"] = "Basic aGVsbG86d29ybGQ="
} assertThat { stepResult ->
stepResult.status isEqualTo 201
json(stepResult.body) matches validator {
"""
{
"otp": "{{string}}"
}
""".trimIndent()
}
}
fun ScenarioBuilder.`validate otp`(otp: String) =
givenHttpCall<NoContent>("validate otp") {
url = "http://localhost:8080/otp"
method = "POST"
headers["Authorization"] = "Basic aGVsbG86d29ybGQ="
body = otp
contentType = "text/plain"
} assertThat { stepResult ->
stepResult.status isEqualTo 204
}
fun ScenarioBuilder.`generate otps`() = nestedScenario<List<String>>("generate 3 OTPs") {
val otp1 = `get otp`() mapResultTo { it.body["otp"] as String }
val otp2 = `get otp`() mapResultTo { it.body["otp"] as String }
val otp3 = `get otp`() mapResultTo { it.body["otp"] as String }
returns { listOf(otp1(), otp2(), otp3()) }
} | 3 | null | 0 | 8 | b6cb85abb86844b1a589a5567f5f1eaf6aa049db | 2,602 | kest | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/outline/Slash.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.filled
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Filled.Slash: ImageVector
get() {
if (_slash != null) {
return _slash!!
}
_slash = Builder(name = "Slash", 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(-0.0061f, 1.4075f)
lineToRelative(1.4142f, -1.4142f)
lineToRelative(22.5991f, 22.5991f)
lineToRelative(-1.4142f, 1.4142f)
close()
}
}
.build()
return _slash!!
}
private var _slash: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 1,406 | icons | MIT License |
presentation/src/commonMain/kotlin/ireader/presentation/ui/reader/ReaderScreen.kt | kazemcodes | 540,829,865 | false | null | package ireader.presentation.ui.reader
import androidx.compose.animation.Crossfade
import androidx.compose.animation.ExperimentalAnimationApi
import androidx.compose.animation.core.tween
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyListState
import androidx.compose.material.ContentAlpha
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.DrawerState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import ireader.domain.models.entities.Chapter
import ireader.domain.preferences.prefs.ReadingMode
import ireader.presentation.ui.reader.components.MainBottomSettingComposable
import ireader.presentation.ui.reader.reverse_swip_refresh.SwipeRefreshState
import ireader.presentation.ui.reader.viewmodel.ReaderScreenViewModel
import kotlinx.coroutines.launch
@ExperimentalAnimationApi
@OptIn(
ExperimentalMaterialApi::class,
ExperimentalMaterial3Api::class
)
@Composable
fun ReadingScreen(
vm: ReaderScreenViewModel,
scrollState: ScrollState,
lazyListState: LazyListState,
swipeState: SwipeRefreshState,
onNext: (reset: Boolean) -> Unit,
onPrev: (reset: Boolean) -> Unit,
readerScreenPreferencesState: ReaderScreenViewModel,
toggleReaderMode: () -> Unit,
onBackgroundColorAndTextColorApply: (bgColor: String, txtColor: String) -> Unit,
snackBarHostState: SnackbarHostState,
drawerState: DrawerState,
onReaderBottomOnSetting: () -> Unit,
onSliderFinished: () -> Unit,
onSliderChange: (index: Float) -> Unit,
onReaderPlay: () -> Unit,
onChapterShown: (chapter: Chapter) -> Unit,
) {
val modalBottomSheetState = rememberModalBottomSheetState(ModalBottomSheetValue.Hidden)
DisposableEffect(key1 = modalBottomSheetState.hashCode()) {
vm.modalBottomSheetState = modalBottomSheetState
onDispose { }
}
val scope = rememberCoroutineScope()
val chapter = vm.stateChapter
LaunchedEffect(key1 = modalBottomSheetState.targetValue) {
when (modalBottomSheetState.targetValue) {
ModalBottomSheetValue.Expanded -> vm.isReaderModeEnable = false
ModalBottomSheetValue.Hidden -> vm.isReaderModeEnable = true
else -> {}
}
}
LaunchedEffect(key1 = vm.isReaderModeEnable) {
when (vm.isReaderModeEnable) {
false -> {
scope.launch {
modalBottomSheetState.show()
}
}
true -> {
scope.launch {
modalBottomSheetState.hide()
}
}
}
}
Box(
modifier = Modifier
.fillMaxSize()
.background(vm.backgroundColor.value),
contentAlignment = Alignment.Center,
) {
if (vm.webViewManger.inProgress && vm.webViewIntegration.value) {
vm.prefFunc.WebView()
}
Crossfade(
modifier = Modifier.fillMaxSize(),
targetState = vm.isLoading && if (vm.readingMode.value == ReadingMode.Continues) vm.chapterShell.isEmpty() else true
) { isLoading ->
when (isLoading) {
true -> {
Box(
modifier = Modifier.fillMaxSize(),
contentAlignment = Alignment.Center
) {
CircularProgressIndicator(
modifier = Modifier.align(Alignment.Center),
color = MaterialTheme.colorScheme.primary
)
}
}
else -> {
ModalBottomSheetLayout(
modifier = Modifier
.fillMaxWidth(),
sheetBackgroundColor = MaterialTheme.colorScheme.surface.copy(ContentAlpha.high),
sheetContentColor = MaterialTheme.colorScheme.onSurface,
scrimColor = Color.Transparent,
sheetElevation = 0.dp,
sheetState = modalBottomSheetState,
sheetContent = {
Column(
Modifier.height(130.dp),
) {
Spacer(modifier = Modifier.height(5.dp))
MainBottomSettingComposable(
scope = scope,
drawerState = drawerState,
chapter = chapter,
chapters = vm.stateChapters,
currentChapterIndex = vm.currentChapterIndex,
onSetting = onReaderBottomOnSetting,
onNext = {
onNext(true)
},
onPrev = {
onPrev(true)
},
onSliderChange = onSliderChange,
onSliderFinished = onSliderFinished,
onPlay = onReaderPlay
)
}
},
) {
ReaderText(
vm = readerScreenPreferencesState,
onNext = {
onNext(false)
},
swipeState = swipeState,
onPrev = { onPrev(false) },
scrollState = scrollState,
modalState = modalBottomSheetState,
toggleReaderMode = toggleReaderMode,
uiState = vm,
lazyListState = lazyListState,
onChapterShown = onChapterShown
)
}
}
}
}
}
}
| 9 | null | 22 | 6 | b6b2414fa002cec2aa0d199871fcfb4c2e190a8f | 7,028 | IReader | Apache License 2.0 |
core/src/main/kotlin/io/paddle/plugin/standard/extensions/Locations.kt | JetBrains-Research | 377,213,824 | false | null | package io.paddle.plugin.standard.extensions
import io.paddle.project.PaddleProject
import io.paddle.utils.config.PaddleApplicationSettings
import io.paddle.utils.ext.Extendable
import java.nio.file.Path
val PaddleProject.locations: Locations
get() = extensions.getOrFail(Locations.Extension.key)
class Locations private constructor(val project: PaddleProject) {
object Extension : PaddleProject.Extension<Locations> {
override val key: Extendable.Key<Locations> = Extendable.Key()
override fun create(project: PaddleProject) = Locations(project)
}
val paddleHome: Path
get() = PaddleApplicationSettings.paddleHome
val registry: Path
get() = PaddleApplicationSettings.registry
}
| 13 | Kotlin | 6 | 20 | 42a26a7f5815961d564f71e3606252fab7a87f82 | 737 | paddle | MIT License |
typescript-kotlin/src/main/kotlin/typescript/createIntersectionTypeNode.kt | turansky | 393,199,102 | false | null | // Automatically generated - do not modify!
@file:JsModule("typescript")
@file:JsNonModule
package typescript
/** @deprecated Use `factory.createIntersectionTypeNode` or the factory supplied by your transformation context instead. */
/*
external val createIntersectionTypeNode: (types: readonly TypeNode[]) => IntersectionTypeNode
*/
| 0 | Kotlin | 1 | 10 | bcf03704c0e7670fd14ec4ab01dff8d7cca46bf0 | 337 | react-types-kotlin | Apache License 2.0 |
straight/src/commonMain/kotlin/me/localx/icons/straight/bold/Interactive.kt | localhostov | 808,861,591 | false | {"Kotlin": 79430321, "HTML": 331, "CSS": 102} | package me.localx.icons.straight.bold
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType
import androidx.compose.ui.graphics.PathFillType.Companion.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.StrokeCap.Companion.Butt
import androidx.compose.ui.graphics.StrokeJoin
import androidx.compose.ui.graphics.StrokeJoin.Companion.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import me.localx.icons.straight.Icons
public val Icons.Bold.Interactive: ImageVector
get() {
if (_interactive != null) {
return _interactive!!
}
_interactive = Builder(name = "Interactive", 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(11.937f, 7.442f)
arcToRelative(4.513f, 4.513f, 0.0f, false, true, 1.543f, 0.273f)
lineToRelative(0.471f, 0.171f)
arcToRelative(4.487f, 4.487f, 0.0f, true, false, -6.064f, 6.066f)
lineToRelative(-0.17f, -0.469f)
arcToRelative(4.505f, 4.505f, 0.0f, false, true, 4.22f, -6.041f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(3.0f, 10.0f)
arcTo(7.0f, 7.0f, 0.0f, false, true, 16.915f, 8.964f)
lineTo(20.0f, 10.084f)
curveToRelative(0.0f, -0.028f, 0.0f, -0.056f, 0.0f, -0.084f)
arcTo(10.0f, 10.0f, 0.0f, true, false, 10.0f, 20.0f)
curveToRelative(0.029f, 0.0f, 0.056f, 0.0f, 0.085f, 0.0f)
lineToRelative(-1.12f, -3.081f)
arcTo(7.0f, 7.0f, 0.0f, false, true, 3.0f, 10.0f)
close()
}
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(24.0f, 13.669f)
lineTo(12.8f, 9.6f)
arcToRelative(2.5f, 2.5f, 0.0f, false, false, -3.2f, 3.2f)
lineTo(13.669f, 24.0f)
lineTo(17.774f, 19.9f)
lineTo(21.879f, 24.0f)
lineTo(24.0f, 21.879f)
lineTo(19.9f, 17.774f)
close()
moveTo(12.782f, 12.782f)
lineTo(18.547f, 14.882f)
lineTo(14.878f, 18.551f)
close()
}
}
.build()
return _interactive!!
}
private var _interactive: ImageVector? = null
| 1 | Kotlin | 0 | 5 | cbd8b510fca0e5e40e95498834f23ec73cc8f245 | 3,279 | icons | MIT License |
feature/folder-insert/android/src/main/java/br/alexandregpereira/hunter/folder/insert/FolderInsertViewState.kt | alexandregpereira | 347,857,709 | false | {"Kotlin": 1323782, "Swift": 74314, "Shell": 139} | /*
* Copyright 2022 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package br.alexandregpereira.hunter.folder.insert
import androidx.lifecycle.SavedStateHandle
import br.alexandregpereira.hunter.folder.insert.ui.MonsterPreviewState
internal data class FolderInsertViewState(
val isOpen: Boolean = false,
val folderName: String = "",
val folderIndexSelected: Int = -1,
val monsterIndexes: List<String> = emptyList(),
val folders: List<Pair<String, Int>> = emptyList(),
val monsterPreviews: List<MonsterPreviewState> = emptyList()
)
internal fun SavedStateHandle.getState(): FolderInsertViewState {
return FolderInsertViewState(
isOpen = this["isOpen"] ?: false,
folderName = this["folderName"] ?: "",
folderIndexSelected = this["folderIndexPositionSelected"] ?: -1,
monsterIndexes = this["monsterIndexes"] ?: emptyList()
)
}
internal fun FolderInsertViewState.saveState(
savedStateHandle: SavedStateHandle
): FolderInsertViewState {
savedStateHandle["isOpen"] = isOpen
savedStateHandle["folderName"] = folderName
savedStateHandle["folderIndexSelected"] = folderIndexSelected
savedStateHandle["monsterIndexes"] = monsterIndexes
return this
}
| 7 | Kotlin | 4 | 80 | ca1695daf3f23e7cbb634b66e62b4fee36440ef8 | 1,753 | Monster-Compendium | Apache License 2.0 |
content-types/content-types-core-services/src/main/kotlin/org/orkg/contenttypes/domain/actions/paper/PaperIdentifierUpdater.kt | TIBHannover | 197,416,205 | false | {"Kotlin": 2966676, "Cypher": 216833, "Python": 4881, "Groovy": 1936, "Shell": 1803, "HTML": 240} | package org.orkg.contenttypes.domain.actions.papers
import org.orkg.contenttypes.domain.Identifiers
import org.orkg.contenttypes.domain.actions.IdentifierUpdater
import org.orkg.contenttypes.domain.actions.UpdatePaperCommand
import org.orkg.contenttypes.domain.actions.UpdatePaperState
import org.orkg.graph.input.LiteralUseCases
import org.orkg.graph.input.StatementUseCases
class PaperIdentifierUpdater(
statementService: StatementUseCases,
literalService: LiteralUseCases
) : IdentifierUpdater(statementService, literalService), UpdatePaperAction {
override operator fun invoke(command: UpdatePaperCommand, state: UpdatePaperState): UpdatePaperState {
if (command.identifiers != null) {
update(
contributorId = command.contributorId,
oldIdentifiers = state.paper!!.identifiers,
newIdentifiers = command.identifiers!!,
identifierDefinitions = Identifiers.paper,
subjectId = state.paper.id
)
}
return state
}
}
| 0 | Kotlin | 1 | 5 | f9de52bdf498fdc200e7f655a52cecff215c1949 | 1,058 | orkg-backend | MIT License |
sample/src/main/java/com/example/webtrekk/androidsdk/mapp/Util.kt | mapp-digital | 166,987,236 | false | {"Kotlin": 395889, "Java": 14412} | package com.example.webtrekk.androidsdk.mapp
internal object Util {
@JvmStatic
fun capitalize(inputWord: String): String {
val words = inputWord.toLowerCase().split("_".toRegex()).toTypedArray()
val builder = StringBuilder()
for (i in words.indices) {
val word = words[i]
if (i > 0 && word.isNotEmpty()) {
builder.append("_")
}
val cap = word.substring(0, 1).toUpperCase() + word.substring(1)
builder.append(cap)
}
return builder.toString()
}
} | 0 | Kotlin | 2 | 13 | 593762e60e568f481d0f38653f79d3a8d007dca9 | 573 | mapp-intelligence-android-sdk-v5 | MIT License |
app/src/main/java/com/furniconbreeze/features/location/shopRevisitStatus/ShopRevisitStatusRepository.kt | DebashisINT | 811,202,727 | false | {"Kotlin": 14691854, "Java": 1021080} | package com.furniconbreeze.features.location.shopRevisitStatus
import com.furniconbreeze.base.BaseResponse
import com.furniconbreeze.features.location.model.ShopDurationRequest
import com.furniconbreeze.features.location.model.ShopRevisitStatusRequest
import io.reactivex.Observable
class ShopRevisitStatusRepository(val apiService : ShopRevisitStatusApi) {
fun shopRevisitStatus(shopRevisitStatus: ShopRevisitStatusRequest?): Observable<BaseResponse> {
return apiService.submShopRevisitStatus(shopRevisitStatus)
}
} | 0 | Kotlin | 0 | 0 | c02d8d092164f1a715f9b98c8a1a3ed7ca177b38 | 534 | UniqueSorterFurnicon | Apache License 2.0 |
app/src/main/java/com/example/project_1/UIComponents/DataAdapter/DataNumber.kt | altaliufun2019 | 172,730,021 | false | null | package com.example.project_1.UIComponents.DataAdapter
import java.util.*
class DataNumber(var id: Int, var date: Date) | 1 | null | 1 | 1 | 60fa7bcbccff8c9d3fadd59cbbe209e7f456afd6 | 121 | project_01.1 | Apache License 2.0 |
ktfx-listeners/src/test/kotlin/javafx/scene/web/WebEngineTest.kt | hendraanggrian | 102,934,147 | false | null | package ktfx.listeners
import javafx.geometry.Rectangle2D
import javafx.scene.web.BaseWebEngineTest
import javafx.scene.web.WebEngine
import javafx.scene.web.WebErrorEvent
import javafx.scene.web.WebEvent
import kotlin.test.Ignore
@Ignore
class WebEngineTest : BaseWebEngineTest() {
override fun WebEngine.callOnAlert(action: (WebEvent<String>) -> Unit) = onAlert(action)
override fun WebEngine.callOnStatusChanged(action: (WebEvent<String>) -> Unit) =
onStatusChanged(action)
override fun WebEngine.callOnResized(action: (WebEvent<Rectangle2D>) -> Unit) =
onResized(action)
override fun WebEngine.callOnVisibilityChanged(action: (WebEvent<Boolean>) -> Unit) =
onVisibilityChanged(action)
override fun WebEngine.callOnError(action: (WebErrorEvent) -> Unit) = onError(action)
}
| 1 | null | 2 | 16 | d7b8aec230fef877ae067d14cb0bc21c53e3d361 | 826 | ktfx | Apache License 2.0 |
line-awesome/src/commonMain/kotlin/compose/icons/lineawesomeicons/PoopSolid.kt | DevSrSouza | 311,134,756 | false | null | package compose.icons.lineawesomeicons
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.PathFillType.NonZero
import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.StrokeCap.Butt
import androidx.compose.ui.graphics.StrokeJoin.Miter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.graphics.vector.ImageVector.Builder
import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.unit.dp
import compose.icons.LineAwesomeIcons
public val LineAwesomeIcons.PoopSolid: ImageVector
get() {
if (_poopSolid != null) {
return _poopSolid!!
}
_poopSolid = Builder(name = "PoopSolid", defaultWidth = 32.0.dp, defaultHeight = 32.0.dp,
viewportWidth = 32.0f, viewportHeight = 32.0f).apply {
path(fill = SolidColor(Color(0xFF000000)), stroke = null, strokeLineWidth = 0.0f,
strokeLineCap = Butt, strokeLineJoin = Miter, strokeLineMiter = 4.0f,
pathFillType = NonZero) {
moveTo(21.125f, 4.0f)
lineTo(19.4688f, 4.625f)
curveTo(17.6055f, 5.3281f, 16.3945f, 6.0547f, 15.5938f, 6.8125f)
curveTo(14.793f, 7.5703f, 14.4141f, 8.4023f, 14.2188f, 9.0313f)
curveTo(14.0234f, 9.6602f, 13.9453f, 10.0273f, 13.8125f, 10.2188f)
curveTo(13.6953f, 10.3867f, 13.4922f, 10.5898f, 12.8438f, 10.7813f)
curveTo(12.832f, 10.7734f, 12.7539f, 10.7227f, 12.75f, 10.7188f)
lineTo(12.7188f, 10.7188f)
curveTo(12.2188f, 10.3906f, 11.6484f, 10.1875f, 11.0938f, 10.0938f)
curveTo(9.4297f, 9.8125f, 7.6875f, 10.5391f, 6.7188f, 12.0938f)
lineTo(6.6875f, 12.125f)
curveTo(6.0938f, 13.1328f, 5.7695f, 14.4102f, 5.9375f, 15.75f)
curveTo(5.9883f, 16.1563f, 6.0898f, 16.5703f, 6.25f, 16.9688f)
curveTo(4.7852f, 17.0547f, 3.4102f, 17.8789f, 2.625f, 19.2188f)
lineTo(2.5938f, 19.2188f)
curveTo(1.375f, 21.3711f, 2.1172f, 24.1484f, 4.2813f, 25.375f)
lineTo(4.3125f, 25.375f)
lineTo(4.3125f, 25.4063f)
curveTo(4.4258f, 25.4609f, 5.7578f, 26.1641f, 7.75f, 26.7813f)
curveTo(9.7422f, 27.3984f, 12.5313f, 28.0f, 16.0f, 28.0f)
curveTo(19.4688f, 28.0f, 22.2539f, 27.4219f, 24.25f, 26.8125f)
curveTo(26.2227f, 26.207f, 27.332f, 25.6133f, 27.7188f, 25.375f)
curveTo(27.7227f, 25.3711f, 27.7461f, 25.3477f, 27.75f, 25.3438f)
curveTo(29.8828f, 24.1055f, 30.6016f, 21.3789f, 29.375f, 19.2813f)
lineTo(29.4063f, 19.2813f)
curveTo(28.832f, 18.2656f, 27.9336f, 17.5742f, 26.9063f, 17.25f)
curveTo(26.9063f, 17.2461f, 26.875f, 17.2539f, 26.875f, 17.25f)
curveTo(26.5586f, 16.1094f, 25.8086f, 15.1328f, 24.7813f, 14.5625f)
curveTo(24.918f, 14.125f, 25.0f, 13.6172f, 25.0f, 13.0f)
curveTo(25.0f, 11.8398f, 24.5859f, 10.8633f, 24.0313f, 10.1563f)
curveTo(23.4766f, 9.4492f, 22.8086f, 8.9766f, 22.25f, 8.5313f)
curveTo(21.6914f, 8.0859f, 21.2422f, 7.6758f, 21.0f, 7.2813f)
curveTo(20.7578f, 6.8867f, 20.6367f, 6.5117f, 20.7813f, 5.75f)
close()
moveTo(18.875f, 7.1875f)
curveTo(18.9688f, 7.6055f, 19.1094f, 8.0117f, 19.3125f, 8.3438f)
curveTo(19.7852f, 9.1133f, 20.418f, 9.6016f, 21.0f, 10.0625f)
curveTo(21.582f, 10.5234f, 22.125f, 10.9648f, 22.4688f, 11.4063f)
curveTo(22.8125f, 11.8477f, 23.0f, 12.2695f, 23.0f, 13.0f)
curveTo(23.0f, 13.4805f, 22.9453f, 13.7734f, 22.875f, 14.0f)
curveTo(20.1484f, 13.6016f, 17.7617f, 12.9141f, 16.0f, 12.25f)
curveTo(15.6484f, 12.1172f, 15.3398f, 11.9766f, 15.0313f, 11.8438f)
curveTo(15.1992f, 11.6953f, 15.3477f, 11.5195f, 15.4688f, 11.3438f)
curveTo(15.918f, 10.6914f, 15.9805f, 10.0586f, 16.125f, 9.5938f)
curveTo(16.2695f, 9.1289f, 16.4336f, 8.7578f, 16.9688f, 8.25f)
curveTo(17.2891f, 7.9453f, 18.1797f, 7.5508f, 18.875f, 7.1875f)
close()
moveTo(10.3125f, 11.9688f)
curveTo(10.7539f, 11.9648f, 11.207f, 12.1016f, 11.625f, 12.375f)
curveTo(12.1758f, 12.7578f, 13.3555f, 13.3594f, 15.3125f, 14.0938f)
curveTo(17.2891f, 14.8359f, 19.9336f, 15.625f, 23.0313f, 16.0313f)
lineTo(23.0625f, 16.0313f)
curveTo(23.7578f, 16.1172f, 24.332f, 16.5273f, 24.6875f, 17.125f)
curveTo(24.332f, 17.1914f, 23.9648f, 17.2852f, 23.625f, 17.4375f)
curveTo(23.5742f, 17.4609f, 23.5195f, 17.4453f, 23.4688f, 17.4688f)
curveTo(23.4297f, 17.4805f, 23.4219f, 17.4922f, 23.4063f, 17.5f)
curveTo(23.375f, 17.5156f, 23.3438f, 17.5156f, 23.3125f, 17.5313f)
curveTo(23.2852f, 17.543f, 23.2539f, 17.5781f, 23.2188f, 17.5938f)
curveTo(23.1328f, 17.6328f, 23.0078f, 17.6836f, 22.8438f, 17.75f)
curveTo(22.5195f, 17.8867f, 22.0352f, 18.0625f, 21.4063f, 18.25f)
curveTo(20.1484f, 18.6211f, 18.3203f, 19.0f, 16.0f, 19.0f)
curveTo(14.2773f, 19.0f, 12.8047f, 18.8047f, 11.6563f, 18.5625f)
curveTo(11.2969f, 18.4766f, 10.9492f, 18.3828f, 10.625f, 18.2813f)
curveTo(9.9727f, 18.0742f, 9.3672f, 17.7773f, 9.375f, 17.7813f)
curveTo(8.4063f, 17.1289f, 8.0117f, 16.3438f, 7.9063f, 15.5f)
curveTo(7.8008f, 14.6563f, 8.0352f, 13.7578f, 8.4063f, 13.125f)
curveTo(8.875f, 12.3711f, 9.5781f, 11.9766f, 10.3125f, 11.9688f)
close()
moveTo(6.2813f, 18.9375f)
curveTo(6.7578f, 18.9023f, 7.2578f, 19.0195f, 7.7188f, 19.2813f)
curveTo(7.7266f, 19.2852f, 7.7422f, 19.3086f, 7.75f, 19.3125f)
curveTo(7.8047f, 19.3438f, 7.875f, 19.375f, 7.9375f, 19.4063f)
curveTo(8.0625f, 19.4727f, 8.207f, 19.5391f, 8.4063f, 19.625f)
curveTo(8.8047f, 19.7969f, 9.3555f, 19.9844f, 10.0625f, 20.1875f)
curveTo(10.3125f, 20.2578f, 10.6172f, 20.3359f, 10.9063f, 20.4063f)
curveTo(11.0117f, 20.4336f, 11.1094f, 20.4727f, 11.2188f, 20.5f)
curveTo(11.2305f, 20.5039f, 11.2383f, 20.4961f, 11.25f, 20.5f)
curveTo(11.6484f, 20.6016f, 12.043f, 20.6914f, 12.4375f, 20.75f)
lineTo(12.4375f, 20.7188f)
curveTo(13.4805f, 20.8906f, 14.6641f, 21.0f, 16.0f, 21.0f)
curveTo(18.5352f, 21.0f, 20.5586f, 20.5742f, 21.9688f, 20.1563f)
curveTo(22.6758f, 19.9453f, 23.2422f, 19.7227f, 23.625f, 19.5625f)
curveTo(23.7656f, 19.5039f, 23.8438f, 19.4492f, 23.9375f, 19.4063f)
lineTo(24.0313f, 19.4063f)
lineTo(24.0625f, 19.375f)
lineTo(24.25f, 19.2813f)
curveTo(25.4922f, 18.6172f, 26.9844f, 19.0117f, 27.6875f, 20.25f)
lineTo(27.6875f, 20.2813f)
curveTo(28.3711f, 21.4492f, 27.9766f, 22.9609f, 26.75f, 23.6563f)
lineTo(26.7188f, 23.6563f)
lineTo(26.7188f, 23.6875f)
curveTo(26.6406f, 23.7344f, 25.5156f, 24.3477f, 23.6875f, 24.9063f)
curveTo(21.8594f, 25.4648f, 19.25f, 26.0f, 16.0f, 26.0f)
curveTo(12.75f, 26.0f, 10.1445f, 25.4727f, 8.3125f, 24.9063f)
curveTo(6.5039f, 24.3438f, 5.5977f, 23.832f, 5.25f, 23.6563f)
curveTo(5.2344f, 23.6484f, 5.2305f, 23.6328f, 5.2188f, 23.625f)
curveTo(4.0234f, 22.918f, 3.6523f, 21.4414f, 4.3438f, 20.2188f)
curveTo(4.6914f, 19.6367f, 5.2109f, 19.2031f, 5.8125f, 19.0313f)
curveTo(5.9648f, 18.9883f, 6.1211f, 18.9492f, 6.2813f, 18.9375f)
close()
}
}
.build()
return _poopSolid!!
}
private var _poopSolid: ImageVector? = null
| 15 | null | 20 | 460 | 651badc4ace0137c5541f859f61ffa91e5242b83 | 8,277 | compose-icons | MIT License |
analysis/src/org/jetbrains/kotlin/idea/caches/resolve/IDEKotlinAsJavaSupport.kt | JetBrains | 278,369,660 | false | null | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.caches.resolve
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.search.GlobalSearchScope
import com.intellij.util.SmartList
import org.jetbrains.kotlin.analysis.decompiled.light.classes.DecompiledLightClassesFactory
import org.jetbrains.kotlin.analysis.decompiled.light.classes.DecompiledLightClassesFactory.getLightClassForDecompiledClassOrObject
import org.jetbrains.kotlin.analysis.decompiled.light.classes.KtLightClassForDecompiledDeclaration
import org.jetbrains.kotlin.analysis.decompiler.psi.file.KtClsFile
import org.jetbrains.kotlin.asJava.KotlinAsJavaSupport
import org.jetbrains.kotlin.asJava.classes.*
import org.jetbrains.kotlin.config.JvmAnalysisFlags
import org.jetbrains.kotlin.fileClasses.javaFileFacadeFqName
import org.jetbrains.kotlin.idea.caches.lightClasses.platformMutabilityWrapper
import org.jetbrains.kotlin.idea.caches.project.*
import org.jetbrains.kotlin.idea.caches.project.IdeaModuleInfo
import org.jetbrains.kotlin.idea.decompiler.navigation.SourceNavigationHelper
import org.jetbrains.kotlin.idea.project.getLanguageVersionSettings
import org.jetbrains.kotlin.idea.project.platform
import org.jetbrains.kotlin.idea.stubindex.*
import org.jetbrains.kotlin.idea.util.ProjectRootsUtil
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.application.withPsiAttachment
import org.jetbrains.kotlin.idea.util.runReadActionInSmartMode
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.platform.jvm.JvmPlatforms
import org.jetbrains.kotlin.platform.jvm.isJvm
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.scopes.MemberScope
open class IDEKotlinAsJavaSupport(private val project: Project) : KotlinAsJavaSupport() {
private val psiManager: PsiManager = PsiManager.getInstance(project)
private val languageVersionSettings = project.getLanguageVersionSettings()
override fun getFacadeNames(packageFqName: FqName, scope: GlobalSearchScope): Collection<String> {
val facadeFilesInPackage = project.runReadActionInSmartMode {
KotlinFileFacadeClassByPackageIndex.getInstance().get(packageFqName.asString(), project, scope)
}
return facadeFilesInPackage.map { it.javaFileFacadeFqName.shortName().asString() }.toSet()
}
override fun getFacadeClassesInPackage(packageFqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> {
val facadeFilesInPackage = runReadAction {
KotlinFileFacadeClassByPackageIndex.getInstance()
.get(packageFqName.asString(), project, scope).platformSourcesFirst()
}
val groupedByFqNameAndModuleInfo = facadeFilesInPackage.groupBy {
Pair(it.javaFileFacadeFqName, it.getModuleInfoPreferringJvmPlatform())
}
return groupedByFqNameAndModuleInfo.flatMap {
val (key, files) = it
val (fqName, moduleInfo) = key
createLightClassForFileFacade(fqName, files, moduleInfo)
}
}
override fun findClassOrObjectDeclarations(fqName: FqName, searchScope: GlobalSearchScope): Collection<KtClassOrObject> {
return project.runReadActionInSmartMode {
KotlinFullClassNameIndex.getInstance().get(
fqName.asString(),
project,
KotlinSourceFilterScope.sourceAndClassFiles(searchScope, project)
)
}
}
override fun findFilesForPackage(fqName: FqName, searchScope: GlobalSearchScope): Collection<KtFile> {
return project.runReadActionInSmartMode {
PackageIndexUtil.findFilesWithExactPackage(
fqName,
KotlinSourceFilterScope.sourceAndClassFiles(
searchScope,
project
),
project
)
}
}
override fun findClassOrObjectDeclarationsInPackage(
packageFqName: FqName,
searchScope: GlobalSearchScope
): Collection<KtClassOrObject> {
return KotlinTopLevelClassByPackageIndex.getInstance().get(
packageFqName.asString(), project,
KotlinSourceFilterScope.sourceAndClassFiles(searchScope, project)
)
}
override fun packageExists(fqName: FqName, scope: GlobalSearchScope): Boolean {
return PackageIndexUtil.packageExists(
fqName,
KotlinSourceFilterScope.sourceAndClassFiles(
scope,
project
)
)
}
override fun getSubPackages(fqn: FqName, scope: GlobalSearchScope): Collection<FqName> {
return PackageIndexUtil.getSubPackageFqNames(
fqn,
KotlinSourceFilterScope.sourceAndClassFiles(
scope,
project
),
MemberScope.ALL_NAME_FILTER
)
}
private val recursiveGuard = ThreadLocal<Boolean>()
private inline fun <T> guardedRun(body: () -> T): T? {
if (recursiveGuard.get() == true) return null
return try {
recursiveGuard.set(true)
body()
} finally {
recursiveGuard.set(false)
}
}
override fun getLightClass(classOrObject: KtClassOrObject): KtLightClass? {
if (!classOrObject.isValid) {
return null
}
val virtualFile = classOrObject.containingFile.virtualFile
if (virtualFile != null) {
when {
ProjectRootsUtil.isProjectSourceFile(project, virtualFile) ->
return KtLightClassForSourceDeclaration.create(
classOrObject,
languageVersionSettings.getFlag(JvmAnalysisFlags.jvmDefaultMode)
)
ProjectRootsUtil.isLibraryClassFile(project, virtualFile) ->
return getLightClassForDecompiledClassOrObject(classOrObject, project)
ProjectRootsUtil.isLibrarySourceFile(project, virtualFile) ->
return guardedRun {
SourceNavigationHelper.getOriginalClass(classOrObject) as? KtLightClass
}
}
}
if ((classOrObject.containingFile as? KtFile)?.analysisContext != null ||
classOrObject.containingFile.originalFile.virtualFile != null
) {
// explicit request to create light class from dummy.kt
return KtLightClassForSourceDeclaration.create(classOrObject, languageVersionSettings.getFlag(JvmAnalysisFlags.jvmDefaultMode))
}
return null
}
override fun getLightClassForScript(script: KtScript): KtLightClass? {
if (!script.isValid) {
return null
}
return KtLightClassForScript.create(script)
}
override fun getFacadeClasses(facadeFqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> {
val filesByModule = findFilesForFacade(facadeFqName, scope).groupBy(PsiElement::getModuleInfoPreferringJvmPlatform)
return filesByModule.flatMap {
createLightClassForFileFacade(facadeFqName, it.value, it.key)
}
}
override fun getScriptClasses(scriptFqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> {
return KotlinScriptFqnIndex.instance.get(scriptFqName.asString(), project, scope).mapNotNull {
getLightClassForScript(it)
}
}
override fun getKotlinInternalClasses(fqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> {
if (fqName.isRoot) return emptyList()
val packageParts = findPackageParts(fqName, scope)
val platformWrapper = findPlatformWrapper(fqName, scope)
return if (platformWrapper != null) packageParts + platformWrapper else packageParts
}
private fun findPackageParts(fqName: FqName, scope: GlobalSearchScope): List<KtLightClassForDecompiledDeclaration> {
val facadeKtFiles = StaticFacadeIndexUtil.getMultifileClassForPart(fqName, scope, project)
val partShortName = fqName.shortName().asString()
val partClassFileShortName = "$partShortName.class"
return facadeKtFiles.mapNotNull { facadeKtFile ->
if (facadeKtFile is KtClsFile) {
val partClassFile = facadeKtFile.virtualFile.parent.findChild(partClassFileShortName) ?: return@mapNotNull null
val javaClsClass = DecompiledLightClassesFactory.createClsJavaClassFromVirtualFile(facadeKtFile, partClassFile, null, project) ?: return@mapNotNull null
KtLightClassForDecompiledDeclaration(javaClsClass, javaClsClass.parent, facadeKtFile, null)
} else {
// TODO should we build light classes for parts from source?
null
}
}
}
private fun findPlatformWrapper(fqName: FqName, scope: GlobalSearchScope): PsiClass? {
return platformMutabilityWrapper(fqName) {
JavaPsiFacade.getInstance(
project
).findClass(it, scope)
}
}
private fun createLightClassForFileFacade(
facadeFqName: FqName,
facadeFiles: List<KtFile>,
moduleInfo: IdeaModuleInfo
): List<PsiClass> = SmartList<PsiClass>().apply {
tryCreateFacadesForSourceFiles(moduleInfo, facadeFqName)?.let { sourcesFacade ->
add(sourcesFacade)
}
facadeFiles.filterIsInstance<KtClsFile>().mapNotNullTo(this) {
DecompiledLightClassesFactory.createLightClassForDecompiledKotlinFile(it, project)
}
}
private fun tryCreateFacadesForSourceFiles(moduleInfo: IdeaModuleInfo, facadeFqName: FqName): PsiClass? {
if (moduleInfo !is ModuleSourceInfo && moduleInfo !is PlatformModuleInfo) return null
return KtLightClassForFacadeImpl.createForFacade(psiManager, facadeFqName, moduleInfo.contentScope())
}
override fun findFilesForFacade(facadeFqName: FqName, scope: GlobalSearchScope): Collection<KtFile> {
return runReadAction {
KotlinFileFacadeFqNameIndex.INSTANCE.get(facadeFqName.asString(), project, scope).platformSourcesFirst()
}
}
override fun getFakeLightClass(classOrObject: KtClassOrObject): KtFakeLightClass =
KtDescriptorBasedFakeLightClass(classOrObject)
override fun createFacadeForSyntheticFile(facadeClassFqName: FqName, file: KtFile): PsiClass =
KtLightClassForFacadeImpl.createForSyntheticFile(facadeClassFqName, file)
// NOTE: this is a hacky solution to the following problem:
// when building this light class resolver will be built by the first file in the list
// (we could assume that files are in the same module before)
// thus we need to ensure that resolver will be built by the file from platform part of the module
// (resolver built by a file from the common part will have no knowledge of the platform part)
// the actual of order of files that resolver receives is controlled by *findFilesForFacade* method
private fun Collection<KtFile>.platformSourcesFirst() = sortedByDescending { it.platform.isJvm() }
}
internal fun PsiElement.getModuleInfoPreferringJvmPlatform(): IdeaModuleInfo {
return getPlatformModuleInfo(JvmPlatforms.unspecifiedJvmPlatform) ?: getModuleInfo()
}
| 1 | null | 30 | 82 | cc81d7505bc3e9ad503d706998ae8026c067e838 | 11,499 | intellij-kotlin | Apache License 2.0 |
feature-tests/src/test/kotlin/fi/vauhtijuoksu/vauhtijuoksuapi/featuretest/BasicTest.kt | Vauhtijuoksu | 394,707,727 | false | {"Kotlin": 389348, "Smarty": 2566, "Dockerfile": 172, "Shell": 106} | package fi.vauhtijuoksu.vauhtijuoksuapi.featuretest
import io.vertx.ext.web.client.WebClient
import io.vertx.junit5.VertxTestContext
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Test
@FeatureTest
class BasicTest {
@Test
fun testServerResponds(webClient: WebClient, testContext: VertxTestContext) {
webClient.get("/gamedata")
.send()
.onFailure(testContext::failNow)
.onSuccess { res ->
testContext.verify {
assertEquals(200, res.statusCode())
}
testContext.completeNow()
}
}
}
| 11 | Kotlin | 0 | 3 | 99b374a55d914f1ef7b01add4a3dbaaa93f26fdd | 652 | vauhtijuoksu-api | MIT License |
projetofinaldmo/app/src/main/java/br/edu/ifsp/arq/ads/dmo/VisualizarGrupoActivity.kt | AfonsoMorvillo | 781,478,469 | false | {"Kotlin": 83756} | package br.edu.ifsp.arq.ads.dmo
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import br.edu.ifsp.arq.ads.dmo.model.Grupo
import br.edu.ifsp.arq.ads.dmo.model.User
import br.edu.ifsp.arq.ads.dmo.viewmodel.GrupoViewModel
import br.edu.ifsp.arq.ads.dmo.viewmodel.PostagemViewModel
import com.google.android.material.floatingactionbutton.FloatingActionButton
import java.text.NumberFormat
import java.util.Locale
class VisualizarGrupoActivity : AppCompatActivity(), PostagemAdapter.OnItemClickListener {
private lateinit var adapter: PostagemAdapter
private lateinit var recyclerView: RecyclerView
private lateinit var coletado: TextView
private lateinit var numberFormat: NumberFormat
private val postagemViewModel by viewModels<PostagemViewModel>()
private val grupoViewModel by viewModels<GrupoViewModel>()
lateinit var user: User
var grupoId: String? = null
lateinit var grupo: Grupo
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
this.supportActionBar?.hide()
setContentView(R.layout.activity_visualizar_grupo)
grupoId = intent.getStringExtra("GROUP_ID")
recyclerView = findViewById(R.id.recyclerViewPostagens)
grupoViewModel.getGrupo(grupoId!!).observe(this, Observer {
grupo = it
setComponents()
})
setAdapter()
setFloatButton()
// Configurar o clique no ícone
val iconView: ImageView = findViewById(R.id.iconView)
iconView.setOnClickListener { view -> onIconClick(view) }
}
private fun setComponents() {
numberFormat = NumberFormat.getNumberInstance(Locale.getDefault())
val nomeGrupo = findViewById<TextView>(R.id.textView)
val meta = findViewById<TextView>(R.id.txtMeta)
coletado = findViewById<TextView>(R.id.txtColetado)
val material = findViewById<TextView>(R.id.txtMaterial)
nomeGrupo.text = grupo.nome
meta.text = numberFormat.format(grupo.meta)
coletado.text = numberFormat.format(grupo.quantidadeAtual)
material.text = grupo.tipoMaterial!!.value
}
private fun setAdapter() {
adapter = PostagemAdapter(this, emptyList())
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = adapter
postagemViewModel.getAllPosts(grupoId).observe(this, Observer {
adapter.updatePostagens(it)
})
}
private fun setFloatButton() {
val fab: FloatingActionButton = findViewById(R.id.fab_add)
fab.setOnClickListener {
val intent = Intent(this, CadastroPostagemActivity::class.java)
intent.putExtra("GROUP_ID", grupoId)
startActivityForResult(intent, REQUEST_CODE_ADD_POST)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_ADD_POST && resultCode == RESULT_OK) {
postagemViewModel.getAllPosts(grupoId).observe(this, Observer {posts ->
adapter.updatePostagens(posts)
val totalQuantidade = posts?.sumOf { it.quantidade ?: 0 } ?: 0
coletado.text = numberFormat.format(totalQuantidade)
})
}
}
companion object {
private const val REQUEST_CODE_ADD_POST = 1
}
override fun onItemClick(postagemId: String) {
val intent = Intent(this, PostagemActivity::class.java)
intent.putExtra("POST_ID", postagemId)
startActivity(intent)
}
fun onIconClick(view: View) {
val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
val clip = ClipData.newPlainText("Group ID", grupoId)
clipboard.setPrimaryClip(clip)
Toast.makeText(this, "Link do Grupo copiado!", Toast.LENGTH_SHORT).show()
}
}
| 0 | Kotlin | 0 | 0 | 7f3385bb36f223228767daa6d54378bdf0a50f8b | 4,415 | projeto-final-dmo | MIT License |
plugins/kotlin/refactorings/kotlin.refactorings.common/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KtPsiClassWrapper.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.memberInfo
import com.intellij.psi.PsiClass
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtPsiFactory
interface KtPsiClassWrapper : KtNamedDeclaration {
val psiClass: PsiClass
}
fun KtPsiClassWrapper(psiClass: PsiClass): KtPsiClassWrapper {
val dummyKtClass = KtPsiFactory(psiClass.project).createClass("class ${psiClass.name}")
return object : KtPsiClassWrapper, KtNamedDeclaration by dummyKtClass {
override fun equals(other: Any?) = psiClass == (other as? KtPsiClassWrapper)?.psiClass
override fun hashCode() = psiClass.hashCode()
override val psiClass: PsiClass
get() = psiClass
}
} | 214 | null | 4829 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 849 | intellij-community | Apache License 2.0 |
plugins/kotlin/refactorings/kotlin.refactorings.common/src/org/jetbrains/kotlin/idea/refactoring/memberInfo/KtPsiClassWrapper.kt | ingokegel | 72,937,917 | false | null | // Copyright 2000-2023 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.refactoring.memberInfo
import com.intellij.psi.PsiClass
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtPsiFactory
interface KtPsiClassWrapper : KtNamedDeclaration {
val psiClass: PsiClass
}
fun KtPsiClassWrapper(psiClass: PsiClass): KtPsiClassWrapper {
val dummyKtClass = KtPsiFactory(psiClass.project).createClass("class ${psiClass.name}")
return object : KtPsiClassWrapper, KtNamedDeclaration by dummyKtClass {
override fun equals(other: Any?) = psiClass == (other as? KtPsiClassWrapper)?.psiClass
override fun hashCode() = psiClass.hashCode()
override val psiClass: PsiClass
get() = psiClass
}
} | 214 | null | 4829 | 2 | b07eabd319ad5b591373d63c8f502761c2b2dfe8 | 849 | intellij-community | Apache License 2.0 |
src/test/kotlin/no/nav/tilleggsstonader/arena/TestConstants.kt | navikt | 747,155,448 | false | {"Kotlin": 42943, "Shell": 414, "Dockerfile": 208} | package no.nav.tilleggsstonader.arena
object TestConstants {
const val FNR = "25518735813"
}
| 1 | Kotlin | 0 | 0 | 8745a4a09dc696b26006a9963bcd219a10728230 | 98 | tilleggsstonader-arena | MIT License |
app/src/main/java/com/example/todo_list/ui/fragment/ScheduleFragment.kt | kimdoyun98 | 536,434,864 | false | {"Kotlin": 63396} | package com.example.todo_list.ui.fragment
import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.todo_list.ui.ScheduleViewModel
import com.example.todo_list.ui.activity.ScheduleRegisterActivity
import com.example.todo_list.adapter.ScheduleAdapter
import com.example.todo_list.databinding.FragmentScheduleBinding
import dagger.hilt.android.AndroidEntryPoint
@AndroidEntryPoint
class ScheduleFragment : Fragment() {
private lateinit var binding : FragmentScheduleBinding
private val viewModel : ScheduleViewModel by viewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
binding.todoViewModel = viewModel
val adapter = ScheduleAdapter(requireContext(), viewModel)
val recyclerView = binding.recyclerview
recyclerView.adapter = adapter
recyclerView.layoutManager = LinearLayoutManager(requireContext())
viewModel.getAll.observe(viewLifecycleOwner) { list ->
// 정렬
viewModel.sortFilter.observe(viewLifecycleOwner) { filter ->
when(filter) {
ScheduleViewModel.LATEST -> adapter.setData(list.sortedByDescending { it.id })
ScheduleViewModel.DEADLINE -> adapter.setData(list.sortedByDescending { it.deadline_date}.reversed())
}
}
}
/***
* 추가 버튼
*/
binding.addButton.setOnClickListener{
val intent = Intent(context, ScheduleRegisterActivity::class.java)
startActivity(intent)
}
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = FragmentScheduleBinding.inflate(layoutInflater, container, false)
return binding.root
}
} | 0 | Kotlin | 0 | 0 | 832bb9cdc6ba8f5be83aa9c2397f62ccede6cc3f | 2,084 | TODO_List | Apache License 2.0 |
src/ar/witanime/src/eu/kanade/tachiyomi/animeextension/ar/witanime/WitAnime.kt | almightyhak | 817,607,446 | false | null | package eu.kanade.tachiyomi.animeextension.ar.witanime
import android.app.Application
import android.util.Base64
import androidx.preference.ListPreference
import androidx.preference.PreferenceScreen
import eu.kanade.tachiyomi.animeextension.ar.witanime.extractors.SharedExtractor
import eu.kanade.tachiyomi.animeextension.ar.witanime.extractors.SoraPlayExtractor
import eu.kanade.tachiyomi.animesource.ConfigurableAnimeSource
import eu.kanade.tachiyomi.animesource.model.AnimeFilterList
import eu.kanade.tachiyomi.animesource.model.SAnime
import eu.kanade.tachiyomi.animesource.model.SEpisode
import eu.kanade.tachiyomi.animesource.model.Video
import eu.kanade.tachiyomi.animesource.online.ParsedAnimeHttpSource
import eu.kanade.tachiyomi.lib.dailymotionextractor.DailymotionExtractor
import eu.kanade.tachiyomi.lib.doodextractor.DoodExtractor
import eu.kanade.tachiyomi.lib.mp4uploadextractor.Mp4uploadExtractor
import eu.kanade.tachiyomi.lib.okruextractor.OkruExtractor
import eu.kanade.tachiyomi.lib.vidbomextractor.VidBomExtractor
import eu.kanade.tachiyomi.network.GET
import eu.kanade.tachiyomi.util.asJsoup
import eu.kanade.tachiyomi.util.parallelCatchingFlatMapBlocking
import okhttp3.Response
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import uy.kohesive.injekt.Injekt
import uy.kohesive.injekt.api.get
class WitAnime : ConfigurableAnimeSource, ParsedAnimeHttpSource() {
override val name = "WIT ANIME"
override val baseUrl = "https://witanime.pics"
override val lang = "ar"
override val supportsLatest = true
override fun headersBuilder() = super.headersBuilder().add("Referer", baseUrl)
private val preferences by lazy {
Injekt.get<Application>().getSharedPreferences("source_$id", 0x0000)
}
// ============================== Popular ===============================
override fun popularAnimeSelector() = "div.anime-list-content div.row div.anime-card-poster div.ehover6"
override fun popularAnimeNextPageSelector() = "ul.pagination a.next"
override fun popularAnimeRequest(page: Int) = GET("$baseUrl/قائمة-الانمي/page/$page")
override fun popularAnimeFromElement(element: Element) = SAnime.create().apply {
element.selectFirst("a")!!.run {
attr("href").takeUnless { it.contains("javascript:") }
?: getEncodedUrl() // Get base64-encoded URLs
}.also { setUrlWithoutDomain(it) }
element.selectFirst("img")!!.also {
title = it.attr("alt")
thumbnail_url = it.attr("abs:src")
}
}
// =============================== Latest ===============================
override fun latestUpdatesRequest(page: Int) = GET("$baseUrl/episode/page/$page/")
override fun latestUpdatesSelector() = popularAnimeSelector()
override fun latestUpdatesNextPageSelector() = popularAnimeNextPageSelector()
override fun latestUpdatesFromElement(element: Element) = popularAnimeFromElement(element)
// =============================== Search ===============================
override fun searchAnimeRequest(page: Int, query: String, filters: AnimeFilterList) = GET("$baseUrl/?search_param=animes&s=$query")
override fun searchAnimeFromElement(element: Element) = popularAnimeFromElement(element)
override fun searchAnimeNextPageSelector() = popularAnimeNextPageSelector()
override fun searchAnimeSelector() = popularAnimeSelector()
// =========================== Anime Details ============================
override fun animeDetailsParse(document: Document) = SAnime.create().apply {
val doc = getRealDoc(document)
thumbnail_url = doc.selectFirst("img.thumbnail")!!.attr("src")
title = doc.selectFirst("h1.anime-details-title")!!.text()
// Genres + useful info
genre = doc.select("ul.anime-genres > li > a, div.anime-info > a").eachText().joinToString()
description = buildString {
// Additional info
doc.select("div.anime-info").eachText().forEach {
append("$it\n")
}
// Description
doc.selectFirst("p.anime-story")?.text()?.also {
append("\n$it")
}
}
doc.selectFirst("div.anime-info:contains(حالة الأنمي)")?.text()?.also {
status = when {
it.contains("يعرض الان", true) -> SAnime.ONGOING
it.contains("مكتمل", true) -> SAnime.COMPLETED
else -> SAnime.UNKNOWN
}
}
}
// ============================== Episodes ==============================
override fun episodeListParse(response: Response) =
getRealDoc(response.asJsoup())
.select(episodeListSelector())
.map(::episodeFromElement)
.reversed()
override fun episodeListSelector() = "div.ehover6 > div.episodes-card-title > h3 a"
override fun episodeFromElement(element: Element) = SEpisode.create().apply {
setUrlWithoutDomain(element.getEncodedUrl())
name = element.text()
episode_number = name.substringAfterLast(" ").toFloatOrNull() ?: 0F
}
// ============================ Video Links =============================
override fun videoListParse(response: Response): List<Video> {
val document = response.asJsoup()
return document.select("ul#episode-servers li a")
.distinctBy { it.text().substringBefore(" -") } // remove duplicates by server name
.parallelCatchingFlatMapBlocking {
val url = it.attr("data-url")
.takeUnless(String::isBlank)
?.let { String(Base64.decode(it, Base64.DEFAULT)) }
?: it.getEncodedUrl()
extractVideos(url)
}
}
private val soraPlayExtractor by lazy { SoraPlayExtractor(client) }
private val doodExtractor by lazy { DoodExtractor(client) }
private val sharedExtractor by lazy { SharedExtractor(client) }
private val dailymotionExtractor by lazy { DailymotionExtractor(client, headers) }
private val okruExtractor by lazy { OkruExtractor(client) }
private val mp4uploadExtractor by lazy { Mp4uploadExtractor(client) }
private val vidBomExtractor by lazy { VidBomExtractor(client) }
private fun extractVideos(url: String): List<Video> {
return when {
url.contains("yonaplay") -> extractFromMulti(url)
url.contains("soraplay") -> {
when {
url.contains("/mirror") -> extractFromMulti(url)
else -> soraPlayExtractor.videosFromUrl(url, headers)
}
}
url.contains("dood") -> {
doodExtractor.videoFromUrl(url, "Dood mirror")
?.let(::listOf)
}
url.contains("4shared") -> {
sharedExtractor.videosFromUrl(url)
?.let(::listOf)
}
url.contains("dropbox") -> {
listOf(Video(url, "Dropbox mirror", url))
}
url.contains("dailymotion") -> {
dailymotionExtractor.videosFromUrl(url)
}
url.contains("ok.ru") -> {
okruExtractor.videosFromUrl(url)
}
url.contains("mp4upload.com") -> {
mp4uploadExtractor.videosFromUrl(url, headers)
}
VIDBOM_REGEX.containsMatchIn(url) -> {
vidBomExtractor.videosFromUrl(url)
}
else -> null
} ?: emptyList()
}
private fun extractFromMulti(url: String): List<Video> {
val newHeaders = when {
url.contains("soraplay") ->
super.headersBuilder().set("referer", "https://yonaplay.org").build()
else -> headers
}
val doc = client.newCall(GET(url, newHeaders)).execute()
.asJsoup()
return doc.select(".OD li").flatMap { element ->
val videoUrl = element.attr("onclick").substringAfter("go_to_player('")
.substringBefore("')")
.let {
when {
it.startsWith("https:") -> it
else -> "https:$it"
}
}
runCatching { extractVideos(videoUrl) }.getOrElse { emptyList() }
}
}
override fun videoListSelector() = throw UnsupportedOperationException()
override fun videoFromElement(element: Element) = throw UnsupportedOperationException()
override fun videoUrlParse(document: Document) = throw UnsupportedOperationException()
override fun List<Video>.sort(): List<Video> {
val quality = preferences.getString(PREF_QUALITY_KEY, PREF_QUALITY_DEFAULT)!!
return sortedWith(
compareBy { it.quality.contains(quality) },
).reversed()
}
// ============================== Settings ==============================
override fun setupPreferenceScreen(screen: PreferenceScreen) {
ListPreference(screen.context).apply {
key = PREF_QUALITY_KEY
title = PREF_QUALITY_TITLE
entries = PREF_QUALITY_ENTRIES
entryValues = PREF_QUALITY_VALUES
setDefaultValue(PREF_QUALITY_DEFAULT)
summary = "%s"
setOnPreferenceChangeListener { _, newValue ->
val selected = newValue as String
val index = findIndexOfValue(selected)
val entry = entryValues[index] as String
preferences.edit().putString(key, entry).commit()
}
}.also(screen::addPreference)
}
// ============================= Utilities ==============================
private fun getRealDoc(document: Document): Document {
return document.selectFirst("div.anime-page-link a")?.let {
client.newCall(GET(it.attr("href"), headers)).execute().asJsoup()
} ?: document
}
private fun Element.getEncodedUrl() = attr("onclick")
.substringAfter("'")
.substringBefore("'")
.let { String(Base64.decode(it, Base64.DEFAULT)) }
companion object {
// From TukTukCinema(AR)
private val VIDBOM_REGEX by lazy { Regex("//(?:v[aie]d[bp][aoe]?m)") }
private const val PREF_QUALITY_KEY = "preferred_quality"
private const val PREF_QUALITY_TITLE = "Preferred quality"
private const val PREF_QUALITY_DEFAULT = "1080"
private val PREF_QUALITY_ENTRIES = arrayOf("1080p", "720p", "480p", "380p", "360p", "240p")
private val PREF_QUALITY_VALUES by lazy {
PREF_QUALITY_ENTRIES.map { it.substringBefore("p") }.toTypedArray()
}
}
}
| 55 | null | 28 | 93 | 507dddff536702999357b17577edc48353eab5ad | 10,752 | aniyomi-extensions | Apache License 2.0 |
analysis/src/main/kotlin/analyzers/TypeInferenceVisitor.kt | SrGaabriel | 837,425,380 | false | {"Kotlin": 203248, "LLVM": 29310, "Rust": 4440} | package me.gabriel.gwydion.analysis.analyzers
import me.gabriel.gwydion.frontend.parsing.SyntaxTreeNode
class TypeInferenceVisitor(private val node: SyntaxTreeNode) {
val queuedVisits = mutableListOf<Pair<SyntaxTreeNode, () -> Any>>()
fun <T : Any> visit(node: SyntaxTreeNode, block: () -> T) {
queuedVisits.add(node to block)
}
} | 0 | Kotlin | 0 | 7 | 44f52c1fc9ee8f5981057fa3b172737dc022782b | 353 | gwydion | Apache License 2.0 |
im-core/src/main/java/com/zj/im/chat/core/IMOption.kt | ZBL-Kiven | 683,927,392 | false | null | package com.zj.im.chat.core
import android.app.Application
import android.app.Notification
import com.zj.im.chat.enums.RuntimeEfficiency
/**
* Created by ZJJ
*
* the IM SDK options ,used for #ChatBase
*
* @see OptionProxy
*
* @param notification start a foreground service to keeping active for sdk when the app was running in background
*
* @param sessionId the foreground service session id
*
* @param debugEnable is allow logging at runtime?
*
* @param runtimeEfficiency the sdk efficiency level for sdk , {@link RuntimeEfficiency#interval }
*
* @param logsCollectionAble set is need collection runtime logs , {@link logsFileName} and saved in somewhere
*/
class IMOption internal constructor(val context: Application, val notification: Notification? = null, val sessionId: Int?, val runtimeEfficiency: RuntimeEfficiency, val logsCollectionAble: () -> Boolean, val logsFilePath: String, val logsMaxRetain: Long, val debugEnable: Boolean) {
companion object {
@Suppress("unused")
fun create(context: Application): OptionProxy {
return OptionProxy(context)
}
}
}
| 0 | Kotlin | 0 | 1 | 9779d1a8dfdb86a672cb5034e8e3d688a270ca3b | 1,128 | IM_Core | The Unlicense |
src/main/kotlin/me/exerro/kwery/queries/FileContentsQuery.kt | exerro | 695,164,229 | false | {"Kotlin": 60754} | package me.exerro.kwery.queries
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.Serializable
import me.exerro.kwery.*
import me.exerro.observables.Observable
import me.exerro.observables.ObservableSignal
import java.nio.file.FileSystems
import java.nio.file.Path
import java.nio.file.StandardWatchEventKinds
/** Query for the contents of a file. */
data class FileContentsQuery(val path: Path): Query<Result<ByteArray>> {
/**
* Handler for [FileContentsQuery] queries which also watches for changes.
* When a file in the specified watchPaths is modified and that path has
* previously been handled (queried), the changed signal will be emitted
* that query.
* @param watchPaths Collection of paths to directories which are being
* watched. Cannot provide paths to files, so if a file
* should be watched, provide the parent directory.
*/
class WatchingHandler(
scope: CoroutineScope,
watchPaths: Collection<Path>,
): ObservableQueryHandler<FileContentsQuery, Result<ByteArray>> {
constructor(scope: CoroutineScope, vararg watchPaths: Path): this(scope, watchPaths.toList())
context(QueryContext, CoroutineScope)
override suspend fun handle(query: FileContentsQuery) = withContext(Dispatchers.IO) {
watchedFiles.add(query.path)
try {
Result.success(query.path.toFile().readBytes())
}
catch (e: Exception) {
Result.failure(e)
}
}
override val changed: Observable<(FileContentsQuery) -> Unit>
private val watchedFiles = mutableSetOf<Path>()
init {
val (signal, emit) = ObservableSignal.createSignal<FileContentsQuery>()
changed = signal
val watchService = FileSystems.getDefault().newWatchService()
for (path in watchPaths) {
path.register(
watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE
)
}
scope.launch(Dispatchers.IO) {
while (true) {
val key = watchService.take()
for (event in key.pollEvents()) {
val context = event.context() as Path
val directory = key.watchable() as Path
val fullPath = directory.resolve(context)
if (fullPath in watchedFiles)
emit(FileContentsQuery(fullPath))
}
key.reset()
}
}
}
}
/**
* Default handler for [FileContentsQuery] which reads files once and doesn't
* watch for changes.
*/
object DefaultHandler: QueryHandler<FileContentsQuery, Result<ByteArray>> {
context(QueryContext, CoroutineScope)
override suspend fun handle(query: FileContentsQuery) = withContext(Dispatchers.IO) {
try {
Result.success(query.path.toFile().readBytes())
}
catch (e: Exception) {
Result.failure(e)
}
}
}
/**
* Handler for [FileContentsQuery] queries which returns a fixed set of
* files.
*/
class MockHandler(
private val files: Map<Path, ByteArray>,
): QueryHandler<FileContentsQuery, Result<ByteArray>> {
constructor(vararg files: Pair<Path, String>):
this(files.toMap().mapValues { (_, v) -> v.toByteArray() })
context(QueryContext, CoroutineScope)
override suspend fun handle(query: FileContentsQuery): Result<ByteArray> {
return when (val contents = files[query.path]) {
null -> Result.failure(Exception("File not found"))
else -> Result.success(contents)
}
}
}
companion object {
val prettyPrint = QueryGraphPrinter.prettyPrinter<FileContentsQuery> { query ->
"FileContents\n${query.path}"
}
}
}
| 0 | Kotlin | 0 | 0 | 91d729c41ee36fbae160f57773e0a9449b3296d8 | 4,338 | kwery | MIT License |
compiler/testData/diagnostics/testsWithStdLib/contracts/complexConditionWithSafeCall.kt | JetBrains | 3,432,266 | false | {"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80} | // ISSUE: KT-62137
class PersonDto (
val name: String
)
fun test() {
val name: String? = null
val person: PersonDto? = null
if (!name.isNullOrEmpty()) {
<!DEBUG_INFO_SMARTCAST!>name<!>.length // Smart cast work
}
if (!person?.name.isNullOrEmpty()) {
person<!UNSAFE_CALL!>.<!>name // Smart cast doesn't work
}
}
| 181 | Kotlin | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 359 | kotlin | Apache License 2.0 |
server/zally-server/src/main/kotlin/org/zalando/zally/apireview/ApiViolationsController.kt | zalando | 76,853,145 | false | null | package org.zalando.zally.apireview
import org.zalando.zally.dto.ApiDefinitionRequest
import org.zalando.zally.dto.ApiDefinitionResponse
import org.zalando.zally.dto.ViolationDTO
import org.zalando.zally.exception.ApiReviewNotFoundException
import org.zalando.zally.exception.InaccessibleResourceUrlException
import org.zalando.zally.exception.MissingApiDefinitionException
import org.zalando.zally.core.ApiValidator
import org.zalando.zally.core.RulesPolicy
import org.zalando.zally.rule.api.Severity
import org.springframework.http.HttpStatus
import org.springframework.http.ResponseEntity
import org.springframework.web.bind.annotation.CrossOrigin
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.PathVariable
import org.springframework.web.bind.annotation.PostMapping
import org.springframework.web.bind.annotation.RequestBody
import org.springframework.web.bind.annotation.RequestHeader
import org.springframework.web.bind.annotation.ResponseBody
import org.springframework.web.bind.annotation.RestController
import org.springframework.web.util.UriComponentsBuilder
import java.util.UUID
@CrossOrigin
@RestController
class ApiViolationsController(
private val rulesValidator: ApiValidator,
private val apiDefinitionReader: ApiDefinitionReader,
private val apiReviewRepository: ApiReviewRepository,
private val serverMessageService: ServerMessageService,
private val configPolicy: RulesPolicy
) {
@ResponseBody
@PostMapping("/api-violations")
fun validate(
@RequestBody(required = true) request: ApiDefinitionRequest,
@RequestHeader(value = "User-Agent", required = false) userAgent: String?,
@RequestHeader(value = "Authorization", required = false) authorization: String?,
uriBuilder: UriComponentsBuilder
): ResponseEntity<ApiDefinitionResponse> {
val apiDefinition = retrieveApiDefinition(request)
val requestPolicy = retrieveRulesPolicy(request)
val violations = rulesValidator.validate(apiDefinition, requestPolicy, authorization)
val review = ApiReview(request, userAgent.orEmpty(), apiDefinition, violations)
apiReviewRepository.save(review)
val location = uriBuilder
.path("/api-violations/{externalId}")
.buildAndExpand(review.externalId)
.toUri()
return ResponseEntity
.status(HttpStatus.OK)
.location(location)
.body(buildApiDefinitionResponse(review))
}
@ResponseBody
@GetMapping("/api-violations/{externalId}")
fun getExistingViolationResponse(
@PathVariable(value = "externalId") externalId: UUID
): ApiDefinitionResponse {
val review = apiReviewRepository.findByExternalId(externalId) ?: throw ApiReviewNotFoundException()
return buildApiDefinitionResponse(review)
}
private fun retrieveRulesPolicy(request: ApiDefinitionRequest): RulesPolicy = request.ignoreRules
.let { configPolicy.withMoreIgnores(request.ignoreRules) }
private fun retrieveApiDefinition(request: ApiDefinitionRequest): String = try {
apiDefinitionReader.read(request)
} catch (e: MissingApiDefinitionException) {
apiReviewRepository.save(ApiReview(request, "", ""))
throw e
} catch (e: InaccessibleResourceUrlException) {
apiReviewRepository.save(ApiReview(request, "", ""))
throw e
}
private fun buildApiDefinitionResponse(review: ApiReview): ApiDefinitionResponse = ApiDefinitionResponse(
externalId = review.externalId,
message = serverMessageService.serverMessage(review.userAgent),
violations = review.ruleViolations
.sortedBy(RuleViolation::type)
.map {
ViolationDTO(
it.ruleTitle,
it.description,
it.type,
it.ruleUrl,
listOfNotNull(it.locationPointer),
it.locationPointer,
it.locationLineStart,
it.locationLineEnd
)
},
violationsCount = listOf(
Severity.MUST to review.mustViolations,
Severity.SHOULD to review.shouldViolations,
Severity.MAY to review.mayViolations,
Severity.HINT to review.hintViolations
).map { it.first.name.toLowerCase() to it.second }.toMap(),
apiDefinition = review.apiDefinition
)
}
| 62 | null | 2 | 882 | 8c7407db2be39041f61b6baa3ee74012ebdb26ad | 4,517 | zally | MIT License |
videocall/src/main/java/com/voximplant/demos/kotlin/video_call/stories/login/LoginActivity.kt | voximplant | 262,341,712 | false | {"Kotlin": 260075} | /*
* Copyright (c) 2011 - 2024, Zingaya, Inc. All rights reserved.
*/
package com.voximplant.demos.kotlin.audio_call.stories.login
import android.animation.Animator
import android.animation.AnimatorInflater
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import androidx.core.widget.doOnTextChanged
import com.google.android.material.textfield.MaterialAutoCompleteTextView
import com.google.android.material.textfield.TextInputLayout
import com.voximplant.demos.kotlin.utils.BaseActivity
import com.voximplant.demos.kotlin.utils.Shared
import com.voximplant.demos.kotlin.audio_call.R
import com.voximplant.demos.kotlin.audio_call.databinding.ActivityLoginBinding
import com.voximplant.demos.kotlin.audio_call.stories.main.MainActivity
import com.voximplant.sdk.client.Node
class LoginActivity : BaseActivity<LoginViewModel>(LoginViewModel::class.java) {
private lateinit var binding: ActivityLoginBinding
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLoginBinding.inflate(layoutInflater)
setContentView(binding.root)
val reducer = AnimatorInflater.loadAnimator(this.applicationContext, R.animator.reduce_size)
val increaser = AnimatorInflater.loadAnimator(this.applicationContext, R.animator.regain_size)
binding.loginButton.setOnTouchListener { view, motionEvent ->
if (motionEvent.action == MotionEvent.ACTION_DOWN) animate(view, reducer)
if (motionEvent.action == MotionEvent.ACTION_UP) animate(view, increaser)
false
}
binding.loginButton.setOnClickListener {
model.login(binding.username.editText?.text.toString(), binding.password.editText?.text.toString())
}
binding.shareLogLoginButton.setOnClickListener {
Shared.shareHelper.shareLog(this)
}
model.didLogin.observe(this) {
Intent(this, MainActivity::class.java).also {
startActivity(it)
}
}
model.usernameFieldError.observe(this) { error ->
if (error != null) {
showError(binding.username, resources.getString(error))
} else {
showError(binding.username, null)
}
}
model.passwordFieldError.observe(this) { error ->
if (error != null) {
showError(binding.password, resources.getString(error))
} else {
showError(binding.password, null)
}
}
model.nodeFieldError.observe(this) { error ->
if (error != null) {
showError(binding.nodeListField, resources.getString(error))
} else {
showError(binding.nodeListField, null)
}
}
binding.username.editText?.doOnTextChanged { _, _, _, _ ->
showError(binding.username, null)
}
binding.password.editText?.doOnTextChanged { _, _, _, _ ->
showError(binding.password, null)
}
model.username.observe(this) { value ->
binding.username.editText?.setText(value)
}
model.password.observe(this) { value ->
binding.password.editText?.setText(value)
}
val nodes = resources.getStringArray(R.array.node_array)
val nodeMenu = (binding.nodeListField.editText as? MaterialAutoCompleteTextView)
nodeMenu?.setSimpleItems(nodes)
nodeMenu?.setOnItemClickListener { _, _, index, _ ->
when (index) {
0 -> model.changeNode(Node.NODE_1)
1 -> model.changeNode(Node.NODE_2)
2 -> model.changeNode(Node.NODE_3)
3 -> model.changeNode(Node.NODE_4)
4 -> model.changeNode(Node.NODE_5)
5 -> model.changeNode(Node.NODE_6)
6 -> model.changeNode(Node.NODE_7)
7 -> model.changeNode(Node.NODE_8)
8 -> model.changeNode(Node.NODE_9)
9 -> model.changeNode(Node.NODE_10)
}
}
model.node.observe(this) { node ->
val nodeIndex = when (node) {
Node.NODE_1 -> 0
Node.NODE_2 -> 1
Node.NODE_3 -> 2
Node.NODE_4 -> 3
Node.NODE_5 -> 4
Node.NODE_6 -> 5
Node.NODE_7 -> 6
Node.NODE_8 -> 7
Node.NODE_9 -> 8
Node.NODE_10 -> 9
null -> null
}
if (nodeIndex != null) {
nodeMenu?.setText(nodes[nodeIndex], false)
}
}
}
private fun showError(textView: TextInputLayout, text: String?) {
textView.error = text
textView.isErrorEnabled = text != null
if (text != null) {
textView.requestFocus()
}
}
private fun animate(view: View, animator: Animator) {
animator.setTarget(view)
animator.start()
}
} | 1 | Kotlin | 2 | 5 | 2fe9f1e901556908a041ffa69065478a65bd489d | 5,198 | android-sdk-kotlin-demo | MIT License |
libandroid-navigation/src/test/java/com/mapbox/navigation/DefaultDirectionsSessionTest.kt | the-losers | 219,723,357 | true | {"Java": 1318178, "Kotlin": 633196, "Python": 4645, "Makefile": 3213, "JavaScript": 3107, "Shell": 1903, "Prolog": 611} | package com.mapbox.navigation
import com.mapbox.geojson.Point
import com.mapbox.navigation.base.route.DirectionsSession
import com.mapbox.navigation.base.route.Route
import com.mapbox.navigation.base.route.Router
import io.mockk.every
import io.mockk.mockk
import io.mockk.verify
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNull
import org.junit.Before
import org.junit.Test
class DefaultDirectionsSessionTest {
private lateinit var session: DefaultDirectionsSession
private val router: Router = mockk(relaxUnitFun = true)
private val origin: Point = mockk(relaxUnitFun = true)
private val waypoints: List<Point> = mockk(relaxUnitFun = true)
private val observer: DirectionsSession.RouteObserver = mockk(relaxUnitFun = true)
private lateinit var routeCallback: ((route: Route) -> Unit)
private val route: Route = mockk(relaxUnitFun = true)
@Before
fun setUp() {
every { router.getRoute(origin, waypoints, captureLambda()) } answers {
routeCallback = thirdArg()
}
session = DefaultDirectionsSession(router, origin, waypoints)
}
@Test
fun initialRouteResponse() {
assertNull(session.currentRoute)
routeCallback.invoke(route)
assertEquals(route, session.currentRoute)
}
@Test
fun setCurrentRoute() {
val newRoute: Route = mockk()
session.currentRoute = newRoute
assertEquals(newRoute, session.currentRoute)
}
@Test
fun getOrigin() {
assertEquals(origin, session.origin)
}
@Test
fun setOrigin() {
val newOrigin: Point = mockk()
session.origin = newOrigin
assertNull(session.currentRoute)
assertEquals(newOrigin, session.origin)
verify { router.getRoute(eq(newOrigin), eq(waypoints), any()) }
}
@Test
fun getWaypoints() {
assertEquals(waypoints, session.waypoints)
}
@Test
fun setWaypoints() {
val newWaypoints: List<Point> = mockk()
session.waypoints = newWaypoints
assertNull(session.currentRoute)
assertEquals(newWaypoints, session.waypoints)
verify { router.getRoute(eq(origin), eq(newWaypoints), any()) }
}
@Test
fun registerObserver() {
session.registerRouteObserver(observer)
verify { observer.onRouteChanged(null) }
val newRoute: Route = mockk()
session.currentRoute = newRoute
verify { observer.onRouteChanged(newRoute) }
}
@Test
fun unregisterObserver() {
session.registerRouteObserver(observer)
verify { observer.onRouteChanged(null) }
session.unregisterRouteObserver(observer)
val newRoute: Route = mockk()
session.currentRoute = newRoute
verify(exactly = 0) { observer.onRouteChanged(newRoute) }
}
@Test
fun cancel() {
session.cancel()
verify { router.cancel() }
}
}
| 0 | null | 0 | 0 | e35f73862d6ee76ce168a36ef0afa436fb3365c7 | 2,947 | mapbox-navigation-android | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/hmppsstrengthsbasedneedsassessmentsapi/oasys/service/OasysAssessmentServiceTest.kt | ministryofjustice | 623,389,131 | false | {"Kotlin": 168271, "Makefile": 2874, "Dockerfile": 1194} | package uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.oasys.service
import io.mockk.clearAllMocks
import io.mockk.every
import io.mockk.junit5.MockKExtension
import io.mockk.mockk
import io.mockk.slot
import io.mockk.verify
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.DisplayName
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.junit.jupiter.api.extension.ExtendWith
import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.oasys.controller.request.CreateAssessmentRequest
import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.oasys.persistence.entity.OasysAssessment
import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.oasys.persistence.repository.OasysAssessmentRepository
import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.oasys.service.exception.OasysAssessmentAlreadyExistsException
import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.oasys.service.exception.OasysAssessmentAlreadyLockedException
import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.oasys.service.exception.OasysAssessmentNotFoundException
import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.persistence.entity.Assessment
import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.persistence.entity.AssessmentVersion
import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.persistence.entity.Tag
import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.service.AssessmentService
import uk.gov.justice.digital.hmpps.hmppsstrengthsbasedneedsassessmentsapi.service.AssessmentVersionService
import java.util.UUID
@ExtendWith(MockKExtension::class)
@DisplayName("OasysAssessmentService")
class OasysAssessmentServiceTest {
private val assessmentService: AssessmentService = mockk()
private val assessmentVersionService: AssessmentVersionService = mockk()
private val oasysAssessmentRepository: OasysAssessmentRepository = mockk()
private val oasysAssessmentService = OasysAssessmentService(
assessmentService,
assessmentVersionService,
oasysAssessmentRepository,
)
private val oasysAssessmentPk = "1234567890"
private val assessment = Assessment()
private val assessmentVersion = AssessmentVersion(assessment = assessment)
@BeforeEach
fun setUp() {
clearAllMocks()
}
@Nested
@DisplayName("createAssessmentWithOasysId")
inner class CreateAssessmentWithOasysId {
@Test
fun `it creates an assessment for a given OASys assessment PK`() {
every { assessmentService.save(any()) } returnsArgument 0
val result = oasysAssessmentService.createAssessmentWithOasysId(oasysAssessmentPk)
assertThat(result.oasysAssessmentPk).isEqualTo(oasysAssessmentPk)
verify { assessmentService.save(any()) }
}
}
@Nested
@DisplayName("findOrCreateAssessment")
inner class FindOrCreateAssessment {
@Test
fun `it finds an assessment for a given OASys assessment PK`() {
every { oasysAssessmentRepository.findByOasysAssessmentPk(any()) } returns OasysAssessment(
oasysAssessmentPk = oasysAssessmentPk,
assessment = assessment,
)
val result = oasysAssessmentService.findOrCreateAssessment(oasysAssessmentPk)
assertThat(result.oasysAssessmentPk).isEqualTo(oasysAssessmentPk)
assertThat(result.assessment).isEqualTo(assessment)
}
@Test
fun `it creates an assessment if unable to find one for a given OASys assessment PK`() {
every { assessmentService.save(any()) } returnsArgument 0
every { oasysAssessmentRepository.findByOasysAssessmentPk(any()) } returns null
val result = oasysAssessmentService.findOrCreateAssessment(oasysAssessmentPk)
assertThat(result.oasysAssessmentPk).isEqualTo(oasysAssessmentPk)
verify { assessmentService.save(any()) }
}
}
@Nested
@DisplayName("find")
inner class Find {
@Test
fun `it finds an assessment for a given OASys assessment PK`() {
every { oasysAssessmentRepository.findByOasysAssessmentPk(any()) } returns OasysAssessment(
oasysAssessmentPk = oasysAssessmentPk,
assessment = assessment,
)
val result = oasysAssessmentService.find(oasysAssessmentPk)
assertThat(result?.oasysAssessmentPk).isEqualTo(oasysAssessmentPk)
assertThat(result?.assessment).isEqualTo(assessment)
}
}
@Nested
@DisplayName("associate")
inner class Associate {
@Test
fun `it throws when an association already exists for the given OASys assessment PK`() {
val request = CreateAssessmentRequest(
oasysAssessmentPk = "1234567890",
previousOasysAssessmentPk = "0987654321",
)
every { oasysAssessmentRepository.findByOasysAssessmentPk(request.oasysAssessmentPk) } returns OasysAssessment(
oasysAssessmentPk = request.oasysAssessmentPk,
assessment = assessment,
)
assertThrows<OasysAssessmentAlreadyExistsException> {
oasysAssessmentService.associate(request.oasysAssessmentPk, request.previousOasysAssessmentPk)
}
}
@Test
fun `it creates an assessment when no old OASys assessment PK is provided`() {
val request = CreateAssessmentRequest(
oasysAssessmentPk = "1234567890",
)
val assessmentUuid = UUID.randomUUID()
val assessment = Assessment(
uuid = assessmentUuid,
assessmentVersions = listOf(assessmentVersion),
oasysAssessments = listOf(
OasysAssessment(oasysAssessmentPk = oasysAssessmentPk, assessment = Assessment(uuid = assessmentUuid)),
),
)
every {
oasysAssessmentRepository.findByOasysAssessmentPk(request.oasysAssessmentPk)
} returns null
every { assessmentService.save(any()) } returns assessment
every { assessmentVersionService.find(any()) } returns assessmentVersion
val result = oasysAssessmentService.associate(request.oasysAssessmentPk)
assertThat(result.uuid).isEqualTo(assessment.uuid)
}
@Test
fun `it associates an assessment when an old OASys assessment PK is provided`() {
val request = CreateAssessmentRequest(
oasysAssessmentPk = "1234567890",
previousOasysAssessmentPk = "0987654321",
)
every {
oasysAssessmentRepository.findByOasysAssessmentPk(request.oasysAssessmentPk)
} returns null
every {
oasysAssessmentRepository.findByOasysAssessmentPk(request.previousOasysAssessmentPk!!)
} returns OasysAssessment(
oasysAssessmentPk = request.previousOasysAssessmentPk!!,
assessment = assessment,
)
val association = slot<OasysAssessment>()
every { oasysAssessmentRepository.save(capture(association)) } returnsArgument 0
every { assessmentVersionService.find(any()) } returns assessmentVersion
val result = oasysAssessmentService.associate(request.oasysAssessmentPk, request.previousOasysAssessmentPk)
assertThat(association.captured.oasysAssessmentPk).isEqualTo(request.oasysAssessmentPk)
assertThat(association.captured.assessment).isEqualTo(assessment)
assertThat(result.uuid).isEqualTo(assessment.uuid)
}
}
@Nested
@DisplayName("lock")
inner class Lock {
@Test
fun `it clones and locks an assessment successfully`() {
val oasysAssessment = OasysAssessment(
oasysAssessmentPk = oasysAssessmentPk,
assessment = assessment,
)
val lockedVersion = AssessmentVersion()
every { oasysAssessmentRepository.findByOasysAssessmentPk(oasysAssessmentPk) } returns oasysAssessment
every { assessmentVersionService.find(match { it.assessmentUuid == assessment.uuid }) } returns assessmentVersion
every { assessmentVersionService.cloneAndTag(assessmentVersion, Tag.LOCKED_INCOMPLETE) } returns lockedVersion
val result = oasysAssessmentService.lock(oasysAssessmentPk)
verify(exactly = 1) { assessmentVersionService.cloneAndTag(assessmentVersion, Tag.LOCKED_INCOMPLETE) }
assertThat(result).isEqualTo(lockedVersion)
}
@Test
fun `it throws an exception when the assessment is already locked`() {
val oasysAssessment = OasysAssessment(
oasysAssessmentPk = oasysAssessmentPk,
assessment = assessment,
)
val lockedVersion = AssessmentVersion(
assessment = assessment,
tag = Tag.LOCKED_INCOMPLETE,
)
every { oasysAssessmentRepository.findByOasysAssessmentPk(oasysAssessmentPk) } returns oasysAssessment
every { assessmentVersionService.find(match { it.assessmentUuid == assessment.uuid }) } returns lockedVersion
every { assessmentVersionService.cloneAndTag(any(), any()) } throws RuntimeException()
assertThrows<OasysAssessmentAlreadyLockedException> { oasysAssessmentService.lock(oasysAssessmentPk) }
verify(exactly = 0) { assessmentVersionService.cloneAndTag(any(), any()) }
}
@Test
fun `it throws an exception when no OASys assessment is found`() {
every {
oasysAssessmentRepository.findByOasysAssessmentPk(oasysAssessmentPk)
} throws OasysAssessmentNotFoundException("1234567890")
assertThrows<OasysAssessmentNotFoundException> { oasysAssessmentService.lock(oasysAssessmentPk) }
verify(exactly = 0) { assessmentVersionService.cloneAndTag(any(), any()) }
}
}
}
| 1 | Kotlin | 0 | 0 | 955a4f5b5a14cd29412430927741dd1f2f8b8f43 | 9,591 | hmpps-strengths-based-needs-assessments-api | MIT License |
src/main/kotlin/com/cimbul/faqueldb/session/CommitTransactionResult.kt | cimbul | 398,552,580 | false | null | package com.cimbul.faqueldb.session
data class CommitTransactionResult(
val transactionId: String,
val commitDigest: Bytes,
val timingInformation: TimingInformation = TimingInformation(),
val consumedIOs: IOUsage = IOUsage(),
)
| 0 | Kotlin | 0 | 3 | 7b187f1e0f3df10f1f98beb16c702ebcf981d5ef | 245 | FaqueLDB | Apache License 2.0 |
mobile-common-lib/src/commonMain/kotlin/fi/riista/common/domain/srva/model/CommonSrvaSpecimen.kt | suomenriistakeskus | 78,840,058 | false | null | package fi.riista.common.domain.srva.model
import fi.riista.common.domain.model.CommonSpecimenData
import fi.riista.common.domain.model.GameAge
import fi.riista.common.domain.model.Gender
import fi.riista.common.model.BackendEnum
import kotlinx.serialization.Serializable
@Serializable
data class CommonSrvaSpecimen(
val gender: BackendEnum<Gender>,
val age: BackendEnum<GameAge>,
)
internal fun CommonSrvaSpecimen.toCommonSpecimenData(): CommonSpecimenData {
return CommonSpecimenData(
gender = gender,
age = age,
)
} | 0 | Kotlin | 0 | 3 | 0115971fb26453c56eb091e319cabed30decd9bb | 553 | oma-riista-android | MIT License |
app/src/main/java/com/livewire/audax/utils/CustomDialog.kt | HDSANAULLAHS | 466,947,990 | false | {"Kotlin": 211156, "Java": 919} | package com.livewire.audax.utils
import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.graphics.BlendMode
import android.graphics.BlendModeColorFilter
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import android.os.Build
import android.view.View
import com.livewire.audax.R
import kotlinx.android.synthetic.main.alert_dialog.view.*
class CustomDialog {
lateinit var dialog: CustomDialog
fun show(context: Context): Dialog {
return show(context, null)
}
fun show(context: Context, title: CharSequence?): Dialog {
val inflater = (context as Activity).layoutInflater
val view = inflater.inflate(R.layout.alert_dialog, null)
view.loadingShade.visibility= View.GONE
view.loading.visibility= View.VISIBLE
dialog = CustomDialog(context)
dialog.setContentView(view)
dialog.show()
return dialog
}
private fun setColorFilter(drawable: Drawable, color: Int) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
drawable.colorFilter = BlendModeColorFilter(color, BlendMode.SRC_ATOP)
} else {
@Suppress("DEPRECATION")
drawable.setColorFilter(color, PorterDuff.Mode.SRC_ATOP)
}
}
fun dismiss(context: Context): Dialog {
val inflater = (context as Activity).layoutInflater
val view = inflater.inflate(R.layout.alert_dialog, null)
view.loadingShade.visibility = View.GONE
view.loading.visibility = View.GONE
dialog.dismiss()
return dialog
}
class CustomDialog(context: Context) : Dialog(context, R.style.CustomDialogTheme) {
init {
// Set Semi-Transparent Color for Dialog Background
window?.decorView?.rootView?.setBackgroundResource(R.color.dialogBackground)
window?.decorView?.setOnApplyWindowInsetsListener { _, insets ->
insets.consumeSystemWindowInsets()
}
}
}
} | 0 | Kotlin | 0 | 0 | 356cfa88f3685882abd1336398defe12ea04f93f | 2,044 | Livewire | Apache License 2.0 |
serialization-msgpack/src/commonTest/kotlin/com/ensarsarajcic/kotlinx/serialization/msgpack/utils/ByteArrayUtilsKtTest.kt | esensar | 302,655,232 | false | null | package com.ensarsarajcic.kotlinx.serialization.msgpack.utils
import kotlin.test.Test
import kotlin.test.assertContentEquals
import kotlin.test.assertEquals
internal class ByteArrayUtilsKtTest {
private val byteTestPairs = arrayOf(
1.toByte() to byteArrayOf(0x01),
0.toByte() to byteArrayOf(0x00),
Byte.MAX_VALUE to byteArrayOf(Byte.MAX_VALUE),
Byte.MIN_VALUE to byteArrayOf(Byte.MIN_VALUE)
)
private val shortTestPairs = arrayOf(
1.toShort() to byteArrayOf(0x00, 0x01),
0.toShort() to byteArrayOf(0x00, 0x00),
Byte.MAX_VALUE.toShort() to byteArrayOf(0x00, Byte.MAX_VALUE),
256.toShort() to byteArrayOf(0x01, 0x00),
(-128).toShort() to byteArrayOf(0xff.toByte(), 0x80.toByte()),
Short.MAX_VALUE to byteArrayOf(0x7f, 0xff.toByte()),
Short.MIN_VALUE to byteArrayOf(0x80.toByte(), 0x00),
)
private val intTestPairs = arrayOf(
65536 to byteArrayOf(0x00, 0x01, 0x00, 0x00),
-65000 to byteArrayOf(0xff.toByte(), 0xff.toByte(), 0x02, 0x18),
-32769 to byteArrayOf(0xff.toByte(), 0xff.toByte(), 0x7f, 0xff.toByte()),
Int.MAX_VALUE to byteArrayOf(0x7f, 0xff.toByte(), 0xff.toByte(), 0xff.toByte()),
Int.MIN_VALUE to byteArrayOf(0x80.toByte(), 0x00, 0x00, 0x00)
)
private val longTestPairs = arrayOf(
4294967296 to byteArrayOf(0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00),
5000000000 to byteArrayOf(0x00, 0x00, 0x00, 0x01, 0x2a, 0x05, 0xf2.toByte(), 0x00),
9223372036854775807 to byteArrayOf(
0x7f, 0xff.toByte(), 0xff.toByte(),
0xff.toByte(), 0xff.toByte(), 0xff.toByte(), 0xff.toByte(), 0xff.toByte()
),
-2147483649 to byteArrayOf(
0xff.toByte(), 0xff.toByte(), 0xff.toByte(), 0xff.toByte(),
0x7f.toByte(), 0xff.toByte(), 0xff.toByte(), 0xff.toByte()
),
-5000000000 to byteArrayOf(
0xff.toByte(), 0xff.toByte(), 0xff.toByte(), 0xfe.toByte(),
0xd5.toByte(), 0xfa.toByte(), 0x0e.toByte(), 0x00.toByte()
)
)
@Test
fun testSplitToByteArrayByte() {
testSplitToByteArrayPairs(byteTestPairs)
}
@Test
fun testJoinToNumberByte() {
testJoinToNumberPairs(byteTestPairs)
}
@Test
fun testSplitToByteArrayShort() {
testSplitToByteArrayPairs(shortTestPairs)
}
@Test
fun testJoinToNumberShort() {
testJoinToNumberPairs(shortTestPairs)
}
@Test
fun testSplitToByteArrayInt() {
testSplitToByteArrayPairs(intTestPairs)
}
@Test
fun testJoinToNumberInt() {
testJoinToNumberPairs(intTestPairs)
}
@Test
fun testSplitToByteArrayLong() {
testSplitToByteArrayPairs(longTestPairs)
}
@Test
fun testJoinToNumberLong() {
testJoinToNumberPairs(longTestPairs)
}
private inline fun <reified T : Number> testSplitToByteArrayPairs(pairs: Array<Pair<T, ByteArray>>) {
pairs.forEach { (number, expected) ->
val result = number.splitToByteArray()
assertContentEquals(expected, result)
}
}
private inline fun <reified T : Number> testJoinToNumberPairs(pairs: Array<Pair<T, ByteArray>>) {
pairs.forEach { (expected, array) ->
val result = array.joinToNumber<T>()
assertEquals(expected, result)
}
}
}
| 8 | null | 9 | 44 | 784c827e913eb07dd7dc14388e9f29d51e9966f1 | 3,417 | kotlinx-serialization-msgpack | MIT License |
features/moviedetails/src/main/java/com/dhorowitz/openmovie/moviedetails/domain/MovieDetailsDomainMapper.kt | horowitz | 328,383,283 | false | null | package com.dhorowitz.openmovie.moviedetails.domain
import com.dhorowitz.openmovie.moviedetails.data.model.MovieDetailsDTO
import com.dhorowitz.openmovie.moviedetails.domain.model.MovieDetails
fun MovieDetailsDTO.toMovieDetails(): MovieDetails = MovieDetails(
id = id,
title = title,
posterPath = "https://image.tmdb.org/t/p/w500$posterPath",
backdropPath = "https://image.tmdb.org/t/p/w500$backdropPath",
overview = overview,
homepage = homepage,
voteAverage = voteAverage,
runtime = runtime,
imdbUrl = "https://www.imdb.com/title/$imdbId"
) | 6 | Kotlin | 3 | 7 | ea7a96fdde555ecd9cce0326149bdf6c9c2b55da | 580 | openMovie | MIT License |
app/src/main/java/com/cookmefsm/features/menuBeat/MenuBeatRepository.kt | DebashisINT | 541,930,486 | false | {"Kotlin": 13445429, "Java": 993208} | package com.cookmefsm.features.menuBeat
import android.content.Context
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import com.fasterxml.jackson.databind.ObjectMapper
import com.cookmefsm.app.FileUtils
import com.cookmefsm.app.Pref
import com.cookmefsm.base.BaseResponse
import com.cookmefsm.features.addshop.model.*
import com.cookmefsm.features.addshop.model.assigntopplist.AddShopUploadImg
import com.cookmefsm.features.addshop.model.assigntopplist.AddshopImageMultiReqbody1
import com.cookmefsm.features.addshop.presentation.ShopListSubmitResponse
import com.cookmefsm.features.addshop.presentation.multiContactRequestData
import com.cookmefsm.features.beatCustom.BeatGetStatusModel
import com.cookmefsm.features.dashboard.presentation.DashboardActivity
import com.google.gson.Gson
import io.reactivex.Observable
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
/**
* Created by saheli on 16-12-2023.
*/
class MenuBeatRepository(val apiService: MenuBeatApi) {
fun currentTabMenubeat(sessiontoken: String, user_id: String, beat_id: String): Observable<MenuBeatResponse> {
return apiService.getCurrentTabData(user_id,sessiontoken,beat_id)
}
fun hirerchyTabMenubeat(sessiontoken: String, user_id: String): Observable<MenuBeatAreaRouteResponse> {
return apiService.getHirerchyTabData(user_id,sessiontoken)
}
} | 0 | Kotlin | 0 | 0 | 1f48da873d81959e9dbf1727e3b0d1cda4a1be63 | 1,431 | Cookme | Apache License 2.0 |
src/main/kotlin/org/opensearch/replication/action/repository/TransportReleaseLeaderResourcesAction.kt | opensearch-project | 323,830,219 | false | {"Kotlin": 1005221, "Python": 17931, "Shell": 8517} | /*
* SPDX-License-Identifier: Apache-2.0
*
* The OpenSearch Contributors require contributions made to
* this file be licensed under the Apache-2.0 license or a
* compatible open source license.
*
* Modifications Copyright OpenSearch Contributors. See
* GitHub history for details.
*/
package org.opensearch.replication.action.repository
import org.opensearch.replication.repository.RemoteClusterRestoreLeaderService
import org.apache.logging.log4j.LogManager
import org.opensearch.action.support.ActionFilters
import org.opensearch.action.support.master.AcknowledgedResponse
import org.opensearch.action.support.single.shard.TransportSingleShardAction
import org.opensearch.cluster.ClusterState
import org.opensearch.cluster.metadata.IndexNameExpressionResolver
import org.opensearch.cluster.routing.ShardsIterator
import org.opensearch.cluster.service.ClusterService
import org.opensearch.common.inject.Inject
import org.opensearch.common.io.stream.StreamInput
import org.opensearch.common.io.stream.Writeable
import org.opensearch.index.shard.ShardId
import org.opensearch.threadpool.ThreadPool
import org.opensearch.transport.TransportActionProxy
import org.opensearch.transport.TransportService
class TransportReleaseLeaderResourcesAction @Inject constructor(threadPool: ThreadPool, clusterService: ClusterService,
transportService: TransportService, actionFilters: ActionFilters,
indexNameExpressionResolver: IndexNameExpressionResolver,
private val restoreLeaderService: RemoteClusterRestoreLeaderService) :
TransportSingleShardAction<ReleaseLeaderResourcesRequest, AcknowledgedResponse>(ReleaseLeaderResourcesAction.NAME,
threadPool, clusterService, transportService, actionFilters,
indexNameExpressionResolver, ::ReleaseLeaderResourcesRequest, ThreadPool.Names.GET) {
init {
TransportActionProxy.registerProxyAction(transportService, ReleaseLeaderResourcesAction.NAME, ::AcknowledgedResponse)
}
companion object {
private val log = LogManager.getLogger(TransportReleaseLeaderResourcesAction::class.java)
}
override fun shardOperation(request: ReleaseLeaderResourcesRequest, shardId: ShardId): AcknowledgedResponse {
log.info("Releasing resources for $shardId with restore-id as ${request.restoreUUID}")
restoreLeaderService.removeLeaderClusterRestore(request.restoreUUID)
return AcknowledgedResponse(true)
}
override fun resolveIndex(request: ReleaseLeaderResourcesRequest?): Boolean {
return true
}
override fun getResponseReader(): Writeable.Reader<AcknowledgedResponse> {
return Writeable.Reader { inp: StreamInput -> AcknowledgedResponse(inp) }
}
override fun shards(state: ClusterState, request: InternalRequest): ShardsIterator? {
return state.routingTable().shardRoutingTable(request.request().leaderShardId).primaryShardIt()
}
}
| 83 | Kotlin | 58 | 48 | 0cc41c620b96a4798adbe2237e48b67269e3e509 | 3,107 | cross-cluster-replication | Apache License 2.0 |
src/test/kotlin/com/fasterxml/jackson/module/kotlin/test/github/Github490.kt | FasterXML | 23,404,083 | false | null | package com.fasterxml.jackson.module.kotlin.test.github
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.node.NullNode
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import org.hamcrest.CoreMatchers
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Test
class TestGithub490 {
val mapper = jacksonObjectMapper()
val value: DataClassWithAllNullableParams = mapper.readValue(
"{" +
"\"jsonNodeValueWithNullAsDefaultProvidedNull\":null, " +
"\"jsonNodeValueProvidedNull\":null}"
)
@Test
fun testKotlinDeserialization_intValue() {
assertThat(
"Nullable missing Int value should be deserialized as null",
value.intValue,
CoreMatchers.nullValue()
)
}
@Test
fun testKotlinDeserialization_stringValue() {
assertThat(
"Nullable missing String value should be deserialized as null",
value.stringValue,
CoreMatchers.nullValue()
)
}
@Test
fun testKotlinDeserialization_jsonNodeValue() {
assertThat(
"Nullable missing JsonNode value should be deserialized as null and not as NullNode",
value.jsonNodeValue,
CoreMatchers.nullValue()
)
}
@Test
fun testKotlinDeserialization_jsonNodeValueProvidedNull() {
assertThat(
"Nullable JsonNode value provided as null should be deserialized as NullNode",
value.jsonNodeValueProvidedNull,
CoreMatchers.equalTo(NullNode.instance)
)
}
@Test
fun testKotlinDeserialization_jsonNodeValueWithNullAsDefault() {
assertThat(
"Nullable by default missing JsonNode value should be deserialized as null and not as NullNode",
value.jsonNodeValueWithNullAsDefault,
CoreMatchers.nullValue()
)
}
@Test
fun testKotlinDeserialization_jsonNodeValueWithNullAsDefaultProvidedNull() {
assertThat(
"Nullable by default JsonNode with provided null value in payload should be deserialized as NullNode",
value.jsonNodeValueWithNullAsDefaultProvidedNull,
CoreMatchers.equalTo(NullNode.instance)
)
}
}
data class DataClassWithAllNullableParams(
val intValue: Int?,
val stringValue: String?,
val jsonNodeValue: JsonNode?,
val jsonNodeValueProvidedNull: JsonNode?,
val jsonNodeValueWithNullAsDefault: JsonNode? = null,
val jsonNodeValueWithNullAsDefaultProvidedNull: JsonNode? = null
)
| 166 | Kotlin | 158 | 932 | fa8ee76a8a00443aa6e8cc401c4e0868219d2d5b | 2,665 | jackson-module-kotlin | Apache License 2.0 |
src/main/kotlin/org/teamvoided/reef/world/gen/configured_feature/LargeCavePillarFeature.kt | TeamVoided | 764,862,779 | false | {"Kotlin": 45534, "Java": 7083} | package org.teamvoided.dusk_autumns_worldgen.worldgen.configured_feature
import com.mojang.serialization.Codec
import net.minecraft.block.Block
import net.minecraft.block.Blocks
import net.minecraft.util.math.BlockPos
import net.minecraft.util.math.Direction
import net.minecraft.util.math.MathHelper
import net.minecraft.util.math.Vec3d
import net.minecraft.util.math.float_provider.FloatProvider
import net.minecraft.util.random.RandomGenerator
import net.minecraft.world.Heightmap
import net.minecraft.world.StructureWorldAccess
import net.minecraft.world.gen.feature.Feature
import net.minecraft.world.gen.feature.util.CaveSurface
import net.minecraft.world.gen.feature.util.CaveSurface.Bounded
import net.minecraft.world.gen.feature.util.FeatureContext
import org.teamvoided.dusk_autumns_worldgen.worldgen.configured_feature.config.LargeCavePillarFeatureConfig
import kotlin.math.min
class LargeCavePillarFeature(codec: Codec<LargeCavePillarFeatureConfig>) :
Feature<LargeCavePillarFeatureConfig>(codec) {
override fun place(context: FeatureContext<LargeCavePillarFeatureConfig>): Boolean {
val structureWorldAccess = context.world
val origin = context.origin
val config = context.config
val random = context.random
if (!CavePillarHelper.canGenerate(structureWorldAccess, origin)) return false
val optional = CaveSurface.create(
structureWorldAccess, origin,
config.floorToCeilingSearchRange,
{ CavePillarHelper.canGenerate(it) },
{ it.isIn(config.canPlaceOn) }
)
if (optional.isEmpty || optional.get() !is Bounded) return false
val bounded = optional.get() as Bounded
if (bounded.height < 4) return false
val i = (bounded.height.toFloat() * config.maxColumnRadiusToCaveHeightRatio).toInt()
val j = MathHelper.clamp(i, config.columnRadius.min, config.columnRadius.max)
val k = MathHelper.nextBetween(random, config.columnRadius.min, j)
val cavePillarGenerator = createGenerator(
config,
origin.withY(bounded.ceiling - 1),
false,
random,
k,
config.stalactiteBluntness,
config.heightScale
)
val cavePillarGenerator2 = createGenerator(
config,
origin.withY(bounded.floor + 1),
true,
random,
k,
config.stalagmiteBluntness,
config.heightScale
)
val windModifier =
if (cavePillarGenerator.generateWind(config) && cavePillarGenerator2.generateWind(config))
WindModifier(origin.y, random, config.windSpeed)
else
WindModifier.create()
if (cavePillarGenerator.canGenerate(structureWorldAccess, windModifier)) {
cavePillarGenerator.generate(structureWorldAccess, random, windModifier)
}
if (cavePillarGenerator2.canGenerate(structureWorldAccess, windModifier)) {
cavePillarGenerator2.generate(structureWorldAccess, random, windModifier)
}
return true
}
internal class CavePillarGenerator(
val config: LargeCavePillarFeatureConfig,
private var pos: BlockPos,
private val isStalagmite: Boolean,
private var scale: Int,
private val bluntness: Double,
private val heightScale: Double
) {
private val baseScale: Int
get() = this.scale(0.0f)
private val bottomY: Int
get() {
if (this.isStalagmite) {
return pos.y
}
return pos.y - this.baseScale
}
private val topY: Int
get() {
if (!this.isStalagmite) {
return pos.y
}
return pos.y + this.baseScale
}
fun canGenerate(world: StructureWorldAccess, wind: WindModifier): Boolean {
while (this.scale > 1) {
val mutable = pos.mutableCopy()
val i = min(10.0, baseScale.toDouble()).toInt()
for (j in 0 until i) {
if (world.getBlockState(mutable).isOf(Blocks.LAVA)) {
return false
}
if (CavePillarHelper.canGenerateBase(world, wind.modify(mutable), this.scale)) {
this.pos = mutable
return true
}
mutable.move(if (this.isStalagmite) Direction.DOWN else Direction.UP)
}
this.scale /= 2
}
return false
}
private fun scale(height: Float): Int {
return CavePillarHelper.scaleHeightFromRadius(
height.toDouble(),
scale.toDouble(), this.heightScale, this.bluntness
).toInt()
}
fun generate(world: StructureWorldAccess, random: RandomGenerator, wind: WindModifier) {
for (i in -this.scale..this.scale) {
block1@ for (j in -this.scale..this.scale) {
var k = 0
val f = MathHelper.sqrt((i * i + j * j).toFloat())
if (f > scale.toFloat() || (scale(f).also {
k = it
}) <= 0) continue
if (random.nextFloat().toDouble() < 0.2) {
k = (k.toFloat() * MathHelper.nextBetween(random, 0.8f, 1.0f)).toInt()
}
val mutable = pos.add(i, 0, j).mutableCopy()
var bl = false
val l = if (this.isStalagmite) world.getTopY(
Heightmap.Type.WORLD_SURFACE_WG,
mutable.x,
mutable.z
) else Int.MAX_VALUE
var m = 0
while (m < k && mutable.y < l) {
val blockPos = wind.modify(mutable)
if (CavePillarHelper.canGenerateOrLava(world, blockPos)) {
bl = true
world.setBlockState(
blockPos,
config.mainBlock.getBlockState(random, blockPos),
Block.NOTIFY_LISTENERS
)
} else if (bl && world.getBlockState(blockPos)
.isIn(config.canPlaceOn)
) continue@block1
mutable.move(if (this.isStalagmite) Direction.UP else Direction.DOWN)
++m
}
}
}
}
fun generateWind(config: LargeCavePillarFeatureConfig): Boolean {
return this.scale >= config.minRadiusForWind && this.bluntness >= config.minBluntnessForWind.toDouble()
}
}
internal class WindModifier {
private val y: Int
private val wind: Vec3d?
constructor(y: Int, random: RandomGenerator?, windSpeed: FloatProvider) {
this.y = y
val f = windSpeed[random]
val g = MathHelper.nextBetween(random, 0.0f, Math.PI.toFloat())
this.wind = Vec3d((MathHelper.cos(g) * f).toDouble(), 0.0, (MathHelper.sin(g) * f).toDouble())
}
private constructor() {
this.y = 0
this.wind = null
}
fun modify(pos: BlockPos): BlockPos {
if (this.wind == null) {
return pos
}
val i = this.y - pos.y
val vec3d = wind.multiply(i.toDouble())
return pos.add(MathHelper.floor(vec3d.x), 0, MathHelper.floor(vec3d.z))
}
companion object {
fun create(): WindModifier {
return WindModifier()
}
}
}
companion object {
private fun createGenerator(
config: LargeCavePillarFeatureConfig,
pos: BlockPos,
isStalagmite: Boolean,
random: RandomGenerator,
scale: Int,
bluntness: FloatProvider,
heightScale: FloatProvider
): CavePillarGenerator {
return CavePillarGenerator(
config, pos, isStalagmite, scale,
bluntness[random].toDouble(),
heightScale[random].toDouble()
)
}
}
} | 0 | Kotlin | 0 | 0 | 70b3cf3622aab9f5ba03ff33aa83456b779a111b | 8,534 | Reef | MIT License |
vkprimer/08-oop-test/src/main/kotlin/AluBfm.kt | frwang96 | 416,809,961 | false | null | /*
* SPDX-License-Identifier: Apache-2.0
*/
@file:Verik
import dut.Op
import io.verik.core.*
class AluBfm : ModuleInterface() {
var clk: Boolean = nc()
var reset_n: Boolean = nc()
var a: Ubit<`8`> = nc()
var b: Ubit<`8`> = nc()
var op: Op = nc()
var start: Boolean = nc()
var done: Boolean = nc()
var result: Ubit<`16`> = nc()
@Run
fun runClk() {
clk = false
repeat(1000) {
delay(10)
clk = !clk
}
println("FAIL timeout")
fatal()
}
@Task
fun resetAlu() {
reset_n = false
repeat(2) { wait(negedge(clk)) }
reset_n = true
start = false
}
@Task
fun sendOp(next_a: Ubit<`8`>, next_b: Ubit<`8`>, next_op: Op) {
op = next_op
if (next_op == Op.RST) {
wait(posedge(clk))
reset_n = false
start = false
wait(posedge(clk))
delay(1)
reset_n = true
} else {
wait(negedge(clk))
a = next_a
b = next_b
start = true
if (next_op == Op.NOP) {
wait(posedge(clk))
delay(1)
} else {
do { wait(negedge(clk)) } while (!done)
}
start = false
}
}
}
| 0 | Kotlin | 1 | 5 | 9a0f5f79b824e69a33dc4f9717d3b9e3ed103180 | 1,342 | verik-examples | Apache License 2.0 |
app/src/main/java/com/starry/greenstash/ui/screens/home/composables/GoalLazyItem.kt | Pool-Of-Tears | 500,278,038 | false | {"Kotlin": 583303} | /**
* MIT License
*
* Copyright (c) [2022 - Present] <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.starry.greenstash.ui.screens.home.composables
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.material3.SnackbarDuration
import androidx.compose.material3.SnackbarHostState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalView
import androidx.compose.ui.unit.dp
import androidx.navigation.NavController
import com.starry.greenstash.MainActivity
import com.starry.greenstash.R
import com.starry.greenstash.database.core.GoalWithTransactions
import com.starry.greenstash.database.transaction.TransactionType
import com.starry.greenstash.ui.navigation.Screens
import com.starry.greenstash.ui.screens.home.GoalCardStyle
import com.starry.greenstash.ui.screens.home.HomeViewModel
import com.starry.greenstash.utils.Constants
import com.starry.greenstash.utils.GoalTextUtils
import com.starry.greenstash.utils.ImageUtils
import com.starry.greenstash.utils.Utils
import com.starry.greenstash.utils.getActivity
import com.starry.greenstash.utils.strongHapticFeedback
import com.starry.greenstash.utils.weakHapticFeedback
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
@Composable
fun GoalLazyColumnItem(
viewModel: HomeViewModel,
item: GoalWithTransactions,
snackBarHostState: SnackbarHostState,
coroutineScope: CoroutineScope,
navController: NavController,
currentIndex: Int
) {
val context = LocalContext.current
val settingsVM = (context.getActivity() as MainActivity).settingsViewModel
val goalCardStyle = settingsVM.goalCardStyle.observeAsState().value!!
val isGoalCompleted = remember(item.goal.goalId) {
item.getCurrentlySavedAmount() >= item.goal.targetAmount
}
val progressPercent = remember(item.goal.goalId) {
((item.getCurrentlySavedAmount() / item.goal.targetAmount) * 100).toInt()
}
val openDeleteDialog = remember { mutableStateOf(false) }
val openArchiveDialog = remember { mutableStateOf(false) }
val localView = LocalView.current
when (goalCardStyle) {
GoalCardStyle.Classic -> {
GoalItemClassic(title = item.goal.title,
primaryText = GoalTextUtils.buildPrimaryText(
context = context,
progressPercent = progressPercent,
goalItem = item,
currencyCode = viewModel.getDefaultCurrency()
),
secondaryText = GoalTextUtils.buildSecondaryText(
context = context,
goalItem = item,
currencyCode = viewModel.getDefaultCurrency(),
datePattern = viewModel.getDateFormatPattern()
),
goalProgress = progressPercent.toFloat() / 100,
goalImage = item.goal.goalImage,
isGoalCompleted = isGoalCompleted,
onDepositClicked = {
localView.weakHapticFeedback()
if (item.getCurrentlySavedAmount() >= item.goal.targetAmount) {
coroutineScope.launch {
snackBarHostState.showSnackbar(context.getString(R.string.goal_already_achieved))
}
} else {
navController.navigate(
Screens.DWScreen.withGoalId(
goalId = item.goal.goalId.toString(),
trasactionType = TransactionType.Deposit.name
)
)
}
},
onWithdrawClicked = {
localView.weakHapticFeedback()
if (item.getCurrentlySavedAmount() == 0f.toDouble()) {
coroutineScope.launch {
snackBarHostState.showSnackbar(context.getString(R.string.withdraw_button_error))
}
} else {
navController.navigate(
Screens.DWScreen.withGoalId(
goalId = item.goal.goalId.toString(),
trasactionType = TransactionType.Withdraw.name
)
)
}
},
onInfoClicked = {
localView.weakHapticFeedback()
navController.navigate(
Screens.GoalInfoScreen.withGoalId(
goalId = item.goal.goalId.toString()
)
)
},
onEditClicked = {
localView.weakHapticFeedback()
navController.navigate(
Screens.InputScreen.withGoalToEdit(
goalId = item.goal.goalId.toString()
)
)
},
onDeleteClicked = {
localView.strongHapticFeedback()
openDeleteDialog.value = true
},
onArchivedClicked = {
localView.weakHapticFeedback()
openArchiveDialog.value = true
}
)
}
GoalCardStyle.Compact -> {
if (currentIndex == 0) {
Spacer(modifier = Modifier.height(5.dp))
}
val goalIcon by remember(item.goal.goalIconId) {
mutableStateOf(
ImageUtils.createIconVector(
item.goal.goalIconId ?: Constants.DEFAULT_GOAL_ICON_ID
)!!
)
}
GoalItemCompact(
title = item.goal.title,
savedAmount = Utils.formatCurrency(
item.getCurrentlySavedAmount(),
viewModel.getDefaultCurrency()
),
daysLeftText = GoalTextUtils.getRemainingDaysText(
context = context,
goalItem = item,
datePattern = viewModel.getDateFormatPattern()
),
goalProgress = progressPercent.toFloat() / 100,
goalIcon = goalIcon,
isGoalCompleted = isGoalCompleted,
onDepositClicked = {
localView.weakHapticFeedback()
if (item.getCurrentlySavedAmount() >= item.goal.targetAmount) {
coroutineScope.launch {
snackBarHostState.showSnackbar(context.getString(R.string.goal_already_achieved))
}
} else {
navController.navigate(
Screens.DWScreen.withGoalId(
goalId = item.goal.goalId.toString(),
trasactionType = TransactionType.Deposit.name
)
)
}
},
onWithdrawClicked = {
localView.weakHapticFeedback()
if (item.getCurrentlySavedAmount() == 0f.toDouble()) {
coroutineScope.launch {
snackBarHostState.showSnackbar(context.getString(R.string.withdraw_button_error))
}
} else {
navController.navigate(
Screens.DWScreen.withGoalId(
goalId = item.goal.goalId.toString(),
trasactionType = TransactionType.Withdraw.name
)
)
}
},
onInfoClicked = {
localView.weakHapticFeedback()
navController.navigate(
Screens.GoalInfoScreen.withGoalId(
goalId = item.goal.goalId.toString()
)
)
},
onEditClicked = {
localView.weakHapticFeedback()
navController.navigate(
Screens.InputScreen.withGoalToEdit(
goalId = item.goal.goalId.toString()
)
)
},
onDeleteClicked = {
localView.strongHapticFeedback()
openDeleteDialog.value = true
},
onArchivedClicked = {
localView.weakHapticFeedback()
openArchiveDialog.value = true
}
)
}
}
HomeDialogs(
openDeleteDialog = openDeleteDialog,
openArchiveDialog = openArchiveDialog,
onDeleteConfirmed = {
viewModel.deleteGoal(item.goal)
coroutineScope.launch {
snackBarHostState.showSnackbar(
message = context.getString(R.string.goal_delete_success),
actionLabel = context.getString(R.string.ok),
duration = SnackbarDuration.Short
)
}
},
onArchiveConfirmed = {
viewModel.archiveGoal(item.goal)
coroutineScope.launch {
snackBarHostState.showSnackbar(
message = context.getString(R.string.goal_archive_success),
actionLabel = context.getString(R.string.ok),
duration = SnackbarDuration.Short
)
}
}
)
}
| 5 | Kotlin | 50 | 616 | 7f662bcc3f6b1051ec35f8439507d2bb39d7bb99 | 11,202 | GreenStash | MIT License |
src/main/kotlin/com/toasttab/pulseman/view/ViewUtils.kt | open-toast | 399,150,014 | false | {"Kotlin": 300586} | /*
* Copyright (c) 2021 Toast Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.toasttab.pulseman.view
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.padding
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.material.TextField
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.toasttab.pulseman.AppTheme
import com.toasttab.pulseman.entities.ButtonState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
/**
* Reusable UI components
*/
object ViewUtils {
@Composable
fun styledTextField(
label: String,
field: String,
modifier: Modifier,
onValueChange: (String) -> Unit
) = TextField(
label = { Text(label) },
value = field,
onValueChange = onValueChange,
singleLine = true,
modifier = modifier
.background(color = AppTheme.colors.backgroundLight)
.border(2.dp, AppTheme.colors.backgroundMedium)
)
@Composable
fun threadedButton(
scope: CoroutineScope,
activeText: String,
waitingText: String,
buttonState: ButtonState,
onButtonStateChange: (ButtonState) -> Unit,
action: suspend () -> Unit
) {
Button(
modifier = Modifier.padding(4.dp),
enabled = buttonState == ButtonState.WAITING,
onClick = {
if (buttonState == ButtonState.WAITING) {
onButtonStateChange(ButtonState.ACTIVE)
scope.launch {
action()
onButtonStateChange(ButtonState.WAITING)
}
}
}
) {
when (buttonState) {
ButtonState.ACTIVE -> Text(activeText)
ButtonState.WAITING -> Text(waitingText)
}
}
}
}
| 3 | Kotlin | 4 | 8 | e7396fcf17f48008cb77b10f759145377f96b559 | 2,569 | pulseman | Apache License 2.0 |
token-support-tokenx-validation/src/main/kotlin/no/nav/tms/token/support/tokenx/validation/tokendings/tokenAuthentication.kt | navikt | 339,078,199 | false | null | package no.nav.tms.token.support.azure.validation.intercept
import io.ktor.application.*
import io.ktor.auth.*
import io.ktor.http.*
import io.ktor.response.*
import io.ktor.util.pipeline.*
import no.nav.tms.token.support.azure.validation.AzureHeader
import no.nav.tms.token.support.azure.validation.AzurePrincipal
import org.slf4j.LoggerFactory
internal fun Authentication.Configuration.azureAccessToken(authenticatorName: String?, verifier: TokenVerifier) {
val provider = AccessTokenAuthenticationProvider.build(authenticatorName)
val log = LoggerFactory.getLogger(AccessTokenAuthenticationProvider::class.java)
provider.pipeline.intercept(AuthenticationPipeline.RequestAuthentication) { context ->
val accessToken = bearerToken
if (accessToken != null) {
try {
val decodedJWT = verifier.verify(accessToken)
context.principal(AzurePrincipal(decodedJWT))
} catch (e: Exception) {
val message = e.message ?: e.javaClass.simpleName
log.debug("Token verification failed: {}", message)
context.respondUnauthorized("Invalid or expired token.")
}
} else {
log.debug("No bearer token found.")
context.respondUnauthorized("No bearer token found.")
}
}
register(provider)
}
private fun AuthenticationContext.respondUnauthorized(message: String) {
challenge("JWTAuthKey", AuthenticationFailedCause.InvalidCredentials) {
call.respond(HttpStatusCode.Unauthorized, message)
it.complete()
}
}
private val bearerRegex = "Bearer .+".toRegex()
private val PipelineContext<*, ApplicationCall>.bearerToken: String? get() {
return tokenFromAzureHeader(call)
?: tokenFromAuthHeader(call)
}
private fun tokenFromAzureHeader(call: ApplicationCall): String? {
return call.request.headers[AzureHeader.Authorization]
?.takeIf { bearerRegex.matches(it) }
?.let { it.split(" ")[1] }
}
private fun tokenFromAuthHeader(call: ApplicationCall): String? {
return call.request.headers[HttpHeaders.Authorization]
?.takeIf { bearerRegex.matches(it) }
?.let { it.split(" ")[1] }
}
private class AccessTokenAuthenticationProvider constructor(config: Configuration) : AuthenticationProvider(config) {
class Configuration(name: String?) : AuthenticationProvider.Configuration(name)
companion object {
fun build(name: String?) = AccessTokenAuthenticationProvider(Configuration(name))
}
}
| 0 | Kotlin | 1 | 1 | 9af53ab1fe7637918f8cd8612a76c213f07d34cf | 2,551 | tms-ktor-token-support | MIT License |
app/src/main/java/com/jcl/exam/emapta/data/db/entities/AccountCurrency.kt | jaylumba | 204,916,908 | false | {"Gradle": 3, "Java Properties": 2, "Shell": 1, "Ignore List": 2, "Batchfile": 1, "Markdown": 1, "Proguard": 1, "Kotlin": 47, "XML": 30, "Java": 2, "C++": 1, "CMake": 1} | package com.jcl.exam.emapta.data.db.entities
data class AccountCurrency(val id: Long,
val currency_id: Long,
val desc: String,
val symbol: String,
var amount: Double) | 1 | null | 1 | 1 | 3b3ae7ae32b22b650e9c4c2302f987bc27876393 | 275 | currency-converter-exam | Apache License 2.0 |
spring/mongo/src/test/kotlin/de/welcz/springmongo/ApplicationTests.kt | enolive | 65,559,078 | false | null | package com.isystk.sample.web.admin
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.extension.ExtendWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.junit.jupiter.SpringExtension
@ExtendWith(SpringExtension::class)
@SpringBootTest
class ApplicationTests {
@Test
fun contextLoads() {
}
} | 9 | null | 6 | 9 | f01141469ac86352f8dc511579ead10dc7563413 | 371 | learning | MIT License |
app/src/main/java/com/ozantopuz/tvshows/util/extension/ImageViewExt.kt | ozantopuz | 385,980,927 | false | null | package com.ozantopuz.tvshows.util.extension
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.ozantopuz.tvshows.R
fun ImageView.loadImage(url: String?) {
url?.let {
Glide.with(this)
.load(BASE_IMAGE_URL + url)
.into(this)
} ?: kotlin.run {
setImageResource(R.drawable.ic_placeholder)
}
}
const val BASE_IMAGE_URL = "https://image.tmdb.org/t/p/w500" | 0 | Kotlin | 0 | 0 | 5bdd206c2e6d53e93af66b8c9a504e2faa933d7a | 429 | TvShows | MIT License |
src/commonMain/kotlin/com/quickbirdstudios/nonEmptyCollection/list/NonEmptyList+plus.kt | ragnese | 352,809,864 | true | {"Kotlin": 64364} | package com.quickbirdstudios.nonEmptyCollection.list
operator fun <T> NonEmptyList<T>.plus(value: T): NonEmptyList<T> = NonEmptyList(full + value)
operator fun <T> List<T>.plus(value: T): NonEmptyList<T> = NonEmptyList(this as Collection<T> + value)
operator fun <T> NonEmptyList<T>.plus(other: List<T>): NonEmptyList<T> = NonEmptyList(full as Collection<T> + other)
operator fun <T> List<T>.plus(
other: NonEmptyList<T>
): NonEmptyList<T> = NonEmptyList(this as Collection<T> + other.full)
operator fun <T> NonEmptyList<T>.plus(
other: NonEmptyList<T>
): NonEmptyList<T> = NonEmptyList(full as Collection<T> + other.full)
operator fun <T> NonEmptyList<T>.plus(
other: Iterable<T>
): NonEmptyList<T> = this + other.toList()
operator fun <T> NonEmptyList<T>.plus(
other: Sequence<T>
): NonEmptyList<T> = this + other.toList()
operator fun <T> NonEmptyList<T>.plus(
other: Array<T>
): NonEmptyList<T> = this + other.toList()
| 0 | Kotlin | 0 | 0 | 8397001e6f104e35f940ad8a0c7b56a3a714b289 | 951 | NonEmptyCollections | MIT License |
plugin/reporting/src/main/kotlin/com/android/build/gradle/internal/test/report/ResilientTestReport.kt | TWiStErRob | 116,494,236 | false | null | package com.android.build.gradle.internal.test.report
import java.io.File
/**
* This class is the bridge between the public world and AGP's internals.
*/
class ResilientTestReport(
reportType: ReportType,
resultDir: File,
reportDir: File
) : TestReport(reportType, resultDir, reportDir) {
override fun generateReport(): CompositeTestResults {
val model = loadModel()
val allClassResults = model.packages.flatMap { it.classes }
allClassResults.forEach(::polyfillResults)
generateFiles(model)
return model
}
private fun polyfillResults(classResults: ClassTestResults) {
val results = classResults.testResultsMap
val template = results.values.first().values.first()
for (testName in results.flatMap { it.value.keys }) {
for (device in results.keys) {
if (!results.getValue(device).containsKey(testName)) {
val test = classResults.addTest(
testName, 0, device, template.project, template.flavor
)
test.ignoredCompat(device, template.project, template.flavor)
//test.addFailure("Missing run data", "N/A", device, template.project, template.flavor)
}
}
}
}
/**
* Internal AGP API not designed for extensibility, so need to hack around a bit.
*/
companion object {
/**
* @see TestReport.loadModel
*/
private fun TestReport.loadModel(): AllTestResults =
TestReport::class.java.getDeclaredMethod("loadModel")
.apply { isAccessible = true }
.invoke(this) as AllTestResults
/**
* @see TestReport.generateFiles
*/
private fun TestReport.generateFiles(model: AllTestResults) {
TestReport::class.java.getDeclaredMethod("generateFiles", AllTestResults::class.java)
.apply { isAccessible = true }
.invoke(this, model)
}
}
}
| 87 | Kotlin | 5 | 7 | 8b6a2f50388252515cfd166d20cc70c1b8d4547d | 1,733 | net.twisterrob.gradle | MIT License |
app/src/main/java/com/alpriest/energystats/ui/login/LoginView.kt | alpriest | 606,081,400 | false | null | package com.alpriest.energystats.ui.login
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.material.MaterialTheme.colors
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Visibility
import androidx.compose.material.icons.filled.VisibilityOff
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.alpriest.energystats.ui.theme.EnergyStatsTheme
import java.text.SimpleDateFormat
import java.util.*
@Composable
fun CredentialsView(
errorMessage: String?,
onLogin: (String, String) -> Unit,
onDemoLogin: () -> Unit
) {
var username by rememberSaveable { mutableStateOf("") }
var password by rememberSaveable { mutableStateOf("") }
var showPassword by remember { mutableStateOf(false) }
Column(
verticalArrangement = Arrangement.Center,
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier
.fillMaxSize()
) {
Text(
"Enter your FoxESS Cloud details",
fontWeight = FontWeight.Bold
)
OutlinedTextField(
value = username,
onValueChange = { username = it },
label = { Text("Username") }
)
OutlinedTextField(
value = password,
onValueChange = { password = it },
label = { Text("Password") },
visualTransformation = if (showPassword) VisualTransformation.None else PasswordVisualTransformation(),
keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password),
trailingIcon = {
val (icon, iconColor) = if (showPassword) {
Pair(
Icons.Filled.Visibility,
colors.primary
)
} else {
Pair(
Icons.Filled.VisibilityOff,
Color.Gray
)
}
IconButton(onClick = { showPassword = !showPassword }) {
Icon(
icon,
contentDescription = "Visibility",
tint = iconColor
)
}
},
)
errorMessage?.let {
Text(
it,
Modifier
.padding(top = 24.dp)
.padding(horizontal = 24.dp),
color = Color.Red
)
}
Row(
modifier = Modifier
.align(Alignment.CenterHorizontally)
.padding(top = 24.dp)
) {
Button(
colors = ButtonDefaults.buttonColors(backgroundColor = Color.LightGray),
onClick = onDemoLogin
) {
Text(
"Try demo",
color = colors.onSecondary
)
}
Spacer(modifier = Modifier.width(24.dp))
Button(onClick = {
onLogin(username, password)
}) {
Text(
"Log me in",
color = colors.onPrimary
)
}
}
}
}
@Preview(showBackground = true)
@Composable
fun CredentialsViewPreview() {
EnergyStatsTheme {
CredentialsView(
errorMessage = "You got something wrong",
onLogin = { _, _ -> },
onDemoLogin = {}
)
}
}
| 6 | null | 3 | 3 | ac10ab887c6145c4e326f68261091a264b654a25 | 4,079 | EnergyStats-Android | MIT License |
platform/testFramework/src/com/intellij/testFramework/FixtureRule.kt | hieuprogrammer | 284,920,751 | false | 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 com.intellij.testFramework
import com.intellij.configurationStore.LISTEN_SCHEME_VFS_CHANGES_IN_TEST_MODE
import com.intellij.ide.highlighter.ProjectFileType
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.AccessToken
import com.intellij.openapi.application.AppUIExecutor
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.impl.coroutineDispatchingContext
import com.intellij.openapi.application.runUndoTransparentWriteAction
import com.intellij.openapi.command.impl.UndoManagerImpl
import com.intellij.openapi.command.undo.DocumentReferenceManager
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.components.impl.stores.IProjectStore
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ex.ProjectEx
import com.intellij.openapi.project.ex.ProjectManagerEx
import com.intellij.openapi.project.impl.ProjectManagerImpl
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.impl.VirtualFilePointerTracker
import com.intellij.project.TestProjectManager
import com.intellij.project.stateStore
import com.intellij.util.containers.forEachGuaranteed
import com.intellij.util.io.sanitizeFileName
import com.intellij.util.throwIfNotEmpty
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import org.jetbrains.annotations.ApiStatus
import org.junit.rules.ExternalResource
import org.junit.rules.TestRule
import org.junit.runner.Description
import org.junit.runners.model.Statement
import java.nio.file.Path
private var sharedModule: Module? = null
open class ApplicationRule : TestRule {
companion object {
init {
Logger.setFactory(TestLoggerFactory::class.java)
}
}
final override fun apply(base: Statement, description: Description): Statement? {
return object : Statement() {
override fun evaluate() {
before(description)
try {
base.evaluate()
}
finally {
after()
}
}
}
}
protected open fun before(description: Description) {
TestApplicationManager.getInstance()
}
protected open fun after() {
}
}
/**
* Rule should be used only and only if you open projects in a custom way in test cases and cannot use [ProjectRule].
*/
class ProjectTrackingRule : TestRule {
override fun apply(base: Statement, description: Description): Statement? {
return object : Statement() {
override fun evaluate() {
(ProjectManager.getInstance() as TestProjectManager).startTracking().use {
base.evaluate()
}
}
}
}
}
/**
* Encouraged using as a ClassRule to avoid project creating for each test.
* Project created on request, so, could be used as a bare (only application).
*/
class ProjectRule(private val runPostStartUpActivities: Boolean = false,
private val preloadServices: Boolean = false,
private val projectDescriptor: LightProjectDescriptor? = null) : ApplicationRule() {
companion object {
@JvmStatic
fun withoutRunningStartUpActivities() = ProjectRule(runPostStartUpActivities = false)
/**
* Think twice before use. And then do not use. To support old code.
*/
@ApiStatus.Internal
fun createStandalone(): ProjectRule {
val result = ProjectRule()
result.before(Description.EMPTY)
return result
}
}
private var sharedProject: ProjectEx? = null
private var testClassName: String? = null
var virtualFilePointerTracker: VirtualFilePointerTracker? = null
var projectTracker: AccessToken? = null
override fun before(description: Description) {
super.before(description)
testClassName = sanitizeFileName(description.className.substringAfterLast('.'))
projectTracker = (ProjectManager.getInstance() as TestProjectManager).startTracking()
}
private fun createProject(): ProjectEx {
val projectFile = TemporaryDirectory.generateTemporaryPath("project_${testClassName}${ProjectFileType.DOT_DEFAULT_EXTENSION}")
val options = createTestOpenProjectOptions(runPostStartUpActivities = runPostStartUpActivities).copy(preloadServices = preloadServices)
val project = (ProjectManager.getInstance() as TestProjectManager).openProject(projectFile, options) as ProjectEx
virtualFilePointerTracker = VirtualFilePointerTracker()
return project
}
override fun after() {
val l = mutableListOf<Throwable>()
l.catchAndStoreExceptions { super.after() }
l.catchAndStoreExceptions { sharedProject?.let { PlatformTestUtil.forceCloseProjectWithoutSaving(it) } }
l.catchAndStoreExceptions { projectTracker?.finish() }
l.catchAndStoreExceptions { virtualFilePointerTracker?.assertPointersAreDisposed() }
l.catchAndStoreExceptions {
sharedProject = null
sharedModule = null
}
throwIfNotEmpty(l)
}
/**
* Think twice before use. And then do not use. To support old code.
*/
@ApiStatus.Internal
fun close() {
after()
}
val projectIfOpened: ProjectEx?
get() = sharedProject
val project: ProjectEx
get() {
var result = sharedProject
if (result == null) {
synchronized(this) {
result = sharedProject
if (result == null) {
result = createProject()
sharedProject = result
}
}
}
return result!!
}
val module: Module
get() {
var result = sharedModule
if (result == null) {
runInEdtAndWait {
(projectDescriptor ?: LightProjectDescriptor()).setUpProject(project, object : LightProjectDescriptor.SetupHandler {
override fun moduleCreated(module: Module) {
result = module
sharedModule = module
}
})
}
}
return result!!
}
}
/**
* rules: outer, middle, inner
* out:
* starting outer rule
* starting middle rule
* starting inner rule
* finished inner rule
* finished middle rule
* finished outer rule
*/
class RuleChain(vararg val rules: TestRule) : TestRule {
override fun apply(base: Statement, description: Description): Statement {
var statement = base
for (i in (rules.size - 1) downTo 0) {
statement = rules[i].apply(statement, description)
}
return statement
}
}
private fun <T : Annotation> Description.getOwnOrClassAnnotation(annotationClass: Class<T>) = getAnnotation(annotationClass) ?: testClass?.getAnnotation(annotationClass)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
annotation class RunsInEdt
class EdtRule : TestRule {
override fun apply(base: Statement, description: Description): Statement {
return if (description.getOwnOrClassAnnotation(RunsInEdt::class.java) == null) {
base
}
else {
statement { runInEdtAndWait { base.evaluate() } }
}
}
}
class InitInspectionRule : TestRule {
override fun apply(base: Statement, description: Description): Statement = statement { runInInitMode { base.evaluate() } }
}
inline fun statement(crossinline runnable: () -> Unit): Statement = object : Statement() {
override fun evaluate() {
runnable()
}
}
/**
* Do not optimise test load speed.
* @see IProjectStore.setOptimiseTestLoadSpeed
*/
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
annotation class RunsInActiveStoreMode
class ActiveStoreRule(private val projectRule: ProjectRule) : TestRule {
override fun apply(base: Statement, description: Description): Statement {
if (description.getOwnOrClassAnnotation(RunsInActiveStoreMode::class.java) == null) {
return base
}
else {
return statement {
projectRule.project.runInLoadComponentStateMode { base.evaluate() }
}
}
}
}
/**
* In test mode component state is not loaded. Project or module store will load component state if project/module file exists.
* So must be a strong reason to explicitly use this method.
*/
inline fun <T> Project.runInLoadComponentStateMode(task: () -> T): T {
val store = stateStore
val isModeDisabled = store.isOptimiseTestLoadSpeed
if (isModeDisabled) {
store.isOptimiseTestLoadSpeed = false
}
try {
return task()
}
finally {
if (isModeDisabled) {
store.isOptimiseTestLoadSpeed = true
}
}
}
inline fun Project.use(task: (Project) -> Unit) {
try {
task(this)
}
finally {
PlatformTestUtil.forceCloseProjectWithoutSaving(this)
}
}
class DisposeNonLightProjectsRule : ExternalResource() {
override fun after() {
val projectManager = ProjectManagerEx.getInstanceExIfCreated() ?: return
projectManager.openProjects.forEachGuaranteed {
if (!ProjectManagerImpl.isLight(it)) {
ApplicationManager.getApplication().invokeAndWait {
projectManager.forceCloseProject(it)
}
}
}
}
}
class DisposeModulesRule(private val projectRule: ProjectRule) : ExternalResource() {
override fun after() {
val project = projectRule.projectIfOpened ?: return
val moduleManager = ModuleManager.getInstance(project)
ApplicationManager.getApplication().invokeAndWait {
moduleManager.modules.forEachGuaranteed {
if (!it.isDisposed && it !== sharedModule) {
moduleManager.disposeModule(it)
}
}
}
}
}
/**
* Only and only if "before" logic in case of exception doesn't require "after" logic - must be no side effects if "before" finished abnormally.
* So, should be one task per rule.
*/
class WrapRule(private val before: () -> () -> Unit) : TestRule {
override fun apply(base: Statement, description: Description): Statement = statement {
val after = before()
try {
base.evaluate()
}
finally {
after()
}
}
}
fun createProjectAndUseInLoadComponentStateMode(tempDirManager: TemporaryDirectory,
directoryBased: Boolean = false,
useDefaultProjectSettings: Boolean = true,
task: (Project) -> Unit) {
val file = tempDirManager.newPath("test${if (directoryBased) "" else ProjectFileType.DOT_DEFAULT_EXTENSION}", refreshVfs = true)
val project = ProjectManagerEx.getInstanceEx().openProject(file, createTestOpenProjectOptions().copy(
isNewProject = true,
useDefaultProjectAsTemplate = useDefaultProjectSettings,
beforeInit = { it.putUserData(LISTEN_SCHEME_VFS_CHANGES_IN_TEST_MODE, true) }
))!!
project.use {
project.runInLoadComponentStateMode {
task(project)
}
}
}
suspend fun loadAndUseProjectInLoadComponentStateMode(tempDirManager: TemporaryDirectory,
projectCreator: (suspend (VirtualFile) -> Path)? = null,
task: suspend (Project) -> Unit) {
createOrLoadProject(tempDirManager, projectCreator, task = task, directoryBased = false, loadComponentState = true)
}
fun refreshProjectConfigDir(project: Project) {
LocalFileSystem.getInstance().findFileByNioFile(project.stateStore.directoryStorePath!!)!!.refresh(false, true)
}
suspend fun <T> runNonUndoableWriteAction(file: VirtualFile, runnable: suspend () -> T): T {
return runUndoTransparentWriteAction {
val result = runBlocking { runnable() }
val documentReference = DocumentReferenceManager.getInstance().create(file)
val undoManager = UndoManager.getGlobalInstance() as UndoManagerImpl
undoManager.nonundoableActionPerformed(documentReference, false)
result
}
}
suspend fun createOrLoadProject(tempDirManager: TemporaryDirectory,
projectCreator: (suspend (VirtualFile) -> Path)? = null,
directoryBased: Boolean = true,
loadComponentState: Boolean = false,
useDefaultProjectSettings: Boolean = true,
task: suspend (Project) -> Unit) {
val file = if (projectCreator == null) {
tempDirManager.newPath("test${if (directoryBased) "" else ProjectFileType.DOT_DEFAULT_EXTENSION}", refreshVfs = false)
}
else {
val dir = tempDirManager.createVirtualDir()
withContext(AppUIExecutor.onWriteThread().coroutineDispatchingContext()) {
runNonUndoableWriteAction(dir) {
projectCreator(dir)
}
}
}
createOrLoadProject(file, useDefaultProjectSettings, projectCreator == null, loadComponentState, task)
}
private suspend fun createOrLoadProject(projectPath: Path,
useDefaultProjectSettings: Boolean,
isNewProject: Boolean,
loadComponentState: Boolean,
task: suspend (Project) -> Unit) {
var options = createTestOpenProjectOptions().copy(
useDefaultProjectAsTemplate = useDefaultProjectSettings,
isNewProject = isNewProject
)
if (loadComponentState) {
options = options.copy(beforeInit = { it.putUserData(LISTEN_SCHEME_VFS_CHANGES_IN_TEST_MODE, true) })
}
val project = ProjectManagerEx.getInstanceEx().openProject(projectPath, options)!!
project.use {
if (loadComponentState) {
project.runInLoadComponentStateMode {
task(project)
}
}
else {
task(project)
}
}
}
suspend fun loadProject(projectPath: Path, task: suspend (Project) -> Unit) {
createOrLoadProject(projectPath, false, false, true, task)
}
/**
* Copy files from [projectPaths] directories to a temp directory, load project from it and pass it to [checkProject].
*/
fun loadProjectAndCheckResults(projectPaths: List<Path>, tempDirectory: TemporaryDirectory, checkProject: suspend (Project) -> Unit) {
@Suppress("RedundantSuspendModifier")
suspend fun copyProjectFiles(dir: VirtualFile): Path {
val projectDir = VfsUtil.virtualToIoFile(dir)
for (projectPath in projectPaths) {
FileUtil.copyDir(projectPath.toFile(), projectDir)
}
VfsUtil.markDirtyAndRefresh(false, true, true, dir)
return projectDir.toPath()
}
runBlocking {
createOrLoadProject(tempDirectory, ::copyProjectFiles, loadComponentState = true, useDefaultProjectSettings = false) {
checkProject(it)
}
}
}
class DisposableRule : ExternalResource() {
private var _disposable = lazy { Disposer.newDisposable() }
val disposable: Disposable
get() = _disposable.value
@Suppress("ObjectLiteralToLambda")
inline fun register(crossinline disposable: () -> Unit) {
Disposer.register(this.disposable, object : Disposable {
override fun dispose() {
disposable()
}
})
}
override fun after() {
if (_disposable.isInitialized()) {
Disposer.dispose(_disposable.value)
}
}
}
class SystemPropertyRule(private val name: String, private val value: String = "true") : ExternalResource() {
private var oldValue: String? = null
public override fun before() {
oldValue = System.getProperty(name)
System.setProperty(name, value)
}
public override fun after() {
val oldValue = oldValue
if (oldValue == null) {
System.clearProperty(name)
}
else {
System.setProperty(name, oldValue)
}
}
} | 191 | null | 4372 | 2 | dc846ecb926c9d9589c1ed8a40fdb20e47874db9 | 15,823 | intellij-community | Apache License 2.0 |
src/lib/kotlin/slatekit-common/src/main/kotlin/slatekit/common/content/ContentType.kt | ColleenKeegan | 174,519,919 | false | {"Text": 22, "Ignore List": 25, "YAML": 1, "Markdown": 20, "Gradle": 44, "Shell": 27, "Batchfile": 27, "Java Properties": 17, "Kotlin": 690, "INI": 2, "Java": 4, "SQL": 1, "XML": 5, "HTML": 1, "CSS": 1, "JavaScript": 1, "Swift": 3} | package slatekit.common.content
open class ContentType(
val http: String,
val ext: String
)
object ContentTypeCsv : ContentType("text/csv", "csv")
object ContentTypeHtml : ContentType("text/html", "html")
object ContentTypeJson : ContentType("application/json", "json")
object ContentTypeText : ContentType("text/plain", "text")
object ContentTypeProp : ContentType("text/plain", "prop")
object ContentTypeXml : ContentType("application/xml", "xml")
| 1 | null | 1 | 1 | bd1d55f2191f729149e901be102c22d7c719793d | 460 | slatekit | Apache License 2.0 |
day9/src/main/java/com/joeygibson/aoc2022/day9/App.kt | joeygibson | 571,669,607 | false | {"Kotlin": 79226, "Shell": 3320, "Python": 1872} | package com.joeygibson.aoc2022.day9
import com.googlecode.lanterna.TextColor
import com.googlecode.lanterna.terminal.DefaultTerminalFactory
import com.googlecode.lanterna.terminal.Terminal
import picocli.CommandLine
import java.io.File
import java.io.IOException
import java.util.concurrent.Callable
import kotlin.system.exitProcess
@CommandLine.Command(
name = "day9",
mixinStandardHelpOptions = true,
version = ["day9 1.0.0"],
description = ["AoC 2022 day9"]
)
class App : Callable<Int> {
@CommandLine.Parameters(index = "0", description = ["The file to process"])
val file: File? = null
private lateinit var terminal: Terminal
private val colors = listOf(
TextColor.ANSI.RED_BRIGHT,
TextColor.ANSI.YELLOW_BRIGHT,
TextColor.ANSI.GREEN_BRIGHT,
TextColor.ANSI.BLUE_BRIGHT,
TextColor.ANSI.WHITE_BRIGHT,
TextColor.ANSI.CYAN_BRIGHT,
TextColor.ANSI.MAGENTA_BRIGHT,
TextColor.RGB(0xdc, 0xdc, 0xdc),
TextColor.RGB(0xc0, 0xc0, 0xc0),
TextColor.RGB(0xd3, 0xd3, 0xd3)
)
@Throws(IOException::class)
override fun call(): Int {
if (file == null) {
println("Usage: day9 <input file>")
exitProcess(1)
}
val moves = readWithoutBlanks(file)
.map {
val chunks = it.split(" ")
Pair(chunks[0], chunks[1].toInt())
}
terminal = setupTerminal()
printResults("part1", part1(moves))
printResults("part2", part2(moves))
return 0
}
private fun part1(moves: List<Pair<String, Int>>): Any {
val headPos = Knot('H', 0, 0)
val tailPos = Knot('T', 0, 0)
var xCatchUp = 0
var yCatchUp = 0
val tailMoves = mutableSetOf<Pair<Int, Int>>(tailPos.coordinates)
for (move in moves) {
repeat(move.second) {
when (move.first) {
"R" -> {
headPos.x += 1
xCatchUp = -1
yCatchUp = 0
}
"L" -> {
headPos.x -= 1
xCatchUp = 1
yCatchUp = 0
}
"U" -> {
headPos.y += 1
xCatchUp = 0
yCatchUp = -1
}
"D" -> {
headPos.y -= 1
xCatchUp = 0
yCatchUp = 1
}
}
if (distance(headPos, tailPos) > 1) {
tailPos.x = headPos.x + xCatchUp
tailPos.y = headPos.y + yCatchUp
tailMoves.add(tailPos.coordinates)
}
}
}
return tailMoves.size
}
private fun distance(head: Knot, tail: Knot): Int {
return Math.sqrt(
Math.pow((tail.x - head.x).toDouble(), 2.0) +
Math.pow((tail.y - head.y).toDouble(), 2.0)
).toInt()
}
private fun setupTerminal(): Terminal {
val defaultTerminalFactory = DefaultTerminalFactory()
val terminal = defaultTerminalFactory.createTerminal()
val foreground = TextColor.Factory.fromString("white")
val background = TextColor.Factory.fromString("black")
terminal.setCursorVisible(false)
terminal.setForegroundColor(foreground)
terminal.setBackgroundColor(background)
return terminal
}
private fun part2(moves: List<Pair<String, Int>>): Any {
val columns = terminal.terminalSize.columns - 1
val rows = terminal.terminalSize.rows - 1
val xModifier = columns / 2
val yModifier = rows / 2
val knots = CharRange('A', 'J')
.map { Knot(it, 0, 0) }
.toList()
knots.forEach {
terminal.clearScreen()
terminal.setCursorPosition((it.x) + xModifier, (-it.y) + yModifier)
terminal.putCharacter(it.name)
terminal.flush()
}
val tailMoves = mutableSetOf(knots[9].coordinates)
for (move in moves) {
terminal.setCursorPosition(0, 0)
terminal.putString(move.toString())
repeat(move.second) {
terminal.setCursorPosition(knots[0].x + xModifier, (-knots[0].y) + yModifier)
terminal.putCharacter(' ')
when (move.first) {
"R" -> {
knots[0].x += 1
}
"L" -> {
knots[0].x -= 1
}
"U" -> {
knots[0].y += 1
}
"D" -> {
knots[0].y -= 1
}
}
for (i in 1..9) {
if (distance(knots[i - 1], knots[i]) > 1) {
var xDiff = knots[i - 1].x - knots[i].x
var yDiff = knots[i - 1].y - knots[i].y
if (xDiff == 2) {
xDiff = 1
} else if (xDiff == -2) {
xDiff = -1
}
if (yDiff == 2) {
yDiff = 1
} else if (yDiff == -2) {
yDiff = -1
}
val oldPos = knots[i].coordinates
knots[i].x += xDiff
knots[i].y += yDiff
assert(distance(knots[i - 1], knots[i]) <= 1)
if (i == 9) {
tailMoves.add(knots[i].coordinates)
}
knots.withIndex()
.forEach { (index, knot) ->
terminal.setCursorPosition(oldPos.first + xModifier, (-oldPos.second) + yModifier)
terminal.putCharacter(' ')
terminal.setCursorPosition((knot.x) + xModifier, (-knot.y) + yModifier)
terminal.setForegroundColor(colors[index])
terminal.putCharacter(knot.name)
terminal.flush()
Thread.sleep(10)
terminal.pollInput()?.let {
resetTerminal(terminal)
exitProcess(0)
}
}
}
}
terminal.pollInput()?.let {
resetTerminal(terminal)
exitProcess(0)
}
}
}
terminal.readInput()
return tailMoves.size
}
private fun resetTerminal(terminal: Terminal) {
terminal.clearScreen()
terminal.setCursorVisible(true)
}
}
data class Knot(val name: Char, var x: Int, var y: Int) {
val coordinates: Pair<Int, Int>
get() = Pair(this.x, this.y)
} | 0 | Kotlin | 0 | 0 | c66e8434fb3156550485c11703aae0a4b36b584b | 7,302 | adventofcode2022 | MIT License |
widget/src/main/java/com/savvasdalkitsis/gameframe/feature/widget/view/PowerWidgetProvider.kt | savvasdalkitsis | 107,058,704 | false | null | /**
* Copyright 2017 <NAME>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* 'Game Frame' is a registered trademark of LEDSEQ
*/
package com.savvasdalkitsis.gameframe.feature.widget.view
import com.savvasdalkitsis.gameframe.R
class PowerWidgetProvider : ClickableWidgetProvider() {
override fun layoutResId() = R.layout.widget_power
override fun onClick() {
presenter.power()
}
}
| 9 | Kotlin | 3 | 8 | 2db2932139b5f410b4ee0922e2e1386c0c6b6aa5 | 914 | gameframe | Apache License 2.0 |
compiler/testData/diagnostics/testsWithJava8/annotations/javaRepeatableRetention.kt | dimatim | 40,043,138 | true | {"Java": 15438163, "Kotlin": 9263212, "JavaScript": 176060, "Protocol Buffer": 40343, "HTML": 23495, "Lex": 17327, "ANTLR": 9689, "CSS": 9358, "Groovy": 4934, "Shell": 3931, "IDL": 3224, "Batchfile": 2831} | // FILE: RepeatableAnnotation.java
import java.lang.annotation.*;
@Repeatable(RepeatableAnnotations.class)
@Retention(RetentionPolicy.RUNTIME)
public @interface RepeatableAnnotation {
}
// FILE: RepeatableAnnotations.java
public @interface RepeatableAnnotations {
RepeatableAnnotation[] value();
}
// FILE: RepeatableUse.kt
RepeatableAnnotation RepeatableAnnotation class My
| 0 | Java | 0 | 0 | ef095dd5599a0fdd96054269a8d2bfa2b2ef28f8 | 389 | kotlin | Apache License 2.0 |
shared/src/main/java/de/loosetie/k8s/dsl/manifests/EventSeries.kt | loosetie | 283,145,621 | false | {"Kotlin": 10664277} | package de.loosetie.k8s.dsl.manifests
import de.loosetie.k8s.dsl.K8sTopLevel
import de.loosetie.k8s.dsl.K8sDslMarker
import de.loosetie.k8s.dsl.K8sManifest
import de.loosetie.k8s.dsl.HasMetadata
@K8sDslMarker
interface EventSeries_core_v1_k8s1_16: K8sManifest {
/** Number of occurrences in this series up to the last heartbeat time */
@K8sDslMarker var count: Int?
/** Time of the last occurrence observed */
val lastObservedTime: MicroTime_meta_v1_k8s1_16?
/** State of this Series: Ongoing or Finished Deprecated. Planned removal for 1.18 */
@K8sDslMarker var state: String?
}
typealias EventSeries_core_v1_k8s1_17 = EventSeries_core_v1_k8s1_16
typealias EventSeries_core_v1_k8s1_18 = EventSeries_core_v1_k8s1_17
@K8sDslMarker
interface EventSeries_core_v1_k8s1_19: K8sManifest {
/** Number of occurrences in this series up to the last heartbeat time */
@K8sDslMarker var count: Int?
/** Time of the last occurrence observed */
val lastObservedTime: MicroTime_meta_v1_k8s1_19?
}
typealias EventSeries_core_v1_k8s1_20 = EventSeries_core_v1_k8s1_19
typealias EventSeries_core_v1_k8s1_21 = EventSeries_core_v1_k8s1_20 | 0 | Kotlin | 0 | 1 | dd616e546de56240a7a4d3edb18cb4f6529e301b | 1,179 | k8s-dsl | Apache License 2.0 |
embrace-android-sdk/src/test/java/io/embrace/android/embracesdk/injection/DataSourceModuleImplTest.kt | embrace-io | 704,537,857 | false | null | package io.embrace.android.embracesdk.injection
import io.embrace.android.embracesdk.fakes.FakeOpenTelemetryModule
import io.embrace.android.embracesdk.fakes.injection.FakeAndroidServicesModule
import io.embrace.android.embracesdk.fakes.injection.FakeAnrModule
import io.embrace.android.embracesdk.fakes.injection.FakeCoreModule
import io.embrace.android.embracesdk.fakes.injection.FakeEssentialServiceModule
import io.embrace.android.embracesdk.fakes.injection.FakeInitModule
import io.embrace.android.embracesdk.fakes.injection.FakeSystemServiceModule
import io.embrace.android.embracesdk.fakes.injection.FakeWorkerThreadModule
import io.embrace.android.embracesdk.internal.injection.DataSourceModuleImpl
import io.embrace.android.embracesdk.internal.worker.WorkerName
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertSame
import org.junit.Test
internal class DataSourceModuleImplTest {
@Test
fun `test default behavior`() {
val fakeInitModule = FakeInitModule()
val module = DataSourceModuleImpl(
fakeInitModule,
FakeCoreModule(),
FakeOpenTelemetryModule(),
FakeEssentialServiceModule(),
FakeSystemServiceModule(),
FakeAndroidServicesModule(),
FakeWorkerThreadModule(fakeInitModule = fakeInitModule, name = WorkerName.BACKGROUND_REGISTRATION),
FakeAnrModule()
)
assertSame(module.dataCaptureOrchestrator, module.embraceFeatureRegistry)
assertNotNull(module.dataCaptureOrchestrator)
assertNotNull(module.breadcrumbDataSource)
assertNotNull(module.tapDataSource)
assertNotNull(module.viewDataSource)
assertNotNull(module.webViewUrlDataSource)
assertNotNull(module.pushNotificationDataSource)
assertNotNull(module.sessionPropertiesDataSource)
assertNotNull(module.applicationExitInfoDataSource)
assertNotNull(module.lowPowerDataSource)
assertNotNull(module.memoryWarningDataSource)
assertNotNull(module.networkStatusDataSource)
assertNotNull(module.sigquitDataSource)
assertNotNull(module.rnActionDataSource)
assertNotNull(module.thermalStateDataSource)
assertNotNull(module.webViewDataSource)
assertNotNull(module.internalErrorDataSource)
}
}
| 22 | null | 8 | 133 | e5b92a8e0ed1ea64602b68ec071780369e0ea915 | 2,334 | embrace-android-sdk | Apache License 2.0 |
app/src/main/java/org/avmedia/gShockPhoneSync/ApiTest.kt | izivkov | 480,047,057 | false | null | package org.avmedia.gShockPhoneSync
import android.content.Context
import android.os.Build
import androidx.annotation.RequiresApi
import kotlinx.coroutines.runBlocking
import org.avmedia.gShockPhoneSync.MainActivity.Companion.api
import org.avmedia.gShockPhoneSync.ui.alarms.AlarmsModel
import org.avmedia.gShockPhoneSync.ui.events.CalendarEvents
import org.avmedia.gShockPhoneSync.ui.events.EventsModel
import org.avmedia.gshockapi.Alarm
import org.avmedia.gshockapi.Settings
import org.avmedia.gshockapi.casio.BluetoothWatch
class ApiTest {
fun run(context: Context) {
runBlocking {
waitForConnectionCached(context)
// api().init ()
println("Button pressed: ${api().getPressedButton()}")
println("Name returned: ${api().getWatchName()}")
println("Battery Level: ${api().getBatteryLevel()}")
println("Timer: ${api().getTimer()}")
println("App Info: ${api().getAppInfo()}")
println("Home Time: ${api().getHomeTime()}")
getDTSState()
getWorldCities()
getRTSForWorldCities()
api().setTime()
val alarms = api().getAlarms()
var model = AlarmsModel
model.alarms.clear()
model.alarms.addAll(alarms)
println("Alarm model: ${model.toJson()}")
model.alarms[0] = Alarm(6, 46, enabled = true, hasHourlyChime = false)
model.alarms[4] = Alarm(9, 25, enabled = false)
api().setAlarms(model.alarms)
handleReminders()
handleSettings()
println("--------------- END ------------------")
}
}
private suspend fun getRTSForWorldCities() {
println("World DTS City 0: ${api().getDSTForWorldCities(0)}")
println("World DTS City 1: ${api().getDSTForWorldCities(1)}")
println("World DTS City 2: ${api().getDSTForWorldCities(2)}")
println("World DTS City 3: ${api().getDSTForWorldCities(3)}")
println("World DTS City 4: ${api().getDSTForWorldCities(4)}")
println("World DTS City 5: ${api().getDSTForWorldCities(5)}")
}
private suspend fun getWorldCities() {
println("World City 0: ${api().getWorldCities(0)}")
println("World City 1: ${api().getWorldCities(1)}")
println("World City 2: ${api().getWorldCities(2)}")
println("World City 3: ${api().getWorldCities(3)}")
println("World City 4: ${api().getWorldCities(4)}")
println("World City 5: ${api().getWorldCities(5)}")
}
private suspend fun getDTSState() {
println("TDS STATE ZERO: ${api().getDSTWatchState(BluetoothWatch.DTS_STATE.ZERO)}")
println("TDS STATE TWO: ${api().getDSTWatchState(BluetoothWatch.DTS_STATE.TWO)}")
println("TDS STATE FOUR: ${api().getDSTWatchState(BluetoothWatch.DTS_STATE.FOUR)}")
}
@RequiresApi(Build.VERSION_CODES.O)
private suspend fun handleReminders() {
var eventsModel = EventsModel
eventsModel.clear()
eventsModel.events.addAll(api().getEventsFromWatch())
println("Event model from Watch: $eventsModel")
eventsModel.events.addAll(CalendarEvents.getEventsFromCalendar(MainActivity.applicationContext()))
println("Event model from Google Calendar: $eventsModel")
api().setEvents(CalendarEvents.getEventsFromCalendar(MainActivity.applicationContext()))
}
private suspend fun handleSettings() {
val settings: Settings = api().getSettings()
settings.dateFormat = "MM:DD"
api().setSettings(settings)
}
private suspend fun handleTimer() {
var timerValue = api().getTimer()
api().setTimer(timerValue)
}
private suspend fun waitForConnectionCached(context: Context) {
api().waitForConnection()
}
} | 2 | null | 6 | 55 | 6531b03d6a36409987cd87deab661a013f0def72 | 3,853 | CasioGShockSmartSync | Apache License 2.0 |
js/js.translator/testData/box/char/charCompareToIntrinsic.kt | gigliovale | 89,726,097 | false | {"Java": 23302590, "Kotlin": 21941511, "JavaScript": 137521, "Protocol Buffer": 56992, "HTML": 49980, "Lex": 18051, "Groovy": 14093, "ANTLR": 9797, "IDL": 7706, "Shell": 5152, "CSS": 4679, "Batchfile": 3721} | package foo
fun box(): String {
assertEquals(true, 'A' < '\uFFFF')
assertEquals(true, 'A' > '\u0000')
assertEquals(true, 'A' <= '\u0041')
assertEquals(true, 'A' >= '\u0041')
return "OK"
} | 184 | Java | 5691 | 6 | ce145c015d6461c840050934f2200dbc11cb3d92 | 210 | kotlin | Apache License 2.0 |
processor/src/test/kotlin/fr/smarquis/sealed/VisibilityModifiersTest.kt | SimonMarquis | 527,279,535 | false | null | /*
* Copyright (C) 2023 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fr.smarquis.sealed
import com.tschuchort.compiletesting.KotlinCompilation
import com.tschuchort.compiletesting.SourceFile
import com.tschuchort.compiletesting.kspWithCompilation
import com.tschuchort.compiletesting.symbolProcessorProviders
import fr.smarquis.sealed.SealedObjectInstances.Visibility.Internal
import fr.smarquis.sealed.SealedObjectInstances.Visibility.Public
import kotlin.reflect.KVisibility.INTERNAL
import kotlin.reflect.KVisibility.PUBLIC
import kotlin.test.Test
import kotlin.test.assertContains
import kotlin.test.assertEquals
class VisibilityModifiersTest {
@SealedObjectInstances
sealed class SealedUnspecifiedVisibility {
object INSTANCE : SealedUnspecifiedVisibility()
}
@Test
fun `unspecified visibility becomes public`() =
assertEquals(PUBLIC, SealedUnspecifiedVisibility::class::sealedObjectInstances.visibility)
@Suppress("RedundantVisibilityModifier")
@SealedObjectInstances
public sealed class SealedImplicitPublicVisibility {
object INSTANCE : SealedImplicitPublicVisibility()
}
@Test
fun `implicit public visibility becomes public`() =
assertEquals(PUBLIC, SealedImplicitPublicVisibility::class::sealedObjectInstances.visibility)
@SealedObjectInstances(visibility = Public)
sealed class SealedExplicitPublicVisibility {
object INSTANCE : SealedExplicitPublicVisibility()
}
@Test
fun `explicit public visibility becomes public`() =
assertEquals(PUBLIC, SealedExplicitPublicVisibility::class::sealedObjectInstances.visibility)
@SealedObjectInstances
internal sealed class SealedImplicitInternalVisibility {
object INSTANCE : SealedImplicitInternalVisibility()
}
@Test
fun `implicit internal visibility becomes internal`() =
assertEquals(INTERNAL, SealedImplicitInternalVisibility::class::sealedObjectInstances.visibility)
@SealedObjectInstances(visibility = Internal)
sealed class SealedExplicitInternalVisibility {
object INSTANCE : SealedExplicitInternalVisibility()
}
@Test
fun `explicit internal visibility becomes internal`() =
assertEquals(INTERNAL, SealedExplicitInternalVisibility::class::sealedObjectInstances.visibility)
sealed class CompanionImplicitInternalVisibility {
@SealedObjectInstances internal companion object
}
@Test
fun `companion implicit internal visibility becomes internal`() =
assertEquals(INTERNAL, CompanionImplicitInternalVisibility::sealedObjectInstances.visibility)
sealed class CompanionExplicitInternalVisibility {
@SealedObjectInstances(visibility = Internal)
companion object
}
@Test
fun `companion explicit internal visibility becomes internal`() =
assertEquals(INTERNAL, CompanionExplicitInternalVisibility::sealedObjectInstances.visibility)
@Test
fun `compilation fails when visibility of sealed class is private`() {
/* Given */
val source = SourceFile.kotlin(
name = "MySealedClass.kt",
contents = """
|import fr.smarquis.sealed.SealedObjectInstances
|
|@SealedObjectInstances
|private sealed class MySealedClass {
| object Object: MySealedClass()
|}
""".trimMargin(),
)
/* When */
val result = KotlinCompilation().apply {
sources = listOf(source)
symbolProcessorProviders = listOf(SealedObjectInstancesProcessorProvider())
kspWithCompilation = true
inheritClassPath = true
}.compile()
/* Then */
assertEquals(KotlinCompilation.ExitCode.COMPILATION_ERROR, result.exitCode)
assertContains(
message = "Error message is printed",
charSequence = result.messages,
other = "MySealedClass.kt:4: Unsupported [private] visibility.",
)
}
@Test
fun `compilation fails when visibility of companion object is private`() {
/* Given */
val source = SourceFile.kotlin(
name = "MySealedClass.kt",
contents = """
|import fr.smarquis.sealed.SealedObjectInstances
|
|sealed class MySealedClass {
| @SealedObjectInstances private companion object
|}
""".trimMargin(),
)
/* When */
val result = KotlinCompilation().apply {
sources = listOf(source)
symbolProcessorProviders = listOf(SealedObjectInstancesProcessorProvider())
kspWithCompilation = true
inheritClassPath = true
}.compile()
/* Then */
assertEquals(KotlinCompilation.ExitCode.COMPILATION_ERROR, result.exitCode)
assertContains(
message = "Error message is printed",
charSequence = result.messages,
other = "MySealedClass.kt:4: Unsupported [private] visibility.",
)
}
@Test
fun `compilation fails when requested visibility of sealed class is larger than actual visibility`() {
/* Given */
val source = SourceFile.kotlin(
name = "MySealedClass.kt",
contents = """
|import fr.smarquis.sealed.SealedObjectInstances
|import fr.smarquis.sealed.SealedObjectInstances.Visibility.Public
|import fr.smarquis.sealed.SealedObjectInstances.RawType.*
|
|@SealedObjectInstances(visibility = Public)
|internal sealed class MySealedClass {
| object Object: MySealedClass()
|}
""".trimMargin(),
)
/* When */
val result = KotlinCompilation().apply {
sources = listOf(source)
symbolProcessorProviders = listOf(SealedObjectInstancesProcessorProvider())
kspWithCompilation = true
inheritClassPath = true
}.compile()
/* Then */
assertEquals(KotlinCompilation.ExitCode.COMPILATION_ERROR, result.exitCode)
assertContains(
message = "Error message is printed for the receiver type",
charSequence = result.messages,
other = "MySealedClass\$sealedObjectInstances.kt:2:12 'public' member exposes its 'internal' receiver type argument MySealedClass",
)
assertContains(
message = "Error message is printed for the return type",
charSequence = result.messages,
other = "MySealedClass\$sealedObjectInstances.kt:2:49 'public' function exposes its 'internal' return type argument MySealedClass",
)
}
@Test
fun `compilation fails when requested visibility of companion object is larger than actual visibility`() {
/* Given */
val source = SourceFile.kotlin(
name = "MySealedClass.kt",
contents = """
|import fr.smarquis.sealed.SealedObjectInstances
|import fr.smarquis.sealed.SealedObjectInstances.Visibility.Public
|import fr.smarquis.sealed.SealedObjectInstances.RawType.*
|
|sealed class MySealedClass {
| @SealedObjectInstances(visibility = Public) internal companion object
|}
""".trimMargin(),
)
/* When */
val result = KotlinCompilation().apply {
sources = listOf(source)
symbolProcessorProviders = listOf(SealedObjectInstancesProcessorProvider())
kspWithCompilation = true
inheritClassPath = true
}.compile()
/* Then */
assertEquals(KotlinCompilation.ExitCode.COMPILATION_ERROR, result.exitCode)
assertContains(
message = "Error message is printed for the receiver type",
charSequence = result.messages,
other = "MySealedClass\$sealedObjectInstances.kt:4:12 'public' member exposes its 'internal' receiver type Companion",
)
}
}
| 7 | null | 0 | 27 | a86bca5fd50af086d6e0ea7c518f309c40b5ca10 | 8,727 | SealedObjectInstances | Apache License 2.0 |
app/src/main/java/com/lkw1120/weatherapp/datasource/LocalDataSource.kt | lkw1120 | 634,133,117 | false | {"Kotlin": 121594} | package com.lkw1120.weatherapp.datasource
import com.lkw1120.weatherapp.datasource.local.AppDataStore
import com.lkw1120.weatherapp.datasource.local.AppDatabase
import com.lkw1120.weatherapp.datasource.local.entity.LocationEntity
import com.lkw1120.weatherapp.datasource.local.entity.WeatherEntity
import javax.inject.Inject
interface LocalDataSource {
suspend fun getFirstLoad(): Boolean
suspend fun setFirstLoad()
suspend fun getSettings(): Map<String, String>
suspend fun updateUnits(units: String)
suspend fun getDatabase(): AppDatabase
suspend fun getLocationInfo(): LocationEntity
suspend fun updateLocationInfo(entity: LocationEntity)
suspend fun getWeatherInfo(): WeatherEntity
suspend fun updateWeatherInfo(entity: WeatherEntity)
}
class LocalDataSourceImpl @Inject constructor(
private val appDatabase: AppDatabase,
private val appDataStore: AppDataStore
) : LocalDataSource {
override suspend fun getFirstLoad(): Boolean {
return appDataStore.getFirstLoad()
}
override suspend fun setFirstLoad() {
appDataStore.setFirstLoad()
}
override suspend fun getSettings(): Map<String, String> {
return appDataStore.getSettings()
}
override suspend fun updateUnits(units: String) {
return appDataStore.updateUnits(units)
}
override suspend fun getDatabase(): AppDatabase {
return appDatabase
}
override suspend fun getLocationInfo(): LocationEntity {
return appDatabase.locationDao().getLocationInfo()
}
override suspend fun updateLocationInfo(entity: LocationEntity) {
appDatabase.locationDao().updateLocationInfo(entity)
}
override suspend fun getWeatherInfo(): WeatherEntity {
return appDatabase.weatherDao().getWeatherInfo()
}
override suspend fun updateWeatherInfo(entity: WeatherEntity) {
appDatabase.weatherDao().updateWeatherInfo(entity)
}
} | 0 | Kotlin | 1 | 0 | 67e95dae017e40a082158a218807d53c71a25c9a | 1,961 | weatherapp | Apache License 2.0 |
paper/src/main/kotlin/gg/flyte/pluginportal/paper/plugin/PPPluginCache.kt | flytegg | 615,918,655 | false | {"Kotlin": 119163} | package gg.flyte.pluginportal.paper.plugin
import com.github.shynixn.mccoroutine.folia.asyncDispatcher
import com.google.common.cache.CacheBuilder
import gg.flyte.pluginportal.api.type.CompactPlugin
import gg.flyte.pluginportal.api.type.MarketplacePlugin
import gg.flyte.pluginportal.paper.PluginPortal
import gg.flyte.twilight.gson.GSON
import kotlinx.coroutines.withContext
import java.io.File
import java.util.concurrent.TimeUnit
object PPPluginCache {
/**
* Key: Search Term
* Value: HashSet<MarketplacePlugin>
*/
private val pluginCache = CacheBuilder.newBuilder()
.expireAfterWrite(60, TimeUnit.MINUTES)
.build<String, HashSet<MarketplacePlugin>>()
private val installedPlugins = HashSet<CompactPlugin>()
private val installedPluginsConfig get(): File = File(PluginPortal.instance.dataFolder, "plugins.json")
val pluginFolder get(): File = PluginPortal.instance.dataFolder.parentFile
val updateFolder get(): File = File(pluginFolder, "update").apply { if (!exists()) mkdirs() }
fun getCachedPlugins() = pluginCache.asMap().values.flatten()
fun getInstalledPlugins() = installedPlugins
fun removeInstalledPlugins(vararg plugin: CompactPlugin) = installedPlugins.removeAll(plugin.toSet())
fun addInstalledPlugins(vararg plugin: CompactPlugin, shouldSave: Boolean = true) = installedPlugins.addAll(plugin)
.also { if (shouldSave) saveInstalledPlugins() }
fun addInstalledPlugins(plugin: HashSet<CompactPlugin>) = installedPlugins.addAll(plugin)
fun getPluginsByName(name: String) = arrayListOf<MarketplacePlugin>().apply {
pluginCache.asMap().keys.forEach {
if (name.startsWith(it, true)) {
addAll(pluginCache.asMap()[it]!!)
}
}
filter { it.displayInfo.name.startsWith(name, true) }
}
suspend fun searchForPluginsByName(name: String): List<MarketplacePlugin> {
mutableListOf<MarketplacePlugin>().apply {
addAll(getPluginsByName(name))
if (size >= 25 || pluginCache.asMap().keys.any { name.startsWith(it, true) })
return this.filter { it.displayInfo.name.startsWith(name, true) }
else {
PluginManager.searchForPlugins(name).let { list ->
pluginCache.put(name, list)
return list.filter {
it.displayInfo.name.startsWith(name) || it.displayInfo.name.contains(name)
}
}
}
}
}
suspend fun loadInstalledPlugins() {
withContext(PluginPortal.asyncContext) {
if (installedPluginsConfig.readText().isEmpty()) {
installedPluginsConfig.writeText("[]")
}
GSON.fromJson(
installedPluginsConfig.readText(),
Array<CompactPlugin>::class.java
).forEach { addInstalledPlugins(it) }
// val requestHashes = HashSet<HashMap<HashType, String>>().apply {
// pluginFolder.listFiles()
// ?.filter { it.name.endsWith(".jar") }
// ?.filter { file -> file.name.startsWith("[PP]") }
// ?.forEach { add(it.getHashes()) }
// }
//
// if (requestHashes.isNotEmpty()) {
// PPClient.recognizePluginByHashes(requestHashes).result.forEach {
// addInstalledPlugins(it.toCompactPlugin())
// }
// }
saveInstalledPlugins()
}
}
fun saveInstalledPlugins() {
installedPluginsConfig.writeText(GSON.toJson(getInstalledPlugins()))
}
fun MarketplacePlugin.isInstalled() = getInstalledPlugins().any { it.id == id }
} | 23 | Kotlin | 9 | 41 | ca77d9ebb86f15e2c8d5d71850b8fc21e856d31c | 3,766 | plugin-portal | MIT License |
fir-low-level-api-ide-impl/testData/partialRawBuilder/memberFunction.kt | JetBrains | 278,369,660 | false | null | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
// FUNCTION: foo
package test.classes
class Outer {
inner class Inner {
fun bar()
fun foo() {
val outer = Outer()
val inner = outer.Inner()
inner.bar()
}
}
} | 0 | null | 29 | 71 | b6789690db56407ae2d6d62746fb69dc99d68c84 | 438 | intellij-kotlin | Apache License 2.0 |
app/src/main/java/com/first_Ideall/utils/StringUtils.kt | ismaelic | 551,328,441 | false | null | package com.first_Ideall.utils
class StringUtils {
companion object {
fun hasCharacter(text: String): Boolean {
return text.trim() != ""
}
}
} | 0 | Kotlin | 0 | 1 | d52f8b7b5a476db5ab77d98181b33d2c2af012e9 | 179 | IDEALL-Android | MIT License |
common-tools/src/main/java/com/likethesalad/android/templates/common/tasks/identifier/action/TemplatesIdentifierAction.kt | LikeTheSalad | 216,664,268 | false | null | package com.likethesalad.android.templates.common.tasks.identifier.action
import com.likethesalad.android.templates.common.configuration.StemConfiguration
import com.likethesalad.android.templates.common.tasks.identifier.data.TemplateItem
import com.likethesalad.android.templates.common.tasks.identifier.data.TemplateItemsSerializer
import com.likethesalad.android.templates.common.utils.CommonConstants
import com.likethesalad.tools.resource.api.android.environment.Language
import com.likethesalad.tools.resource.api.android.impl.AndroidResourceType
import com.likethesalad.tools.resource.api.android.modules.string.StringAndroidResource
import com.likethesalad.tools.resource.api.collection.ResourceCollection
import com.likethesalad.tools.resource.locator.android.extension.configuration.data.ResourcesProvider
import dagger.assisted.Assisted
import dagger.assisted.AssistedFactory
import dagger.assisted.AssistedInject
import java.io.File
class TemplatesIdentifierAction @AssistedInject constructor(
@Assisted private val localResources: ResourcesProvider,
@Assisted private val outputFile: File,
private val configuration: StemConfiguration,
private val templateItemsSerializer: TemplateItemsSerializer
) {
@AssistedFactory
interface Factory {
fun create(localResources: ResourcesProvider, outputFile: File): TemplatesIdentifierAction
}
fun execute() {
val templates = getTemplatesFromResources()
outputFile.writeText(templateItemsSerializer.serialize(templates))
}
private fun getTemplatesFromResources(): List<TemplateItem> {
return if (configuration.searchForTemplatesInLanguages()) {
getTemplatesFromAllCollections()
} else {
val mainLanguageResources = localResources.resources.getMergedResourcesForLanguage(Language.Default)
getTemplatesForCollection(mainLanguageResources)
}
}
private fun getTemplatesFromAllCollections(): List<TemplateItem> {
val resources = localResources.resources
val allLanguages = resources.listLanguages()
val templates = mutableSetOf<TemplateItem>()
allLanguages.forEach { language ->
val collection = resources.getMergedResourcesForLanguage(language)
val collectionTemplates = getTemplatesForCollection(collection)
templates.addAll(collectionTemplates)
}
return templates.toList()
}
@Suppress("UNCHECKED_CAST")
private fun getTemplatesForCollection(resourceCollection: ResourceCollection): List<TemplateItem> {
val stringResources = resourceCollection.getResourcesByType(AndroidResourceType.StringType)
val templates = filterTemplates(stringResources as List<StringAndroidResource>)
return templates.sortedBy { it.name() }.map {
TemplateItem(it.name(), it.type().getName())
}
}
private fun filterTemplates(stringResources: List<StringAndroidResource>): List<StringAndroidResource> {
return stringResources.filter { stringResource ->
CommonConstants.PLACEHOLDER_REGEX.containsMatchIn(stringResource.stringValue())
}
}
} | 2 | null | 9 | 170 | 1ca6112fb5bdd07f8282f2dc3a46479796d4b48b | 3,181 | android-stem | MIT License |
ImageLoader/src/main/java/cn/quibbler/imageloader/cache/memory/impl/FIFOLimitedMemoryCache.kt | quibbler01 | 524,270,844 | false | {"Kotlin": 252007} | package cn.quibbler.imageloader.cache.memory.impl
import android.graphics.Bitmap
import cn.quibbler.imageloader.cache.memory.LimitedMemoryCache
import java.lang.ref.Reference
import java.lang.ref.WeakReference
import java.util.*
/**
* Limited {@link Bitmap bitmap} cache. Provides {@link Bitmap bitmaps} storing. Size of all stored bitmaps will not to
* exceed size limit. When cache reaches limit size then cache clearing is processed by FIFO principle.<br />
* <br />
* <b>NOTE:</b> This cache uses strong and weak references for stored Bitmaps. Strong references - for limited count of
* Bitmaps (depends on cache size), weak references - for all other cached Bitmaps.
*
* @author Sergey Tarasevich (nostra13[at]gmail[dot]com)
* @since 1.0.0
*/
class FIFOLimitedMemoryCache : LimitedMemoryCache {
private val queue = Collections.synchronizedList(LinkedList<Bitmap>())
constructor(sizeLimit: Int) : super(sizeLimit)
override fun put(key: String, value: Bitmap): Boolean {
if (super.put(key, value)) {
queue.add(value)
return true
} else {
return false
}
}
override fun remove(key: String): Bitmap? {
val value = super.get(key)
value?.let {
queue.remove(value)
}
return super.remove(key)
}
override fun clear() {
queue.clear()
super.clear()
}
override fun getSize(value: Bitmap?): Int = if (value != null) {
value.rowBytes * value.height
} else {
0
}
override fun removeNext(): Bitmap? {
return queue.removeAt(0)
}
override fun createReference(value: Bitmap): Reference<Bitmap> {
return WeakReference<Bitmap>(value)
}
} | 0 | Kotlin | 0 | 0 | d2fae5a52fe791f0338bd303f3f7cb128fa7e504 | 1,752 | ImageLoader | Apache License 2.0 |
apollo-normalized-cache-sqlite/src/jvmTest/kotlin/com/apollographql/apollo3/cache/normalized/sql/CreateDriver.kt | apollographql | 69,469,299 | false | null | package com.apollographql.apollo3.cache.normalized.sql
import com.squareup.sqldelight.db.SqlDriver
import com.squareup.sqldelight.sqlite.driver.JdbcSqliteDriver
actual fun createDriver(): SqlDriver =
JdbcSqliteDriver(JdbcSqliteDriver.IN_MEMORY).also {
ApolloDatabase.Schema.create(it)
}
| 129 | null | 559 | 3,046 | 7a1a291d5edc7d66d088c06b47975ef8a79fc439 | 303 | apollo-android | MIT License |
korge/src/commonMain/kotlin/com/soywiz/korge3d/RenderContext3D.kt | zhch0633 | 365,435,090 | true | {"Kotlin": 2876182, "Java": 182026, "Shell": 1955, "Batchfile": 1618} | package com.soywiz.korge3d
import com.soywiz.kds.*
import com.soywiz.korag.*
import com.soywiz.korge.render.*
import com.soywiz.korma.geom.*
@Korge3DExperimental
class RenderContext3D() {
lateinit var ag: AG
lateinit var rctx: RenderContext
val shaders = Shaders3D()
val textureUnit = AG.TextureUnit()
val bindMat4 = Matrix3D()
val bones = Array(128) { Matrix3D() }
val tmepMat = Matrix3D()
val projMat: Matrix3D = Matrix3D()
val lights = arrayListOf<Light3D>()
val projCameraMat: Matrix3D = Matrix3D()
val cameraMat: Matrix3D = Matrix3D()
val cameraMatInv: Matrix3D = Matrix3D()
val dynamicVertexBufferPool = Pool { ag.createVertexBuffer() }
val dynamicIndexBufferPool = Pool { ag.createIndexBuffer() }
val ambientColor: Vector3D = Vector3D()
}
| 0 | null | 0 | 1 | dcddb3eb4d9e34a263a235089237deb89f339cd3 | 767 | korge | Apache License 2.0 |
js/js.translator/testData/box/expression/function/anonymousWithLambda.kt | JakeWharton | 99,388,807 | false | null | // IGNORE_BACKEND: JS_IR
// EXPECTED_REACHABLE_NODES: 1110
fun box(): String {
val a = (fun(): String {
val o = { "O" }
return o() + "K"
})
return a()
} | 184 | null | 5691 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 180 | kotlin | Apache License 2.0 |
benchmark/benchmark-macro/src/main/java/androidx/benchmark/macro/CompilationMode.kt | androidx | 256,589,781 | false | null | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.benchmark.macro
import android.os.Build
import android.util.Log
import androidx.annotation.IntRange
import androidx.annotation.RequiresApi
import androidx.annotation.RestrictTo
import androidx.benchmark.Arguments
import androidx.benchmark.DeviceInfo
import androidx.benchmark.Shell
import androidx.benchmark.macro.CompilationMode.Full
import androidx.benchmark.macro.CompilationMode.Ignore
import androidx.benchmark.macro.CompilationMode.None
import androidx.benchmark.macro.CompilationMode.Partial
import androidx.benchmark.userspaceTrace
import androidx.core.os.BuildCompat
import androidx.profileinstaller.ProfileInstallReceiver
import org.junit.AssumptionViolatedException
/**
* Type of compilation to use for a Macrobenchmark.
*
* This compilation mode controls pre-compilation that occurs before running the setup / measure
* blocks of the benchmark.
*
* On Android N+ (API 24+), there are different levels of compilation supported:
*
* * [Partial] - the default configuration of [Partial] will partially pre-compile your application,
* if a Baseline Profile is included in your app. This represents the most realistic fresh-install
* experience on an end-user's device. You can additionally or instead use
* [Partial.warmupIterations] to use Profile Guided Optimization, using the benchmark content to
* guide pre-compilation to mimic an application's performance after some, and JIT-ing has occurred.
*
* * [Full] - the app is fully pre-compiled. This is generally not representative of real user
* experience, as apps are not fully pre-compiled on user devices more recent than Android N
* (API 24). `Full` can be used to show unrealistic but potentially more stable performance by
* removing the noise/inconsistency from just-in-time compilation within benchmark runs. Note that
* `Full` compilation will often be slower than [Partial] compilation, as the increased code size
* creates more cost for disk loading during startup, and increases pressure in the instruction
* cache.
*
* * [None] - the app isn't pre-compiled at all, bypassing the default compilation that should
* generally be done at install time, e.g. by the Play Store. This will illustrate worst case
* performance, and will show you performance of your app if you do not enable baseline profiles,
* useful for judging the performance impact of the baseline profiles included in your application.
*
* * [Ignore] - the state of compilation will be ignored. The intended use-case is for a developer
* to customize the compilation state for an app; and then tell Macrobenchmark to leave it
* unchanged.
*
* On Android M (API 23), only [Full] is supported, as all apps are always fully compiled.
*
* To understand more how these modes work, you can see comments for each class, and also see the
* [Android Runtime compilation modes](https://source.android.com/devices/tech/dalvik/configure#compilation_options)
* (which are passed by benchmark into
* [`cmd compile`](https://source.android.com/devices/tech/dalvik/jit-compiler#force-compilation-of-a-specific-package)
* to compile the target app).
*/
sealed class CompilationMode {
@androidx.annotation.OptIn(markerClass = [BuildCompat.PrereleaseSdkCheck::class])
internal fun resetAndCompile(
packageName: String,
allowCompilationSkipping: Boolean = true,
killProcessBlock: () -> Unit,
warmupBlock: () -> Unit
) {
if (Build.VERSION.SDK_INT >= 24) {
if (Arguments.enableCompilation || !allowCompilationSkipping) {
Log.d(TAG, "Resetting $packageName")
// The compilation mode chooses whether a reset is required or not.
// Currently the only compilation mode that does not perform a reset is
// CompilationMode.Ignore.
if (shouldReset()) {
// It's not possible to reset the compilation profile on `user` builds.
// The flag `enablePackageReset` can be set to `true` on `userdebug` builds in
// order to speed-up the profile reset. When set to false, reset is performed
// uninstalling and reinstalling the app.
if (BuildCompat.isAtLeastU() || Shell.isSessionRooted()) {
// Package reset enabled
Log.d(TAG, "Re-compiling $packageName")
// cmd package compile --reset returns a "Success" or a "Failure" to stdout.
// Rather than rely on exit codes which are not always correct, we
// specifically look for the work "Success" in stdout to make sure reset
// actually happened.
val output = Shell.executeScriptCaptureStdout(
"cmd package compile --reset $packageName"
)
check(output.trim() == "Success" || output.contains("PERFORMED")) {
"Unable to recompile $packageName (out=$output)"
}
} else {
// User builds pre-U. Kick off a full uninstall-reinstall
Log.d(TAG, "Reinstalling $packageName")
reinstallPackage(packageName)
}
}
// Write skip file to stop profile installer from interfering with the benchmark
writeProfileInstallerSkipFile(packageName, killProcessBlock = killProcessBlock)
compileImpl(packageName, killProcessBlock, warmupBlock)
} else {
Log.d(TAG, "Compilation is disabled, skipping compilation of $packageName")
}
}
}
/**
* A more expensive alternative to `compile --reset` which doesn't preserve app data, but
* does work on older APIs without root
*/
private fun reinstallPackage(packageName: String) {
userspaceTrace("reinstallPackage") {
// Copy APKs to /data/local/temp
val apkPaths = Shell.pmPath(packageName)
val tempApkPaths: List<String> = apkPaths.mapIndexed { index, apkPath ->
val tempApkPath =
"/data/local/tmp/$packageName-$index-${System.currentTimeMillis()}.apk"
Log.d(TAG, "Copying APK $apkPath to $tempApkPath")
Shell.executeScriptSilent(
"cp $apkPath $tempApkPath"
)
tempApkPath
}
val tempApkPathsString = tempApkPaths.joinToString(" ")
try {
// Uninstall package
// This is what effectively clears the ART profiles
Log.d(TAG, "Uninstalling $packageName")
var output = Shell.executeScriptCaptureStdout("pm uninstall $packageName")
check(output.trim() == "Success") {
"Unable to uninstall $packageName ($output)"
}
// Install the APK from /data/local/tmp
Log.d(TAG, "Installing $packageName")
// Provide a `-t` argument to `pm install` to ensure test packages are
// correctly installed. (b/231294733)
output = Shell.executeScriptCaptureStdout("pm install -t $tempApkPathsString")
check(output.trim() == "Success" || output.contains("PERFORMED")) {
"Unable to install $packageName (out=$output)"
}
} finally {
// Cleanup the temporary APK
Log.d(TAG, "Deleting $tempApkPathsString")
Shell.executeScriptSilent("rm $tempApkPathsString")
}
}
}
/**
* Writes a skip file via a [ProfileInstallReceiver] broadcast, so profile installation
* does not interfere with benchmarks.
*/
private fun writeProfileInstallerSkipFile(packageName: String, killProcessBlock: () -> Unit) {
val result = ProfileInstallBroadcast.skipFileOperation(packageName, "WRITE_SKIP_FILE")
if (result != null) {
Log.w(
TAG,
"""
$packageName should use the latest version of `androidx.profileinstaller`
for stable benchmarks. ($result)"
""".trimIndent()
)
}
Log.d(TAG, "Killing process $packageName")
killProcessBlock()
}
@RequiresApi(24)
internal abstract fun compileImpl(
packageName: String,
killProcessBlock: () -> Unit,
warmupBlock: () -> Unit
)
@RequiresApi(24)
internal abstract fun shouldReset(): Boolean
/**
* No pre-compilation - a compilation profile reset is performed and the entire app will be
* allowed to Just-In-Time compile as it runs.
*
* Note that later iterations may perform differently, as app code is jitted.
*/
// Leaving possibility for future configuration (such as interpreted = true)
@Suppress("CanSealedSubClassBeObject")
@RequiresApi(24)
class None : CompilationMode() {
override fun toString(): String = "None"
override fun compileImpl(
packageName: String,
killProcessBlock: () -> Unit,
warmupBlock: () -> Unit
) {
// nothing to do!
}
override fun shouldReset(): Boolean = true
}
/**
* This compilation mode doesn't perform any reset or compilation, leaving the user the choice
* to implement these steps.
*/
// Leaving possibility for future configuration
@ExperimentalMacrobenchmarkApi
@Suppress("CanSealedSubClassBeObject")
class Ignore : CompilationMode() {
override fun toString(): String = "Ignore"
override fun compileImpl(
packageName: String,
killProcessBlock: () -> Unit,
warmupBlock: () -> Unit
) {
// Do nothing.
}
override fun shouldReset(): Boolean = false
}
/**
* Partial ahead-of-time app compilation.
*
* The default parameters for this mimic the default state of an app partially pre-compiled by
* the installer - such as via Google Play.
*
* Either [baselineProfileMode] must be set to non-[BaselineProfileMode.Disable], or
* [warmupIterations] must be set to a non-`0` value.
*
* Note: `[baselineProfileMode] = [BaselineProfileMode.Require]` is only supported for APKs that
* have the ProfileInstaller library included, and have been built by AGP 7.0+ to package the
* baseline profile in the APK.
*/
@RequiresApi(24)
class Partial @JvmOverloads constructor(
/**
* Controls whether a Baseline Profile should be used to partially pre compile the app.
*
* Defaults to [BaselineProfileMode.Require]
*
* @see BaselineProfileMode
*/
val baselineProfileMode: BaselineProfileMode = BaselineProfileMode.Require,
/**
* If greater than 0, your macrobenchmark will run an extra [warmupIterations] times before
* compilation, to prepare
*/
@IntRange(from = 0)
val warmupIterations: Int = 0
) : CompilationMode() {
init {
require(warmupIterations >= 0) {
"warmupIterations must be non-negative, was $warmupIterations"
}
require(
baselineProfileMode != BaselineProfileMode.Disable || warmupIterations > 0
) {
"Must set baselineProfileMode != Ignore, or warmup iterations > 0 to define" +
" which portion of the app to pre-compile."
}
}
override fun toString(): String {
return if (
baselineProfileMode == BaselineProfileMode.Require && warmupIterations == 0
) {
"BaselineProfile"
} else if (baselineProfileMode == BaselineProfileMode.Disable && warmupIterations > 0) {
"WarmupProfile(iterations=$warmupIterations)"
} else {
"Partial(baselineProfile=$baselineProfileMode,iterations=$warmupIterations)"
}
}
override fun compileImpl(
packageName: String,
killProcessBlock: () -> Unit,
warmupBlock: () -> Unit
) {
if (baselineProfileMode != BaselineProfileMode.Disable) {
// Ignores the presence of a skip file.
val installErrorString = ProfileInstallBroadcast.installProfile(packageName)
if (installErrorString == null) {
// baseline profile install success, kill process before compiling
Log.d(TAG, "Killing process $packageName")
killProcessBlock()
cmdPackageCompile(packageName, "speed-profile")
} else {
if (baselineProfileMode == BaselineProfileMode.Require) {
throw RuntimeException(installErrorString)
} else {
Log.d(TAG, installErrorString)
}
}
}
if (warmupIterations > 0) {
repeat(this.warmupIterations) {
warmupBlock()
}
// For speed profile compilation, ART team recommended to wait for 5 secs when app
// is in the foreground, dump the profile, wait for another 5 secs before
// speed-profile compilation.
Thread.sleep(5000)
val saveResult = ProfileInstallBroadcast.saveProfile(packageName)
if (saveResult == null) {
killProcessBlock() // success, have to manually kill process
} else {
if (Shell.isSessionRooted()) {
// fallback on `killall -s SIGUSR1`, if available with root
Log.d(
TAG,
"Unable to saveProfile with profileinstaller ($saveResult), trying kill"
)
val response = Shell.executeScriptCaptureStdoutStderr(
"killall -s SIGUSR1 $packageName"
)
check(response.isBlank()) {
"Failed to dump profile for $packageName ($response),\n" +
" and failed to save profile with broadcast: $saveResult"
}
} else {
throw RuntimeException(saveResult)
}
}
cmdPackageCompile(packageName, "speed-profile")
}
}
override fun shouldReset(): Boolean = true
}
/**
* Full ahead-of-time compilation.
*
* Equates to `cmd package compile -f -m speed <package>` on API 24+.
*
* On Android M (API 23), this is the only supported compilation mode, as all apps are
* fully compiled ahead-of-time.
*/
@Suppress("CanSealedSubClassBeObject") // Leaving possibility for future configuration
class Full : CompilationMode() {
override fun toString(): String = "Full"
override fun compileImpl(
packageName: String,
killProcessBlock: () -> Unit,
warmupBlock: () -> Unit
) {
if (Build.VERSION.SDK_INT >= 24) {
cmdPackageCompile(packageName, "speed")
}
// Noop on older versions: apps are fully compiled at install time on API 23 and below
}
override fun shouldReset(): Boolean = true
}
/**
* No JIT / pre-compilation, all app code runs on the interpreter.
*
* Note: this mode will only be supported on rooted devices with jit disabled. For this reason,
* it's only available for internal benchmarking.
*
* TODO: migrate this to an internal-only flag on [None] instead
*
* @suppress
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
object Interpreted : CompilationMode() {
override fun toString(): String = "Interpreted"
override fun compileImpl(
packageName: String,
killProcessBlock: () -> Unit,
warmupBlock: () -> Unit
) {
// Nothing to do - handled externally
}
override fun shouldReset(): Boolean = true
}
companion object {
/**
* Represents the default compilation mode for the platform, on an end user's device.
*
* This is a post-store-install app configuration for this device's SDK
* version - [`Partial(BaselineProfileMode.UseIfAvailable)`][Partial] on API 24+, and
* [Full] prior to API 24 (where all apps are fully AOT compiled).
*
* On API 24+, Baseline Profile pre-compilation is used if possible, but no error will be
* thrown if installation fails.
*
* Generally, it is preferable to explicitly pass a compilation mode, such as
* [`Partial(BaselineProfileMode.Required)`][Partial] to avoid ambiguity, and e.g. validate
* an app's BaselineProfile can be correctly used.
*/
@JvmField
val DEFAULT: CompilationMode = if (Build.VERSION.SDK_INT >= 24) {
Partial(
baselineProfileMode = BaselineProfileMode.UseIfAvailable,
warmupIterations = 0
)
} else {
// API 23 is always fully compiled
Full()
}
@RequiresApi(24)
internal fun cmdPackageCompile(packageName: String, compileArgument: String) {
val stdout = Shell.executeScriptCaptureStdout(
"cmd package compile -f -m $compileArgument $packageName"
)
check(stdout.trim() == "Success" || stdout.contains("PERFORMED")) {
"Failed to compile (out=$stdout)"
}
}
}
}
/**
* Returns true if the CompilationMode can be run with the device's current VM settings.
*
* Used by jetpack-internal benchmarks to skip CompilationModes that would self-suppress.
*
* @suppress
*/
@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP_PREFIX)
fun CompilationMode.isSupportedWithVmSettings(): Boolean {
// Only check for supportedVmSettings when CompilationMode.Interpreted is being requested.
// More context: b/248085179
val interpreted = this == CompilationMode.Interpreted
return if (interpreted) {
val getProp = Shell.getprop("dalvik.vm.extra-opts")
val vmRunningInterpretedOnly = getProp.contains("-Xusejit:false")
// true if requires interpreted, false otherwise
vmRunningInterpretedOnly
} else {
true
}
}
internal fun CompilationMode.assumeSupportedWithVmSettings() {
if (!isSupportedWithVmSettings()) {
throw AssumptionViolatedException(
when {
DeviceInfo.isRooted && this == CompilationMode.Interpreted ->
"""
To run benchmarks with CompilationMode $this,
you must disable jit on your device with the following command:
`adb shell setprop dalvik.vm.extra-opts -Xusejit:false; adb shell stop; adb shell start`
""".trimIndent()
DeviceInfo.isRooted && this != CompilationMode.Interpreted ->
"""
To run benchmarks with CompilationMode $this,
you must enable jit on your device with the following command:
`adb shell setprop dalvik.vm.extra-opts \"\"; adb shell stop; adb shell start`
""".trimIndent()
else ->
"You must toggle usejit on the VM to use CompilationMode $this, this requires" +
"rooting your device."
}
)
}
}
| 29 | null | 937 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 20,830 | androidx | Apache License 2.0 |
composeApp/src/commonMain/kotlin/me/gustavolopezxyz/common/db/AccountRepository.kt | gusaln | 736,062,721 | false | {"Kotlin": 304914} | /*
* Copyright (c) 2023. <NAME>. All rights reserved.
*/
package me.gustavolopezxyz.common.db
import app.cash.sqldelight.Query
import app.cash.sqldelight.coroutines.asFlow
import kotlinx.coroutines.flow.Flow
import me.gustavolopezxyz.common.data.Account
import me.gustavolopezxyz.common.data.AccountType
import me.gustavolopezxyz.common.ext.toCurrency
import me.gustavolopezxyz.common.money.Currency
class AccountRepository(private val db: Database) {
private val accountQueries: AccountQueries = db.accountQueries
fun getAll(): List<Account> {
return accountQueries.selectAll().executeAsList()
}
fun getById(ids: Collection<Long>): List<Account> {
return accountQueries.selectById(ids).executeAsList()
}
fun findByIdOrNull(id: Long): Account? {
return accountQueries.selectById(listOf(id)).executeAsOneOrNull()
}
fun findById(id: Long): Account {
return accountQueries.selectById(listOf(id)).executeAsOne()
}
fun getByType(types: Collection<AccountType>): List<Account> {
return accountQueries.selectByType(types).executeAsList()
}
fun getByType(type: AccountType): List<Account> {
return accountQueries.selectByType(listOf(type)).executeAsList()
}
fun allAsFlow(): Flow<Query<Account>> {
return accountQueries.selectAll().asFlow()
}
fun create(type: AccountType, name: String, currency: Currency) {
return accountQueries.insertAccount(type, name, currency.toString())
}
fun update(original: Account, modified: Account) = update(
original.accountId,
modified.type,
modified.name,
modified.currency.toCurrency()
)
fun update(modified: Account) = update(
modified.accountId,
modified.type,
modified.name,
modified.currency.toCurrency()
)
private fun update(
accountId: Long,
type: AccountType,
name: String,
currency: Currency,
) {
return accountQueries.updateAccount(
type = type,
name = name,
currency = currency.code,
accountId = accountId,
)
}
fun recomputeBalance(account: Account) = recomputeBalance(account.accountId)
fun recomputeBalance(accountId: Long) {
accountQueries.recomputeBalanceOf(accountId)
}
fun recomputeBalances() {
accountQueries.recomputeAllBalances()
}
} | 0 | Kotlin | 0 | 1 | d1e56bb6dce4a0d9c430a8d4f6bcf67b1249ea52 | 2,453 | wimm | MIT License |
app/src/main/java/com/example/f1racingcompanion/data/nextsessiondto/CircuitDto.kt | wkol | 408,953,651 | false | {"Kotlin": 315517, "Java": 220} | package com.example.f1racingcompanion.data.nextsessiondto
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
data class CircuitDto(
@Json(name = "circuitName")
val circuitName: String,
@Json(name = "circuitId")
val circuitId: String
)
| 0 | Kotlin | 0 | 7 | d181a1710fdd59b043e40495032910625c0d473d | 304 | F1RacingCompanion | MIT License |
imagek_glide_ext/src/main/java/com/mozhimen/imagek/glide/ext/ImageKGlideModelLoader.kt | mozhimen | 762,736,762 | false | null | package com.mozhimen.imagek.glide.helpers
import com.bumptech.glide.load.Options
import com.bumptech.glide.load.model.ModelLoader
import com.bumptech.glide.signature.ObjectKey
import com.mozhimen.basick.elemk.commons.IA_AListener
import com.mozhimen.imagek.glide.mos.ImageKGlideFile
import okhttp3.Call
import java.io.InputStream
/**
* @ClassName ImageKFileIdLoader
* @Description TODO
* @Author Mozhimen & <NAME>
* @Version 1.0
*/
class ImageKGlideModelLoader(
private val _client: Call.Factory,
private val _listener: IA_AListener<String?>
) : ModelLoader<ImageKGlideFile, InputStream> {
override fun handles(model: ImageKGlideFile): Boolean {
if (model.url?.isNotEmpty() == true) {
return true
}
return model.fileId.isNotEmpty()
}
override fun buildLoadData(model: ImageKGlideFile, width: Int, height: Int, options: Options): ModelLoader.LoadData<InputStream>? {
return ModelLoader.LoadData(ObjectKey(model), OkHttpInputStreamDataFetcher(_client, model, _listener))
}
} | 0 | null | 7 | 3 | 9318604f6fbd4b93c09d0a8aab55fa854a535990 | 1,049 | AImageKit | Apache License 2.0 |
app/src/main/java/com/warchaser/trailrecoder/LocationService.kt | Warchaser | 663,861,462 | false | null | package com.warchaser.trailrecoder
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.Service
import android.content.Intent
import android.os.IBinder
import com.amap.api.location.AMapLocation
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.AMapLocationListener
import com.warchaser.baselib.tools.NLog
import com.warchaser.baselib.tools.PackageUtil
import com.warchaser.trailrecoder.tools.LocationUtil
class LocationService : Service() {
private val TAG : String = PackageUtil.getSimpleClassName(this)
private var mLocationClient : AMapLocationClient? = null
private var mNotificationManager : NotificationManager? = null
private var mNotification : Notification? = null
private val CHANNEL_ID = "com.warchaser.trailrecoder.LocationService"
private val NOTIFICATION_ID = 1001
override fun onCreate() {
super.onCreate()
}
override fun onDestroy() {
super.onDestroy()
cancelNotification()
}
private fun startLocating(){
takeIf { mLocationClient == null }.run {
try {
mLocationClient = AMapLocationClient(this@LocationService)
} catch (e : Throwable) {
e.message?.run {
NLog.eWithFile(TAG, this)
}
}
}
mLocationClient?.run {
setLocationListener(mLocationListener)
setLocationOption(LocationUtil.getDefaultLocationOption())
startLocation()
}
startForeground()
}
private val mLocationListener = object : AMapLocationListener{
override fun onLocationChanged(location: AMapLocation?) {
NLog.i(TAG, "mLocationListener.onLocationChanged()")
}
}
private fun startForeground(){
startForeground(NOTIFICATION_ID, getNotification())
}
private fun getNotification() : Notification {
if(mNotificationManager == null){
mNotificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager?
}
Notification.Builder(this, CHANNEL_ID).setSmallIcon(R.mipmap.ic_launcher).run {
NotificationChannel(CHANNEL_ID, "LocationService", NotificationManager.IMPORTANCE_HIGH).run {
setSound(null, null)
mNotificationManager?.createNotificationChannel(this)
}
setOnlyAlertOnce(true)
mNotification = build().apply {
flags != Notification.FLAG_FOREGROUND_SERVICE
}
}
return mNotification!!
}
private fun cancelNotification(){
mNotificationManager?.run {
NLog.e(TAG, "CancelNotification()")
cancel(NOTIFICATION_ID)
stopForeground(STOP_FOREGROUND_DETACH)
}
mNotificationManager = null
}
override fun onBind(intent: Intent?): IBinder? = null
} | 0 | Kotlin | 0 | 0 | 7b205ff1f7378e23affeeebd0ca9862c8426d3a2 | 2,991 | TrailRecorder | Apache License 2.0 |
app/src/main/java/br/com/helpdev/githubers/worker/UsersDispatchers.kt | gbzarelli | 168,407,845 | false | null | package br.com.helpdev.githubers.worker
import androidx.work.*
fun dispatchListUsersWorker(lastId: Int = 0) {
dispatchUsersWorker(Data.Builder().apply { putInt(GithubUsersWorker.DATA_INT_LAST_ID, lastId) })
}
fun dispatchUserWorker(login: String) {
dispatchUsersWorker(Data.Builder().apply { putString(GithubUsersWorker.DATA_LOAD_ONLY_USER, login) })
}
/**
* Enqueue a {@link GithubUsersWorker} for execute only one time
* when has network connection
*/
private fun dispatchUsersWorker(data: Data.Builder) {
WorkManager.getInstance()
.enqueueUniqueWork(
GithubUsersWorker::class.java.simpleName,
ExistingWorkPolicy.KEEP,
OneTimeWorkRequestBuilder<GithubUsersWorker>()
.setInputData(data.build())
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.build()
).build()
)
} | 0 | Kotlin | 1 | 4 | b09ebd33fc772d1cd3df5911675a933382a85ba7 | 991 | githubers | Apache License 2.0 |
addresses/src/commonMain/kotlin/geo/AddressDto.kt | aSoft-Ltd | 694,870,214 | false | {"Kotlin": 15901} | @file:JsExport // TODO: Remove JsExport annotation and use the AddressPresenter for Js
@file:Suppress("NON_EXPORTABLE_TYPE")
package geo
import kollections.List
import kollections.map
import kollections.plus
import kollections.reversed
import kotlinx.JsExport
import kotlinx.serialization.Serializable
@Serializable
data class AddressDto(
val country: Country,
val entries: List<Entry>
) {
fun toLines() = (entries.reversed().map { it.value ?: "" } + country.label)
} | 0 | Kotlin | 0 | 0 | 191d605ede8135525b0da0024a00a8b6a9cd59fb | 482 | geo-api | MIT License |
app/src/main/java/com/e444er/cleanmovie/feature_explore/data/remote/ExploreApi.kt | e444er | 597,756,971 | false | null | package com.e444er.cleanmovie.feature_explore.data.remote
import com.e444er.cleanmovie.core.data.dto.ApiResponse
import com.e444er.cleanmovie.core.util.Constants
import com.e444er.cleanmovie.feature_explore.data.dto.SearchDto
import com.e444er.cleanmovie.feature_home.data.dto.MovieDto
import com.e444er.cleanmovie.feature_home.data.dto.TvSeriesDto
import retrofit2.http.GET
import retrofit2.http.Query
interface ExploreApi {
@GET("discover/movie")
suspend fun discoverMovie(
@Query("page") page: Int = Constants.STARTING_PAGE,
@Query("language") language: String,
@Query("with_genres") genres: String = "",
@Query("sort_by") sort: String
): ApiResponse<MovieDto>
@GET("discover/tv")
suspend fun discoverTv(
@Query("page") page: Int = Constants.STARTING_PAGE,
@Query("language") language: String,
@Query("with_genres") genres: String = "",
@Query("sort_by") sort: String
): ApiResponse<TvSeriesDto>
@GET("search/multi")
suspend fun multiSearch(
@Query("query") query: String,
@Query("language") language: String,
@Query("page") page: Int = Constants.STARTING_PAGE
): ApiResponse<SearchDto>
} | 0 | Kotlin | 0 | 0 | 1c939de424b4eb254fd4258f4e56e4399bdfb3cd | 1,221 | KinoGoClean | Apache License 2.0 |
src/commonMain/kotlin/ai/hypergraph/kaliningraph/parsing/CFG.kt | breandan | 245,074,037 | false | null | @file:Suppress("NonAsciiCharacters")
package ai.hypergraph.kaliningraph.parsing
import ai.hypergraph.kaliningraph.graphs.LabeledGraph
import ai.hypergraph.kaliningraph.sampling.choose
import ai.hypergraph.kaliningraph.tokenizeByWhitespace
import ai.hypergraph.kaliningraph.types.*
import kotlin.jvm.JvmName
import kotlin.time.*
typealias Σᐩ = String
typealias Production = Π2<Σᐩ, List<Σᐩ>>
// TODO: make this immutable
typealias CFG = Set<Production>
val Production.LHS: Σᐩ get() = first
val Production.RHS: List<Σᐩ> get() =
second.let { if (it.size == 1) it.map(Σᐩ::stripEscapeChars) else it }
/**
* "Freezes" the enclosed CFG, making it immutable and caching its hashCode for
* much faster equality checks unlike the default LinkedHashSet implementation,
* which must recompute hashCode(), incurring O(n) cost in the size of the CFG.
* This is only necessary because we are using the cache { ... } pattern, which
* will be slow to compute the first time, but much faster on subsequent calls.
* Storing the hashCode() in a field avoids recomputing it on every read.
*/
fun CFG.freeze(): CFG = if (this is FrozenCFG) this else FrozenCFG(this)
private class FrozenCFG(val cfg: CFG): CFG by cfg {
val cfgId = cfg.hashCode()
override fun equals(other: Any?) =
((other as? FrozenCFG)?.cfgId == cfgId) || (other as? CFG) == cfg
override fun hashCode(): Int = cfgId
}
val CFG.language: CFL by cache { CFL(this) }
val CFG.delimiters: Array<Σᐩ> by cache { (terminals.sortedBy { -it.length } + arrayOf(HOLE_MARKER, " ")).toTypedArray() }
val CFG.nonterminals: Set<Σᐩ> by cache { map { it.LHS }.toSet() }
val CFG.symbols: Set<Σᐩ> by cache { nonterminals + flatMap { it.RHS } }
val CFG.terminals: Set<Σᐩ> by cache { symbols - nonterminals }
val CFG.terminalUnitProductions: Set<Production>
by cache { filter { it.RHS.size == 1 && it.RHS[0] !in nonterminals } }
val CFG.unitProductions: Set<Production> by cache { filter { it.RHS.size == 1 } }
val CFG.nonterminalProductions: Set<Production> by cache { filter { it !in terminalUnitProductions } }
val CFG.unitNonterminals: Set<Σᐩ> by cache { terminalUnitProductions.map { it.LHS }.toSet() }
val CFG.bimap: BiMap by cache { BiMap(this) }
// Maps nonterminal sets to their terminals, n.b., each terminal can be generated
// by multiple nonterminals, and each nonterminal can generate multiple terminals
val CFG.tmap: Map<Set<Σᐩ>, Set<Σᐩ>> by cache {
terminals.map { bimap[listOf(it)] to it }.groupBy { it.first }
.mapValues { it.value.map { it.second }.toSet() }
}
// Maps each nonterminal to the set of nonterminals that can generate it
val CFG.vindex: Array<IntArray> by cache {
Array(bindex.indexedNTs.size) { i ->
bimap[bindex[i]].filter { it.size > 1 }
.flatMap { listOf(bindex[it[0]], bindex[it[1]]) }.toIntArray()
}
}
val CFG.bindex: Bindex<Σᐩ> by cache { Bindex(nonterminals) }
val CFG.normalForm: CFG by cache { normalize() }
val CFG.depGraph: LabeledGraph by cache { dependencyGraph() }
val CFG.revDepGraph: LabeledGraph by cache { revDependencyGraph() }
// Terminals which are blocked from being synthesized by a solver
val CFG.blocked: MutableSet<Σᐩ> by cache { mutableSetOf() }
val CFG.originalForm: CFG by cache { rewriteHistory[this]?.get(0) ?: this }
val CFG.nonparametricForm: CFG by cache { rewriteHistory[this]!![1] }
//val CFG.originalForm by cache { rewriteHistory[this]!![0] }
//val CFG.nonparametricForm by cache { rewriteHistory[this]!![1] }
/** Backing fields for [reachableSymbols], [reachableSymbolsViaUnitProds]
* TODO: back the fields with functions instead of vis versa using mutable maps?
* - Pros: early accesses are faster with a gradually-filled map
* - Cons: immutable fields follow convention, easier to reason about
*/
val CFG.reachability by cache { mutableMapOf<Σᐩ, Set<Σᐩ>>() }
// Equivalence class of an NT B are all NTs, A ->* B ->* C
// reachable via unit productions (in forward or reverse)
val CFG.unitReachability by cache {
symbols.associateWith { from ->
LabeledGraph {
unitProductions.map { it.LHS to it.RHS[0] }
// .filter { (a, b) -> nonterminals.containsAll(listOf(a, b)) }
.forEach { (a, b) -> a - b }
}.let {
setOf(from) + (it.transitiveClosure(setOf(from)) +
it.reversed().transitiveClosure(setOf(from)))
}.filter { it in nonterminals }
}
}
val CFG.noNonterminalStubs: CFG by cache {
println("Disabling nonterminal stubs!")
filter { it.RHS.none { it.isNonterminalStubIn(this) } }.toSet().freeze()
.also { rewriteHistory.put(it, freeze().let { rewriteHistory[it]!! + listOf(it)}) }
.also { it.blocked.addAll(blocked) }
}
val CFG.noEpsilonOrNonterminalStubs: CFG by cache {
println("Disabling nonterminal stubs!")
filter { it.RHS.none { it.isNonterminalStubIn(this) } }
.filter { "ε" !in it.toString() }.toSet().freeze()
.also { rewriteHistory.put(it, freeze().let { rewriteHistory[it]!! + listOf(it)}) }
.also { it.blocked.addAll(blocked) }
}
val CFG.parikhFPCache: Map<Σᐩ, BitvecPosetInterval> by cache { TODO() }
// Maps each symbol to the set of nonterminals that can generate it
val CFG.generators: Map<Σᐩ, Set<Σᐩ>> by cache {
map { prod -> prod.RHS.map { it to prod.LHS } }.flatten()
.groupBy { it.first }.mapValues { it.value.map { it.second }.toSet() }
}
val CFG.nonterminalFormulas: Map<Σᐩ, Σᐩ> by cache {
nonterminals.associateWith { nt -> toFormula(nt) }
}
/**
* Maps each nonterminal to terminals that can be reached from it. At least one of
* each of these terminals must be present in the input string for the nonterminal
* to be matched. If a string does not contain any of these terminals, we know the
* nonterminal is not contained in the parse tree, and can prune it from the CFG.
*
* Γ |- A -> a
* -----------------------
* Γ |- φ[A] = a
*
* Γ |- A -> B C
* -----------------------
* Γ |- φ[A] = φ[B] ʌ φ[C]
*
* Γ |- A -> B | C
* -----------------------
* Γ |- φ[A] = φ[B] v φ[C]
*/
fun CFG.toFormula(nt: Σᐩ): Σᐩ =
when (nt) {
in terminals -> nt
!in nonterminals -> "false"
else -> bimap[nt].joinToString(" or ", "( ", " )") {
it.joinToString(" and ", "( ", " )") { toFormula(it) }
}
} // TODO: fix stack blowup when there is a cycle in the CFG
// Prunes all nonterminals that represent a finite set of terminals down to the root
// Usually this is a tree-like structure, but it can also be a DAG of nonterminals
val CFG.pruneTreelikeNonterminals: CFG by cache {
println("Pruning treelike nonterminals!")
filter { it.RHS.any { !it.isTreelikeNonterminalIn(this) } || "ε" in it.LHS }.toSet()
.let { cfg ->
val brokenReferences = cfg.terminals
cfg +
// Restore preexisting nonterminal stubs for all remaining treelike nonterminals
brokenReferences.filter { "<$it>" in terminals }.map { it to listOf("<$it>") } +
cfg.nonterminals.filter { it.isOrganicNonterminal() }.map { it to listOf("<$it>") } +
// Restore old nonterminal stubs for unreferenced unit productions
brokenReferences.filter { it.isSyntheticNonterminal() && it in nonterminals }
.map { l -> filter { it.LHS == l }.map { l to it.RHS } }
.flatten()
// .first()
.toSet().also { println("Restored productions: ${it.prettyPrint()}") }
}
.let { it.transformIntoCNF() }
.also { rewriteHistory.put(it, freeze().let { listOf(rewriteHistory[it]!![0]) + listOf(it)}) }
.also { it.blocked.addAll(blocked) }
}
// Returns true iff the receiver is a nonterminal whose descendants
// are themselves either (1) treelike nonterminals or (2) terminals
private fun Σᐩ.isTreelikeNonterminalIn(
cfg: CFG,
reachables: Set<Σᐩ> = cfg.reachableSymbols(this) - this,
nonTreeLike: Set<Σᐩ> = setOf(this)
): Bln = when {
"ε" in this -> true
(reachables intersect nonTreeLike).isNotEmpty() -> false
else -> reachables.all { it in cfg.terminals ||
it.isTreelikeNonterminalIn(cfg, nonTreeLike = nonTreeLike + reachables) }
}
val CFG.joinMap: JoinMap by cache { JoinMap(this) }
class JoinMap(val CFG: CFG) {
// TODO: Doesn't appear to confer any significant speedup? :/
val precomputedJoins: MutableMap<Π2A<Set<Σᐩ>>, Set<Π3A<Σᐩ>>> =
CFG.nonterminals.choose(1..3).let { it * it }
.associateWith { subsets -> subsets.let { (l, r) -> join(l, r) } }
.also { println("Precomputed join map has ${it.size} entries.") }.toMutableMap()
fun join(l: Set<Σᐩ>, r: Set<Σᐩ>, tryCache: Bln = false): Set<Π3A<Σᐩ>> =
if (tryCache) precomputedJoins[l to r] ?: join(l, r, false).also { precomputedJoins[l to r] = it }
else (l * r).flatMap { (l, r) -> CFG.bimap[listOf(l, r)].map { Triple(it, l, r) } }.toSet()
@JvmName("setJoin")
operator fun get(l: Set<Σᐩ>, r: Set<Σᐩ>): Set<Σᐩ> =
join(l, r, false).map { it.first }.toSet()
@JvmName("treeJoin")
operator fun get(left: Forest, right: Forest): Forest =
join(left.map { it.root }.toSet(), right.map { it.root }.toSet(), false)
.map { (rt, l, r) ->
Tree(rt, null, left.first { it.root == l }, right.first { it.root == r })
}.toSet()
}
// Maps indices to nonterminals and nonterminals to indices
class Bindex<T>(
val set: Set<T>,
val indexedNTs: List<T> = set.toList(),
val ntIndices: Map<T, Int> = indexedNTs.zip(indexedNTs.indices).toMap()
): List<T> by indexedNTs {
constructor(map: Map<Int, T>) : this(map.values.toSet(), map.values.toList(), map.entries.associate { it.value to it.key })
operator fun get(s: T): Int = ntIndices[s] ?: 1.also { println("Unknown nonterminal: $s"); null!! }
fun getUnsafe(s: T): Int? = ntIndices[s]
override fun toString(): String = indexedNTs.mapIndexed { i, it -> "$i: $it" }.joinToString("\n", "Bindex:\n", "\n")
}
// Maps variables to expansions and expansions to variables in a grammar
class BiMap(cfg: CFG) {
val L2RHS by lazy { cfg.groupBy({ it.LHS }, { it.RHS }).mapValues { it.value.toSet() } }
val R2LHS by lazy { cfg.groupBy({ it.RHS }, { it.LHS }).mapValues { it.value.toSet() } }
val TDEPS: Map<Σᐩ, Set<Σᐩ>> by lazy { // Maps all symbols to NTs that can generate them
mutableMapOf<Σᐩ, MutableSet<Σᐩ>>().apply {
for ((l, r) in cfg) for (symbol in r)
getOrPut(symbol) { mutableSetOf() }.add(l)
}
}
val NDEPS: Map<Σᐩ, Set<Σᐩ>> by lazy { // Maps all NTs to the symbols they can generate
mutableMapOf<Σᐩ, MutableSet<Σᐩ>>().apply {
for ((l, r) in cfg) for (symbol in r)
getOrPut(l) { mutableSetOf() }.add(symbol)
}
}
val TRIPL by lazy {
R2LHS.filter { it.key.size == 2 }
.map { it.value.map { v -> v to it.key[0] to it.key[1] } }.flatten()
}
val X2WZ: Map<Σᐩ, List<Triple<Σᐩ, Σᐩ, Σᐩ>>> by lazy {
TRIPL.groupBy { it.second }.mapValues { it.value }
}
val UNITS by lazy {
cfg.filter { it.RHS.size == 1 && it.RHS[0] !in cfg.nonterminals }
.groupBy({ it.LHS }, { it.RHS[0] }).mapValues { it.value.toSet() }
}
operator fun get(p: List<Σᐩ>): Set<Σᐩ> = R2LHS[p] ?: emptySet()
operator fun get(p: Σᐩ): Set<List<Σᐩ>> = L2RHS[p] ?: emptySet()
operator fun get(p: Set<Σᐩ>): Set<Σᐩ> = TDEPS.entries.filter { it.value == p }.map { it.key }.toSet()
}
/*
Γ ⊢ ∀ v.[α→*]∈G ⇒ α→[β] "If all productions rooted at α
----------------------- □β yield β, then α necessarily yields β"
Γ ⊢ □ α→[β]
Γ ⊢ □ ω→[α] □ α→[β]
----------------------- trans
Γ ⊢ □ ω → [α]∪[β]
Γ ⊢ s∈Σ\Σ' v'∈V.□v'→[s] "Any production containing a nonterminal that
----------------------- elim necessarily generates a terminal that is not
Γ ⊢ ∀ρ,v∈ρ G' ← G'\ρ in the subgrammar can be safely removed."
*/
val CFG.mustGenerate by cache { inevitableSymbols() }
fun CFG.inevitableSymbols(map: Map<Σᐩ, Set<Σᐩ>> = emptyMap()): Map<Σᐩ, Set<Σᐩ>> {
val newMap = map.toMutableMap()
symbols.forEach { smb ->
// println("Testing $smb")
bimap.TDEPS[smb]?.forEach { nt ->
// println("Testing $smb -> $nt")
if (bimap[nt].all { smb in it || nt in it }) {
// println("Worked! $nt => $smb")
newMap[nt] = newMap.getOrPut(nt) { setOf(nt) } +
newMap.getOrPut(smb) { setOf(smb) }
}
// else {
// if (smb == "NEWLINE")
// println("Failed! $nt !=> $smb, first ${bimap[nt].first { smb !in it }}")
// }
}
newMap[smb] = newMap.getOrPut(smb) { setOf(smb) }
}
return if (newMap == map) map else inevitableSymbols(newMap)
}
fun Bln.explain(cfg: CFG, prod: Production, reason: String = "") = this.also{
if(it) {
println("Removed [${prod.LHS} -> ${prod.RHS.joinToString(" ")}] because $reason")
if (cfg.count { it.first == prod.LHS } == 1) println("And no other productions were left for `${prod.LHS}`!")
}
}
fun CFG.removeTerminalsVerbose(allowed: Set<Σᐩ>, otps: Set<Production> = this.terminalUnitProductions, origTerms: Set<Σᐩ> = this.terminals, mustGenerate: Map<Σᐩ, Set<Σᐩ>> = this.mustGenerate): CFG {
val deadNTs = mutableSetOf<Σᐩ>()
val next = toMutableSet().apply { removeAll { prod ->
(
// (prod in otps && (prod.RHS.first() !in allowed))
// .explain(this, prod, "the terminal `${prod.RHS.first()}` is not allowed") ||
(mustGenerate[prod.LHS]?.any { (it in origTerms && it !in allowed)
.explain(this, prod, "LHS value `${prod.LHS}` must generate `$it` and `$it` was not allowed") } == true) ||
prod.RHS.any { rhs -> mustGenerate[rhs]?.any { (it in origTerms && it !in allowed)
.explain(this, prod, "RHS value `$rhs` must generate `$it` and `$it` was not allowed") } == true }
).also { if (it && this.count { it.first == prod.first } == 1) {
println("Added `${prod.first}` to deadNTs!")
deadNTs.add(prod.LHS) }
}
} }
next.removeAll { prod ->
prod.RHS.any { rhs ->
(rhs in deadNTs).explain(next, prod, "the RHS value `$rhs` is a dead NT!") ||
(rhs !in origTerms).explain(next, prod, "the RHS terminal `$rhs` was a chopped NT")
}
}
return if (next.size == size) this else next.removeTerminalsVerbose(allowed, otps, origTerms, mustGenerate)
}
fun CFG.removeTerminals(
allowed: Set<Σᐩ>,
deadNTs: Set<Σᐩ> = emptySet(),
origTerms: Set<Σᐩ> = this.terminals,
mustGenerate: Map<Σᐩ, Set<Σᐩ>> = this.mustGenerate
): CFG {
val deadNTs = deadNTs.toMutableSet()
val next = toMutableSet().apply {
removeAll { prod ->
(prod.RHS + prod.LHS).toSet().any { mustGenerate[it]?.any { it in origTerms && it !in allowed || it in deadNTs } == true }
.also { if (it && count { it.first == prod.first } == 1) deadNTs.add(prod.LHS) }
}
}
next.removeAll { prod -> prod.RHS.any { rhs -> rhs in deadNTs || (rhs in next.terminals && rhs !in origTerms) } }
val new = next.removeUselessSymbols()
return if (new.size == size) this else new.removeTerminals(allowed, deadNTs, origTerms, mustGenerate)
}
/*
Specializes the CFG to a set of terminals X, by recursively pruning
every nonterminal v which necessarily generates a terminal t' ∉ X and
every nonterminal that necessarily generates v. We call the set of all
productions that remain after pruning, the preimage of G under T or the "subgrammar".
*/
fun CFG.subgrammar(image: Set<Σᐩ>): CFG =
removeTerminals(image)
.also { rewriteHistory.put(it, freeze().let { rewriteHistory[it]!! + listOf(it)}) }
.freeze()
fun CFG.forestHash(s: Σᐩ) = parseForest(s).map { it.structureEncode() }.hashCode()
fun CFG.nonterminalHash(s: Σᐩ) = s.tokenizeByWhitespace().map { preimage(it) }.hashCode()
fun CFG.preimage(vararg nts: Σᐩ): Set<Σᐩ> = bimap.R2LHS[nts.toList()] ?: emptySet()
fun CFG.dependencyGraph() =
LabeledGraph { forEach { prod -> prod.second.forEach { rhs -> prod.LHS - rhs } } }
fun CFG.revDependencyGraph() =
LabeledGraph { forEach { prod -> prod.second.forEach { rhs -> rhs - prod.LHS } } }
fun CFG.jsonify() = "cfg = {\n" +
bimap.L2RHS.entries.joinToString("\n") {
("\"${it.key}\": [${it.value.joinToString(", ") {
it.joinToString(", ", "(", ")") { "\"$it\"" }
}}],")
} + "\n}" | 0 | null | 9 | 98 | 239d016004b6591439f53a597a7a108c38f1dce8 | 16,050 | galoisenne | Apache License 2.0 |
src/main/java/dev/arbor/gtnn/api/pattern/APredicates.kt | Arborsm | 714,203,348 | false | {"Kotlin": 460320, "Java": 75109} | package dev.arbor.gtnn.api.pattern
import com.gregtechceu.gtceu.api.GTValues.*
import com.gregtechceu.gtceu.api.machine.multiblock.PartAbility
import com.gregtechceu.gtceu.api.pattern.Predicates
import com.gregtechceu.gtceu.api.pattern.TraceabilityPredicate
import com.gregtechceu.gtceu.api.pattern.error.PatternStringError
import com.lowdragmc.lowdraglib.utils.BlockInfo
import dev.arbor.gtnn.api.block.BlockMaps
import net.minecraft.network.chat.Component
@SuppressWarnings("unused")
object APredicates {
fun plantCasings(): TraceabilityPredicate {
return TraceabilityPredicate({
val blockState = it.getBlockState()
for (entry in BlockMaps.ALL_CP_CASINGS) {
if (blockState.`is`(entry.value.get())) {
val stats = entry.key
val currentPlantCasing = it.matchContext.getOrPut("PlantCasing", stats)
if (!currentPlantCasing.equals(stats)) {
it.setError(PatternStringError("gtnn.multiblock.pattern.error.plant_casings"))
return@TraceabilityPredicate false
}
return@TraceabilityPredicate true
}
}
return@TraceabilityPredicate false
}, {
BlockMaps.ALL_CP_CASINGS.values
.map { BlockInfo.fromBlockState(it.get().defaultBlockState()) }
.toTypedArray()
}).addTooltips(Component.translatable("gtnn.multiblock.pattern.error.plant_casings"))
}
fun pipeBlock(): TraceabilityPredicate {
return TraceabilityPredicate({
val blockState = it.getBlockState()
for (entry in BlockMaps.ALL_CP_TUBES) {
if (blockState.`is`(entry.value.get())) {
val stats = entry.key
val currentPipeBlock = it.matchContext.getOrPut("Pipe", stats)
if (!currentPipeBlock.equals(stats)) {
it.setError(PatternStringError("gtnn.multiblock.pattern.error.pipe"))
return@TraceabilityPredicate false
}
return@TraceabilityPredicate true
}
}
return@TraceabilityPredicate false
}, {
BlockMaps.ALL_CP_TUBES
.map { BlockInfo.fromBlockState(it.value.get().defaultBlockState()) }
.toTypedArray()
}).addTooltips(Component.translatable("gtnn.multiblock.pattern.error.pipe"))
}
fun machineCasing(): TraceabilityPredicate {
return TraceabilityPredicate({
val blockState = it.getBlockState()
for (entry in BlockMaps.ALL_MACHINE_CASINGS) {
if (blockState.`is`(entry.value.get())) {
val stats = entry.key
val currentMachineCasing = it.matchContext.getOrPut("MachineCasing", stats)
if (!currentMachineCasing.equals(stats)) {
it.setError(PatternStringError("gtnn.multiblock.pattern.error.machine_casing"))
return@TraceabilityPredicate false
}
return@TraceabilityPredicate true
}
}
return@TraceabilityPredicate false
}, {
BlockMaps.ALL_MACHINE_CASINGS
.map { BlockInfo.fromBlockState(it.value.get().defaultBlockState()) }
.toTypedArray()
}).addTooltips(Component.translatable("gtnn.multiblock.pattern.error.machine_casing"))
}
fun ability(ability: PartAbility): TraceabilityPredicate {
val tiers = listOf(ULV, LV, MV, HV, EV, IV, LuV, ZPM, UV).filter { it <= 1 }.toIntArray()
return Predicates.blocks(*(if (tiers.isEmpty()) ability.allBlocks else ability.getBlocks(*tiers)).toTypedArray())
}
}
| 3 | Kotlin | 6 | 8 | 73292b30ae541944f13f5b541091a67b9cc7d51a | 3,869 | GT-- | MIT License |
src/main/kotlin/name/oshurkov/books/file/fb2/parser/Gson.kt | dmitry-oshurkov | 307,598,181 | false | null | package name.oshurkov.books.file.fb2.parser
/**
* Created by kurs on 30.7.17.
*/
class Gson
| 0 | Kotlin | 0 | 1 | 7bb9e08427880b1fea843c0326ba5ee5d86426d3 | 95 | books | MIT License |
app/src/main/java/com/lukitor/myapplicationC/ActivityFormInput.kt | lukifenca | 367,644,543 | false | null | package com.lukitor.myapplicationC
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.lukitor.myapplicationC.databinding.ActivityFormInputBinding
class ActivityFormInput : AppCompatActivity() {
lateinit var binding: ActivityFormInputBinding
var dataDiri = HashMap<String, String>()
var dataMedis = HashMap<String, String>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding= ActivityFormInputBinding.inflate(layoutInflater)
setContentView(binding.root)
if(intent.hasExtra("medis")){
dataMedis=intent.getSerializableExtra("medis") as HashMap<String, String>
}
if(intent.hasExtra("data")){
dataDiri=intent.getSerializableExtra("data") as HashMap<String, String>
binding.etNama.setText(dataDiri["nama"])
binding.etUmur.setText(dataDiri["umur"])
binding.etEmail.setText(dataDiri["email"])
binding.etTinggiBadan.setText(dataDiri["tinggi"])
binding.etBeratBadan.setText(dataDiri["berat"])
}
binding.pgFormIdentity.progress=50
binding.etNama.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if(count>0){
binding.txtFieldNama.error = null
binding.txtFieldNama.helperText = ""
}
if(count==0){
binding.txtFieldNama.helperText = "*Required"
}
}
override fun afterTextChanged(s: Editable?) {
}
})
binding.etUmur.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if(count>0){
binding.txtUmur.error = null
binding.txtUmur.helperText = ""
}
if(count==0){
binding.txtUmur.helperText = "*Required"
}
}
override fun afterTextChanged(s: Editable?) {
}
})
binding.etEmail.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if(count>0){
binding.txtEmail.error = null
binding.txtEmail.helperText = ""
}
if(count==0){
binding.txtEmail.helperText = "*Required"
}
}
override fun afterTextChanged(s: Editable?) {
}
})
binding.etBeratBadan.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if(count>0){
binding.txtInputBeratBadan.error = null
binding.txtInputBeratBadan.helperText = ""
}
if(count==0){
binding.txtInputBeratBadan.helperText = "*Required"
}
}
override fun afterTextChanged(s: Editable?) {
}
})
binding.etTinggiBadan.addTextChangedListener(object : TextWatcher {
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
if(count>0){
binding.txtInputTinggiBadan.error = null
binding.txtInputTinggiBadan.helperText = ""
}
if(count==0){
binding.txtInputTinggiBadan.helperText = "*Required"
}
}
override fun afterTextChanged(s: Editable?) {
}
})
binding.fabNextToBM.setOnClickListener(View.OnClickListener {
var status = true;
if (binding.etNama.text!!.isEmpty()) {
status = false
binding.txtFieldNama.isErrorEnabled = true
binding.txtFieldNama.error = "Field Ini Harus Diisi !"
}
if (binding.etUmur.text!!.isEmpty()) {
status = false
binding.txtUmur.isErrorEnabled = true
binding.txtUmur.error = "Field Ini Harus Diisi !"
}
if (binding.etEmail.text!!.isEmpty()){
status = false
binding.txtEmail.isErrorEnabled = true
binding.txtEmail.error = "Field Ini Harus Diisi !"
}
if (binding.etBeratBadan.text!!.isEmpty()) {
status = false
binding.txtInputBeratBadan.isErrorEnabled = true
binding.txtInputBeratBadan.error = "Field Ini Harus Diisi !"
}
if (binding.etTinggiBadan.text!!.isEmpty()) {
status = false
binding.txtInputTinggiBadan.isErrorEnabled = true
binding.txtInputTinggiBadan.error = "Field Ini Harus Diisi !"
}
if (status) {
dataDiri["nama"] = binding.etNama.text.toString()
dataDiri["umur"] = binding.etUmur.text.toString()
dataDiri["email"] = binding.etEmail.text.toString()
dataDiri["berat"] = binding.etBeratBadan.text.toString()
dataDiri["tinggi"] = binding.etTinggiBadan.text.toString()
var intentKirim = Intent(this, ActivityFormMedis::class.java)
intentKirim.putExtra("data", dataDiri)
intentKirim.putExtra("medis", dataMedis)
startActivity(intentKirim)
}
})
supportActionBar?.hide()
}
override fun onBackPressed() {
super.onBackPressed()
finish()
}
} | 0 | Kotlin | 0 | 1 | 58fd1ce69902bb63400de11f599e619767ce53d0 | 6,591 | CapstoneProject | MIT License |
generators/test-generator/tests/org/jetbrains/kotlin/generators/TestGenerator.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.generators
import org.jetbrains.kotlin.generators.model.MethodModel
abstract class TestGenerator(
methodGenerators: List<MethodGenerator<*>>
) {
protected val methodGenerators: Map<MethodModel.Kind, MethodGenerator<*>> =
methodGenerators.associateBy { it.kind }.withDefault { error("Generator for method with kind $it not found") }
abstract fun generateAndSave(testClass: TestGroup.TestClass, dryRun: Boolean, mainClassName: String?): GenerationResult
data class GenerationResult(val newFileGenerated: Boolean, val testSourceFilePath: String)
}
| 181 | null | 5748 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 813 | kotlin | Apache License 2.0 |
junit/src/main/kotlin/com/tomasznajda/ktx/junit/AssertExt.kt | tomasznajda | 148,339,649 | false | null | package com.tomasznajda.ktx.junit
import org.hamcrest.CoreMatchers
import org.junit.Assert
import kotlin.reflect.KClass
fun assertEquals(expected: Any?, actual: Any?) = Assert.assertEquals(expected, actual)
fun <T : Any> Any.assertIsInstanceOf(clazz: KClass<T>) =
Assert.assertThat(this, CoreMatchers.`is`(CoreMatchers.instanceOf(clazz.java))) | 0 | Kotlin | 4 | 22 | 5efbd11492dbcc634c34990d8dcb90e9fd07ce17 | 354 | useful-ktx | Apache License 2.0 |
app/src/main/java/com/umaplasticsfsm/features/taskManagement/PriorityTaskSel.kt | DebashisINT | 740,356,583 | false | {"Kotlin": 13950763, "Java": 1000924} | package com.umaplasticsfsm.features.taskManagement
import com.umaplasticsfsm.base.BaseResponse
data class PriorityTaskSel(var task_priority_list:ArrayList<TaskPriorityResponse> = ArrayList()): BaseResponse()
data class TaskPriorityResponse (var task_priority_id:String = "",
var task_priority_name:String = "")
| 0 | Kotlin | 0 | 0 | 2ccc871bdcf7df2d08825d0b9ded73b11495519e | 354 | UmaPlastics | Apache License 2.0 |
src/commonMain/kotlin/com/handtruth/mc/minecraft/proto/ResponsePaket.kt | handtruth | 258,816,135 | false | null | package com.handtruth.mc.minecraft.proto
import com.handtruth.mc.minecraft.model.ServerStatus
import com.handtruth.mc.minecraft.util.json
import com.handtruth.mc.paket.Paket
import com.handtruth.mc.paket.PaketCreator
import com.handtruth.mc.paket.fields.string
class ResponsePaket(message: ServerStatus) : Paket() {
override val id = PaketID.HandshakeRequestResponse
var message by string(json, message)
companion object : PaketCreator<ResponsePaket> {
override fun produce() = ResponsePaket(
ServerStatus(
ServerStatus.Version("", -1),
ServerStatus.Players(0, 0, null)
)
)
}
}
| 0 | Kotlin | 0 | 0 | 786d546cf537a98c8222d202a69d8473a6cc52c7 | 669 | mctools | MIT License |
app/src/main/java/com/raul/macias/wikiheroes/view/viewholder/CharacterViewHolder.kt | xR4ULx | 313,670,556 | false | {"Gradle": 3, "Java Properties": 4, "Shell": 1, "Text": 1, "Ignore List": 3, "Batchfile": 1, "Git Attributes": 1, "Markdown": 1, "INI": 7, "Proguard": 1, "Kotlin": 119, "XML": 222, "Java": 5} | package com.raul.macias.wikiheroes.view.viewholder
import androidx.databinding.DataBindingUtil
import android.view.View
import com.raul.macias.wikiheroes.databinding.ItemCharacterBinding
import com.raul.macias.wikiheroes.models.Character
import com.raul.macias.wikiheroes.view.ui.home.ItemCharacterViewModel
class CharacterViewHolder(view: View, val delegate: Delegate) : BaseViewHolder(view) {
//here we define actions that we handle
interface Delegate {
fun onItemClick(character: Character, view: View)
}
private lateinit var character: Character
private val binding by lazy { DataBindingUtil.bind<ItemCharacterBinding>(view) }
override fun bindData(data: Any?) {
if (data is Character) {
character = data
drawUI()
}
}
private fun drawUI() {
binding.apply {
binding?.vModel = ItemCharacterViewModel(character)
binding?.executePendingBindings()
}
}
override fun onClick(view: View?) {
delegate.onItemClick(character, itemView)
}
override fun onLongClick(view: View?): Boolean {
return false
}
} | 1 | null | 1 | 1 | d76d4736780b156d2b8133e794cca2de6b408f28 | 1,165 | kotlin_api_marvel | MIT License |
bot/connector-messenger/src/main/kotlin/fr/vsct/tock/bot/connector/messenger/model/webhook/OptinWebhook.kt | curinator | 207,578,255 | true | {"Kotlin": 3731711, "TypeScript": 587148, "HTML": 201325, "CSS": 60702, "JavaScript": 4142, "Shell": 2610} | /*
* Copyright (C) 2017 VSCT
*
* 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 fr.vsct.tock.bot.connector.messenger.model.webhook
import fr.vsct.tock.bot.connector.messenger.model.Recipient
import fr.vsct.tock.bot.connector.messenger.model.Sender
import fr.vsct.tock.bot.engine.user.PlayerId
import fr.vsct.tock.bot.engine.user.PlayerType
/**
*
*/
data class OptinWebhook(
override val sender: Sender?,
override val recipient: Recipient,
override val timestamp: Long,
val optin: Optin
) : Webhook() {
override fun playerId(playerType: PlayerType): PlayerId =
PlayerId(
sender?.id ?: optin.userRef ?: error("null sender field in webhook"),
if (playerType == PlayerType.user && sender?.id == null) PlayerType.temporary else playerType
)
} | 0 | null | 0 | 1 | dd37ec79ba29b4f6aacff704ca3400b41df47efb | 1,321 | tock | Apache License 2.0 |
composeApp/src/commonMain/kotlin/com.jerryokafor.smshare/screens/navigation/SideNav.kt | jerryOkafor | 759,464,735 | false | {"Kotlin": 218893, "Swift": 869, "HTML": 334, "Ruby": 254, "CSS": 102} | /*
* MIT License
*
* Copyright (c) 2024 SM Share Project
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.jerryokafor.smshare.screens.navigation
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.Logout
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.ChevronRight
import androidx.compose.material.icons.filled.Tag
import androidx.compose.material3.Badge
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ModalDrawerSheet
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.surfaceColorAtElevation
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.Painter
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.jerryokafor.smshare.component.ChannelWithName
import com.jerryokafor.smshare.component.iconIndicatorForAccountType
import com.jerryokafor.smshare.core.model.Account
import com.jerryokafor.smshare.theme.FillingSpacer
import org.jetbrains.compose.resources.painterResource
import org.jetbrains.compose.resources.stringResource
import smshare.composeapp.generated.resources.Res
import smshare.composeapp.generated.resources.avatar6
import smshare.composeapp.generated.resources.main_app_name
import smshare.composeapp.generated.resources.title_accounts
import smshare.composeapp.generated.resources.title_add_account
import smshare.composeapp.generated.resources.title_logout
import smshare.composeapp.generated.resources.title_manage_tags
import smshare.composeapp.generated.resources.title_more
import kotlin.math.min
sealed interface SideNavMenuAction {
data object Logout : SideNavMenuAction
data object AddNewConnection : SideNavMenuAction
data object ManageTags : SideNavMenuAction
}
fun spacedByWithFooter(space: Dp) = object : Arrangement.Vertical {
override val spacing = space
override fun Density.arrange(
totalSize: Int,
sizes: IntArray,
outPositions: IntArray,
) {
if (sizes.isEmpty()) return
val spacePx = space.roundToPx()
var occupied = 0
var lastSpace = 0
sizes.forEachIndexed { index, size ->
if (index == sizes.lastIndex) {
outPositions[index] = totalSize - size
} else {
outPositions[index] = min(occupied, totalSize - size)
}
lastSpace = min(spacePx, totalSize - outPositions[index] - size)
occupied = outPositions[index] + size + lastSpace
}
occupied -= lastSpace
}
}
@Composable
fun SideNav(
accounts: List<Account>,
onClose: (SideNavMenuAction?) -> Unit
) {
ModalDrawerSheet(
modifier = Modifier.width(280.dp),
drawerContainerColor = MaterialTheme.colorScheme.background,
) {
LazyColumn(
modifier = Modifier.fillMaxHeight(),
verticalArrangement = spacedByWithFooter(0.dp)
) {
item {
Text(
text = stringResource(Res.string.main_app_name),
modifier = Modifier.padding(
start = 16.dp,
end = 16.dp,
top = 16.dp,
bottom = 8.dp
),
style = MaterialTheme.typography.titleLarge,
)
}
item {
Spacer(modifier = Modifier.height(8.dp))
MenuGroup {
SideNavMenu(
title = "Content",
subTitle = "Save your ideas",
) {
onClose(null)
}
HorizontalDivider(modifier = Modifier.height(0.5.dp).padding(horizontal = 8.dp))
SideNavMenu(
title = "Calendar",
subTitle = "See your schedule wide",
) {
onClose(null)
}
}
}
item {
Text(
text = stringResource(Res.string.title_accounts),
modifier = Modifier.padding(
start = 16.dp,
end = 16.dp,
top = 16.dp,
bottom = 8.dp
)
)
MenuGroup {
accounts.forEachIndexed { index, account ->
ChannelItemMenu(
name = account.name,
avatar = painterResource(Res.drawable.avatar6),
postsCount = account.postsCount,
indicator = iconIndicatorForAccountType(account.type),
onClick = { onClose(null) },
)
//Add divider except for the last item
if (index < accounts.size - 1) {
HorizontalDivider(
modifier = Modifier
.height(0.5.dp)
.padding(start = 80.dp, end = 8.dp)
)
}
}
if (accounts.isEmpty()) {
Row(
modifier = Modifier.padding(
vertical = 8.dp,
horizontal = 16.dp
).fillParentMaxWidth(),
horizontalArrangement = Arrangement.Center
) { Text("No Account", color = MaterialTheme.colorScheme.error) }
}
}
}
item {
Spacer(modifier = Modifier.height(8.dp))
MenuGroup {
MoreMenuItem(
title = stringResource(Res.string.title_add_account),
icon = Icons.Default.Add,
onClick = { onClose(SideNavMenuAction.AddNewConnection) },
)
HorizontalDivider(modifier = Modifier.height(0.5.dp))
MoreMenuItem(
title = stringResource(Res.string.title_manage_tags),
icon = Icons.Default.Tag,
onClick = { onClose(SideNavMenuAction.ManageTags) })
}
}
item {
Text(
text = stringResource(Res.string.title_more),
modifier = Modifier.padding(
start = 16.dp,
end = 16.dp,
top = 16.dp,
bottom = 8.dp
)
)
MenuGroup(modifier = Modifier) {
MoreMenuItem(
title = stringResource(Res.string.title_logout),
color = Color.Red,
icon = Icons.AutoMirrored.Filled.Logout,
onClick = { onClose(SideNavMenuAction.Logout) }
)
}
Spacer(modifier = Modifier.height(50.dp))
}
}
}
}
@Composable
fun MenuGroup(
modifier: Modifier = Modifier,
content: @Composable ColumnScope.() -> Unit
) {
Surface(
modifier = modifier,
color = MaterialTheme.colorScheme
.surfaceColorAtElevation(elevation = 5.dp)
.copy(alpha = 0.5f),
content = {
Column {
content()
}
},
)
}
@Composable
fun SideNavMenu(
title: String,
subTitle: String,
onClick: () -> Unit = {},
) {
Surface(onClick = onClick) {
Row(
modifier = Modifier.fillMaxWidth()
.padding(start = 16.dp, end = 8.dp, bottom = 8.dp, top = 8.dp),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically,
) {
Column {
Text(text = title, style = MaterialTheme.typography.labelLarge)
Spacer(modifier = Modifier.height(8.dp))
Text(text = subTitle, style = MaterialTheme.typography.bodySmall)
}
Spacer(modifier = Modifier.width(16.dp))
FillingSpacer()
Icon(
imageVector = Icons.Default.ChevronRight,
contentDescription = null,
)
}
}
}
@Composable
fun ChannelItemMenu(
modifier: Modifier = Modifier,
name: String,
postsCount: Int = 0,
avatar: Painter,
indicator: Painter,
avatarSize: Dp = 40.dp,
textStyle: TextStyle = MaterialTheme.typography.titleMedium,
color: Color = MaterialTheme.colorScheme.surface,
contentDescription: String? = null,
onClick: () -> Unit = {},
trailingContent: @Composable () -> Unit = {
if (postsCount > 1) {
Badge(
modifier = Modifier,
containerColor = Color.Gray,
) {
Text(
modifier = Modifier.padding(horizontal = 8.dp),
text = "$postsCount",
)
}
}
},
) {
Surface(onClick = onClick, color = color) {
Row(
modifier = modifier.fillMaxWidth()
.padding(start = 16.dp, end = 8.dp, bottom = 8.dp, top = 8.dp),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically,
) {
ChannelWithName(
modifier = Modifier.weight(4f),
name = name,
avatar = avatar,
indicator = indicator,
avatarSize = avatarSize,
textStyle = textStyle,
contentDescription = contentDescription,
)
FillingSpacer()
trailingContent()
}
}
}
@Composable
fun MoreMenuItem(
title: String,
icon: ImageVector,
color: Color = MaterialTheme.colorScheme.background,
onClick: () -> Unit = {},
) {
Surface(onClick = onClick) {
Row(
modifier = Modifier.fillMaxWidth()
.padding(start = 16.dp, end = 8.dp, bottom = 8.dp, top = 8.dp),
horizontalArrangement = Arrangement.Start,
verticalAlignment = Alignment.CenterVertically,
) {
Surface(
color = color,
shape = RoundedCornerShape(10),
) {
Icon(
modifier = Modifier.padding(4.dp),
imageVector = icon,
contentDescription = null,
tint = Color.White,
)
}
Spacer(modifier = Modifier.width(16.dp))
Text(text = title, style = MaterialTheme.typography.labelLarge)
FillingSpacer()
Icon(
imageVector = Icons.Default.ChevronRight,
contentDescription = null,
)
}
}
}
| 0 | Kotlin | 0 | 0 | 7637f249781b0500869c2eb2d78f9bac9cc30293 | 13,328 | SMShare | MIT License |
content/src/main/java/com/kafka/content/domain/language/UpdateLanguages.kt | vipulyaara | 170,554,386 | false | null | package com.kafka.content.domain.language
import com.kafka.data.model.AppCoroutineDispatchers
import com.kafka.data.model.Interactor
import com.kafka.content.data.language.LanguageRepository
import com.kafka.data.entities.Language
import com.kafka.data.injection.ProcessLifetime
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.plus
import javax.inject.Inject
class UpdateLanguages @Inject constructor(
dispatchers: AppCoroutineDispatchers,
@ProcessLifetime processScope: CoroutineScope,
private val languageRepository: LanguageRepository
) : Interactor<UpdateLanguages.Params>() {
override val scope: CoroutineScope = processScope + dispatchers.io
override suspend fun doWork(params: Params) {
languageRepository.saveLanguages(params.languages)
}
data class Params(val languages: List<Language>)
}
| 0 | Kotlin | 4 | 18 | 71a639047c246aa62c33fa472ab70100da25f727 | 857 | Kafka | Apache License 2.0 |
src/main/kotlin/org/example/demo/domain/ProductPriceChanged.kt | adrisalas | 710,959,750 | false | {"Kotlin": 8447} | package org.example.demo.domain
import java.math.BigDecimal
data class ProductPriceChanged(
val productCode: String,
val price: BigDecimal
) | 0 | Kotlin | 0 | 1 | 350ce87f58d349467218760c3ae82937bfa2b270 | 150 | spring-testcontainer-kafka-mysql | MIT License |
app/src/main/java/com/example/lunchtray/LunchTrayScreen.kt | kelvingcr | 679,250,425 | false | null | /*
* Copyright (C) 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.lunchtray
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowBack
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.NavHostController
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.currentBackStackEntryAsState
import androidx.navigation.compose.rememberNavController
import com.example.lunchtray.datasource.DataSource
import com.example.lunchtray.ui.AccompanimentMenuScreen
import com.example.lunchtray.ui.CheckoutScreen
import com.example.lunchtray.ui.EntreeMenuScreen
import com.example.lunchtray.ui.OrderViewModel
import com.example.lunchtray.ui.SideDishMenuScreen
import com.example.lunchtray.ui.StartOrderScreen
// TODO: Screen enum
enum class LunchTrayScreen(@StringRes val title: Int) {
Start(title = R.string.app_name),
Entree(title = R.string.choose_entree),
SideDish(title = R.string.choose_side_dish),
Accompaniment(title = R.string.choose_accompaniment),
OrderCheckout(title = R.string.order_checkout),
}
// TODO: AppBar
@Composable
fun AppBarLunchTray(
currentScreen: LunchTrayScreen,
canNavigateBack: Boolean,
navigateUp: () -> Unit,
modifier: Modifier = Modifier
) {
TopAppBar(
title = {
Text(text = stringResource(id = currentScreen.title))
},
colors = TopAppBarDefaults.mediumTopAppBarColors(containerColor = MaterialTheme.colorScheme.primaryContainer),
modifier = modifier,
navigationIcon = {
if(canNavigateBack) {
IconButton(onClick = navigateUp ) {
Icon(imageVector = Icons.Filled.ArrowBack, contentDescription = "Back")
}
}
}
)
}
@Composable
fun LunchTrayApp(
navController: NavHostController = rememberNavController(),
viewModel: OrderViewModel = viewModel()
) {
val backStackEntry by navController.currentBackStackEntryAsState()
val currentScreen = LunchTrayScreen.valueOf(backStackEntry?.destination?.route ?: LunchTrayScreen.Start.name)
Scaffold(
topBar = {
AppBarLunchTray(
currentScreen = currentScreen,
navigateUp = { navController.navigateUp() },
canNavigateBack = navController.previousBackStackEntry != null
)
}
) { innerPadding ->
val uiState by viewModel.uiState.collectAsState()
// TODO: Navigation host
NavHost(navController = navController, startDestination = LunchTrayScreen.Start.name, modifier = Modifier.padding(innerPadding)) {
composable(LunchTrayScreen.Start.name) {
StartOrderScreen(onStartOrderButtonClicked = { navController.navigate(LunchTrayScreen.Entree.name) }, modifier = Modifier.fillMaxSize())
}
composable(LunchTrayScreen.Entree.name) {
EntreeMenuScreen(
options = DataSource.entreeMenuItems,
onCancelButtonClicked = { onCancelOrder(viewModel = viewModel, navController = navController) },
onNextButtonClicked = { navController.navigate(LunchTrayScreen.SideDish.name) },
onSelectionChanged = { viewModel.updateEntree(it)}
)
}
composable(LunchTrayScreen.SideDish.name) {
SideDishMenuScreen(
options = DataSource.sideDishMenuItems,
onCancelButtonClicked = { onCancelOrder(viewModel = viewModel, navController = navController) },
onNextButtonClicked = { navController.navigate(LunchTrayScreen.Accompaniment.name) },
onSelectionChanged = { viewModel.updateSideDish(it) }
)
}
composable(LunchTrayScreen.Accompaniment.name) {
AccompanimentMenuScreen(
options = DataSource.accompanimentMenuItems,
onCancelButtonClicked = { onCancelOrder(viewModel = viewModel, navController = navController) },
onNextButtonClicked = { navController.navigate(LunchTrayScreen.OrderCheckout.name) },
onSelectionChanged = {viewModel.updateAccompaniment(it)}
)
}
composable(LunchTrayScreen.OrderCheckout.name) {
CheckoutScreen(
orderUiState = uiState,
onNextButtonClicked = { /*TODO*/ },
onCancelButtonClicked = { onCancelOrder(viewModel = viewModel, navController = navController) })
}
}
}
}
private fun onCancelOrder(
viewModel: OrderViewModel,
navController: NavHostController
) {
viewModel.resetOrder()
navController.popBackStack(LunchTrayScreen.Start.name, inclusive = false)
}
| 0 | Kotlin | 0 | 0 | b3f32b11816fff50a92080fbf87a02630d46504f | 6,204 | Lunch-Tray | Apache License 2.0 |
js/js.translator/testData/box/incremental/multipleReimport.kt | JakeWharton | 99,388,807 | false | null | // EXPECTED_REACHABLE_NODES: 491
// MODULE: lib1
// FILE: lib1.kt
fun foo() = "O"
fun bar() = "K"
// MODULE: lib2(lib1)
// FILE: lib2a.kt
// PROPERTY_WRITE_COUNT: name=lib1 count=1
// PROPERTY_WRITE_COUNT: name=$$imports$$ count=1
inline fun o() = foo()
// FILE: lib2b.kt
inline fun k() = bar()
// MODULE: main(lib2)
// FILE: main.kt
// RECOMPILE
fun box() = o() + k() | 184 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 376 | kotlin | Apache License 2.0 |
sykepenger-model/src/test/kotlin/no/nav/helse/spleis/e2e/NyOgFremtidigSøknadOutOfOrder.kt | navikt | 193,907,367 | false | null | package no.nav.helse.spleis.e2e
import no.nav.helse.hendelser.Sykmeldingsperiode
import no.nav.helse.hendelser.til
import no.nav.helse.person.ArbeidsgiverVisitor
import no.nav.helse.person.TilstandType.*
import no.nav.helse.person.Vedtaksperiode
import no.nav.helse.april
import no.nav.helse.februar
import no.nav.helse.januar
import no.nav.helse.mars
import no.nav.helse.økonomi.Prosentdel.Companion.prosent
import org.junit.jupiter.api.Assertions.assertEquals
import org.junit.jupiter.api.Assertions.assertTrue
import org.junit.jupiter.api.Test
internal class NyOgFremtidigSøknadOutOfOrder : AbstractEndToEndTest() {
@Test
fun `Håndterer perioder som kommer inn i feil rekkefølge`() {
håndterSykmelding(Sykmeldingsperiode(1.februar, 28.februar, 100.prosent))
håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar, 100.prosent))
inspektør.arbeidsgiver.accept(visitor = object : ArbeidsgiverVisitor {
override fun preVisitPerioder(vedtaksperioder: List<Vedtaksperiode>) {
assertTrue(vedtaksperioder.isNotEmpty())
assertEquals(vedtaksperioder, vedtaksperioder.sorted())
}
})
assertTilstander(1.vedtaksperiode, START, MOTTATT_SYKMELDING_FERDIG_GAP, MOTTATT_SYKMELDING_UFERDIG_FORLENGELSE)
assertTilstander(2.vedtaksperiode, START, MOTTATT_SYKMELDING_FERDIG_GAP)
}
@Test
fun `Håndterer ny sykmelding som ligger tidligere i tid`() {
håndterSykmelding(Sykmeldingsperiode(23.mars(2020), 29.mars(2020), 100.prosent))
håndterSykmelding(Sykmeldingsperiode(30.mars(2020), 2.april(2020), 100.prosent))
håndterSykmelding(Sykmeldingsperiode(10.april(2020), 20.april(2020), 100.prosent))
håndterSykmelding(Sykmeldingsperiode(19.mars(2020), 22.mars(2020), 100.prosent))
assertTilstander(1.vedtaksperiode, START, MOTTATT_SYKMELDING_FERDIG_GAP, MOTTATT_SYKMELDING_UFERDIG_FORLENGELSE)
assertTilstander(2.vedtaksperiode, START, MOTTATT_SYKMELDING_UFERDIG_FORLENGELSE)
assertTilstander(3.vedtaksperiode, START, MOTTATT_SYKMELDING_UFERDIG_GAP)
assertTilstander(4.vedtaksperiode, START, MOTTATT_SYKMELDING_FERDIG_GAP)
}
@Test
fun `ny sykmelding overlapper med periode trukket tilbake pga inntektsmelding`() {
håndterSykmelding(Sykmeldingsperiode(1.februar, 28.februar, 100.prosent))
håndterInntektsmelding(listOf(20.januar til 4.februar))
håndterSykmelding(Sykmeldingsperiode(20.januar, 31.januar, 100.prosent))
assertForkastetPeriodeTilstander(1.vedtaksperiode, START, MOTTATT_SYKMELDING_FERDIG_GAP, AVVENTER_SØKNAD_FERDIG_GAP, TIL_INFOTRYGD)
}
@Test
fun `når inntektsmeldingen ikke treffer vedtaksperioden bak`() {
håndterSykmelding(Sykmeldingsperiode(1.februar, 28.februar, 100.prosent))
håndterInntektsmelding(listOf(1.januar til 16.januar))
håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar, 100.prosent))
assertTilstander(1.vedtaksperiode, START, MOTTATT_SYKMELDING_FERDIG_GAP, MOTTATT_SYKMELDING_UFERDIG_FORLENGELSE)
assertTilstander(2.vedtaksperiode, START, MOTTATT_SYKMELDING_FERDIG_GAP)
}
@Test
fun `når det er gap mellom periodene ved innlesing av ny søknad`() {
håndterSykmelding(Sykmeldingsperiode(15.februar, 28.februar, 100.prosent))
håndterSykmelding(Sykmeldingsperiode(1.januar, 31.januar, 100.prosent))
assertTilstander(1.vedtaksperiode, START, MOTTATT_SYKMELDING_FERDIG_GAP, MOTTATT_SYKMELDING_UFERDIG_GAP)
assertTilstander(2.vedtaksperiode, START, MOTTATT_SYKMELDING_FERDIG_GAP)
}
@Test
fun `Sykmelding i omvendt rekkefølge - gap`() {
håndterSykmelding(Sykmeldingsperiode(1.januar, 2.januar, 100.prosent))
håndterSykmelding(Sykmeldingsperiode(10.januar, 20.januar, 100.prosent))
håndterInntektsmelding(listOf(1.januar til 16.januar))
håndterSykmelding(Sykmeldingsperiode(3.januar, 5.januar, 100.prosent))
assertForkastetPeriodeTilstander(1.vedtaksperiode, START, MOTTATT_SYKMELDING_FERDIG_GAP, AVVENTER_SØKNAD_FERDIG_GAP, TIL_INFOTRYGD)
assertForkastetPeriodeTilstander(2.vedtaksperiode, START, MOTTATT_SYKMELDING_UFERDIG_GAP, AVVENTER_SØKNAD_UFERDIG_FORLENGELSE, TIL_INFOTRYGD)
}
@Test
fun `Sykmelding i omvendt rekkefølge - forlengelse`() {
håndterSykmelding(Sykmeldingsperiode(1.januar, 2.januar, 100.prosent))
håndterSykmelding(Sykmeldingsperiode(10.januar, 20.januar, 100.prosent))
håndterInntektsmelding(listOf(1.januar til 16.januar))
håndterSykmelding(Sykmeldingsperiode(3.januar, 9.januar, 100.prosent))
assertForkastetPeriodeTilstander(1.vedtaksperiode, START, MOTTATT_SYKMELDING_FERDIG_GAP, AVVENTER_SØKNAD_FERDIG_GAP, TIL_INFOTRYGD)
assertForkastetPeriodeTilstander(2.vedtaksperiode, START, MOTTATT_SYKMELDING_UFERDIG_GAP, AVVENTER_SØKNAD_UFERDIG_FORLENGELSE, TIL_INFOTRYGD)
}
}
| 0 | null | 2 | 4 | a3ba622f138449986fc9fd44e467104a61b95577 | 4,971 | helse-spleis | MIT License |
net.akehurst.language.comparisons/agl/src/jvm8Test/kotlin/Java8_compare_Test_antlrSpec.kt | dhakehurst | 197,245,665 | false | null | /**
* Copyright (C) 2018 Dr. <NAME> (http://dr.david.h.akehurst.net)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.akehurst.language.comparisons.agl
import net.akehurst.language.agl.grammar.grammar.AglGrammarSemanticAnalyser
import net.akehurst.language.agl.processor.Agl
import net.akehurst.language.agl.syntaxAnalyser.ContextSimple
import net.akehurst.language.api.asm.AsmSimple
import net.akehurst.language.api.parser.ParseFailedException
import net.akehurst.language.api.processor.LanguageProcessor
import net.akehurst.language.api.sppt.SharedPackedParseTree
import net.akehurst.language.comparisons.common.FileData
import net.akehurst.language.comparisons.common.Java8TestFiles
import net.akehurst.language.comparisons.common.Results
import net.akehurst.language.comparisons.common.TimeLogger
import org.junit.*
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
import java.io.IOException
import java.nio.file.Files
import kotlin.test.assertTrue
@RunWith(Parameterized::class)
class Java8_compare_Test_antlrOptm(val file: FileData) {
companion object {
const val col = "agl_antlr_optm"
var totalFiles = 0
@JvmStatic
@Parameterized.Parameters(name = "{index}: {0}")
fun files(): Collection<FileData> {
val f = Java8TestFiles.files.subList(0, 4800) // after this we get java.lang.OutOfMemoryError: Java heap space
totalFiles = f.size
println("Number of files to test against: ${f.size}")
return f
}
fun createAndBuildProcessor(aglFile: String): LanguageProcessor<AsmSimple, ContextSimple> {
val bytes = Java8_compare_Test_antlrOptm::class.java.getResourceAsStream(aglFile).readBytes()
val javaGrammarStr = String(bytes)
val res = Agl.processorFromString<AsmSimple, ContextSimple>(
grammarDefinitionStr = javaGrammarStr,
aglOptions = Agl.options {
semanticAnalysis {
// switch off ambiguity analysis for performance
option(AglGrammarSemanticAnalyser.OPTIONS_KEY_AMBIGUITY_ANALYSIS, false)
}
}
)
// no need to build because, sentence is parsed twice in the test
return res.processor!!
}
val optmAntlrJava8Processor = createAndBuildProcessor("/agl/Java8AntlrOptm.agl")
var input: String? = null
fun parseWithJava8OptmAntlr(file: FileData): SharedPackedParseTree? {
return try {
TimeLogger("${col}-fst", file).use { timer ->
optmAntlrJava8Processor.parse( input!!,Agl.parseOptions { goalRuleName("compilationUnit") })
timer.success()
}
TimeLogger("${col}-snd", file).use { timer ->
val res = optmAntlrJava8Processor.parse(input!!,Agl.parseOptions { goalRuleName("compilationUnit") })
timer.success()
res.sppt
}
} catch (e: ParseFailedException) {
println("Error: ${e.message}")
Results.logError("${col}-fst", file)
assertTrue(file.isError)
null
}
}
@BeforeClass
@JvmStatic
fun init() {
Results.reset()
}
@AfterClass
@JvmStatic
fun end() {
Results.write()
}
}
@Before
fun setUp() {
try {
input = String(Files.readAllBytes(file.path))
} catch (e: IOException) {
e.printStackTrace()
Assert.fail(e.message)
}
}
@Test
fun agl_antlr_optm_compilationUnit() {
print("File: ${file.index} of $totalFiles")
parseWithJava8OptmAntlr(file)
}
} | 3 | null | 7 | 45 | 177abcb60c51efcfc2432174f5d6620a7db89928 | 4,399 | net.akehurst.language | Apache License 2.0 |
sphinx/screens-detail/delete-podcast-detail/delete-podcast-detail/src/main/java/chat/sphinx/example/delete_media_detail/ui/DeleteDetailNotifySideEffect.kt | stakwork | 340,103,148 | false | {"Kotlin": 4002700, "Java": 403469, "JavaScript": 4745, "HTML": 4706, "Shell": 2453} | package chat.sphinx.example.delete_media_detail.ui
import android.content.Context
import chat.sphinx.resources.SphinxToastUtils
import io.matthewnelson.android_feature_toast_utils.show
import io.matthewnelson.concept_views.sideeffect.SideEffect
internal class DeleteDetailNotifySideEffect(val value: String): SideEffect<Context>() {
override suspend fun execute(value: Context) {
SphinxToastUtils().show(value, this.value)
}
}
| 99 | Kotlin | 11 | 18 | 01d4be42df107d5e4fa8d2411f5390aeea60ea74 | 445 | sphinx-kotlin | MIT License |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.