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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
js/js.tests/test/org/jetbrains/kotlin/js/test/ir/AbstractJsBlackBoxCodegenTestBase.kt | JetBrains | 3,432,266 | false | null | /*
* Copyright 2010-2021 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.js.test
import org.jetbrains.kotlin.js.test.handlers.*
import org.jetbrains.kotlin.platform.js.JsPlatforms
import org.jetbrains.kotlin.test.Constructor
import org.jetbrains.kotlin.test.TargetBackend
import org.jetbrains.kotlin.test.backend.BlackBoxCodegenSuppressor
import org.jetbrains.kotlin.test.builders.TestConfigurationBuilder
import org.jetbrains.kotlin.test.builders.classicFrontendHandlersStep
import org.jetbrains.kotlin.test.builders.irHandlersStep
import org.jetbrains.kotlin.test.builders.jsArtifactsHandlersStep
import org.jetbrains.kotlin.test.directives.DiagnosticsDirectives
import org.jetbrains.kotlin.test.directives.DiagnosticsDirectives.DIAGNOSTICS
import org.jetbrains.kotlin.test.directives.JsEnvironmentConfigurationDirectives
import org.jetbrains.kotlin.test.frontend.classic.handlers.ClassicDiagnosticsHandler
import org.jetbrains.kotlin.test.model.*
import org.jetbrains.kotlin.test.runners.AbstractKotlinCompilerWithTargetBackendTest
import org.jetbrains.kotlin.test.runners.codegen.commonClassicFrontendHandlersForCodegenTest
import org.jetbrains.kotlin.test.services.JsLibraryProvider
import org.jetbrains.kotlin.test.services.configuration.CommonEnvironmentConfigurator
import org.jetbrains.kotlin.test.services.configuration.JsEnvironmentConfigurator
import org.jetbrains.kotlin.test.services.sourceProviders.CoroutineHelpersSourceFilesProvider
import java.lang.Boolean.getBoolean
abstract class AbstractJsBlackBoxCodegenTestBase<R : ResultingArtifact.FrontendOutput<R>, I : ResultingArtifact.BackendInput<I>, A : ResultingArtifact.Binary<A>>(
val targetFrontend: FrontendKind<R>,
targetBackend: TargetBackend,
private val pathToTestDir: String,
private val testGroupOutputDirPrefix: String,
private val skipMinification: Boolean = getBoolean("kotlin.js.skipMinificationTest"),
) : AbstractKotlinCompilerWithTargetBackendTest(targetBackend) {
abstract val frontendFacade: Constructor<FrontendFacade<R>>
abstract val frontendToBackendConverter: Constructor<Frontend2BackendConverter<R, I>>
abstract val backendFacade: Constructor<BackendFacade<I, A>>
abstract val afterBackendFacade: Constructor<AbstractTestFacade<A, BinaryArtifacts.Js>>?
abstract val recompileFacade: Constructor<AbstractTestFacade<BinaryArtifacts.Js, BinaryArtifacts.Js>>
override fun TestConfigurationBuilder.configuration() {
globalDefaults {
frontend = targetFrontend
targetPlatform = JsPlatforms.defaultJsPlatform
dependencyKind = DependencyKind.Binary
}
val pathToRootOutputDir = System.getProperty("kotlin.js.test.root.out.dir") ?: error("'kotlin.js.test.root.out.dir' is not set")
defaultDirectives {
+DiagnosticsDirectives.REPORT_ONLY_EXPLICITLY_DEFINED_DEBUG_INFO
JsEnvironmentConfigurationDirectives.PATH_TO_ROOT_OUTPUT_DIR with pathToRootOutputDir
JsEnvironmentConfigurationDirectives.PATH_TO_TEST_DIR with pathToTestDir
JsEnvironmentConfigurationDirectives.TEST_GROUP_OUTPUT_DIR_PREFIX with testGroupOutputDirPrefix
+JsEnvironmentConfigurationDirectives.TYPED_ARRAYS
+JsEnvironmentConfigurationDirectives.GENERATE_NODE_JS_RUNNER
if (skipMinification) +JsEnvironmentConfigurationDirectives.SKIP_MINIFICATION
if (getBoolean("kotlin.js.ir.skipRegularMode")) +JsEnvironmentConfigurationDirectives.SKIP_REGULAR_MODE
}
forTestsNotMatching("compiler/testData/codegen/box/diagnostics/functions/tailRecursion/*") {
defaultDirectives {
DIAGNOSTICS with "-warnings"
}
}
forTestsNotMatching("compiler/testData/codegen/boxError/*") {
enableMetaInfoHandler()
}
useConfigurators(
::CommonEnvironmentConfigurator,
::JsEnvironmentConfigurator,
)
useAdditionalSourceProviders(
::JsAdditionalSourceProvider,
::CoroutineHelpersSourceFilesProvider,
)
useAdditionalService(::JsLibraryProvider)
useAfterAnalysisCheckers(
::JsFailingTestSuppressor,
::BlackBoxCodegenSuppressor,
::JsArtifactsDumpHandler
)
facadeStep(frontendFacade)
classicFrontendHandlersStep {
commonClassicFrontendHandlersForCodegenTest()
useHandlers(::ClassicDiagnosticsHandler)
}
facadeStep(frontendToBackendConverter)
irHandlersStep()
facadeStep(backendFacade)
afterBackendFacade?.let { facadeStep(it) }
facadeStep(recompileFacade)
jsArtifactsHandlersStep {
useHandlers(
::NodeJsGeneratorHandler,
::JsBoxRunner,
::JsMinifierRunner,
::JsAstHandler
)
}
}
}
| 184 | null | 5771 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 5,104 | kotlin | Apache License 2.0 |
android-kotlin/android-extensions-idea/testData/android/parcel/checker/constructors.kt | JetBrains | 60,701,247 | false | null | package test
import kotlinx.parcelize.Parcelize
import android.os.Parcelable
@Parcelize
class A : Parcelable
@Parcelize
class B(val firstName: String, val secondName: String) : Parcelable
@Parcelize
class C(val firstName: String, <error descr="[PARCELABLE_CONSTRUCTOR_PARAMETER_SHOULD_BE_VAL_OR_VAR] 'Parcelable' constructor parameter should be 'val' or 'var'">secondName</error>: String) : Parcelable
@Parcelize
class D(val firstName: String, vararg val secondName: String) : Parcelable
@Parcelize
class E(val firstName: String, val secondName: String) : Parcelable {
constructor() : this("", "")
}
@Parcelize
class <error descr="[PARCELABLE_SHOULD_HAVE_PRIMARY_CONSTRUCTOR] 'Parcelable' should have a primary constructor">F</error> : Parcelable {
constructor(a: String) {
println(a)
}
}
| 125 | null | 4813 | 857 | 8d22f48a9233679e85e42e8a7ed78bbff2c82ddb | 816 | android | Apache License 2.0 |
app/src/main/java/com/funnypaper/simme/data/local/entity/SplineEntity.kt | FunnyPaper | 731,113,350 | false | {"Kotlin": 146083} | package com.funnypaper.simme.data.local.entity
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.ForeignKey
import androidx.room.Index
import androidx.room.PrimaryKey
import com.funnypaper.simme.domain.model.SplineModel
@Entity(
tableName = "spline",
foreignKeys = [
ForeignKey(
entity = BoardEntity::class,
parentColumns = ["id"],
childColumns = ["board_id"]
)
],
indices = [Index("board_id")]
)
data class SplineEntity(
@PrimaryKey(autoGenerate = true)
val id: Int = 0,
@ColumnInfo("board_id")
val boardId: Int,
val name: String,
@ColumnInfo("beat_length")
val beatLength: Float,
val path: SplineModel,
) {
init {
require(name.isNotBlank())
require(beatLength > 0f)
}
}
| 0 | Kotlin | 0 | 0 | 48ea4876ef47cfddbfa8a8b79324d164c7403df4 | 829 | SIMME | MIT License |
app/src/test/java/com/openwallet/ui/activity/fragment/resetpassword/model/ResetPasswordViewModelTest.kt | hsbc | 742,467,592 | false | {"Kotlin": 502702, "Java": 40426} | package com.openwallet.ui.activity.fragment.resetpassword.model
import androidx.arch.core.executor.testing.InstantTaskExecutorRule
import androidx.lifecycle.MutableLiveData
import com.google.gson.JsonObject
import com.openwallet.app.AppViewModel
import com.openwallet.app.OpenWalletApplication
import com.openwallet.ext.request
import com.openwallet.network.ApiRepository
import com.openwallet.network.ApiService
import com.openwallet.network.exception.ExceptionEngineImpl
import com.openwallet.network.state.ResultState
import com.openwallet.ui.activity.fragment.register.model.RegisterUserNameResponseData
import com.openwallet.ui.activity.fragment.wallet.model.NetworkResponse
import com.openwallet.ui.activity.rule.MainCoroutineRule
import com.kunminx.architecture.ui.callback.UnPeekLiveData
import io.mockk.*
import junit.framework.TestCase
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.runBlocking
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.junit.MockitoJUnitRunner
import retrofit2.Retrofit
@OptIn(ExperimentalCoroutinesApi::class)
@RunWith(MockitoJUnitRunner::class)
class ResetPasswordViewModelTest : TestCase() {
@get:Rule
var mainCoroutineRule = MainCoroutineRule() // 解决 viewModelScope.launch
@get:Rule
var instantTaskExecutorRule = InstantTaskExecutorRule()
private val testCoroutineDispatcher = mainCoroutineRule.testDispatcher
val retrofit = mockk<Retrofit>()
val ipfsRetrofit = mockk<Retrofit>()
val apiService = mockk<ApiService>()
val apiRepository = mockk<ApiRepository>()
val viewModel = ResetPasswordViewModel(apiRepository)
val appViewModel = mockk<AppViewModel>()
var secretToken = UnPeekLiveData.Builder<String>().setAllowNullValue(true).create()
@Before
public override fun setUp() {
super.setUp()
MockKAnnotations.init(this)
}
//@After
public override fun tearDown() {
}
@Test
fun testResetPassword() = runBlocking {
//val callMock = Mockito.mock(MutableLiveData::class.java) as MutableLiveData<ResultState<NetworkResponse<ResetPasswordResponseData>>>
val resetPassword = "<PASSWORD>"
viewModel.exceptionEngine = ExceptionEngineImpl()
mockkObject(OpenWalletApplication)
every { OpenWalletApplication.Companion.appViewModel } returns appViewModel
every { OpenWalletApplication.appViewModel.loginToken} returns "token"
every { OpenWalletApplication.appViewModel.secretToken } returns secretToken
every { OpenWalletApplication.appViewModel.secretToken.value} returns "token"
val request = JsonObject()
request.addProperty("newPassword", resetPassword)
request.addProperty("token",OpenWalletApplication.appViewModel.secretToken.value)
val data = ResetPasswordResponseData("data")
var response = NetworkResponse<ResetPasswordResponseData>("message",true,data)
val resultState = ResultState.onAppSuccess(response)
var expectedResult = MutableLiveData<ResultState<NetworkResponse<ResetPasswordResponseData>>>()
expectedResult.value = resultState
every { retrofit.create(ApiService::class.java) } answers { apiService }
every { retrofit.create(ApiService::class.java) } returns apiService
coEvery { apiRepository.resetPassword(request) } coAnswers { response }
// coEvery { viewModel.request({ response }, expectedResult).runCatching { }
// .onSuccess {
// val request = JsonObject()
// request.addProperty("newPassword", resetPassword)
// request.addProperty("token",OpenWalletApplication.appViewModel.secretToken.value)
// apiRepository.resetPassword(request).status
// }
// } coAnswers { mockk<Result<Unit>>() }
//coEvery { viewModel.resetPassword(resetPassword) } returns expectedResult
// Mockito.`when`(
// viewModel.resetPassword(
// resetPassword
// )
// ).thenReturn(callMock)
val actualResult = viewModel.resetPassword(resetPassword)
//verify { viewModel.resetPassword(resetPassword) }
assertEquals(expectedResult.value,actualResult.value)
}
} | 0 | Kotlin | 0 | 1 | b72ac403ce1e38139ab42548967e08e6db347ddd | 4,335 | OpenWallet-aOS | Apache License 2.0 |
dsl/src/main/kotlin/cloudshift/awscdk/dsl/services/ec2/CfnVPCEndpointServicePermissionsPropsDsl.kt | cloudshiftinc | 667,063,030 | false | null | @file:Suppress("RedundantVisibilityModifier","RedundantUnitReturnType","RemoveRedundantQualifierName","unused","UnusedImport","ClassName","REDUNDANT_PROJECTION","DEPRECATION")
package cloudshift.awscdk.dsl.services.ec2
import cloudshift.awscdk.common.CdkDslMarker
import kotlin.String
import kotlin.collections.Collection
import kotlin.collections.MutableList
import software.amazon.awscdk.services.ec2.CfnVPCEndpointServicePermissionsProps
/**
* Properties for defining a `CfnVPCEndpointServicePermissions`.
*
* Example:
*
* ```
* // The code below shows an example of how to instantiate this type.
* // The values are placeholders you should change.
* import software.amazon.awscdk.services.ec2.*;
* CfnVPCEndpointServicePermissionsProps cfnVPCEndpointServicePermissionsProps =
* CfnVPCEndpointServicePermissionsProps.builder()
* .serviceId("serviceId")
* // the properties below are optional
* .allowedPrincipals(List.of("allowedPrincipals"))
* .build();
* ```
*
* [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-ec2-vpcendpointservicepermissions.html)
*/
@CdkDslMarker
public class CfnVPCEndpointServicePermissionsPropsDsl {
private val cdkBuilder: CfnVPCEndpointServicePermissionsProps.Builder =
CfnVPCEndpointServicePermissionsProps.builder()
private val _allowedPrincipals: MutableList<String> = mutableListOf()
/**
* @param allowedPrincipals The Amazon Resource Names (ARN) of one or more principals (for
* example, users, IAM roles, and AWS accounts ).
* Permissions are granted to the principals in this list. To grant permissions to all principals,
* specify an asterisk (*). Permissions are revoked for principals not in this list. If the list is
* empty, then all permissions are revoked.
*/
public fun allowedPrincipals(vararg allowedPrincipals: String) {
_allowedPrincipals.addAll(listOf(*allowedPrincipals))
}
/**
* @param allowedPrincipals The Amazon Resource Names (ARN) of one or more principals (for
* example, users, IAM roles, and AWS accounts ).
* Permissions are granted to the principals in this list. To grant permissions to all principals,
* specify an asterisk (*). Permissions are revoked for principals not in this list. If the list is
* empty, then all permissions are revoked.
*/
public fun allowedPrincipals(allowedPrincipals: Collection<String>) {
_allowedPrincipals.addAll(allowedPrincipals)
}
/**
* @param serviceId The ID of the service.
*/
public fun serviceId(serviceId: String) {
cdkBuilder.serviceId(serviceId)
}
public fun build(): CfnVPCEndpointServicePermissionsProps {
if(_allowedPrincipals.isNotEmpty()) cdkBuilder.allowedPrincipals(_allowedPrincipals)
return cdkBuilder.build()
}
}
| 1 | Kotlin | 0 | 0 | 17c41bdaffb2e10d31b32eb2282b73dd18be09fa | 2,793 | awscdk-dsl-kotlin | Apache License 2.0 |
app/src/main/java/com/jaiselrahman/wastatus/ui/playlist/PlaylistViewModel.kt | jaiselrahman | 171,029,157 | false | null | package com.jaiselrahman.wastatus.ui.videos
import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import androidx.paging.LivePagedListBuilder
import androidx.paging.PagedList
import com.jaiselrahman.wastatus.data.PlaylistDataSource
import com.jaiselrahman.wastatus.data.api.Status
import com.jaiselrahman.wastatus.model.Video
import com.jaiselrahman.wastatus.ui.base.BaseViewModel
class PlaylistViewModel : ViewModel(), BaseViewModel {
private var dataSourceFactory: PlaylistDataSource.Factory
private var livePagedList: LiveData<PagedList<Video>>
private var status: LiveData<Status>
init {
val config = PagedList.Config.Builder()
.setEnablePlaceholders(false)
.setPageSize(PAGE_SIZE)
.setInitialLoadSizeHint(PAGE_SIZE)
.setPrefetchDistance(PREFETCH_SIZE)
.build()
dataSourceFactory = PlaylistDataSource.Factory(PAGE_SIZE.toLong())
status = Transformations.switchMap(dataSourceFactory.liveDataSource()) {
it.status
}
livePagedList = LivePagedListBuilder(dataSourceFactory, config)
.build()
}
override fun getLivePagedList(): LiveData<PagedList<Video>> {
return livePagedList
}
override fun getStatus(): LiveData<Status> {
return status
}
override fun reset() {
dataSourceFactory.reset()
}
companion object {
internal const val PAGE_SIZE = 20
internal const val PREFETCH_SIZE = 5
}
} | 0 | null | 1 | 1 | 555be1b2ef99e873e044b1580ea0f2d08d125633 | 1,567 | WAStatus | Apache License 2.0 |
app-compose/src/androidTest/java/com/example/android/trackr/compose/ui/TagGroupTest.kt | android | 344,900,266 | false | null | /*
* Copyright (C) 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 com.nims.fruitful.app.ui
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithText
import androidx.test.ext.junit.runners.AndroidJUnit4
import com.nims.fruitful.app.data.Tag
import com.nims.fruitful.app.data.TagColor
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
class TagGroupTest {
@get:Rule
val rule = createComposeRule()
@Suppress("SameParameterValue")
private fun createTags(n: Int): List<Tag> {
return (1..n).map { i ->
Tag(
id = i.toLong(),
label = "tag $i",
color = TagColor.YELLOW
)
}
}
@Test
fun all() {
rule.setContent {
FruitfulTheme {
TagGroup(
tags = createTags(10)
)
}
}
for (i in 1..10) {
rule.onNodeWithText("tag $i").assertIsDisplayed()
}
}
@Test
fun limit() {
rule.setContent {
FruitfulTheme {
TagGroup(
tags = createTags(10),
max = 6
)
}
}
for (i in 1..6) {
rule.onNodeWithText("tag $i").assertIsDisplayed()
}
for (i in 7..10) {
rule.onNodeWithText("tag $i").assertDoesNotExist()
}
rule.onNodeWithText("+4").assertIsDisplayed()
}
}
| 20 | Kotlin | 93 | 645 | 9b7c22d6e7b2782959389ed115730efcfcddc790 | 2,172 | trackr | Apache License 2.0 |
app/src/main/java/com/adriantache/bigfivepersonalitytest/json/Domain.kt | adriantache | 114,641,994 | false | null | package com.adriantache.bigfivepersonalitytest.json
import com.squareup.moshi.JsonQualifier
/**
* annotation for JSON domain field
**/
@Retention(AnnotationRetention.RUNTIME)
@JsonQualifier
annotation class Domain | 1 | Kotlin | 3 | 19 | d73e66303c3aab1e40c2018724deace321a1375b | 218 | Big-Five-Personality-Test | MIT License |
src/main/kotlin/com/skillw/pouvoir/internal/core/script/javascript/JSGlobal.kt | Glom-c | 396,683,163 | false | null | package com.skillw.pouvoir.internal.core.script.javascript
import com.skillw.pouvoir.Pouvoir
import com.skillw.pouvoir.internal.manager.PouConfig
import com.skillw.pouvoir.util.listSubFiles
import com.skillw.pouvoir.util.serverFolder
import taboolib.common.platform.function.warning
import java.io.File
import javax.script.ScriptContext
import javax.script.ScriptEngine
import javax.script.SimpleBindings
object JSGlobal {
private val globalScripts = HashSet<File>()
private val configScripts = HashSet<File>()
private val globalMembers = HashMap<String, Any>()
internal fun reloadGlobalScripts() {
fun addScript(file: File) {
if (file.extension == "js") {
addToGlobal(file)
configScripts += file
}
}
fun removeScript(file: File) {
removeGlobal(file)
}
configScripts.forEach(::removeScript)
configScripts.clear()
val script = PouConfig["script"]
script.getStringList("global-scripts")
.ifEmpty { listOf("plugins/Pouvoir/scripts/core/") }
.forEach { path ->
val file = File(serverFolder, path)
if (!file.exists()) {
warning("No such file path: $path")
return@forEach
}
file.let {
if (it.isDirectory) it.listSubFiles().forEach(::addScript) else addScript(it)
}
}
Pouvoir.scriptManager.values.forEach {
it.script.engine.importGlobalScripts()
}
}
private fun updateImports() {
val builder = StringBuilder()
val prefix = "load(\""
val suffix = "\")\n"
globalScripts.forEach {
builder.append(prefix + it.path.replace("\\", "/") + suffix)
}
val imports = builder.toString()
val engine = PouJavaScriptEngine.engine
engine.eval(imports)
globalMembers.clear()
globalMembers.putAll(engine.context.getBindings(ScriptContext.ENGINE_SCOPE))
}
fun addToGlobal(file: File) {
if (file.isDirectory) {
file.listSubFiles().filter { it.extension == "js" }.forEach {
globalScripts += it
}
} else
globalScripts += file
updateImports()
}
fun removeGlobal(file: File) {
if (file.isDirectory) {
file.listSubFiles().filter { it.extension == "js" }.forEach {
globalScripts -= it
}
} else
globalScripts -= file
updateImports()
}
internal fun ScriptEngine.importGlobalScripts() {
this.context.setBindings(SimpleBindings().apply { putAll(globalMembers) }, ScriptContext.GLOBAL_SCOPE)
}
} | 3 | Kotlin | 8 | 9 | 35b93485f5f4c2d5c534a2765ff7cfb8f34dd737 | 2,805 | Pouvoir | MIT License |
src/main/kotlin/no/nav/toi/kandidatvarsel/AzureAuthentication.kt | navikt | 768,528,587 | false | {"Kotlin": 92600, "Dockerfile": 255} | package no.nav.toi.kandidatvarsel
import com.auth0.jwk.JwkProviderBuilder
import com.auth0.jwk.SigningKeyNotFoundException
import com.auth0.jwt.JWT
import com.auth0.jwt.JWTVerifier
import com.auth0.jwt.algorithms.Algorithm
import com.auth0.jwt.exceptions.JWTVerificationException
import com.auth0.jwt.exceptions.MissingClaimException
import com.auth0.jwt.exceptions.TokenExpiredException
import com.auth0.jwt.interfaces.Claim
import com.auth0.jwt.interfaces.DecodedJWT
import com.auth0.jwt.interfaces.RSAKeyProvider
import io.javalin.Javalin
import io.javalin.http.*
import io.javalin.security.RouteRole
import no.nav.toi.kandidatvarsel.Rolle.UNPROTECTED
import org.eclipse.jetty.http.HttpHeader
import java.lang.System.getenv
import java.net.URI
import java.security.interfaces.RSAPublicKey
import java.util.*
import java.util.concurrent.TimeUnit
enum class Rolle: RouteRole {
REKBIS_ARBEIDSGIVERRETTET,
REKBIS_JOBBSØKERRETTET,
REKBIS_UTVIKLER,
UNPROTECTED,
}
data class Issuer(
val issuer: String,
val jwksUri: String,
val audience: String,
) {
/** Setter opp en jwtVerifier som verifiserer token */
fun verifier(): JWTVerifier {
val jwkProvider = JwkProviderBuilder(URI(jwksUri).toURL())
.cached(10, 1, TimeUnit.HOURS)
.build()
val algorithm = Algorithm.RSA256(object : RSAKeyProvider {
override fun getPublicKeyById(keyId: String) = jwkProvider.get(keyId).publicKey as RSAPublicKey
override fun getPrivateKey() = throw IllegalStateException()
override fun getPrivateKeyId() = throw IllegalStateException()
})
return JWT.require(algorithm)
.withIssuer(issuer)
.withAudience(audience)
.build()
}
}
class AzureAdConfig(
private val issuers: List<Issuer>,
private val rekbisUtvikler: UUID,
private val rekbisArbeidsgiverrettet: UUID,
private val rekbisJobbsøkerrettet: UUID,
) {
private val verifiers = issuers.map { it.verifier() }
fun verify(token: String): DecodedJWT {
for (verifier in verifiers) {
try {
return verifier.verify(token)
} catch (e: SigningKeyNotFoundException) {
// Token ikke utstedt for denne verifieren, prøv neste
}
}
throw UnauthorizedResponse("Token not issued for any of the configured issuers")
}
private fun rolleForUuid(uuid: UUID): Rolle? {
return when (uuid) {
rekbisUtvikler -> Rolle.REKBIS_UTVIKLER
rekbisArbeidsgiverrettet -> Rolle.REKBIS_ARBEIDSGIVERRETTET
rekbisJobbsøkerrettet -> Rolle.REKBIS_JOBBSØKERRETTET
else -> { log.warn("Ukjent rolle-UUID: $uuid"); null }
}
}
fun rollerForUuider(uuider: Collection<UUID>): Set<Rolle> =
uuider.mapNotNull { rolleForUuid(it) }.toSet()
companion object {
fun nais() = AzureAdConfig(
issuers = listOfNotNull(
Issuer(
audience = getenv("AZURE_APP_CLIENT_ID"),
issuer = getenv("AZURE_OPENID_CONFIG_ISSUER"),
jwksUri = getenv("AZURE_OPENID_CONFIG_JWKS_URI"),
),
if (getenv("NAIS_CLUSTER_NAME") == "dev-gcp")
Issuer(
audience = getenv("FAKEDINGS_APP_CLIENT_ID"),
issuer = getenv("FAKEDINGS_OPENID_CONFIG_ISSUER"),
jwksUri = getenv("FAKEDINGS_OPENID_CONFIG_JWKS_URI"),
)
else null
),
rekbisUtvikler = getUuid("AD_GROUP_REKBIS_UTVIKLER"),
rekbisArbeidsgiverrettet = getUuid("AD_GROUP_REKBIS_ARBEIDSGIVERRETTET"),
rekbisJobbsøkerrettet = getUuid("AD_GROUP_REKBIS_JOBBSOKERRETTET"),
)
private fun getUuid(name: String) = UUID.fromString(getenvOrThrow(name))
}
}
interface Principal {
fun mayAccess(routeRoles: Set<RouteRole>): Boolean
}
/** Representerer en autensiert nav-ansatt */
data class UserPrincipal(
val navident: String,
val roller: Set<Rolle>,
): Principal {
override fun mayAccess(routeRoles: Set<RouteRole>) =
UNPROTECTED in routeRoles || roller.any { it in routeRoles }
companion object {
fun fromClaims(claims: Map<String, Claim>, azureAdConfig: AzureAdConfig): UserPrincipal {
val navIdent = claims["NAVident"]?.asString() ?:
throw MissingClaimException("NAVident")
val groups = claims["groups"]?.asList(UUID::class.java) ?:
throw UnauthorizedResponse("groups")
return UserPrincipal(
navident = navIdent,
roller = azureAdConfig.rollerForUuider(groups)
)
}
}
}
/**
* Henter ut en autensiert bruker fra en kontekst. Kaster InternalServerErrorResponse om det ikke finnes en autensiert bruker
*/
fun Context.authenticatedUser() = attribute<UserPrincipal>("principal")
?: run {
log.error("No authenticated user found!")
throw InternalServerErrorResponse()
}
/**
* Setter opp token-verifisering på en path på Javalin-serveren
*/
fun Javalin.azureAdAuthentication(azureAdConfig: AzureAdConfig): Javalin {
return beforeMatched { ctx ->
val token = ctx.hentToken() ?: run {
if (UNPROTECTED in ctx.routeRoles()) {
return@beforeMatched
}
log.error("Kall mot {} uten token", ctx.path())
throw UnauthorizedResponse()
}
val claims = azureAdConfig.verify(token).claims
val principal = UserPrincipal.fromClaims(claims, azureAdConfig)
if (!principal.mayAccess(ctx.routeRoles())) {
secureLog.error("principal=${principal} tried to access ${ctx.path()}, but is not authorized. Must have at least one of ${ctx.routeRoles()}")
log.error("principal tried to access ${ctx.path()}, but does not have any required role ${ctx.routeRoles()}. See secure log for principal.")
throw ForbiddenResponse()
}
ctx.attribute("principal", principal)
}
.exception(JWTVerificationException::class.java) { e, ctx ->
when (e) {
is TokenExpiredException -> log.info("AzureAD-token expired on {}", e.expiredOn)
else -> log.error("Unexpected exception {} while authenticating AzureAD-token", e::class.simpleName, e)
}
ctx.status(HttpStatus.UNAUTHORIZED).result("")
}.exception(SigningKeyNotFoundException::class.java) { _, ctx ->
log.warn("Noen prøvde å aksessere endepunkt med en token signert med en falsk issuer")
ctx.status(HttpStatus.UNAUTHORIZED).result("")
}.exception(MissingClaimException::class.java) { e, ctx ->
if (e.claimName == "groups") {
ctx.status(HttpStatus.FORBIDDEN).result("")
} else {
log.warn("Noen prøvde å aksessere endepunkt med en token med manglende claim", e)
ctx.status(HttpStatus.UNAUTHORIZED).result("")
}
}
}
/**
* Henter token ut fra header fra en Context
*/
fun Context.hentToken(): String? {
val authorizationHeader = header(HttpHeader.AUTHORIZATION.name)
?: return null
if (!authorizationHeader.startsWith("Bearer ")) {
log.error("Authorization header not with 'Bearer ' prefix!")
throw UnauthorizedResponse()
}
return authorizationHeader.removePrefix("Bearer ")
}
| 0 | Kotlin | 0 | 0 | 5745dfd8430ee775675708eb089048340cf6d68a | 7,572 | rekrutteringsbistand-kandidatvarsel-api | MIT License |
src/Day04.kt | thomasreader | 573,047,664 | false | null | import java.io.Reader
fun main() {
val testInput = """
2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8
""".trimIndent()
check(partOne(testInput.reader()) == 2)
val input = file("Day04.txt")
println(partOne(input.bufferedReader()))
check(partTwo(testInput.reader()) == 4)
println(partTwo(input.bufferedReader()))
}
private fun partOne(source: Reader): Int {
var fullyCountains = 0
source.forEachLine { line ->
val (a, b) = line.split(',')
val (aMin, aMax) = a.split('-').map { it.toInt() }
val (bMin, bMax) = b.split('-').map { it.toInt() }
val aNumbers = (aMin..aMax).toSet()
val bNumbers = (bMin..bMax).toSet()
if (aNumbers.containsAll(bNumbers) || bNumbers.containsAll(aNumbers)) {
fullyCountains++
}
}
return fullyCountains
}
private fun partTwo(source: Reader): Int {
var overlaps = 0
source.forEachLine { line ->
val (a, b) = line.split(',')
val (aMin, aMax) = a.split('-').map { it.toInt() }
val (bMin, bMax) = b.split('-').map { it.toInt() }
val aNumbers = (aMin..aMax).toSet()
val bNumbers = (bMin..bMax).toSet()
val intersect = aNumbers.intersect(bNumbers)
if (intersect.isNotEmpty()) {
overlaps++
}
}
return overlaps
} | 0 | Kotlin | 0 | 0 | eff121af4aa65f33e05eb5e65c97d2ee464d18a6 | 1,391 | advent-of-code-2022-kotlin | Apache License 2.0 |
bbfgradle/tmp/results/diffCompile/jorbvyg.kt | DaniilStepanov | 346,008,310 | false | {"Markdown": 122, "Gradle": 762, "Gradle Kotlin DSL": 649, "Java Properties": 23, "Shell": 49, "Ignore List": 20, "Batchfile": 26, "Git Attributes": 8, "Kotlin": 82508, "Protocol Buffer": 12, "Java": 6674, "Proguard": 12, "XML": 1698, "Text": 13298, "INI": 221, "JavaScript": 294, "JAR Manifest": 2, "Roff": 217, "Roff Manpage": 38, "JSON": 199, "HTML": 2429, "AsciiDoc": 1, "YAML": 21, "EditorConfig": 1, "OpenStep Property List": 19, "C": 79, "Objective-C": 68, "C++": 169, "Swift": 68, "Pascal": 1, "Python": 4, "CMake": 2, "Objective-C++": 12, "Groovy": 45, "Dockerfile": 3, "Diff": 1, "EJS": 1, "CSS": 6, "Ruby": 6, "SVG": 50, "JFlex": 3, "Maven POM": 107, "JSON with Comments": 9, "Ant Build System": 53, "Graphviz (DOT)": 78, "Scala": 1} | // Different compile happens on:JVM ,JVM -Xnew-inference
fun foo(a: Any
) {
a as BooleanArray
a!!.size
}
| 1 | null | 1 | 1 | e772ef1f8f951873ebe7d8f6d73cf19aead480fa | 107 | kotlinWithFuzzer | Apache License 2.0 |
admin/app/src/main/java/com/yazan98/groupyadmin/screens/ProfileScreen.kt | Yazan98 | 226,006,997 | false | {"Gradle": 6, "Java Properties": 4, "Shell": 2, "Text": 1, "Ignore List": 4, "Batchfile": 2, "Markdown": 1, "JSON": 2, "Proguard": 2, "Kotlin": 72, "XML": 143, "Java": 1} | package com.yazan98.groupyadmin.screens
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.auth.FirebaseAuth
import com.yazan98.groupyadmin.R
import com.yazan98.groupyadmin.logic.ProfileRepository
import com.yazan98.groupyadmin.models.Profile
import io.vortex.android.prefs.VortexPrefs
import io.vortex.android.ui.VortexMessageDelegation
import kotlinx.android.synthetic.main.screen_profile.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
class ProfileScreen : AppCompatActivity() {
private val repository: ProfileRepository by lazy {
ProfileRepository(listener)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.screen_profile)
GlobalScope.launch {
VortexPrefs.get("UserID", "")?.let {
showLoading()
repository.getProfileById(it as String)
}
}
OutButton?.apply {
this.setOnClickListener {
GlobalScope.launch {
VortexPrefs.put("UserStatus", false)
FirebaseAuth.getInstance().signOut()
startActivity(Intent(this@ProfileScreen, MainActivity::class.java))
finish()
}
}
}
}
private val listener = object : ProfileRepository.ProfileListener {
override suspend fun onOperationSuccess(profile: Profile) {
withContext(Dispatchers.Main) {
hideLoading()
profile.let { p ->
Name?.let {
it.text = p.name
}
Email?.let {
it.text = p.email
}
AccountType?.let {
it.setText(p.accountType)
}
Bio?.let {
it.text = p.bio
}
ID?.let {
it.text = p.id
}
}
}
}
override suspend fun onOperationFailed(message: String) {
withContext(Dispatchers.Main) {
VortexMessageDelegation().showShortMessage(message, this@ProfileScreen)
}
}
}
private suspend fun showLoading() {
withContext(Dispatchers.Main) {
linearLayout2?.let {
it.visibility = View.GONE
}
ProfileLoader?.let {
it.visibility = View.VISIBLE
}
Icon?.let {
it.visibility = View.GONE
}
}
}
private suspend fun hideLoading() {
withContext(Dispatchers.Main) {
linearLayout2?.let {
it.visibility = View.VISIBLE
}
ProfileLoader?.let {
it.visibility = View.GONE
}
Icon?.let {
it.visibility = View.VISIBLE
}
}
}
}
| 1 | null | 1 | 1 | bbefd5b4a567982d31cfb70ec2adb2a9fbb35ca2 | 3,248 | Groupy | Apache License 2.0 |
src/pilha/estatica/pilhaInvertida/Main.kt | pedrofernandeslopes | 763,226,285 | false | {"Kotlin": 71189} | fun main(args: Array<String>) {
var pilha: Empilhavel = PilhaInvertida(7)
pilha.empilhar("Instituto")
pilha.empilhar("Federal")
println("Topo: ${pilha.espiar()}")
pilha.empilhar("de")
pilha.empilhar("Educação")
pilha.empilhar("Ciência")
pilha.empilhar("e")
println("Topo: ${pilha.espiar()}")
println("Pilha=${pilha.imprimir()}")
} | 0 | Kotlin | 0 | 0 | 6d64070b507016a5b786a5269c1bb5bfa7742aa4 | 370 | estrutura-de-dados-ifba | MIT License |
graph/graph-adapter-input-rest-spring-mvc/src/test/kotlin/eu/tib/orkg/prototype/statements/application/BulkStatementControllerUnitTest.kt | TIBHannover | 197,416,205 | false | {"Kotlin": 2449567, "Cypher": 215872, "Python": 4880, "Groovy": 1936, "Shell": 1803, "HTML": 240} | package eu.tib.orkg.prototype.statements.application
import com.ninjasquad.springmockk.MockkBean
import eu.tib.orkg.prototype.auth.api.AuthUseCase
import eu.tib.orkg.prototype.core.rest.ExceptionHandler
import eu.tib.orkg.prototype.statements.testing.fixtures.createResource
import eu.tib.orkg.prototype.statements.testing.fixtures.createStatement
import eu.tib.orkg.prototype.spring.testing.fixtures.pageOf
import eu.tib.orkg.prototype.spring.spi.FeatureFlagService
import eu.tib.orkg.prototype.statements.api.StatementUseCases
import eu.tib.orkg.prototype.statements.domain.model.StatementId
import eu.tib.orkg.prototype.statements.domain.model.ThingId
import eu.tib.orkg.prototype.statements.spi.TemplateRepository
import eu.tib.orkg.prototype.statements.testing.fixtures.createPredicate
import eu.tib.orkg.prototype.testing.andExpectPage
import eu.tib.orkg.prototype.testing.andExpectStatement
import eu.tib.orkg.prototype.testing.annotations.UsesMocking
import eu.tib.orkg.prototype.testing.spring.restdocs.RestDocsTest
import eu.tib.orkg.prototype.testing.spring.restdocs.documentedDeleteRequestTo
import eu.tib.orkg.prototype.testing.spring.restdocs.documentedGetRequestTo
import eu.tib.orkg.prototype.testing.spring.restdocs.documentedPutRequestTo
import io.mockk.clearAllMocks
import io.mockk.confirmVerified
import io.mockk.every
import io.mockk.just
import io.mockk.mockk
import io.mockk.runs
import io.mockk.verify
import java.security.Principal
import java.util.*
import org.hamcrest.Matchers.hasSize
import org.junit.jupiter.api.AfterEach
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest
import org.springframework.data.domain.PageRequest
import org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath
import org.springframework.restdocs.payload.PayloadDocumentation.responseFields
import org.springframework.restdocs.payload.PayloadDocumentation.subsectionWithPath
import org.springframework.restdocs.request.RequestDocumentation.parameterWithName
import org.springframework.restdocs.request.RequestDocumentation.requestParameters
import org.springframework.test.context.ContextConfiguration
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath
import org.springframework.test.web.servlet.result.MockMvcResultMatchers.status
@ContextConfiguration(classes = [BulkStatementController::class, ExceptionHandler::class])
@WebMvcTest(controllers = [BulkStatementController::class])
@UsesMocking
internal class BulkStatementControllerUnitTest : RestDocsTest("bulk-statements") {
@MockkBean
private lateinit var statementService: StatementUseCases
@Suppress("unused") // Required to properly initialize ApplicationContext, but not used in the test.
@MockkBean
private lateinit var templateRepository: TemplateRepository
@Suppress("unused") // Required to properly initialize ApplicationContext, but not used in the test.
@MockkBean
private lateinit var flags: FeatureFlagService
@Suppress("unused") // Required to properly initialize ApplicationContext, but not used in the test.
@MockkBean
private lateinit var userRepository: AuthUseCase
@BeforeEach
fun resetState() {
clearAllMocks()
}
@AfterEach
fun verifyMocks() {
confirmVerified(statementService, templateRepository, flags, userRepository)
}
@Test
fun lookupBySubjects() {
val r1 = ThingId("R1")
val r2 = ThingId("R2")
val r3 = ThingId("R3")
val r4 = ThingId("R4")
val p1 = ThingId("P1")
val p2 = ThingId("P2")
val s1 = createStatement(
id = StatementId("S1"),
subject = createResource(r1),
predicate = createPredicate(p1),
`object` = createResource(r2)
)
val s2 = createStatement(
id = StatementId("S2"),
subject = createResource(id = r3),
predicate = createPredicate(id = p2),
`object` = createResource(id = r4)
)
val pageable = PageRequest.of(0, 5)
every { statementService.findAllBySubject(r1, any()) } returns pageOf(s1, pageable = pageable)
every { statementService.findAllBySubject(r3, any()) } returns pageOf(s2, pageable = pageable)
every { statementService.countStatementsAboutResources(any()) } returns emptyMap()
every { flags.isFormattedLabelsEnabled() } returns false
mockMvc
.perform(documentedGetRequestTo("/api/statements/subjects/?ids={ids}", "$r1,$r3"))
.andExpect(status().isOk)
.andExpect(jsonPath("$").isArray)
.andExpect(jsonPath("$", hasSize<Int>(2)))
.andExpect(jsonPath("$[*].id").isNotEmpty)
.andExpectPage("$[*].statements")
.andDo(
documentationHandler.document(
requestParameters(parameterWithName("ids").description("The list of resource iIds to fetch on")),
responseFields(
fieldWithPath("[].id").description("The subject id that was used to fetch the following statements"),
subsectionWithPath("[].statements").description("Page of statements whose subject id matches the id from the search parameter"),
)
)
)
.andDo(generateDefaultDocSnippets())
verify(exactly = 1) {
statementService.findAllBySubject(r1, any())
statementService.findAllBySubject(r3, any())
}
verify(exactly = 2) {
statementService.countStatementsAboutResources(any())
flags.isFormattedLabelsEnabled()
}
}
@Test
fun lookupByObjects() {
val r1 = ThingId("R1")
val r2 = ThingId("R2")
val r3 = ThingId("R3")
val r4 = ThingId("R4")
val p1 = ThingId("P1")
val p2 = ThingId("P2")
val s1 = createStatement(
id = StatementId("S1"),
subject = createResource(r1),
predicate = createPredicate(p1),
`object` = createResource(r2)
)
val s2 = createStatement(
id = StatementId("S2"),
subject = createResource(r3),
predicate = createPredicate(p2),
`object` = createResource(r4)
)
val pageable = PageRequest.of(0, 5)
every { statementService.findAllByObject(r2, any()) } returns pageOf(s1, pageable = pageable)
every { statementService.findAllByObject(r4, any()) } returns pageOf(s2, pageable = pageable)
every { statementService.countStatementsAboutResources(any()) } returns emptyMap()
every { flags.isFormattedLabelsEnabled() } returns false
mockMvc
.perform(documentedGetRequestTo("/api/statements/objects/?ids={ids}", "$r2,$r4"))
.andExpect(status().isOk)
.andExpect(jsonPath("$").isArray)
.andExpect(jsonPath("$", hasSize<Int>(2)))
.andExpect(jsonPath("$[*].id").isNotEmpty)
.andExpectPage("$[*].statements")
.andDo(
documentationHandler.document(
requestParameters(parameterWithName("ids").description("The list of object ids to fetch on")),
responseFields(
fieldWithPath("[].id").description("The object id that was used to fetch the following statements"),
subsectionWithPath("[].statements").description("Page of statements whose object id matches the id from the search parameter"),
)
)
)
.andDo(generateDefaultDocSnippets())
verify(exactly = 1) {
statementService.findAllByObject(r2, any())
statementService.findAllByObject(r4, any())
}
verify(exactly = 2) {
statementService.countStatementsAboutResources(any())
flags.isFormattedLabelsEnabled()
}
}
@Test
fun editResourceStatements() {
val r1 = ThingId("R1")
val r2 = ThingId("R2")
val r3 = ThingId("R3")
val r4 = ThingId("R4")
val p1 = ThingId("P1")
val p2 = ThingId("P2")
val s1 = createStatement(
id = StatementId("S1"),
subject = createResource(r1),
predicate = createPredicate(p1),
`object` = createResource(r2)
)
val s2 = createStatement(
id = StatementId("S2"),
subject = createResource(r3),
predicate = createPredicate(p2),
`object` = createResource(r4)
)
val newP = createPredicate(ThingId("P3"))
val newO = createResource(ThingId("R5"))
val newS1 = createStatement(
id = s1.id!!,
subject = s1.subject,
predicate = newP,
`object` = newO
)
val newS2 = createStatement(
id = s2.id!!,
subject = s2.subject,
predicate = newP,
`object` = newO
)
val payload = objectMapper.writeValueAsString(
mapOf(
"predicate_id" to newP.id,
"object_id" to newO.id,
)
)
every { statementService.update(match { it.statementId == s1.id || it.statementId == s2.id }) } just runs
every { statementService.findById(s1.id!!) } returns Optional.of(newS1)
every { statementService.findById(s2.id!!) } returns Optional.of(newS2)
every { statementService.countStatementsAboutResources(any()) } returns emptyMap()
every { flags.isFormattedLabelsEnabled() } returns false
mockMvc
.perform(documentedPutRequestTo("/api/statements/?ids={ids}", "${s1.id},${s2.id}", body = payload))
.andExpect(status().isOk)
.andExpect(jsonPath("$").isArray)
.andExpect(jsonPath("$", hasSize<Int>(2)))
.andExpect(jsonPath("$[*].id").isNotEmpty)
.andExpectStatement("$[*].statement")
.andDo(
documentationHandler.document(
requestParameters(parameterWithName("ids").description("The list of statements to update")),
responseFields(
fieldWithPath("[].id").description("The statement id"),
subsectionWithPath("[].statement").description("The statement representation of the updated statement"),
)
)
)
.andDo(generateDefaultDocSnippets())
verify(exactly = 1) {
statementService.update(match { it.statementId == s1.id })
statementService.update(match { it.statementId == s2.id })
statementService.findById(s1.id!!)
statementService.findById(s2.id!!)
statementService.countStatementsAboutResources(any())
flags.isFormattedLabelsEnabled()
}
}
@Test
fun delete() {
val s1 = StatementId("S1")
val s2 = StatementId("S2")
val principal: Principal = mockk()
every { statementService.delete(setOf(s1, s2)) } just runs
every { principal.name } returns "user"
mockMvc
.perform(documentedDeleteRequestTo("/api/statements/?ids={ids}", "$s1,$s2").principal(principal))
.andExpect(status().isNoContent)
.andDo(
documentationHandler.document(
requestParameters(parameterWithName("ids").description("The list of ids of statements to delete"))
)
)
.andDo(generateDefaultDocSnippets())
verify(exactly = 1) { statementService.delete(setOf(s1, s2)) }
verify(exactly = 2) { principal.name }
confirmVerified(principal)
}
}
| 0 | Kotlin | 2 | 5 | a5eceabf6ae74cc5be5290aac6029ce585455ea5 | 11,932 | orkg-backend | MIT License |
plugins/client/graphql-kotlin-client-generator/src/test/data/jackson/union/unionquerywithinlinefragments/BasicUnion.kt | ExpediaGroup | 148,706,161 | false | null | package com.expediagroup.graphql.generated.unionquerywithinlinefragments
import com.expediagroup.graphql.client.Generated
import com.fasterxml.jackson.`annotation`.JsonSubTypes
import com.fasterxml.jackson.`annotation`.JsonTypeInfo
import com.fasterxml.jackson.`annotation`.JsonTypeInfo.As.PROPERTY
import com.fasterxml.jackson.`annotation`.JsonTypeInfo.Id.NAME
import kotlin.Int
import kotlin.String
/**
* Very basic union of BasicObject and ComplexObject
*/
@Generated
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "__typename",
defaultImpl = DefaultBasicUnionImplementation::class
)
@JsonSubTypes(value = [com.fasterxml.jackson.annotation.JsonSubTypes.Type(value =
BasicObject::class, name="BasicObject"),com.fasterxml.jackson.annotation.JsonSubTypes.Type(value
= ComplexObject::class, name="ComplexObject")])
public interface BasicUnion
/**
* Some basic description
*/
@Generated
public data class BasicObject(
public val id: Int,
/**
* Object name
*/
public val name: String
) : BasicUnion
/**
* Multi line description of a complex type.
* This is a second line of the paragraph.
* This is final line of the description.
*/
@Generated
public data class ComplexObject(
/**
* Some unique identifier
*/
public val id: Int,
/**
* Some object name
*/
public val name: String,
/**
* Optional value
* Second line of the description
*/
public val optional: String?
) : BasicUnion
/**
* Fallback BasicUnion implementation that will be used when unknown/unhandled type is encountered.
*/
@Generated
public class DefaultBasicUnionImplementation() : BasicUnion
| 51 | null | 340 | 1,717 | bce5bc46590c8a12a1c5a0a70970202660eea4bb | 1,674 | graphql-kotlin | Apache License 2.0 |
src/main/kotlin/com/pineypiney/game_engine/resources/text/Font.kt | PineyPiney | 491,900,499 | false | {"Kotlin": 679789, "GLSL": 33407} | package com.pineypiney.game_engine.resources.text
import com.pineypiney.game_engine.GameEngineI
import com.pineypiney.game_engine.objects.text.Text
import com.pineypiney.game_engine.objects.util.shapes.TextMesh
import com.pineypiney.game_engine.resources.shaders.Shader
import com.pineypiney.game_engine.resources.shaders.ShaderLoader
import com.pineypiney.game_engine.util.ResourceKey
import glm_.vec2.Vec2
abstract class Font {
abstract val name: String
abstract val shader: Shader
abstract fun getCharWidth(char: Char): Float
abstract fun getCharHeight(char: Char): Vec2
abstract fun getWidth(text: String): Float
abstract fun getHeight(text: String): Float
fun getSize(text: String): Vec2 = Vec2(getWidth(text), getHeight(text))
abstract fun getShape(text: String, bold: Boolean, alignment: Int): TextMesh
fun getAlignmentOffset(text: String, alignment: Int): Pair<FloatArray, Float>{
val alignX = alignment and 7
val alignY = alignment and 0x70
val lines = text.split('\n')
val offsetX = FloatArray(lines.size){
val width = getWidth(lines[it])
when(alignX){
Text.ALIGN_RIGHT -> -width
Text.ALIGN_CENTER_H -> width * -.5f
else -> 0f
}
}
val height = getHeight(text)
val offsetY = when(alignY){
Text.ALIGN_TOP -> -height
Text.ALIGN_CENTER_V -> height * -.5f
else -> 0f
}
return offsetX to offsetY
}
companion object {
val fontShader = ShaderLoader[ResourceKey("vertex/menu"), ResourceKey("fragment/text")]
val defaultFont: Font; get() = FontLoader[ResourceKey(GameEngineI.defaultFont)]
}
} | 0 | Kotlin | 0 | 0 | ea19730171692c9a12eee6d49fe2bbb545028274 | 1,568 | GameEngine | MIT License |
workshop/vertx/vertx-sqlclient-demo/src/test/kotlin/io/bluetape4k/workshop/sqlclient/model/User.kt | debop | 625,161,599 | false | {"Kotlin": 7504333, "HTML": 502995, "Java": 2273, "JavaScript": 1351, "Shell": 1301, "CSS": 444, "Dockerfile": 121, "Mustache": 82} | package io.bluetape4k.workshop.sqlclient.model
import java.io.Serializable
data class User(
val id: Long,
val firstName: String,
val lastName: String,
): Serializable
| 0 | Kotlin | 0 | 1 | ce3da5b6bddadd29271303840d334b71db7766d2 | 181 | bluetape4k | MIT License |
kt-klaxon/src/main/kotlin/HelloFunction.kt | delabassee | 142,158,942 | false | null |
package com.delabassee
import com.beust.klaxon.*
data class Country(
@Json(name = "country")
val name: String,
val capital: String,
val population: Int )
fun hello(input: String): String {
val myCountries= listOf(
Country("Belgium", "Brussels", 11_190_846 ),
Country("Brazil", "Brasilia", 210_969_008),
Country("Croatia", "Zargeb", 4_164_783),
Country("France", "Paris", 65_233_271 ),
Country("New Zealand", "Wellington", 4_749_598 ) )
val result = myCountries.find(){it.name.toLowerCase() == input.toLowerCase()}
if (result != null)
return ( Klaxon().toJsonString(result))
else
return (
json {
obj(
"status" to 404,
"msg" to "Country not found"
).toJsonString(true)
}
)
} | 0 | Kotlin | 0 | 0 | 74ce075e86936a247529f4c51d343ca1f475f2ce | 940 | fn-snippets | Apache License 2.0 |
app/src/main/java/za/co/nemesisnet/budgettracker/ui/nav/EnterExpenseDestination.kt | NemesisGuy | 716,458,071 | false | {"Kotlin": 45174} | package za.co.nemesisnet.budgettracker.ui.nav
import za.co.nemesisnet.budgettracker.R
object EnterExpenseDestination : NavigationDestination {
override val route = "enter_expense"
override val titleRes = R.string.enter_expense
}
| 0 | Kotlin | 0 | 0 | abafcbffb5dc73fdea3012b95b5d315dc0c250f9 | 240 | BudgetTracker | MIT License |
core/validation/src/commonMain/kotlin/io/spherelabs/validation/di/Koin.validation.kt | getspherelabs | 687,455,894 | false | {"Kotlin": 917584, "Ruby": 6814, "Swift": 1128, "Shell": 1048} | package io.spherelabs.validation.di
import io.spherelabs.validation.DefaultEmailValidation
import io.spherelabs.validation.DefaultKeyPasswordValidation
import io.spherelabs.validation.DefaultNameValidation
import io.spherelabs.validation.DefaultPasswordValidation
import io.spherelabs.validation.DefaultWebsiteValidation
import io.spherelabs.validation.EmailValidation
import io.spherelabs.validation.KeyPasswordValidation
import io.spherelabs.validation.NameValidation
import io.spherelabs.validation.PasswordValidation
import io.spherelabs.validation.WebsiteValidation
import org.koin.dsl.module
val validationModule = module {
single<EmailValidation> { DefaultEmailValidation() }
single<NameValidation> { DefaultNameValidation() }
single<PasswordValidation> { DefaultPasswordValidation() }
single<WebsiteValidation> { DefaultWebsiteValidation() }
single<KeyPasswordValidation> { DefaultKeyPasswordValidation() }
}
| 18 | Kotlin | 27 | 236 | 902a0505c5eaf0f3848a5e06afaec98c1ed35584 | 939 | anypass-kmp | Apache License 2.0 |
cgps-core/src/main/java/com/genius/cgps/HardwareCGPS.kt | GeniusRUS | 140,468,471 | false | {"Kotlin": 72335} | @file:Suppress("UNUSED")
package com.genius.cgps
import android.Manifest
import android.content.Context
import android.location.*
import android.os.Build
import android.os.Bundle
import androidx.annotation.IntRange
import androidx.core.content.ContextCompat
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.SendChannel
import kotlinx.coroutines.flow.flow
import java.util.*
import java.util.concurrent.TimeoutException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlin.coroutines.suspendCoroutine
/**
* A class that uses the built-in location services in the Android framework
*
* Should be guaranteed to work on all devices that have a GPS module
*
* The use of this class is not as preferable as its analogue [GoogleCGPS] or [HuaweiCGPS],
* since working with GPS directly is a very energy-intensive operation
*
* @property context is needed to check permissions and for working with system location services
* @constructor receiving [Context] instance for working with Android geolocation service
*
* @author <NAME>
*/
class HardwareCGPS(private val context: Context) : CGPS {
private val manager: LocationManager? by lazy { ContextCompat.getSystemService(context, LocationManager::class.java) }
/**
* Retrieves the last known location of the user from the device's GPS adapter
*
* Required permission [Manifest.permission.ACCESS_COARSE_LOCATION]
*
* @return [Location] user location
* @throws LocationException in case of undefined errors. In this case, the reason is written in [LocationException.message]
* @throws LocationDisabledException in case of disabled GPS adapter
* @throws SecurityException in case of missing permission [Manifest.permission.ACCESS_COARSE_LOCATION] for obtaining geolocation
*/
@Throws(LocationException::class, LocationDisabledException::class, SecurityException::class)
override suspend fun lastLocation() = suspendCoroutine { coroutine ->
if (manager == null) {
coroutine.resumeWithException(
LocationException(
LocationException.ErrorType.LOCATION_MANAGER,
"Location manager not found"
)
)
} else if (!isLocationEnabled(manager)) {
coroutine.resumeWithException(LocationDisabledException())
} else if (!context.checkPermission(true)) {
coroutine.resumeWithException(SecurityException("Permissions for GPS was not given"))
} else {
val defaultCriteria = Criteria().apply {
accuracy = Criteria.ACCURACY_COARSE
isCostAllowed = true
powerRequirement = Criteria.POWER_MEDIUM
}
val provider = manager?.getBestProvider(defaultCriteria, true)
if (provider == null) {
coroutine.resumeWithException(
LocationException(
LocationException.ErrorType.FIDELITY,
"Provider not found for this accuracy: ${defaultCriteria.accuracy} and power: ${defaultCriteria.powerRequirement}"
)
)
} else {
val location = manager?.getLastKnownLocation(provider)
if (location == null) {
coroutine.resumeWithException(
LocationException(
LocationException.ErrorType.LAST_LOCATION,
"Last location not found"
)
)
} else {
coroutine.resume(location)
}
}
}
}
override suspend fun actualLocationWithEnable(
@Accuracy accuracy: Int,
@IntRange(from = 0) timeout: Long
): Location {
throw IllegalStateException("Hardware actual location cannot be executed with enable intent")
}
/**
* Receives the current location of the user from the device's GPS service
*
* For flexibility in requesting a location, you can specify [accuracy], [timeout]
*
* The stages of checking and possible throwing of errors coincide with the order of the error descriptions below.
*
* Required permission [Manifest.permission.ACCESS_FINE_LOCATION]
*
* @param accuracy the accuracy of the obtained coordinates. The default is [Accuracy.BALANCED]
* @param timeout timeout for getting coordinates. Default 5000 milliseconds
* @return [Location] user location
* @throws LocationException in case of undefined errors. In this case, the reason is written in [LocationException.message]
* @throws LocationDisabledException in case of disabled GPS adapter
* @throws SecurityException in case of missing permissions for obtaining geolocation
* @throws TimeoutException in case the timeout of the geolocation request has been exceeded
*/
@Throws(
LocationException::class,
LocationDisabledException::class,
SecurityException::class,
TimeoutException::class
)
override suspend fun actualLocation(
@Accuracy accuracy: Int,
@IntRange(from = 0) timeout: Long
): Location {
val coroutine = CompletableDeferred<Location>()
if (manager == null) {
coroutine.completeExceptionally(
LocationException(
LocationException.ErrorType.LOCATION_MANAGER,
"Location manager not found"
)
)
} else if (!isLocationEnabled(manager)) {
coroutine.completeExceptionally(LocationDisabledException())
} else if (!context.checkPermission(false)) {
coroutine.completeExceptionally(SecurityException("Permissions for GPS was not given"))
} else {
val listener = coroutine.createLocationListener()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
val provider = manager?.getBestProvider(accuracy.toCriteria(), true)
if (provider == null || manager == null) {
coroutine.completeExceptionally(
LocationException(
LocationException.ErrorType.FIDELITY,
"LocationManager not instantiated or provider instance is not defined"
)
)
return coroutine.await()
}
manager?.getCurrentLocation(
provider,
null,
context.mainExecutor
) { location ->
coroutine.complete(location)
}
} else {
@Suppress("DEPRECATION")
manager?.requestSingleUpdate(accuracy.toCriteria(), listener, context.mainLooper)
}
try {
withTimeout(timeout) {
coroutine.await()
}
} catch (e: TimeoutCancellationException) {
if (coroutine.isActive) {
coroutine.completeExceptionally(TimeoutException("Location timeout on $timeout ms"))
}
} finally {
manager?.removeUpdates(listener)
}
}
return coroutine.await()
}
/**
* Receives the current location of the user from the device's GPS service
*
* For flexibility in requesting a location, you can specify [accuracy], [timeout]
*
* Since a [Job] instance is returned, there is a mechanism that can control the life cycle of this request
*
* At the end of the work on receiving coordinates, it closes [SendChannel] and unsubscribes [LocationManager] from its listener
*
* Required permission [Manifest.permission.ACCESS_FINE_LOCATION]
*
* @param accuracy the accuracy of the obtained coordinates. The default is [Accuracy.BALANCED]
* @param timeout timeout for getting coordinates. The default is 10_000 milliseconds
* @param interval time interval for getting coordinates. Default 5000 milliseconds
* @return [flow] stream with results [Result]
* @throws LocationException in case of undefined errors. In this case, the reason is written in [LocationException.message]
* @throws LocationDisabledException in case of disabled GPS adapter
* @throws SecurityException in case of missing permissions for obtaining geolocation
* @throws TimeoutException in case the timeout of the geolocation request has been exceeded
*/
override fun requestUpdates(
@Accuracy accuracy: Int,
@IntRange(from = 0) timeout: Long,
@IntRange(from = 0) interval: Long
) = flow {
while (true) {
try {
val location = actualLocation(accuracy, timeout)
emit(Result.success(location))
} catch (e: Exception) {
emit(Result.failure(e))
}
delay(interval)
}
}
private fun CompletableDeferred<Location>.createLocationListener(): LocationListener {
return object : LocationListener {
override fun onLocationChanged(location: Location) {
complete(location)
}
@Deprecated(message = "Deprecated for Android Q+", replaceWith = ReplaceWith(""))
override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
completeExceptionally(
LocationException(
LocationException.ErrorType.OTHER,
"Status $provider changed: $status with extras $extras"
)
)
}
}
override fun onProviderEnabled(provider: String) {
completeExceptionally(
LocationException(
LocationException.ErrorType.OTHER,
"Provider $provider enabled"
)
)
}
override fun onProviderDisabled(provider: String) {
completeExceptionally(
LocationException(
LocationException.ErrorType.OTHER,
"Provider $provider disabled"
)
)
}
}
}
private fun Int.toCriteria(): Criteria = Criteria().apply {
accuracy = when (this@toCriteria) {
Accuracy.HIGH -> Criteria.ACCURACY_HIGH
Accuracy.BALANCED -> Criteria.ACCURACY_MEDIUM
Accuracy.LOW -> Criteria.ACCURACY_LOW
else -> Criteria.NO_REQUIREMENT
}
isCostAllowed = true
powerRequirement = when (this@toCriteria) {
Accuracy.HIGH -> Criteria.POWER_HIGH
Accuracy.BALANCED -> Criteria.POWER_MEDIUM
Accuracy.LOW -> Criteria.POWER_LOW
else -> Criteria.NO_REQUIREMENT
}
}
private enum class HardwareAccuracy(val accuracy: Int, val power: Int) {
FINE(Criteria.ACCURACY_FINE, Criteria.POWER_HIGH),
COARSE(Criteria.ACCURACY_COARSE, Criteria.POWER_MEDIUM),
}
} | 0 | Kotlin | 0 | 2 | d5c3e2ced7d53acec2744869b26b0c3368ebc834 | 11,405 | CGPS | Apache License 2.0 |
editor/src/main/java/good/damn/editor/anchors/internal/VEIAnchorableInternal.kt | GoodDamn | 850,249,504 | false | {"Kotlin": 68918, "Java": 700} | package good.damn.editor.anchors.internal
import android.graphics.Canvas
import android.graphics.PointF
interface VEIAnchorableInternal {
fun draw(
canvas: Canvas
)
fun checkAnchor(
from: PointF,
to: PointF,
touch: PointF
): PointF?
} | 0 | Kotlin | 0 | 1 | 7889c135f817b773958e4a5fcda1eeaaa9410505 | 287 | VectorEditorAndroid | MIT License |
plugins/markdown/core/src/org/intellij/plugins/markdown/fileActions/importFrom/googleDocs/GoogleDocsFileLoader.kt | JetBrains | 2,489,216 | 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.intellij.plugins.markdown.fileActions.importFrom.googleDocs
import com.google.api.client.auth.oauth2.Credential
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport
import com.google.api.client.googleapis.json.GoogleJsonResponseException
import com.google.api.client.json.JsonFactory
import com.google.api.client.json.gson.GsonFactory
import com.google.api.services.drive.Drive
import com.intellij.openapi.components.Service
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.ThrowableComputable
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.util.concurrency.annotations.RequiresBackgroundThread
import com.intellij.util.io.createFile
import org.intellij.plugins.markdown.MarkdownBundle
import org.intellij.plugins.markdown.fileActions.export.MarkdownExportProvider
import org.intellij.plugins.markdown.fileActions.utils.GoogleCommonUtils
import org.intellij.plugins.markdown.ui.MarkdownNotifications
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.IOException
import java.nio.file.Files
import java.nio.file.StandardCopyOption
import kotlin.io.path.exists
@Service
class GoogleDocsFileLoader {
fun loadFileFromGoogleDisk(project: Project, credential: Credential, docsId: String): VirtualFile? =
try {
GoogleCommonUtils.runProcessWithGoogleCredentials(project, credential) {
ProgressManager.getInstance().runProcessWithProgressSynchronously(ThrowableComputable {
val driveFiles = getAllFilesFromDrive(credential)
downloadFileFromDrive(driveFiles, docsId)
}, MarkdownBundle.message("markdown.google.load.file.progress.title"), true, project)
}
}
catch (e: GoogleJsonResponseException) {
handleResponseExceptions(e, project)
null
}
@RequiresBackgroundThread
private fun getAllFilesFromDrive(credential: Credential): Drive.Files {
val httpTransport = GoogleNetHttpTransport.newTrustedTransport()
return Drive
.Builder(httpTransport, jsonFactory, credential)
.build()
.files()
}
@RequiresBackgroundThread
private fun downloadFileFromDrive(driveFiles: Drive.Files, docsId: String): VirtualFile {
val outputStream = ByteArrayOutputStream()
val fileName = with(driveFiles) {
export(docsId, mimeType).executeAndDownloadTo(outputStream)
get(docsId).setFields("id, name").execute().name
}
val tempFile = File.createTempFile(fileName, ".docx").apply {
outputStream().use { outputStream.writeTo(it) }
}
val renamedFile = moveContentFromTempFile(tempFile, fileName)
return VfsUtil.findFileByIoFile(renamedFile, true)!!
}
private fun moveContentFromTempFile(tempFile: File, fileName: String): File {
try {
val targetFilePath = File(tempFile.parent, "$fileName.docx").toPath()
return Files
.move(tempFile.toPath(), targetFilePath, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE).apply {
if (!exists()) createFile()
}.toFile()
}
catch (e: IOException) {
LOG.debug(e)
return tempFile
}
}
private fun handleResponseExceptions(e: GoogleJsonResponseException, project: Project) =
when (e.statusCode) {
404 -> {
MarkdownNotifications.showError(
project,
id = MarkdownExportProvider.Companion.NotificationIds.exportFailed,
message = MarkdownBundle.message("markdown.google.file.download.error.msg"),
title = MarkdownBundle.message("markdown.google.file.download.error.title")
)
LOG.debug(
MarkdownBundle.message("markdown.google.file.download.error.title"),
MarkdownBundle.message("markdown.google.file.download.error.msg")
)
}
else -> LOG.info(e.localizedMessage)
}
companion object {
private const val mimeType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
private val jsonFactory: JsonFactory get() = GsonFactory.getDefaultInstance()
private val LOG = logger<GoogleDocsFileLoader>()
}
}
| 233 | null | 4912 | 15,461 | 9fdd68f908db0b6bb6e08dc33fafb26e2e4712af | 4,397 | intellij-community | Apache License 2.0 |
sample/src/main/java/xyz/louiscad/splittiessample/AppInit.kt | AdamMc331 | 116,874,219 | false | null | /*
* Copyright (c) 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.
*/
package com.louiscad.splittiessample
import android.app.Application
import android.content.ContentProvider
import timber.log.Timber
/**
* Initializes some app wide things (e.g. the logging library Timber).
* This object needs to be invoked (`AppInit`) in a [ContentProvider] or an [Application].
*/
object AppInit {
init {
if (BuildConfig.DEBUG) Timber.plant(Timber.DebugTree())
}
}
| 1 | null | 1 | 1 | 8d321ef24a137e84301051fde22cca6686cffe32 | 996 | Splitties | Apache License 2.0 |
app/src/main/kotlin/ru/art2000/androraider/view/settings/ISettingsController.kt | ARTI1208 | 179,843,834 | false | null | package ru.art2000.androraider.view.settings
import javafx.scene.control.Button
import javafx.scene.control.TextField
import ru.art2000.androraider.arch.IController
interface ISettingsController : IController {
var javaSourcesPathSelectButton: Button
var apktoolPathSelectButton: Button
var frameworkFilePathSelectButton: Button
var frameworkFolderPathSelectButton: Button
var clearDataButton: Button
var javaSourcesPath: TextField
var apktoolPath: TextField
var frameworkPath: TextField
} | 11 | Kotlin | 0 | 0 | a75ec6ceb09ba1d24ddb77afc63776b856f0197e | 533 | AnDroRaider | MIT License |
features/dd-sdk-android-session-replay/src/main/kotlin/com/datadog/android/sessionreplay/internal/recorder/mapper/UnsupportedViewMapper.kt | DataDog | 219,536,756 | false | {"Kotlin": 7850465, "Java": 236752, "C": 79303, "Shell": 63027, "C++": 32351, "Python": 5556, "CMake": 2000} | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadog.android.sessionreplay.internal.recorder.mapper
import android.view.View
import com.datadog.android.sessionreplay.internal.recorder.MappingContext
import com.datadog.android.sessionreplay.internal.recorder.ViewUtilsInternal
import com.datadog.android.sessionreplay.model.MobileSegment
import com.datadog.android.sessionreplay.utils.AsyncJobStatusCallback
import com.datadog.android.sessionreplay.utils.ColorStringFormatter
import com.datadog.android.sessionreplay.utils.DrawableToColorMapper
import com.datadog.android.sessionreplay.utils.ViewBoundsResolver
import com.datadog.android.sessionreplay.utils.ViewIdentifierResolver
internal class UnsupportedViewMapper(
viewIdentifierResolver: ViewIdentifierResolver,
colorStringFormatter: ColorStringFormatter,
viewBoundsResolver: ViewBoundsResolver,
drawableToColorMapper: DrawableToColorMapper
) : BaseWireframeMapper<View, MobileSegment.Wireframe.PlaceholderWireframe>(
viewIdentifierResolver,
colorStringFormatter,
viewBoundsResolver,
drawableToColorMapper
) {
override fun map(view: View, mappingContext: MappingContext, asyncJobStatusCallback: AsyncJobStatusCallback):
List<MobileSegment.Wireframe.PlaceholderWireframe> {
val pixelsDensity = mappingContext.systemInformation.screenDensity
val viewGlobalBounds = viewBoundsResolver.resolveViewGlobalBounds(view, pixelsDensity)
return listOf(
MobileSegment.Wireframe.PlaceholderWireframe(
id = resolveViewId(view),
x = viewGlobalBounds.x,
y = viewGlobalBounds.y,
width = viewGlobalBounds.width,
height = viewGlobalBounds.height,
label = resolveViewTitle(view)
)
)
}
// region Internal
private fun resolveViewTitle(view: View): String {
val viewUtilsInternal = ViewUtilsInternal()
return if (viewUtilsInternal.isToolbar(view)) {
return TOOLBAR_LABEL
} else {
DEFAULT_LABEL
}
}
// endregion
companion object {
internal const val TOOLBAR_LABEL = "Toolbar"
internal const val DEFAULT_LABEL = "Unsupported view"
}
}
| 54 | Kotlin | 57 | 140 | de8989f0056124457b3296a6d6c2d91b70f181aa | 2,486 | dd-sdk-android | Apache License 2.0 |
sd-client-app/src/jvmMain/kotlin/de/lostmekka/sdwuic/Main.kt | LostMekka | 600,748,935 | false | null | package de.lostmekka.sdwuic
import androidx.compose.desktop.ui.tooling.preview.Preview
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.material.Button
import androidx.compose.material.Checkbox
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.Icon
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.PlayArrow
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.application
import de.lostmekka.sdwuic.components.ImageTileList
import de.lostmekka.sdwuic.components.Input
import de.lostmekka.sdwuic.components.Select
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
fun main() = application {
Window(onCloseRequest = ::exitApplication) {
App()
}
}
@Composable
@Preview
fun App() {
var prompt by remember { mutableStateOf("") }
var negativePrompt by remember { mutableStateOf("") }
var modelData by remember { mutableStateOf<Triple<Int, String, List<String>>?>(null) }
var samplerData by remember { mutableStateOf<Triple<Int, String, List<String>>?>(null) }
var steps by remember { mutableStateOf(25) }
var batchSize by remember { mutableStateOf(4) }
var cfgScale by remember { mutableStateOf(7f) }
var useTiling by remember { mutableStateOf(false) }
val isInitialized = modelData != null && samplerData != null
var working by remember { mutableStateOf(false) }
var images by remember { mutableStateOf<List<ByteArray>>(listOf()) }
var currGenerator by remember { mutableStateOf<Generator?>(null) }
var generatorStatus by remember { mutableStateOf("waiting to start") }
var progressStatus by remember { mutableStateOf<String?>(null) }
var canUpdateGenerator by remember { mutableStateOf(false) }
remember {
CoroutineScope(Dispatchers.IO).launch {
println("getting models")
val samplersJob = async { Api.getAvailableSamplers() }
val modelsJob = async { Api.getAvailableModels() }
val currModelJob = async { Api.getCurrentModel() }
val samplers = samplersJob.await()
val models = modelsJob.await()
val currModel = currModelJob.await()
samplerData = Triple(0, samplers.first(), samplers)
modelData = Triple(models.indexOf(currModel), currModel, models)
}
}
fun busyOperation(op: suspend () -> Unit) {
working = true
CoroutineScope(Dispatchers.IO).launch {
op()
working = false
}
}
fun onProgress(progress: Progress) {
if (progress.currentImage != null) images = listOf(progress.currentImage)
progressStatus = "%.2f%%".format(progress.progress * 100)
}
fun generate(batchSize: Int) {
busyOperation {
Api.setModel(modelData!!.second)
images = Api.generate(
request = Txt2ImgRequest(
prompt = prompt,
negativePrompt = negativePrompt,
sampler = samplerData!!.second,
width = 512,
height = 512,
steps = steps,
batchSize = batchSize,
cfgScale = cfgScale,
tiling = useTiling,
),
progressDelayInMs = 1000,
onProgress = ::onProgress,
)
progressStatus = null
}
}
fun generatorConfigFromCurrentState() =
GeneratorConfig(
prompt = prompt,
sampler = samplerData!!.second, // TODO: make sure samplers are loaded at this point
model = modelData!!.second, // TODO: make sure models are loaded at this point
negativePrompt = negativePrompt,
steps = steps,
batchSize = batchSize,
cfgScale = cfgScale,
tiling = useTiling,
)
fun onEnterPressedInTextInput() {
val gen = currGenerator
if (gen == null) {
if (!working) generate(batchSize)
} else {
gen.config = generatorConfigFromCurrentState()
canUpdateGenerator = false
}
}
MaterialTheme {
Column {
modelData
?.also { (index, _, models) ->
Select(index, models) { newIndex, newModel ->
if (modelData?.second != newModel) {
if (currGenerator == null) {
modelData = null
CoroutineScope(Dispatchers.IO).launch {
Api.setModel(newModel)
modelData = Triple(newIndex, newModel, models)
}
} else {
modelData = Triple(newIndex, newModel, models)
canUpdateGenerator = true
}
}
}
}
?: CircularProgressIndicator()
samplerData
?.also { (index, _, samplers) ->
Select(index, samplers) { newIndex, newSampler ->
samplerData = Triple(newIndex, newSampler, samplers)
canUpdateGenerator = true
}
}
?: CircularProgressIndicator()
Input(
label = "Positive prompt",
value = prompt,
parser = { it },
onChange = {
prompt = it
canUpdateGenerator = true
},
onEnter = ::onEnterPressedInTextInput,
)
Input(
label = "Negative prompt",
value = negativePrompt,
parser = { it },
onChange = {
negativePrompt = it
canUpdateGenerator = true
},
onEnter = ::onEnterPressedInTextInput,
)
Row {
Column(modifier = Modifier.weight(1f)) {
Input(
label = "Batch size",
value = batchSize,
parser = { value -> value.toIntOrNull()?.takeIf { it in 1..16 } },
onChange = {
batchSize = it
canUpdateGenerator = true
},
onEnter = ::onEnterPressedInTextInput,
)
}
Column(modifier = Modifier.weight(1f)) {
Input(
label = "Steps",
value = steps,
parser = { value -> value.toIntOrNull()?.takeIf { it in 1..100 } },
onChange = {
steps = it
canUpdateGenerator = true
},
onEnter = ::onEnterPressedInTextInput,
)
}
Column(modifier = Modifier.weight(1f)) {
Input(
label = "Cfg scale",
value = cfgScale,
parser = { value -> value.toFloatOrNull()?.takeIf { it in 1f..30f } },
onChange = {
cfgScale = it
canUpdateGenerator = true
},
onEnter = ::onEnterPressedInTextInput,
)
}
Column(modifier = Modifier.weight(1f)) {
Row {
Checkbox(
checked = useTiling,
onCheckedChange = {
useTiling = it
canUpdateGenerator = true
},
modifier = Modifier.align(Alignment.CenterVertically),
)
Text("Tiling", modifier = Modifier.align(Alignment.CenterVertically))
}
}
}
Row {
Button(
onClick = {
currGenerator = Generator(
config = generatorConfigFromCurrentState(),
onStatusChange = { generatorStatus = it },
onProgress = ::onProgress,
)
canUpdateGenerator = false
},
enabled = currGenerator == null && isInitialized,
content = {
Icon(Icons.Default.PlayArrow, null)
Text("start generator")
},
)
Button(
onClick = {
currGenerator?.config = generatorConfigFromCurrentState()
canUpdateGenerator = false
},
enabled = currGenerator != null && canUpdateGenerator,
content = {
Icon(Icons.Default.Refresh, null)
Text("update generator config")
},
)
Button(
onClick = {
// TODO: prevent multiple clicks
currGenerator?.let {
CoroutineScope(Dispatchers.IO).launch {
it.close()
currGenerator = null
progressStatus = null
}
}
},
enabled = currGenerator != null,
content = {
Icon(Icons.Default.Close, null)
Text("stop generator")
},
)
}
Row {
Text("Generator status: $generatorStatus")
Text(progressStatus?.let { "($it)" } ?: "")
}
Row {
Button(
onClick = { generate(1) },
enabled = !working && currGenerator == null && isInitialized,
content = {
Icon(Icons.Default.Search, null)
Text("generate single image")
},
)
Button(
onClick = { generate(batchSize) },
enabled = !working && currGenerator == null && isInitialized,
content = {
Icon(Icons.Default.Search, null)
Text("generate single batch")
},
)
}
if (images.isNotEmpty()) ImageTileList(images, 256.dp)
}
}
}
| 0 | Kotlin | 0 | 0 | 27029321b990924439d9b346cb8d522f70fd14a5 | 11,854 | stable-diffusion-webui-client | Apache License 2.0 |
clevertap-core/src/main/java/com/clevertap/android/sdk/inapp/customtemplates/CustomTemplatesExt.kt | CleverTap | 42,078,482 | false | {"Java": 1808395, "Kotlin": 1695745, "HTML": 10233} | package com.clevertap.android.sdk.inapp.customtemplates
import com.clevertap.android.sdk.inapp.customtemplates.CustomTemplate.FunctionBuilder
import com.clevertap.android.sdk.inapp.customtemplates.CustomTemplate.TemplateBuilder
/**
* Utility function to define a set of [CustomTemplate]s
*/
fun templatesSet(vararg templates: CustomTemplate): Set<CustomTemplate> {
return setOf(*templates)
}
/**
* Utility function to build a [CustomTemplate]. Same as using a [TemplateBuilder] directly.
*/
fun template(buildBlock: TemplateBuilder.() -> Unit): CustomTemplate {
val builder = TemplateBuilder()
buildBlock(builder)
return builder.build()
}
/**
* Utility function to build a [CustomTemplate]. Same as using a [FunctionBuilder] directly.
*/
fun function(isVisual: Boolean, buildBlock: FunctionBuilder.() -> Unit): CustomTemplate {
val builder = FunctionBuilder(isVisual)
buildBlock(builder)
return builder.build()
}
| 9 | Java | 74 | 80 | 2968228861fc6584424c28e30ddc570994465d79 | 951 | clevertap-android-sdk | MIT License |
kommerce-users/src/main/kotlin/com/github/kommerce/users/repo/AiromemUsersRepo.kt | michalperlak | 247,168,850 | false | null | package com.github.kommerce.users.repo
import arrow.core.Option
import com.github.kommerce.common.repo.AiromemRepository
import com.github.kommerce.users.domain.Email
import com.github.kommerce.users.domain.User
import com.github.kommerce.users.domain.UserId
import java.nio.file.Path
class AiromemUsersRepo(path: Path) : UsersRepository {
private val repository = AiromemRepository<UserId, User>(path)
override fun getUser(id: UserId): Option<User> = repository.getById(id)
override fun getByEmail(email: Email): Option<User> = repository.findOneBy(email) { it.email }
override fun add(newUser: User): User = repository.add(newUser)
override fun getAllUsers(): List<User> = repository.getAll()
override fun deleteAll() = repository.deleteAll()
} | 0 | Kotlin | 0 | 0 | 642fb6087e4a9ed8902c1fc5ef2927a6f324f657 | 777 | kommerce | MIT License |
js/js.ast/src/org/jetbrains/kotlin/js/backend/ast/jsScopes.kt | JakeWharton | 99,388,807 | false | null | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.kotlin.js.backend.ast
import java.util.*
class JsObjectScope(parent: JsScope, description: String) : JsScope(parent, description)
object JsDynamicScope : JsScope(null, "Scope for dynamic declarations") {
override fun doCreateName(name: String) = JsName(name, false)
}
open class JsFunctionScope(parent: JsScope, description: String) : JsDeclarationScope(parent, description) {
override fun hasOwnName(name: String): Boolean = RESERVED_WORDS.contains(name) || super.hasOwnName(name)
open fun declareNameUnsafe(identifier: String): JsName = super.declareName(identifier)
}
open class JsDeclarationScope(parent: JsScope, description: String, useParentScopeStack: Boolean = false) : JsScope(parent, description) {
private val labelScopes: Stack<LabelScope> =
if (parent is JsDeclarationScope && useParentScopeStack) parent.labelScopes else Stack<LabelScope>()
private val topLabelScope
get() = if (labelScopes.isNotEmpty()) labelScopes.peek() else null
open fun enterLabel(label: String): JsName {
val scope = LabelScope(topLabelScope, label)
labelScopes.push(scope)
return scope.labelName
}
open fun exitLabel() {
assert(labelScopes.isNotEmpty()) { "No scope to exit from" }
labelScopes.pop()
}
open fun findLabel(label: String): JsName? =
topLabelScope?.findName(label)
private inner class LabelScope(parent: LabelScope?, val ident: String) : JsScope(parent, "Label scope for $ident") {
val labelName: JsName
init {
val freshIdent = when {
ident in RESERVED_WORDS -> getFreshIdent(ident)
parent != null -> parent.getFreshIdent(ident)
else -> ident
}
labelName = JsName(freshIdent, false)
}
override fun findOwnName(name: String): JsName? =
if (name == ident) labelName else null
/**
* Safe call is necessary, because hasOwnName can be called
* in constructor before labelName is initialized (see KT-4394)
*/
@Suppress("UNNECESSARY_SAFE_CALL")
override fun hasOwnName(name: String): Boolean =
name in RESERVED_WORDS
|| name == ident
|| name == labelName?.ident
|| parent?.hasOwnName(name) ?: false
}
companion object {
val RESERVED_WORDS: Set<String> = setOf(
// keywords
"await", "break", "case", "catch", "continue", "debugger", "default", "delete", "do", "else", "finally", "for", "function", "if",
"in", "instanceof", "new", "return", "switch", "this", "throw", "try", "typeof", "var", "void", "while", "with",
// future reserved words
"class", "const", "enum", "export", "extends", "import", "super",
// as future reserved words in strict mode
"implements", "interface", "let", "package", "private", "protected", "public", "static", "yield",
// additional reserved words
"null", "true", "false",
// disallowed as variable names in strict mode
"eval", "arguments",
// global identifiers usually declared in a typical JS interpreter
"NaN", "isNaN", "Infinity", "undefined",
"Error", "Object", "Math", "String", "Number", "Boolean", "Date", "Array", "RegExp", "JSON",
// global identifiers usually declared in know environments (node.js, browser, require.js, WebWorkers, etc)
"require", "define", "module", "window", "self",
// the special Kotlin object
"Kotlin"
)
}
}
class DelegatingJsFunctionScopeWithTemporaryParent(
private val delegatingScope: JsFunctionScope,
parent: JsScope
) : JsFunctionScope(parent, "<delegating scope to delegatingScope>") {
override fun hasOwnName(name: String): Boolean =
delegatingScope.hasOwnName(name)
override fun findOwnName(ident: String): JsName? =
delegatingScope.findOwnName(ident)
override fun declareNameUnsafe(identifier: String): JsName =
delegatingScope.declareNameUnsafe(identifier)
override fun declareName(identifier: String): JsName =
delegatingScope.declareName(identifier)
override fun declareFreshName(suggestedName: String): JsName =
delegatingScope.declareFreshName(suggestedName)
override fun enterLabel(label: String): JsName =
delegatingScope.enterLabel(label)
override fun exitLabel() =
delegatingScope.exitLabel()
override fun findLabel(label: String): JsName? =
delegatingScope.findLabel(label)
}
| 132 | null | 5074 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 5,435 | kotlin | Apache License 2.0 |
app/src/main/java/io/chaldeaprjkt/gamespace/gamebar/SessionService.kt | crdroidandroid | 492,680,724 | false | null | /*
* Copyright (C) 2021 Chaldeaprjkt
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.chaldeaprjkt.gamespace.gamebar
import android.annotation.SuppressLint
import android.app.ActivityTaskManager
import android.app.GameManager
import android.app.Service
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.os.RemoteException
import android.os.UserHandle
import android.util.Log
import dagger.hilt.android.AndroidEntryPoint
import io.chaldeaprjkt.gamespace.data.AppSettings
import io.chaldeaprjkt.gamespace.data.GameSession
import io.chaldeaprjkt.gamespace.data.SystemSettings
import io.chaldeaprjkt.gamespace.utils.GameModeUtils
import io.chaldeaprjkt.gamespace.utils.ScreenUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import javax.inject.Inject
@AndroidEntryPoint(Service::class)
class SessionService : Hilt_SessionService() {
@Inject
lateinit var appSettings: AppSettings
@Inject
lateinit var settings: SystemSettings
@Inject
lateinit var session: GameSession
@Inject
lateinit var screenUtils: ScreenUtils
@Inject
lateinit var gameModeUtils: GameModeUtils
private val scope = CoroutineScope(Job() + Dispatchers.IO)
private val gameBarConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
isBarConnected = true
gameBar = (service as GameBarService.GameBarBinder).getService()
onGameBarReady()
}
override fun onServiceDisconnected(name: ComponentName?) {
isBarConnected = false
stopSelf()
}
}
private lateinit var commandIntent: Intent
private lateinit var gameBar: GameBarService
private lateinit var gameManager: GameManager
private var isBarConnected = false
@SuppressLint("WrongConstant")
override fun onCreate() {
super.onCreate()
try {
screenUtils.bind()
} catch (e: RemoteException) {
Log.d(TAG, e.toString())
}
gameManager = getSystemService(Context.GAME_SERVICE) as GameManager
gameModeUtils.bind(gameManager)
isRunning = true
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
intent?.let { commandIntent = it }
super.onStartCommand(intent, flags, startId)
if (intent == null && flags == 0 && startId > 1) {
return tryStartFromDeath()
}
when (intent?.action) {
START -> startGameBar()
STOP -> stopSelf()
}
return START_STICKY
}
private fun startGameBar() {
Intent(this, GameBarService::class.java).apply {
bindServiceAsUser(this, gameBarConnection, Context.BIND_AUTO_CREATE, UserHandle.CURRENT)
}
}
override fun onBind(intent: Intent?): IBinder? = null
override fun onDestroy() {
if (isBarConnected) {
gameBar.onGameLeave()
unbindService(gameBarConnection)
}
session.unregister()
gameModeUtils.unbind()
screenUtils.unbind()
isRunning = false
super.onDestroy()
}
private fun onGameBarReady() {
if (!isBarConnected) {
startGameBar()
return
}
try {
session.unregister()
if (!::commandIntent.isInitialized) {
// something is not right, bailing out
stopSelf()
}
val app = commandIntent.getStringExtra(EXTRA_PACKAGE_NAME)
session.register(app)
applyGameModeConfig(app)
gameBar.onGameStart()
screenUtils.stayAwake = appSettings.stayAwake
} catch (e: Exception) {
Log.d(TAG, e.toString())
}
}
private fun tryStartFromDeath(): Int {
val game = ActivityTaskManager.getService()
?.focusedRootTaskInfo
?.topActivity?.packageName
?: return START_NOT_STICKY
if (!settings.userGames.any { it.packageName == game }) {
return START_NOT_STICKY
}
commandIntent = Intent(START).putExtra(EXTRA_PACKAGE_NAME, game)
startGameBar()
return START_STICKY
}
private fun applyGameModeConfig(app: String) {
val preferred = settings.userGames.firstOrNull { it.packageName == app }
?.mode ?: GameModeUtils.defaultPreferredMode
gameModeUtils.activeGame = settings.userGames.firstOrNull { it.packageName == app }
scope.launch {
gameManager.getAvailableGameModes(app)
.takeIf { it.contains(preferred) }
?.run { gameManager.setGameMode(app, preferred) }
}
}
companion object {
const val TAG = "SessionService"
const val START = "game_start"
const val STOP = "game_stop"
const val EXTRA_PACKAGE_NAME = "package_name"
var isRunning = false
private set
fun start(context: Context, app: String) = Intent(context, SessionService::class.java)
.apply {
action = START
putExtra(EXTRA_PACKAGE_NAME, app)
}
.takeIf { !isRunning }
?.run { context.startServiceAsUser(this, UserHandle.CURRENT) }
fun stop(context: Context) = Intent(context, SessionService::class.java)
.apply { action = STOP }
.takeIf { isRunning }
?.run { context.stopServiceAsUser(this, UserHandle.CURRENT) }
}
}
| 2 | null | 9 | 8 | df6296d74d3a452374225eec55efaffed4cc5333 | 6,300 | android_packages_apps_GameSpace | Apache License 2.0 |
app/src/main/java/org/y20k/transistor/MainActivity.kt | CrepeTF | 342,317,736 | true | {"Kotlin": 333565} | /*
* MainActivity.kt
* Implements the MainActivity class
* MainActivity is the default activity that can host the player fragment and the settings fragment
*
* This file is part of
* TRANSISTOR - Radio App for Android
*
* Copyright (c) 2015-21 - Y20K.org
* Licensed under the MIT-License
* http://opensource.org/licenses/MIT
*/
package org.y20k.transistor
import android.content.Context
import android.content.SharedPreferences
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import androidx.preference.PreferenceManager
import org.y20k.transistor.helpers.AppThemeHelper
import org.y20k.transistor.helpers.FileHelper
import org.y20k.transistor.helpers.LogHelper
import org.y20k.transistor.helpers.PreferencesHelper
/*
* MainActivity class
*/
class MainActivity: AppCompatActivity() {
/* Define log tag */
private val TAG: String = LogHelper.makeLogTag(MainActivity::class.java)
/* Main class variables */
private lateinit var appBarConfiguration: AppBarConfiguration
/* Overrides onCreate from AppCompatActivity */
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// set up views
setContentView(R.layout.activity_main)
// create .nomedia file - if not yet existing
FileHelper.createNomediaFile(getExternalFilesDir(null))
// set up action bar
setSupportActionBar(findViewById(R.id.main_toolbar))
val navController = findNavController(R.id.main_host_container)
appBarConfiguration = AppBarConfiguration(navController.graph)
setupActionBarWithNavController(navController, appBarConfiguration)
// register listener for changes in shared preferences
PreferenceManager.getDefaultSharedPreferences(this as Context).registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener)
}
/* Overrides onSupportNavigateUp from AppCompatActivity */
override fun onSupportNavigateUp(): Boolean {
// Taken from: https://developer.android.com/guide/navigation/navigation-ui#action_bar
val navController = findNavController(R.id.main_host_container)
return navController.navigateUp(appBarConfiguration) || super.onSupportNavigateUp()
}
/* Overrides onDestroy from AppCompatActivity */
override fun onDestroy() {
super.onDestroy()
// unregister listener for changes in shared preferences
PreferenceManager.getDefaultSharedPreferences(this as Context).unregisterOnSharedPreferenceChangeListener(sharedPreferenceChangeListener)
}
/*
* Defines the listener for changes in shared preferences
*/
private val sharedPreferenceChangeListener = SharedPreferences.OnSharedPreferenceChangeListener { sharedPreferences, key ->
when (key) {
Keys.PREF_THEME_SELECTION -> {
AppThemeHelper.setTheme(PreferencesHelper.loadThemeSelection(this@MainActivity))
}
}
}
/*
* End of declaration
*/
}
| 1 | Kotlin | 1 | 3 | 250e29996f8d6822a76b99016142eb8ab4ada9eb | 3,251 | Junction | MIT License |
src/main/kotlin/uk/gov/justice/digital/hmpps/approvedpremisesapi/seed/cas2/Cas2ApplicationsSeedJob.kt | ministryofjustice | 515,276,548 | false | null | package uk.gov.justice.digital.hmpps.approvedpremisesapi.seed.cas2
import org.slf4j.LoggerFactory
import org.springframework.core.io.DefaultResourceLoader
import org.springframework.util.FileCopyUtils
import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.Cas2ApplicationEntity
import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.Cas2ApplicationJsonSchemaEntity
import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.Cas2ApplicationRepository
import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.Cas2StatusUpdateEntity
import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.Cas2StatusUpdateRepository
import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.ExternalUserRepository
import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.NomisUserEntity
import uk.gov.justice.digital.hmpps.approvedpremisesapi.jpa.entity.NomisUserRepository
import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.reference.Cas2PersistedApplicationStatus
import uk.gov.justice.digital.hmpps.approvedpremisesapi.model.reference.Cas2PersistedApplicationStatusFinder
import uk.gov.justice.digital.hmpps.approvedpremisesapi.seed.SeedJob
import uk.gov.justice.digital.hmpps.approvedpremisesapi.service.cas2.JsonSchemaService
import java.io.IOException
import java.io.InputStreamReader
import java.time.OffsetDateTime
import java.util.UUID
class Cas2ApplicationsSeedJob(
fileName: String,
private val repository: Cas2ApplicationRepository,
private val userRepository: NomisUserRepository,
private val externalUserRepository: ExternalUserRepository,
private val statusUpdateRepository: Cas2StatusUpdateRepository,
private val jsonSchemaService: JsonSchemaService,
private val statusFinder: Cas2PersistedApplicationStatusFinder,
) : SeedJob<Cas2ApplicationSeedCsvRow>(
id = UUID.randomUUID(),
fileName = fileName,
requiredHeaders = setOf("id", "nomsNumber", "crn", "state", "createdBy", "createdAt", "submittedAt", "statusUpdates", "location"),
) {
private val log = LoggerFactory.getLogger(this::class.java)
override fun deserializeRow(columns: Map<String, String>) = Cas2ApplicationSeedCsvRow(
id = UUID.fromString(columns["id"]!!.trim()),
nomsNumber = columns["nomsNumber"]!!.trim(),
crn = columns["crn"]!!.trim(),
state = columns["state"]!!.trim(),
createdBy = columns["createdBy"]!!.trim(),
createdAt = OffsetDateTime.parse(columns["createdAt"]),
submittedAt = parseDateIfNotNull(emptyToNull(columns["submittedAt"])),
statusUpdates = columns["statusUpdates"]!!.trim(),
location = columns["location"]!!.trim(),
)
override fun processRow(row: Cas2ApplicationSeedCsvRow) {
log.info("Setting up Application id ${row.id}")
if (repository.findById(row.id).isPresent()) {
return log.info("Skipping ${row.id}: already seeded")
}
val applicant = userRepository.findByNomisUsername(row.createdBy) ?: throw RuntimeException("Could not find applicant with nomisUsername ${row.createdBy}")
try {
createApplication(row, applicant)
} catch (exception: Exception) {
throw RuntimeException("Could not create application ${row.id}", exception)
}
}
private fun createApplication(row: Cas2ApplicationSeedCsvRow, applicant: NomisUserEntity) {
val application = repository.save(
Cas2ApplicationEntity(
id = row.id,
crn = row.crn,
nomsNumber = row.nomsNumber,
createdAt = row.createdAt,
createdByUser = applicant,
data = dataFor(state = row.state, nomsNumber = row.nomsNumber),
document = documentFor(state = row.state, nomsNumber = row.nomsNumber),
submittedAt = row.submittedAt,
schemaVersion = jsonSchemaService.getNewestSchema(Cas2ApplicationJsonSchemaEntity::class.java),
schemaUpToDate = true,
),
)
if (row.statusUpdates != "0") {
repeat(row.statusUpdates.toInt()) { idx -> createStatusUpdate(idx, application) }
}
}
private fun createStatusUpdate(idx: Int, application: Cas2ApplicationEntity) {
log.info("Seeding status update $idx for application ${application.id}")
val assessor = externalUserRepository.findAll().random()
val status = findStatusAtPosition(idx)
statusUpdateRepository.save(
Cas2StatusUpdateEntity(
id = UUID.randomUUID(),
application = application,
assessor = assessor,
description = status.description,
label = status.label,
statusId = status.id,
createdAt = OffsetDateTime.now(),
),
)
}
private fun findStatusAtPosition(idx: Int): Cas2PersistedApplicationStatus {
return statusFinder.active()[idx]
}
private fun dataFor(state: String, nomsNumber: String): String {
if (state != "NOT_STARTED") {
return dataFixtureFor(nomsNumber)
}
return "{}"
}
private fun documentFor(state: String, nomsNumber: String): String {
if (listOf("SUBMITTED", "IN_REVIEW").contains(state)) {
return documentFixtureFor(nomsNumber)
}
return "{}"
}
private fun dataFixtureFor(nomsNumber: String): String {
return loadFixtureAsResource("data_$nomsNumber.json")
}
private fun documentFixtureFor(nomsNumber: String): String {
return loadFixtureAsResource("document_$nomsNumber.json")
}
private fun loadFixtureAsResource(filename: String): String {
val path = "db/seed/local+dev+test/cas2_application_data/$filename"
val loader = DefaultResourceLoader()
return try {
val resource = loader.getResource(path)
val reader = InputStreamReader(resource.inputStream, "UTF-8")
FileCopyUtils.copyToString(reader)
} catch (e: IOException) {
log.warn("FAILED to load seed fixture: " + e.message!!)
"{}"
}
}
private fun emptyToNull(value: String?) = value?.ifBlank { null }
private fun parseDateIfNotNull(date: String?) = date?.let { OffsetDateTime.parse(it) }
}
data class Cas2ApplicationSeedCsvRow(
val id: UUID,
val nomsNumber: String,
val crn: String,
val state: String, // NOT_STARTED | IN-PROGRESS | SUBMITTED | IN_REVIEW
val createdBy: String,
val createdAt: OffsetDateTime,
val submittedAt: OffsetDateTime?,
val statusUpdates: String,
val location: String,
)
| 32 | null | 2 | 4 | bc7d57577d3f4c2521132c4a3da340e23729b0e5 | 6,284 | hmpps-approved-premises-api | MIT License |
src/test/kotlin/no/nav/familie/ef/iverksett/brev/DistribuerVedtaksbrevTaskTest.kt | navikt | 357,821,728 | false | null | package no.nav.familie.ef.iverksett.brev
import io.mockk.every
import io.mockk.mockk
import io.mockk.slot
import io.mockk.verify
import no.nav.familie.ef.iverksett.iverksetting.domene.DistribuerVedtaksbrevResultat
import no.nav.familie.ef.iverksett.iverksetting.domene.JournalpostResultat
import no.nav.familie.ef.iverksett.iverksetting.tilstand.TilstandRepository
import no.nav.familie.ef.iverksett.tilbakekreving.OpprettTilbakekrevingTask
import no.nav.familie.prosessering.domene.Task
import no.nav.familie.prosessering.domene.TaskRepository
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import java.time.LocalDateTime
import java.util.Properties
import java.util.UUID
internal class DistribuerVedtaksbrevTaskTest {
private val journalpostClient = mockk<JournalpostClient>()
private val tilstandRepository = mockk<TilstandRepository>()
private val distribuerVedtaksbrevTask = DistribuerVedtaksbrevTask(journalpostClient, tilstandRepository)
@Test
internal fun `skal distribuere brev`() {
val behandlingId = UUID.randomUUID()
val journalpostId = "123456789"
val bestillingId = "111"
val distribuerVedtaksbrevResultat = slot<DistribuerVedtaksbrevResultat>()
every { tilstandRepository.hentJournalpostResultat(behandlingId) } returns JournalpostResultat(
journalpostId,
LocalDateTime.now()
)
every { journalpostClient.distribuerBrev(journalpostId) } returns bestillingId
every {
tilstandRepository.oppdaterDistribuerVedtaksbrevResultat(
behandlingId,
capture(distribuerVedtaksbrevResultat)
)
} returns Unit
distribuerVedtaksbrevTask.doTask(Task(DistribuerVedtaksbrevTask.TYPE, behandlingId.toString(), Properties()))
verify(exactly = 1) { journalpostClient.distribuerBrev(journalpostId) }
verify(exactly = 1) { tilstandRepository.oppdaterDistribuerVedtaksbrevResultat(behandlingId, any()) }
assertThat(distribuerVedtaksbrevResultat.captured.bestillingId).isEqualTo(bestillingId)
assertThat(distribuerVedtaksbrevResultat.captured.dato).isNotNull()
}
}
| 12 | Kotlin | 0 | 0 | 9785e50dc2f1dbc65ef4ab60e23282504f7a85b0 | 2,229 | familie-ef-iverksett | MIT License |
app/src/main/java/com/breezebengaldetergentproducts/features/damageProduct/api/GetDamageProductListRegRepository.kt | DebashisINT | 863,405,964 | false | {"Kotlin": 15991783, "Java": 1032672} | package com.breezebengaldetergentproducts.features.damageProduct.api
import android.content.Context
import android.net.Uri
import android.text.TextUtils
import android.util.Log
import com.breezebengaldetergentproducts.app.FileUtils
import com.breezebengaldetergentproducts.base.BaseResponse
import com.breezebengaldetergentproducts.features.NewQuotation.model.*
import com.breezebengaldetergentproducts.features.addshop.model.AddShopRequestData
import com.breezebengaldetergentproducts.features.addshop.model.AddShopResponse
import com.breezebengaldetergentproducts.features.damageProduct.model.DamageProductResponseModel
import com.breezebengaldetergentproducts.features.damageProduct.model.delBreakageReq
import com.breezebengaldetergentproducts.features.damageProduct.model.viewAllBreakageReq
import com.breezebengaldetergentproducts.features.login.model.userconfig.UserConfigResponseModel
import com.breezebengaldetergentproducts.features.myjobs.model.WIPImageSubmit
import com.breezebengaldetergentproducts.features.photoReg.model.*
import com.fasterxml.jackson.databind.ObjectMapper
import com.google.gson.Gson
import io.reactivex.Observable
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
class GetDamageProductListRegRepository(val apiService : GetDamageProductListApi) {
fun viewBreakage(req: viewAllBreakageReq): Observable<DamageProductResponseModel> {
return apiService.viewBreakage(req)
}
fun delBreakage(req: delBreakageReq): Observable<BaseResponse>{
return apiService.BreakageDel(req.user_id!!,req.breakage_number!!,req.session_token!!)
}
} | 0 | Kotlin | 0 | 0 | 0cd8b29158b494893e3d7be77b87a725e3d49abf | 1,646 | BengalDetergentProducts | Apache License 2.0 |
src/test/kotlin/uk/gov/justice/digital/hmpps/prisonertonomisupdate/activities/SchedulesServiceTest.kt | ministryofjustice | 445,140,246 | false | {"Kotlin": 1290877, "Mustache": 1803, "Dockerfile": 1118} | @file:OptIn(ExperimentalCoroutinesApi::class)
package uk.gov.justice.digital.hmpps.prisonertonomisupdate.activities
import com.microsoft.applicationinsights.TelemetryClient
import jakarta.validation.ValidationException
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Nested
import org.junit.jupiter.api.Test
import org.junit.jupiter.api.assertThrows
import org.mockito.ArgumentMatchers.anyLong
import org.mockito.kotlin.any
import org.mockito.kotlin.check
import org.mockito.kotlin.eq
import org.mockito.kotlin.isNull
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.springframework.web.reactive.function.client.WebClientResponseException
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.activities.model.ActivityCategory
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.activities.model.ActivityLite
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.activities.model.ActivityScheduleInstance
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.activities.model.ActivityScheduleLite
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.nomissync.model.UpdateCourseScheduleResponse
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.services.NomisApiService
import java.time.LocalDate
import java.time.LocalDateTime
class SchedulesServiceTest {
private val activitiesApiService: ActivitiesApiService = mock()
private val nomisApiService: NomisApiService = mock()
private val mappingService: ActivitiesMappingService = mock()
private val telemetryClient: TelemetryClient = mock()
private val schedulesService = SchedulesService(activitiesApiService, nomisApiService, mappingService, telemetryClient)
@Nested
inner class AmendScheduledInstance {
private fun aDomainEvent() =
ScheduledInstanceDomainEvent(
eventType = "activities.scheduled-instance.amended",
additionalInformation = ScheduledInstanceAdditionalInformation(ACTIVITY_SCHEDULE_ID, SCHEDULE_INSTANCE_ID),
version = "1.0",
description = "description",
)
@Test
fun `should throw and raise telemetry if cannot load Activity Schedule`() = runTest {
whenever(activitiesApiService.getScheduledInstance(anyLong()))
.thenThrow(WebClientResponseException.NotFound::class.java)
assertThrows<WebClientResponseException.NotFound> {
schedulesService.updateScheduledInstance(aDomainEvent())
}
verify(activitiesApiService).getScheduledInstance(SCHEDULE_INSTANCE_ID)
verify(telemetryClient).trackEvent(
eq("activity-scheduled-instance-amend-failed"),
check<Map<String, String>> {
assertThat(it["dpsScheduledInstanceId"]).isEqualTo(SCHEDULE_INSTANCE_ID.toString())
},
isNull(),
)
}
@Test
fun `should throw and raise telemetry if cannot find mappings`() = runTest {
whenever(activitiesApiService.getScheduledInstance(anyLong())).thenReturn(newScheduledInstance())
whenever(mappingService.getMappings(anyLong()))
.thenThrow(WebClientResponseException.NotFound::class.java)
assertThrows<WebClientResponseException.NotFound> {
schedulesService.updateScheduledInstance(aDomainEvent())
}
verify(mappingService).getMappings(ACTIVITY_SCHEDULE_ID)
verify(telemetryClient).trackEvent(
eq("activity-scheduled-instance-amend-failed"),
check<Map<String, String>> {
assertThat(it["scheduleDate"]).isEqualTo("2023-02-23")
assertThat(it["startTime"]).isEqualTo("08:00")
assertThat(it["endTime"]).isEqualTo("11:00")
assertThat(it["prisonId"]).isEqualTo("LEI")
},
isNull(),
)
}
@Test
fun `should throw and raise telemetry if cannot find scheduled instance mapping`() = runTest {
whenever(activitiesApiService.getScheduledInstance(anyLong())).thenReturn(newScheduledInstance())
whenever(mappingService.getMappings(anyLong())).thenReturn(
ActivityMappingDto(
NOMIS_CRS_ACTY_ID,
ACTIVITY_SCHEDULE_ID,
ACTIVITY_ID,
"ACTIVITY_CREATED",
listOf(),
LocalDateTime.now(),
),
)
assertThrows<ValidationException> {
schedulesService.updateScheduledInstance(aDomainEvent())
}.also {
assertThat(it.message).isEqualTo("Mapping for Activity's scheduled instance id not found: $SCHEDULE_INSTANCE_ID")
}
verify(mappingService).getMappings(ACTIVITY_SCHEDULE_ID)
verify(telemetryClient).trackEvent(
eq("activity-scheduled-instance-amend-failed"),
check<Map<String, String>> {
assertThat(it["nomisCourseActivityId"]).isEqualTo("$NOMIS_CRS_ACTY_ID")
assertThat(it["scheduleDate"]).isEqualTo("2023-02-23")
assertThat(it["startTime"]).isEqualTo("08:00")
assertThat(it["endTime"]).isEqualTo("11:00")
},
isNull(),
)
}
@Test
fun `should throw and raise telemetry if fails to update Nomis`() = runTest {
whenever(activitiesApiService.getScheduledInstance(anyLong())).thenReturn(newScheduledInstance())
whenever(mappingService.getMappings(anyLong())).thenReturn(
ActivityMappingDto(
NOMIS_CRS_ACTY_ID,
ACTIVITY_SCHEDULE_ID,
ACTIVITY_ID,
"ACTIVITY_CREATED",
listOf(
ActivityScheduleMappingDto(
SCHEDULE_INSTANCE_ID,
NOMIS_CRS_SCH_ID,
"ACTIVITY_CREATED",
),
),
LocalDateTime.now(),
),
)
whenever(nomisApiService.updateScheduledInstance(anyLong(), any()))
.thenThrow(WebClientResponseException.ServiceUnavailable::class.java)
assertThrows<WebClientResponseException.ServiceUnavailable> {
schedulesService.updateScheduledInstance(aDomainEvent())
}
verify(nomisApiService).updateScheduledInstance(eq(NOMIS_CRS_ACTY_ID), any())
verify(telemetryClient).trackEvent(
eq("activity-scheduled-instance-amend-failed"),
check<Map<String, String>> {
assertThat(it["nomisCourseActivityId"]).isEqualTo(NOMIS_CRS_ACTY_ID.toString())
assertThat(it["prisonId"]).isEqualTo("LEI")
},
isNull(),
)
}
@Test
fun `should raise telemetry when update of Nomis successful`() = runTest {
whenever(activitiesApiService.getScheduledInstance(anyLong())).thenReturn(newScheduledInstance())
whenever(mappingService.getMappings(anyLong())).thenReturn(
ActivityMappingDto(
NOMIS_CRS_ACTY_ID,
ACTIVITY_SCHEDULE_ID,
ACTIVITY_ID,
"ACTIVITY_CREATED",
listOf(
ActivityScheduleMappingDto(
SCHEDULE_INSTANCE_ID,
NOMIS_CRS_SCH_ID,
"ACTIVITY_CREATED",
),
),
LocalDateTime.now(),
),
)
whenever(nomisApiService.updateScheduledInstance(anyLong(), any())).thenReturn(UpdateCourseScheduleResponse(NOMIS_CRS_SCH_ID))
schedulesService.updateScheduledInstance(aDomainEvent())
verify(nomisApiService).updateScheduledInstance(
eq(NOMIS_CRS_ACTY_ID),
check {
with(it) {
assertThat(date).isEqualTo("2023-02-23")
assertThat(startTime).isEqualTo("08:00")
assertThat(endTime).isEqualTo("11:00")
}
},
)
verify(telemetryClient).trackEvent(
eq("activity-scheduled-instance-amend-success"),
check<Map<String, String>> {
assertThat(it["dpsScheduledInstanceId"]).isEqualTo(SCHEDULE_INSTANCE_ID.toString())
assertThat(it["dpsActivityScheduleId"]).isEqualTo(ACTIVITY_SCHEDULE_ID.toString())
assertThat(it["nomisCourseActivityId"]).isEqualTo(NOMIS_CRS_ACTY_ID.toString())
assertThat(it["scheduleDate"]).isEqualTo("2023-02-23")
assertThat(it["startTime"]).isEqualTo("08:00")
assertThat(it["endTime"]).isEqualTo("11:00")
assertThat(it["nomisCourseScheduleId"]).isEqualTo(NOMIS_CRS_SCH_ID.toString())
assertThat(it["prisonId"]).isEqualTo("LEI")
},
isNull(),
)
}
}
}
private fun newScheduledInstance() = ActivityScheduleInstance(
id = SCHEDULE_INSTANCE_ID,
date = LocalDate.parse("2023-02-23"),
startTime = "08:00",
endTime = "11:00",
cancelled = true,
attendances = listOf(),
cancelledTime = null,
cancelledBy = null,
activitySchedule =
ActivityScheduleLite(
id = ACTIVITY_SCHEDULE_ID,
description = "test",
capacity = 10,
slots = listOf(),
startDate = LocalDate.parse("2023-02-01"),
scheduleWeeks = 1,
activity =
ActivityLite(
id = ACTIVITY_ID,
prisonCode = "LEI",
attendanceRequired = true,
inCell = false,
pieceWork = false,
outsideWork = false,
payPerSession = ActivityLite.PayPerSession.H,
summary = "test",
riskLevel = "risk",
minimumEducationLevel = listOf(),
category =
ActivityCategory(
id = 123,
code = "ANY",
description = "any",
name = "any",
),
createdTime = LocalDateTime.parse("2023-02-10T08:34:38"),
activityState = ActivityLite.ActivityState.LIVE,
allocated = 5,
capacity = 10,
onWing = false,
offWing = false,
paid = true,
),
),
)
| 2 | Kotlin | 0 | 2 | cb523828b23bbf57983c5c99c67fee2821ef8a51 | 9,565 | hmpps-prisoner-to-nomis-update | MIT License |
compose/ui/ui/src/androidInstrumentedTest/kotlin/androidx/compose/ui/input/InputInLayerTest.kt | androidx | 256,589,781 | false | {"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019} | /*
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.compose.ui.input
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Matrix
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.LayoutCoordinates
import androidx.compose.ui.layout.onPlaced
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.test.onNodeWithTag
import androidx.compose.ui.test.performTouchInput
import androidx.compose.ui.unit.IntSize
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import org.junit.Rule
import org.junit.Test
@MediumTest
class InputInLayerTest {
@get:Rule val rule = createComposeRule()
@Test
fun reusedLayerIsReset() {
val tag = "Outer Box"
var size = IntSize.Zero
var showRed by mutableStateOf(true)
var rootPoint = Offset.Zero
lateinit var outerLayoutCoordinates: LayoutCoordinates
rule.setContent {
Box(
Modifier.fillMaxSize().testTag(tag).onPlaced {
size = it.size
outerLayoutCoordinates = it
}
) {
if (showRed) {
Spacer(
modifier =
Modifier.graphicsLayer(scaleY = 0.5f)
.fillMaxSize()
.background(Color.Red)
.clickable { showRed = false }
.onPlaced {
val matrix = Matrix()
outerLayoutCoordinates.transformFrom(it, matrix)
rootPoint = matrix.map(Offset.Zero)
},
)
} else {
Spacer(
modifier =
Modifier.graphicsLayer()
.fillMaxSize()
.background(Color.Blue)
.clickable { showRed = true }
.onPlaced {
val matrix = Matrix()
outerLayoutCoordinates.transformFrom(it, matrix)
rootPoint = matrix.map(Offset.Zero)
},
)
}
}
}
rule.waitForIdle()
assertThat(showRed).isTrue()
assertThat(rootPoint.y).isWithin(1f).of(size.height / 4f)
rule.onNodeWithTag(tag).performTouchInput {
down(Offset(size.width / 2f, size.height / 2f))
up()
}
rule.waitForIdle()
assertThat(showRed).isFalse()
assertThat(rootPoint.y).isWithin(1f).of(0f)
rule.onNodeWithTag(tag).performTouchInput {
down(Offset.Zero)
up()
}
rule.waitForIdle()
assertThat(showRed).isTrue()
assertThat(rootPoint.y).isWithin(1f).of(size.height / 4f)
}
}
| 30 | Kotlin | 974 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 4,189 | androidx | Apache License 2.0 |
buildSrc/src/main/kotlin/constants.kt | AppsCDN | 362,898,757 | true | {"Kotlin": 59604, "Swift": 3832} | const val KOTLIN_VERSION = "1.4.31"
const val KTOR_VERSION = "1.5.2"
const val COROUTINES_VERSION = "1.4.3-native-mt"
| 0 | null | 0 | 1 | 50db02ebbab4baba74dab73410dbf6d966c9dd7e | 118 | CoinGecko-Kotlin | MIT License |
app/src/main/java/info/juanmendez/breedgallery/ui/breedlist/viewmodel/BreedObservable.kt | juanmendez | 121,443,075 | false | null | package info.juanmendez.breedgallery.ui.breedlist.viewmodel
import android.databinding.BaseObservable
import android.databinding.Bindable
import info.juanmendez.breedgallery.BR
import info.juanmendez.breedgallery.models.Breed
/**
* Created by <NAME> on 2/15/18.
*
* This is an observable used for recyclerView holder and its view
*/
class BreedObservable : BaseObservable() {
private var _breed = Breed("", listOf())
var breed: Breed
@Bindable get() = _breed
set(value) {
_breed = value
notifyPropertyChanged(BR.breed)
}
} | 0 | Kotlin | 0 | 1 | bb108ca4648466c66eebc437884388f9875dc9f7 | 586 | PetGallery | The Unlicense |
code/demo/src/main/kotlin/com/example/demo/DemoApplication.kt | Grenguar | 349,338,242 | false | {"TypeScript": 3438, "Kotlin": 2702, "JavaScript": 497, "Dockerfile": 142} | package com.example.demo
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import com.example.demo.DemoController
import org.springframework.context.annotation.Bean
@SpringBootApplication
class DemoApplication
fun main(args: Array<String>) {
runApplication<DemoApplication>(*args)
}
| 0 | TypeScript | 0 | 2 | 8c266ed07cfdadc55bf48d2348fc96ea0a9b702c | 353 | cdk-ecs-fargate-spring-secrets | MIT License |
src/main/kotlin/com/kiptechie/rooms/MemberAlreadyExistsException.kt | kiptechie | 430,393,558 | false | null | package com.kiptechie.rooms
class MemberAlreadyExistsException : Exception(
"There is already a member with that username in the room"
) | 0 | Kotlin | 0 | 1 | e5598239c5a42436c800fc242d754ada206c79c7 | 141 | ktor-chat | MIT License |
src/commonMain/kotlin/com/github/kotlinizer/mqtt/topic/TopicMatcher.kt | kotlinization | 182,853,094 | false | null | package com.github.kotlinizer.mqtt.topic
internal class TopicMatcher {
fun matches(subscribedTo: String, receivedOn: String): Boolean {
return if (subscribedTo.contains('#')) {
val subscribedPrefix = subscribedTo
.removeSuffix("#")
.removeSuffix("/")
receivedOn.startsWith(subscribedPrefix)
} else {
subscribedTo == receivedOn
}
}
} | 0 | Kotlin | 3 | 3 | 418eb2587ed2726d24e443fe537d50710fd481b3 | 434 | kotlin-mqtt-client | Apache License 2.0 |
app/src/main/java/net/xaethos/trackernotifier/StoryActivity.kt | xaethos | 42,404,910 | false | null | package net.xaethos.trackernotifier
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.design.widget.CollapsingToolbarLayout
import android.support.design.widget.TabLayout
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.widget.TextView
import net.xaethos.trackernotifier.api.TrackerClient
import net.xaethos.trackernotifier.fragments.BaseResourceFragment
import net.xaethos.trackernotifier.fragments.StoryCommentsFragment
import net.xaethos.trackernotifier.fragments.StoryDetailsFragment
import net.xaethos.trackernotifier.models.Story
import net.xaethos.trackernotifier.subscribers.toastError
import rx.Observable
import rx.android.schedulers.AndroidSchedulers
import rx.subjects.BehaviorSubject
private val EXTRA_PROJECT_ID = "net.xaethos.trackernotifier.projectId"
private val EXTRA_STORY_ID = "net.xaethos.trackernotifier.storyId"
private val EXTRA_STORY_HINT = "net.xaethos.trackernotifier.storyHint"
private fun getTypeDrawable(@Story.Type storyType: String?) = when (storyType) {
Story.TYPE_FEATURE -> R.drawable.ic_star_white_24dp
Story.TYPE_BUG -> R.drawable.ic_bug_report_white_24dp
Story.TYPE_CHORE -> R.drawable.ic_settings_white_24dp
Story.TYPE_RELEASE -> R.drawable.ic_flag_white_24dp
else -> 0
}
class StoryActivity : AppCompatActivity(), BaseResourceFragment.ResourceSource<Story> {
private var projectId: Long = 0
private var storyId: Long = 0
private val storySubject = BehaviorSubject.create<Story>()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
projectId = intent.getLongExtra(EXTRA_PROJECT_ID, 0)
storyId = intent.getLongExtra(EXTRA_STORY_ID, 0)
val storyHint = intent.getSerializableExtra(EXTRA_STORY_HINT) as Story
setContentView(R.layout.activity_story)
val toolbarLayout = findViewById(R.id.toolbar_layout) as CollapsingToolbarLayout
setSupportActionBar(toolbarLayout.findViewById(R.id.toolbar) as Toolbar)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
setupAppBar(toolbarLayout, storyHint)
val viewPager = findViewById(R.id.pager) as ViewPager
viewPager.adapter = SectionsPagerAdapter()
val tabBar = findViewById(R.id.tab_bar) as TabLayout
tabBar.setupWithViewPager(viewPager)
val storyObservable: Observable<Story>
if (projectId == 0L) {
storyObservable = TrackerClient.instance.stories.show(storyId)
} else {
storyObservable = TrackerClient.instance.stories.show(projectId, storyId)
}
storyObservable
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ story ->
storySubject.onNext(story)
setupAppBar(toolbarLayout, story)
},
{ toastError(it) }
)
}
private fun setupAppBar(appBar: CollapsingToolbarLayout, story: Story?) {
appBar.title = story?.name
val type = story?.story_type
val typeView = findViewById(R.id.text_type) as TextView
typeView.text = type
typeView.setCompoundDrawablesWithIntrinsicBounds(getTypeDrawable(type), 0, 0, 0)
val stateView = findViewById(R.id.text_state) as TextView
stateView.text = story?.current_state
}
override val resourceObservable: Observable<Story>
get() = storySubject.asObservable()
private inner class SectionsPagerAdapter : FragmentPagerAdapter(supportFragmentManager) {
override fun getItem(position: Int) = when (position) {
0 -> StoryDetailsFragment()
1 -> StoryCommentsFragment.newInstance(projectId)
else -> null
}
override fun getCount() = 2
override fun getPageTitle(position: Int) = when (position) {
0 -> getString(R.string.title_fragment_story_details)
1 -> getString(R.string.title_fragment_story_comments)
else -> null
}
}
companion object {
fun forStory(context: Context, projectId: Long, story: Story): Intent {
val intent = Intent(context, StoryActivity::class.java)
intent.putExtra(EXTRA_PROJECT_ID, projectId)
intent.putExtra(EXTRA_STORY_ID, story.id)
intent.putExtra(EXTRA_STORY_HINT, story)
return intent
}
}
}
| 0 | Kotlin | 1 | 0 | 46f589eb8e4759a587dbc4a6d9fa5d4c33a8ff59 | 4,647 | tracker-notifier | MIT License |
navigation-material/src/main/java/com/google/accompanist/navigation/material/SheetContentHost.kt | google | 261,392,630 | 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.accompanist.navigation.material
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.rememberUpdatedState
import androidx.compose.runtime.saveable.SaveableStateHolder
import androidx.compose.runtime.snapshotFlow
import androidx.navigation.NavBackStackEntry
import androidx.navigation.compose.LocalOwnersProvider
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.drop
/**
* Hosts a [BottomSheetNavigator.Destination]'s [NavBackStackEntry] and its
* [BottomSheetNavigator.Destination.content] and provides a [onSheetDismissed] callback. It also
* shows and hides the [ModalBottomSheetLayout] through the [sheetState] when the sheet content
* enters or leaves the composition.
*
* @param backStackEntry The [NavBackStackEntry] holding the [BottomSheetNavigator.Destination],
* or null if there is no [NavBackStackEntry]
* @param sheetState The [ModalBottomSheetState] used to observe and control the sheet visibility
* @param onSheetDismissed Callback when the sheet has been dismissed. Typically, you'll want to
* pop the back stack here.
*/
@ExperimentalMaterialNavigationApi
@OptIn(ExperimentalMaterialApi::class)
@Composable
internal fun ColumnScope.SheetContentHost(
backStackEntry: NavBackStackEntry?,
sheetState: ModalBottomSheetState,
saveableStateHolder: SaveableStateHolder,
onSheetShown: (entry: NavBackStackEntry) -> Unit,
onSheetDismissed: (entry: NavBackStackEntry) -> Unit,
) {
if (backStackEntry != null) {
val currentOnSheetShown by rememberUpdatedState(onSheetShown)
val currentOnSheetDismissed by rememberUpdatedState(onSheetDismissed)
LaunchedEffect(sheetState, backStackEntry) {
snapshotFlow { sheetState.isVisible }
// We are only interested in changes in the sheet's visibility
.distinctUntilChanged()
// distinctUntilChanged emits the initial value which we don't need
.drop(1)
.collect { visible ->
if (visible) {
currentOnSheetShown(backStackEntry)
} else {
currentOnSheetDismissed(backStackEntry)
}
}
}
backStackEntry.LocalOwnersProvider(saveableStateHolder) {
@Suppress("DEPRECATION")
val content = (backStackEntry.destination as BottomSheetNavigator.Destination).content
content(backStackEntry)
}
}
}
| 88 | null | 937 | 7,396 | 52a660d1988f838dc8b8ff84ee5f267b060b6e04 | 3,414 | accompanist | Apache License 2.0 |
hmpps-prisoner-search-indexer/src/test/kotlin/uk/gov/justice/digital/hmpps/prisonersearch/indexer/integration/wiremock/IncentivesApiMockServer.kt | ministryofjustice | 636,804,116 | false | null | package uk.gov.justice.digital.hmpps.prisonersearchindexer.integration.wiremock
import com.github.tomakehurst.wiremock.WireMockServer
import com.github.tomakehurst.wiremock.client.WireMock.aResponse
import com.github.tomakehurst.wiremock.client.WireMock.get
import com.github.tomakehurst.wiremock.client.WireMock.getRequestedFor
import com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo
import com.github.tomakehurst.wiremock.client.WireMock.urlPathMatching
import org.junit.jupiter.api.extension.AfterAllCallback
import org.junit.jupiter.api.extension.BeforeAllCallback
import org.junit.jupiter.api.extension.BeforeEachCallback
import org.junit.jupiter.api.extension.ExtensionContext
class IncentivesMockServer : WireMockServer(8096) {
fun stubHealthPing(status: Int) {
stubFor(
get("/health/ping").willReturn(
aResponse()
.withHeader("Content-Type", "application/json")
.withBody(if (status == 200) "pong" else "some error")
.withStatus(status),
),
)
}
fun stubCurrentIncentive(
iepCode: String = "STD",
iepLevel: String = "Standard",
iepTime: String = "2022-11-10T15:47:24.682335",
nextReviewDate: String = "2023-11-18",
) {
stubFor(
get(urlPathMatching("/iep/reviews/booking/\\d+"))
.willReturn(
aResponse()
.withHeader("Content-Type", "application/json")
.withStatus(201)
.withBody(
"""
{
"id": 5850394,
"iepCode": "$iepCode",
"iepLevel": "$iepLevel",
"prisonerNumber": "A9412DY",
"bookingId": 1203242,
"iepDate": "2022-11-10",
"iepTime": "$iepTime",
"locationId": "RECP",
"iepDetails": [],
"nextReviewDate": "$nextReviewDate",
"daysSinceReview": 12
}
""".trimIndent(),
),
),
)
}
fun verifyGetCurrentIncentiveRequest(bookingId: Long) {
verify(
getRequestedFor(urlEqualTo("/iep/reviews/booking/$bookingId?with-details=false")),
)
}
}
class IncentivesApiExtension : BeforeAllCallback, AfterAllCallback, BeforeEachCallback {
companion object {
@JvmField
val incentivesApi = IncentivesMockServer()
}
override fun beforeAll(context: ExtensionContext): Unit = incentivesApi.start()
override fun beforeEach(context: ExtensionContext): Unit = incentivesApi.resetAll()
override fun afterAll(context: ExtensionContext): Unit = incentivesApi.stop()
}
| 1 | null | 1 | 2 | 2ac87f7349d61e3d274bcb20b11be285c5a50700 | 2,621 | hmpps-prisoner-search | MIT License |
app/src/main/java/com/mateuszcholyn/wallet/frontend/view/screen/categoryScreen/CategoryFormStateless.kt | mateusz-nalepa | 467,673,984 | false | {"Kotlin": 606018} | package com.mateuszcholyn.wallet.frontend.view.screen.categoryScreen
import android.annotation.SuppressLint
import androidx.annotation.StringRes
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.Button
import androidx.compose.material.CircularProgressIndicator
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.res.stringResource
import com.mateuszcholyn.wallet.R
import com.mateuszcholyn.wallet.frontend.view.composables.ValidatedTextFieldV2
import com.mateuszcholyn.wallet.frontend.view.screen.util.actionButton.ErrorModalState
import com.mateuszcholyn.wallet.frontend.view.screen.util.actionButton.MyErrorDialogProxy
import com.mateuszcholyn.wallet.frontend.view.util.EMPTY_STRING
import com.mateuszcholyn.wallet.frontend.view.util.defaultButtonModifier
import com.mateuszcholyn.wallet.frontend.view.util.defaultModifier
enum class CategorySubmitButton {
DISABLED,
ENABLED,
LOADING,
}
enum class CategoryScreenMode {
CATEGORY,
SUB_CATEGORY,
}
data class CategoryFormUiState(
// val categoryScreenMode: CategoryScreenMode = CategoryScreenMode.SUB_CATEGORY,
val categoryScreenMode: CategoryScreenMode = CategoryScreenMode.CATEGORY,
val categoryName: String = EMPTY_STRING,
val subCategoryName: String = EMPTY_STRING,
val isFormInvalid: Boolean = false,
val submitButtonState: CategorySubmitButton = CategorySubmitButton.DISABLED,
val showCategoryAlreadyExistsWarning: Boolean = false,
val errorModalState: ErrorModalState = ErrorModalState.NotVisible,
@StringRes
val buttonLabelKey: Int = R.string.button_addCategory,
)
data class CategoryFormUiActions(
val onCategoryValueChanged: (String) -> Unit,
val onErrorModalClose: () -> Unit,
val onFormSubmit: () -> Unit,
)
@SuppressLint("UnrememberedMutableState")
@Composable
fun CategoryFormStateless(
categoryFormUiState: CategoryFormUiState,
categoryFormUiActions: CategoryFormUiActions,
) {
val state = rememberScrollState()
Column(modifier = defaultModifier.verticalScroll(state)) {
when (categoryFormUiState.categoryScreenMode) {
CategoryScreenMode.CATEGORY -> {
ValidatedTextFieldV2(
textFieldLabel = stringResource(R.string.common_category),
value = categoryFormUiState.categoryName,
onValueChange = {
categoryFormUiActions.onCategoryValueChanged.invoke(it)
},
isValueInvalid = categoryFormUiState.isFormInvalid,
valueInvalidText = stringResource(R.string.validation_incorrectCategoryName),
modifier = defaultModifier,
)
}
CategoryScreenMode.SUB_CATEGORY -> {
ValidatedTextFieldV2(
enabled = false,
textFieldLabel = stringResource(R.string.main_category),
value = categoryFormUiState.categoryName,
onValueChange = {
categoryFormUiActions.onCategoryValueChanged.invoke(it)
},
isValueInvalid = categoryFormUiState.isFormInvalid,
valueInvalidText = stringResource(R.string.validation_incorrectCategoryName),
modifier = defaultModifier,
)
ValidatedTextFieldV2(
textFieldLabel = stringResource(R.string.sub_category),
value = categoryFormUiState.categoryName,
onValueChange = {},
isValueInvalid = categoryFormUiState.isFormInvalid,
valueInvalidText = stringResource(R.string.validation_incorrectCategoryName),
modifier = defaultModifier,
)
}
}
// chyba bym to wywalił całkowicie XD
// if (categoryFormUiState.showCategoryAlreadyExistsWarning) {
// Text(
// text = stringResource(R.string.validation_warning_category_already_exists),
// color = MaterialTheme.colors.primary,
// modifier = defaultModifier,
// )
// }
MyErrorDialogProxy(
errorModalState = categoryFormUiState.errorModalState,
onErrorModalClose = categoryFormUiActions.onErrorModalClose
)
Button(
enabled = categoryFormUiState.submitButtonState == CategorySubmitButton.ENABLED,
onClick = {
categoryFormUiActions.onFormSubmit.invoke()
},
modifier = defaultButtonModifier,
) {
if (categoryFormUiState.submitButtonState == CategorySubmitButton.LOADING) {
CircularProgressIndicator(color = MaterialTheme.colors.onPrimary)
} else {
Text(stringResource(categoryFormUiState.buttonLabelKey))
}
}
}
}
| 0 | Kotlin | 0 | 0 | 3213bca91abc9aae68f43b5b2b627561ee1437b9 | 5,162 | wallet | Apache License 2.0 |
app/src/main/java/com/jacktor/batterylab/interfaces/views/MenuInterface.kt | jacktor-stan | 773,048,759 | false | {"Kotlin": 705997, "Java": 4558, "C++": 3298, "C": 458, "CMake": 284} | package com.jacktor.batterylab.interfaces.views
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Build
import android.view.LayoutInflater
import android.widget.Toast
import androidx.appcompat.content.res.AppCompatResources
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.jacktor.batterylab.MainActivity
import com.jacktor.batterylab.PremiumActivity
import com.jacktor.batterylab.R
import com.jacktor.batterylab.databinding.ShowScriptDialogBinding
import com.jacktor.batterylab.fragments.ChargeDischargeFragment
import com.jacktor.batterylab.fragments.HistoryFragment
import com.jacktor.batterylab.fragments.KernelFragment
import com.jacktor.batterylab.helpers.HistoryHelper
import com.jacktor.batterylab.interfaces.KernelInterface.Companion.executeShellFile
import com.jacktor.batterylab.interfaces.KernelInterface.Companion.getKernelFromFile
import com.jacktor.batterylab.interfaces.KernelInterface.Companion.resetScript
import com.jacktor.batterylab.interfaces.PremiumInterface
import com.jacktor.batterylab.utilities.Constants.SCRIPT_FILE_NAME
import com.jacktor.batterylab.utilities.PreferencesKeys.EXECUTE_SCRIPT_ON_BOOT
import com.jacktor.batterylab.utilities.Prefs
import com.jacktor.rootchecker.RootChecker
interface MenuInterface {
fun MainActivity.inflateMenu() {
when (fragment) {
is HistoryFragment -> {
topAppBar.inflateMenu(R.menu.history_menu)
topAppBar.menu.findItem(R.id.clear_history).apply {
isVisible = PremiumInterface.isPremium && HistoryHelper.isHistoryNotEmpty(
this@inflateMenu
)
setOnMenuItemClickListener {
HistoryHelper.clearHistory(this@inflateMenu, this)
true
}
}
topAppBar.menu.findItem(R.id.history_premium).apply {
isVisible = !PremiumInterface.isPremium
setOnMenuItemClickListener {
val intent = Intent(applicationContext, PremiumActivity::class.java)
startActivity(intent)
true
}
}
}
is KernelFragment -> {
topAppBar.inflateMenu(R.menu.kernel_menu)
topAppBar.menu.findItem(R.id.show_command).apply {
setOnMenuItemClickListener {
val binding = ShowScriptDialogBinding.inflate(
LayoutInflater.from(this@inflateMenu), null, false
)
val dialog = MaterialAlertDialogBuilder(this@inflateMenu)
val clipboard =
[email protected](Context.CLIPBOARD_SERVICE) as ClipboardManager?
binding.script.setText(getKernelFromFile(this@inflateMenu))
binding.resetScript.text =
[email protected](R.string.reset_script).uppercase()
//Dialog
dialog.setView(binding.root.rootView)
dialog.apply {
setIcon(
AppCompatResources.getDrawable(
this@inflateMenu, R.drawable.ic_script_24dp
)
)
setTitle(getString(R.string.bash_script).uppercase())
setCancelable(false)
setNegativeButton(getString(R.string.copy_txt).uppercase()) { dialogBtn, _ ->
clipboard!!.setPrimaryClip(
ClipData.newPlainText(
SCRIPT_FILE_NAME, binding.script.text
)
)
dialogBtn.cancel()
}
setPositiveButton(getString(R.string.close).uppercase()) { dialogBtn, _ ->
dialogBtn.cancel()
}
setNeutralButton(getString(R.string.execute).uppercase()) { dialogBtn, _ ->
if (RootChecker(this@inflateMenu).isRooted) executeShellFile(this@inflateMenu)
dialogBtn.cancel()
}
show()
}
//Check root
if (!RootChecker(this@inflateMenu).isRooted) {
binding.resetScript.isEnabled = false
binding.enableScript.isEnabled = false
}
//Reset script button
binding.resetScript.setOnClickListener {
MaterialAlertDialogBuilder(this@inflateMenu).apply {
setIcon(
AppCompatResources.getDrawable(
this@inflateMenu, R.drawable.ic_reset_all_settings_24dp
)
)
setTitle(getString(R.string.reset_script))
setMessage(getString(R.string.reset_script_dialog))
setPositiveButton(R.string.cancel) { d, _ -> d.dismiss() }
setNegativeButton(R.string.yes_continue) { dialogBtn, _ ->
resetScript(this@inflateMenu)
binding.script.setText(getKernelFromFile(this@inflateMenu))
KernelFragment.instance?.kernelInformation()
dialogBtn.cancel()
}
show()
}
}
//Switch autostart script
binding.enableScript.isChecked = Prefs(this@inflateMenu).getBoolean(
EXECUTE_SCRIPT_ON_BOOT, resources.getBoolean(
R.bool
.execute_script_on_boot
)
)
binding.enableScript.setOnCheckedChangeListener { _, isChecked ->
Prefs(this@inflateMenu).setBoolean(EXECUTE_SCRIPT_ON_BOOT, isChecked)
if (isChecked) {
Toast.makeText(
this@inflateMenu,
getString(R.string.enable_execute_script_on_boot),
Toast.LENGTH_SHORT
).show()
} else {
Toast.makeText(
this@inflateMenu,
getString(R.string.disable_execute_script_on_boot),
Toast.LENGTH_SHORT
).show()
}
}
true
}
}
}
else -> {
topAppBar.inflateMenu(R.menu.main_menu)
topAppBar.menu.findItem(R.id.instruction).isVisible = getCurrentCapacity(
this
) > 0.0 && (fragment is ChargeDischargeFragment || fragment is KernelFragment)
topAppBar.menu.findItem(R.id.instruction).setOnMenuItemClickListener {
showInstruction()
true
}
topAppBar.menu.findItem(R.id.faq).setOnMenuItemClickListener {
showFaq()
true
}
topAppBar.menu.findItem(R.id.tips).setOnMenuItemClickListener {
MaterialAlertDialogBuilder(this).apply {
setIcon(R.drawable.ic_tips_for_extending_battery_life_24dp)
setTitle(getString(R.string.tips_dialog_title))
setMessage(
getString(R.string.tip1) + getString(R.string.tip2) + getString(R.string.tip3) + getString(
R.string.tip4
)
)
setPositiveButton(android.R.string.ok) { d, _ -> d.dismiss() }
show()
}
true
}
topAppBar.menu.findItem(R.id.premium)
topAppBar.menu.findItem(R.id.premium).setOnMenuItemClickListener {
val intent = Intent(applicationContext, PremiumActivity::class.java)
startActivity(intent)
true
}
}
}
}
fun MainActivity.clearMenu() = topAppBar.menu.clear()
fun MainActivity.showInstruction() {
MaterialAlertDialogBuilder(this).apply {
setIcon(R.drawable.ic_instruction_not_supported_24dp)
setTitle(getString(R.string.instruction))
setMessage(
getString(R.string.instruction_message) +
getString(R.string.instruction_message_enable_fast_charge_option) +
getString(R.string.instruction_message_do_not_kill_the_service) +
getString(
R.string.instruction_message_dont_kill_my_app
)
)
setPositiveButton(android.R.string.ok) { d, _ -> d.dismiss() }
setCancelable(false)
show()
}
}
fun MainActivity.showFaq() {
if (showFaqDialog == null) {
showFaqDialog = MaterialAlertDialogBuilder(this).apply {
setIcon(R.drawable.ic_faq_question_24dp)
setTitle(getString(R.string.faq))
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) setMessage(
getString(R.string.faq_how_does_the_app_work) + getString(R.string.faq_capacity_added) + getString(
R.string.faq_where_does_the_app_get_the_ccl
) + getString(R.string.faq_why_is_ccl_not_displayed) + getString(R.string.faq_i_have_everything_in_zeros) + getString(
R.string.faq_units
) + getString(R.string.faq_current_capacity) + getString(R.string.faq_residual_capacity_is_higher) + getString(
R.string.faq_battery_wear_changes_when_charger_is_disconnected
) + getString(R.string.faq_battery_wear_not_change) + getString(R.string.faq_with_each_charge_battery_wear_changes)
)
else setMessage(
getString(R.string.faq_how_does_the_app_work) + getString(R.string.faq_capacity_added) + getString(
R.string.faq_where_does_the_app_get_the_ccl
) + getString(R.string.faq_why_is_ccl_not_displayed) + getString(R.string.faq_i_have_everything_in_zeros) + getString(
R.string.faq_units
) + getString(R.string.faq_current_capacity) + getString(R.string.faq_residual_capacity_is_higher) + getString(
R.string.faq_battery_wear_changes_when_charger_is_disconnected
) + getString(R.string.faq_battery_wear_not_change) + getString(R.string.faq_with_each_charge_battery_wear_changes) + getString(
R.string.faq_where_does_the_app_get_the_number_of_cycles_android
) + getString(R.string.faq_not_displayed_number_of_cycles_android)
)
setPositiveButton(android.R.string.ok) { _, _ ->
showFaqDialog = null
}
setCancelable(false)
show()
}
}
}
} | 0 | Kotlin | 1 | 3 | 6409caae85d430339d94b8802c3a8ecfb7ab746f | 12,383 | battery-lab | Apache License 2.0 |
app/src/main/java/eu/kanade/tachiyomi/data/track/kitsu/KitsuInterceptor.kt | mihonapp | 743,704,912 | false | null | package eu.kanade.tachiyomi.data.track.kitsu
import eu.kanade.tachiyomi.BuildConfig
import kotlinx.serialization.json.Json
import okhttp3.Interceptor
import okhttp3.Response
import uy.kohesive.injekt.injectLazy
class KitsuInterceptor(private val kitsu: Kitsu) : Interceptor {
private val json: Json by injectLazy()
/**
* OAuth object used for authenticated requests.
*/
private var oauth: OAuth? = kitsu.restoreToken()
override fun intercept(chain: Interceptor.Chain): Response {
val originalRequest = chain.request()
val currAuth = oauth ?: throw Exception("Not authenticated with Kitsu")
val refreshToken = currAuth.refresh_token!!
// Refresh access token if expired.
if (currAuth.isExpired()) {
val response = chain.proceed(KitsuApi.refreshTokenRequest(refreshToken))
if (response.isSuccessful) {
newAuth(json.decodeFromString(response.body.string()))
} else {
response.close()
}
}
// Add the authorization header to the original request.
val authRequest = originalRequest.newBuilder()
.addHeader("Authorization", "Bearer ${oauth!!.access_token}")
.header("User-Agent", "Mewtachi v${BuildConfig.VERSION_NAME} (${BuildConfig.APPLICATION_ID})")
.header("Accept", "application/vnd.api+json")
.header("Content-Type", "application/vnd.api+json")
.build()
return chain.proceed(authRequest)
}
fun newAuth(oauth: OAuth?) {
this.oauth = oauth
kitsu.saveToken(oauth)
}
}
| 262 | null | 4 | 8,984 | 8f9a325895bb7b94c2ec92dd969094fc30b3b5e2 | 1,641 | mihon | Apache License 2.0 |
sample/src/main/java/net/mm2d/webclip/SettingsFragment.kt | TrendingTechnology | 201,249,129 | true | {"Kotlin": 104865} | /*
* Copyright (c) 2019 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.webclip
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import androidx.preference.PreferenceFragmentCompat
import net.mm2d.webclip.settings.Key
/**
* @author [大前良介 (<NAME>)](mailto:<EMAIL>)
*/
class SettingsFragment : PreferenceFragmentCompat() {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
addPreferencesFromResource(R.xml.preference)
findPreference(Key.VERSION_NUMBER.name).summary = BuildConfig.VERSION_NAME
findPreference(Key.SOURCE_CODE.name).setOnPreferenceClickListener {
startActivity(Intent(activity, MainActivity::class.java).also {
it.action = Intent.ACTION_VIEW
it.addCategory(Intent.CATEGORY_BROWSABLE)
it.data = Uri.parse("https://github.com/ohmae/touch-icon-extractor")
})
true
}
findPreference(Key.LICENSE.name).setOnPreferenceClickListener {
startActivity(Intent(activity, MainActivity::class.java).also {
it.action = Intent.ACTION_VIEW
it.addCategory(Intent.CATEGORY_BROWSABLE)
it.data = Uri.parse("file:///android_asset/license.html")
})
true
}
}
}
| 0 | Kotlin | 0 | 0 | 31173de4d1a35e3e7cc58eabab5a3d2e78169d5d | 1,426 | touch-icon-extractor | MIT License |
app/src/test/java/FileReader.kt | Rahula-12 | 853,794,873 | false | {"Kotlin": 97510} | package com.learning.mygenai
import androidx.appcompat.widget.ThemedSpinnerAdapter.Helper
import java.io.InputStreamReader
object FileReader {
fun readFile(file:String):String {
val inputStream=Helper::class.java.getResourceAsStream(file)
val builder=StringBuilder()
val inputStreamReader=InputStreamReader(inputStream,"UTF-8")
inputStreamReader.readLines().forEach{
builder.append(it+"\n")
}
return builder.toString()
}
} | 0 | Kotlin | 0 | 0 | c3f35c2a29c951d36e0b797a8fb6be3df47b67e4 | 494 | GenzAI | MIT License |
agiletoast/src/main/java/work/wanghao/agiletoast/widget/ToastStyle.kt | Doublemine | 81,313,767 | false | null | package work.wanghao.agiletoast.widget
/**
* @author doublemine
* Created on 2017/02/09 22:27.
* Summary:
*/
enum class ToastStyle {
NORMAL
,
CORNER
,
FILL
} | 1 | null | 1 | 3 | e3b7f50c83ce5c6b00add696657d372cf44e62dd | 189 | AgileToast | Apache License 2.0 |
rewrite-test/src/main/kotlin/org/openrewrite/java/NoWhitespaceAfterTest.kt | openrewrite | 263,442,622 | false | null | /*
* Copyright 2021 the original author or authors.
* <p>
* 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
* <p>
* https://www.apache.org/licenses/LICENSE-2.0
* <p>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openrewrite.java
import org.assertj.core.api.Assertions.assertThat
import org.junit.jupiter.api.Test
import org.openrewrite.ExecutionContext
import org.openrewrite.InMemoryExecutionContext
import org.openrewrite.Recipe
import org.openrewrite.Tree
import org.openrewrite.java.cleanup.NoWhitespaceAfter
import org.openrewrite.java.style.NoWhitespaceAfterStyle
import org.openrewrite.java.format.AutoFormatVisitor
import org.openrewrite.java.style.Checkstyle
import org.openrewrite.style.NamedStyles
@Suppress(
"CStyleArrayDeclaration",
"StringConcatenationMissingWhitespace",
"ConstantConditions",
"UnusedAssignment",
"UnaryPlus",
"ReturnOfThis",
"SimplifiableAnnotation"
)
interface NoWhitespaceAfterTest : JavaRecipeTest {
override val recipe: Recipe?
get() = NoWhitespaceAfter()
fun noWhitespaceAfterStyle(with: NoWhitespaceAfterStyle.() -> NoWhitespaceAfterStyle = { this }) =
listOf(
NamedStyles(
Tree.randomId(), "test", "test", "test", emptySet(), listOf(
Checkstyle.noWhitespaceAfterStyle().run { with(this) }
)
)
)
@Test
fun arrayAccess(jp: JavaParser.Builder<*, *>) = assertChanged(
parser = jp.styles(noWhitespaceAfterStyle()).build(),
before = """
class Test {
static void method(int[] n) {
int m = n [0];
}
}
""",
after = """
class Test {
static void method(int[] n) {
int m = n[0];
}
}
""",
afterConditions = { cu ->
val nucu = AutoFormatVisitor<ExecutionContext>().visit(cu, InMemoryExecutionContext {})
assertThat(nucu).isEqualTo(cu)
}
)
@Test
fun variableDeclaration(jp: JavaParser.Builder<*, *>) = assertChanged(
parser = jp.styles(noWhitespaceAfterStyle()).build(),
before = """
class Test {
static void method() {
int [] [] a;
int [] b;
int c, d = 0;
}
}
""",
after = """
class Test {
static void method() {
int[][] a;
int[] b;
int c, d = 0;
}
}
""",
afterConditions = { cu ->
val nucu = AutoFormatVisitor<ExecutionContext>().visit(cu, InMemoryExecutionContext {})
assertThat(nucu).isEqualTo(cu)
}
)
@Test
fun arrayVariableDeclaration(jp: JavaParser.Builder<*, *>) = assertChanged(
parser = jp.styles(noWhitespaceAfterStyle()).build(),
before = """
class Test {
static void method() {
int[] n = { 1, 2};
int[] p = {1, 2 };
}
}
""",
after = """
class Test {
static void method() {
int[] n = {1, 2};
int[] p = {1, 2};
}
}
""",
afterConditions = { cu ->
val nucu = AutoFormatVisitor<ExecutionContext>().visit(cu, InMemoryExecutionContext {})
assertThat(nucu).isEqualTo(cu)
}
)
@Test
fun assignment(jp: JavaParser.Builder<*, *>) = assertChanged(
parser = jp.styles(noWhitespaceAfterStyle()).build(),
before = """
class Test {
static void method(int m) {
long o = - m;
}
}
""",
after = """
class Test {
static void method(int m) {
long o = -m;
}
}
""",
afterConditions = { cu ->
val nucu = AutoFormatVisitor<ExecutionContext>().visit(cu, InMemoryExecutionContext {})
assertThat(nucu).isEqualTo(cu)
}
)
@Test
fun unaryOperation(jp: JavaParser.Builder<*, *>) = assertChanged(
parser = jp.styles(noWhitespaceAfterStyle()).build(),
before = """
class Test {
static void method(int m) {
++ m;
-- m;
int o = + m;
o = ~ m;
boolean b = false;
b = ! b;
}
}
""",
after = """
class Test {
static void method(int m) {
++m;
--m;
int o = +m;
o = ~m;
boolean b = false;
b = !b;
}
}
""",
afterConditions = { cu ->
val nucu = AutoFormatVisitor<ExecutionContext>().visit(cu, InMemoryExecutionContext {})
assertThat(nucu).isEqualTo(cu)
}
)
@Test
fun typecastOperation(jp: JavaParser.Builder<*, *>) = assertChanged(
parser = jp.styles(noWhitespaceAfterStyle {
withTypecast(true)
}).build(),
before = """
class Test {
static void method(int m) {
long o = - m;
m = (int) o;
}
}
""",
after = """
class Test {
static void method(int m) {
long o = -m;
m = (int)o;
}
}
""",
afterConditions = { cu ->
val nucu = AutoFormatVisitor<ExecutionContext>().visit(cu, InMemoryExecutionContext {})
assertThat(nucu).isEqualTo(cu)
}
)
@Test
fun methodReference(jp: JavaParser.Builder<*, *>) = assertChanged(
parser = jp.styles(noWhitespaceAfterStyle {
withMethodRef(true)
}).build(),
before = """
import java.util.stream.Stream;
class Test {
static void method(Stream<Object> stream) {
stream.forEach(System.out:: println);
}
}
""",
after = """
import java.util.stream.Stream;
class Test {
static void method(Stream<Object> stream) {
stream.forEach(System.out::println);
}
}
""",
afterConditions = { cu ->
val nucu = AutoFormatVisitor<ExecutionContext>().visit(cu, InMemoryExecutionContext {})
assertThat(nucu).isEqualTo(cu)
}
)
@Test
fun methodReturnTypeSignatureAsArray(jp: JavaParser.Builder<*, *>) = assertChanged(
parser = jp.styles(noWhitespaceAfterStyle()).build(),
before = """
class Test {
static int [] [] methodArr() {
return null;
}
}
""",
after = """
class Test {
static int[][] methodArr() {
return null;
}
}
""",
afterConditions = { cu ->
val nucu = AutoFormatVisitor<ExecutionContext>().visit(cu, InMemoryExecutionContext {})
assertThat(nucu).isEqualTo(cu)
}
)
@Test
fun fieldAccess(jp: JavaParser.Builder<*, *>) = assertChanged(
parser = jp.styles(noWhitespaceAfterStyle {
withDot(true)
}).build(),
before = """
class Test {
int m = 0;
void method0() {
int n = this. m;
}
static void method1() {
new Test()
.m = 2;
}
}
""",
after = """
class Test {
int m = 0;
void method0() {
int n = this.m;
}
static void method1() {
new Test()
.m = 2;
}
}
""",
afterConditions = { cu ->
val nucu = AutoFormatVisitor<ExecutionContext>().visit(cu, InMemoryExecutionContext {})
assertThat(nucu).isEqualTo(cu)
}
)
@Test
fun annotation(jp: JavaParser.Builder<*, *>) = assertChanged(
parser = jp.styles(noWhitespaceAfterStyle()).build(),
before = """
class Test {
@ Override
public boolean equals(Object o) {
return false;
}
}
""",
after = """
class Test {
@Override
public boolean equals(Object o) {
return false;
}
}
""",
afterConditions = { cu ->
val nucu = AutoFormatVisitor<ExecutionContext>().visit(cu, InMemoryExecutionContext {})
assertThat(nucu).isEqualTo(cu)
}
)
@Test
fun doNotAllowLinebreak(jp: JavaParser.Builder<*, *>) = assertChanged(
parser = jp.styles(noWhitespaceAfterStyle {
withAllowLineBreaks(false)
.withDot(true)
}).build(),
before = """
class Test {
int m;
static void fieldAccess() {
new Test().
m = 2;
}
void methodInvocationChain() {
test().
test();
}
Test test() {
return this;
}
}
""",
after = """
class Test {
int m;
static void fieldAccess() {
new Test().m = 2;
}
void methodInvocationChain() {
test().test();
}
Test test() {
return this;
}
}
""",
afterConditions = { cu ->
val nucu = AutoFormatVisitor<ExecutionContext>().visit(cu, InMemoryExecutionContext {})
assertThat(nucu).isEqualTo(cu)
}
)
@Test
fun doNotChangeAnnotationValueInNewArray(jp: JavaParser.Builder<*, *>) = assertUnchanged(
parser = jp.styles(noWhitespaceAfterStyle()).build(),
before = """
@SuppressWarnings(value = {
"all",
"unchecked"
})
class Test {
}
"""
)
@Test
fun doNotChangeFirstAndLastValuesOfArrayInitializer(jp: JavaParser.Builder<*, *>) = assertUnchanged(
parser = jp.styles(noWhitespaceAfterStyle()).build(),
before = """
class Test {
int[] ns = {
0,
1
};
}
"""
)
}
| 47 | null | 51 | 431 | 5515571843fc3ce486fbf9a83258779d90517a0a | 11,705 | rewrite | Apache License 2.0 |
core/src/main/java/io/blockv/core/client/Blockv.kt | VatomInc | 401,319,567 | true | {"Kotlin": 317235, "Java": 3833} | /*
* BlockV AG. Copyright (c) 2018, all rights reserved.
*
* Licensed under the BlockV SDK License (the "License"); you may not use this file or the BlockV SDK except in
* compliance with the License accompanying it. Unless required by applicable law or agreed to in writing, the BlockV
* SDK distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
* ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations
* under the License.
*
*/
package io.blockv.core.client
import android.content.Context
import io.blockv.common.internal.json.JsonModule
import io.blockv.common.internal.net.NetModule
import io.blockv.common.internal.net.rest.auth.Authenticator
import io.blockv.common.internal.net.rest.auth.AuthenticatorImpl
import io.blockv.common.internal.net.rest.auth.JwtDecoderImpl
import io.blockv.common.internal.net.rest.auth.ResourceEncoderImpl
import io.blockv.common.internal.net.websocket.WebsocketImpl
import io.blockv.common.internal.repository.Preferences
import io.blockv.common.model.*
import io.blockv.core.client.manager.*
import io.blockv.face.client.FaceManager
import io.blockv.face.client.FaceManagerImpl
import io.blockv.faces.*
import io.reactivex.Flowable
import io.reactivex.Single
import io.reactivex.plugins.RxJavaPlugins
import org.json.JSONObject
import java.io.File
import kotlin.reflect.KClass
class Blockv {
private val preferences: Preferences
private val jsonModule: JsonModule
private val auth: Authenticator
val appId: String
val netModule: NetModule
val userManager: UserManager
val vatomManager: VatomManager
val resourceManager: ResourceManager
val activityManager: ActivityManager
init {
RxJavaPlugins.setErrorHandler { throwable ->
throwable.printStackTrace()
}
}
private val cacheDir: File
@Volatile
private var internalEventManager: EventManager? = null
val eventManager: EventManager
get() {
if (internalEventManager == null) {
try {
internalEventManager = EventManagerImpl(WebsocketImpl(preferences, jsonModule, auth), jsonModule)
} catch (e: NoClassDefFoundError) {
throw MissingWebSocketDependencyException()
} catch (e: Exception) {
throw MissingWebSocketDependencyException()
}
}
return internalEventManager!!
}
@Volatile
private var internalFaceManager: FaceManager? = null
val faceManager: FaceManager
get() {
if (internalFaceManager == null) {
try {
val encoder = ResourceEncoderImpl(preferences)
internalFaceManager = FaceManagerImpl(io.blockv.face.client.ResourceManagerImpl(cacheDir, encoder),
object : io.blockv.face.client.manager.UserManager {
override fun getCurrentUser(): Single<PublicUser> {
return userManager.getCurrentUser()
.map {
PublicUser(
it.id,
if (it.isNamePublic) it.firstName else "",
if (it.isNamePublic) it.lastName else "",
if (it.isAvatarPublic) it.avatarUri else ""
)
}
}
override fun getPublicUser(userId: String): Single<PublicUser> {
return userManager.getPublicUser(userId)
}
},
object : io.blockv.face.client.manager.VatomManager {
override fun preformAction(action: String, payload: JSONObject): Single<JSONObject> {
return vatomManager.preformAction(action, payload)
}
override fun getVatoms(vararg ids: String): Single<List<Vatom>> {
return vatomManager.getVatoms(*ids)
}
override fun getInventory(id: String?, page: Int, limit: Int): Single<List<Vatom>> {
return vatomManager.getInventory(id, page, limit)
}
},
object : io.blockv.face.client.manager.EventManager {
override fun getVatomStateEvents(): Flowable<WebSocketEvent<StateUpdateEvent>> {
return eventManager.getVatomStateEvents()
}
override fun getInventoryEvents(): Flowable<WebSocketEvent<InventoryEvent>> {
return eventManager.getInventoryEvents()
}
},
object : io.blockv.face.client.manager.JsonSerializer {
override fun <T : Model> deserialize(kclass: KClass<T>, json: JSONObject): T? {
return jsonModule.deserialize(kclass, json)
}
override fun <T : Model> serialize(data: T): JSONObject? {
return jsonModule.serialize(data)
}
}
)
internalFaceManager!!.registerFace(ImageFace.factory)
internalFaceManager!!.registerFace(ImageProgressFace.factory)
internalFaceManager!!.registerFace(ImagePolicyFace.factory)
internalFaceManager!!.registerFace(ImageLayeredFace.factory)
internalFaceManager!!.registerFace(WebFace.factory)
} catch (e: NoClassDefFoundError) {
throw MissingFaceModuleException()
} catch (e: Exception) {
throw MissingFaceModuleException()
}
}
return internalFaceManager!!
}
constructor(context: Context, appId: String) {
this.cacheDir = context.cacheDir
this.jsonModule = JsonModule()
this.appId = appId
this.preferences = Preferences(context, jsonModule)
this.preferences.environment = Environment(
Environment.DEFAULT_SERVER,
Environment.DEFAULT_WEBSOCKET,
appId
)
this.resourceManager = ResourceManagerImpl(ResourceEncoderImpl(preferences), preferences)
this.auth = AuthenticatorImpl(this.preferences, jsonModule)
this.netModule = NetModule(
auth,
preferences,
jsonModule
)
this.userManager = UserManagerImpl(
netModule.userApi,
auth,
preferences,
JwtDecoderImpl()
)
this.vatomManager = VatomManagerImpl(netModule.vatomApi)
this.activityManager = ActivityManagerImpl(netModule.activityApi)
}
constructor(context: Context, environment: Environment) {
this.cacheDir = context.cacheDir
this.jsonModule = JsonModule()
this.appId = environment.appId
this.preferences = Preferences(context, jsonModule)
this.preferences.environment = environment
this.resourceManager = ResourceManagerImpl(ResourceEncoderImpl(preferences), preferences)
this.auth = AuthenticatorImpl(this.preferences, jsonModule)
this.netModule = NetModule(auth, preferences, jsonModule)
this.userManager = UserManagerImpl(
netModule.userApi,
auth,
preferences,
JwtDecoderImpl()
)
this.vatomManager = VatomManagerImpl(netModule.vatomApi)
this.activityManager = ActivityManagerImpl(netModule.activityApi)
}
constructor(
context: Context,
appId: String,
preferences: Preferences,
jsonModule: JsonModule,
netModule: NetModule,
userManager: UserManager,
vatomManager: VatomManager,
activityManager: ActivityManager,
eventManager: EventManager,
resourceManager: ResourceManager
) {
this.cacheDir = context.cacheDir
this.appId = appId
this.preferences = preferences
this.preferences.environment = Environment(
Environment.DEFAULT_SERVER,
Environment.DEFAULT_WEBSOCKET,
appId
)
this.jsonModule = jsonModule
this.netModule = netModule
this.userManager = userManager
this.vatomManager = vatomManager
this.resourceManager = resourceManager
this.internalEventManager = eventManager
this.activityManager = activityManager
this.auth = AuthenticatorImpl(this.preferences, jsonModule)
}
class MissingWebSocketDependencyException :
Exception("Include dependency 'com.neovisionaries:nv-websocket-client:2.5' to use the event manager.")
class MissingFaceModuleException :
Exception("Include dependency 'io.blockv.sdk:face:+' to use the face manager.")
} | 0 | null | 0 | 1 | e306fc8255172df99eb0f63ba639c58960c29951 | 8,179 | android-sdk | RSA Message-Digest License |
app/src/main/java/ch/filmreel/model/MovieWithQuestionAndAnswers.kt | GenZHAW | 539,026,296 | false | null | version https://git-lfs.github.com/spec/v1
oid sha256:75fcb71cc9b265c01d6bc491289adfefcf789030f8d189be1132ccba898a0c10
size 679
| 10 | Kotlin | 0 | 0 | c90f8a39bf5fd78130efb42b182bc1d4010c0479 | 128 | FILMREEL | Apache License 2.0 |
app/src/main/java/com/henrikherzig/playintegritychecker/attestation/Requests.kt | herzhenr | 588,969,794 | false | {"Kotlin": 118298, "Java": 4275} | package com.henrikherzig.playintegritychecker.attestation
import android.content.ContentValues
import android.util.Log
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody
import org.json.JSONObject
/**
* sends generic api call and checks for errors in the response
*/
fun getApiCall(apiUrl: String, entrypoint: String, query: String = ""): String {
val client = OkHttpClient()
val request: Request = Request.Builder()
.get()
.url("$apiUrl$entrypoint?$query")
.build()
val response: Response = client.newCall(request).execute()
if (!response.isSuccessful) {
val `object` = JSONObject(response.body!!.string())
val messageString = `object`.getString("Error")
Log.d(ContentValues.TAG, "Error response from API Server. Message:\n'$messageString'")
throw AttestationException("Error response from API Server. Message:\n'$messageString'")
// return "Api request error. Code: " + response.code
}
val responseBody: ResponseBody? = response.body
if (responseBody == null) {
Log.d(ContentValues.TAG, "Error response from API Server (empty response) \n ${response.code}")
throw AttestationException("Error response from API Server (empty response) \n ${response.code}")
}
return responseBody.string()
} | 5 | Kotlin | 10 | 91 | 8361fc92f2f7c5afd48ff76274e5be9f3acdf2ab | 1,366 | spic-android | MIT License |
idea/testData/quickfix/addStarProjections/inner/inner7.kt | JakeWharton | 99,388,807 | true | null | // "Add star projections" "true"
class A {
class B<T> {
inner class C<U> {
inner class D
fun test(x: Any) = x is D<caret>
}
}
} | 284 | Kotlin | 5162 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 175 | kotlin | Apache License 2.0 |
core/network/src/main/java/com/mburakcakir/network/di/NetworkModule.kt | mburakcakir | 812,291,624 | false | {"Kotlin": 81965} | package com.mburakcakir.network.di
import android.content.Context
import com.chuckerteam.chucker.api.ChuckerInterceptor
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.qualifiers.ApplicationContext
import dagger.hilt.components.SingletonComponent
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import javax.inject.Singleton
@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
@Provides
@Singleton
fun provideOkHttpClient(@ApplicationContext context: Context): OkHttpClient {
return OkHttpClient.Builder().addInterceptor(ChuckerInterceptor(context)).build()
}
@Provides
@Singleton
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
return Retrofit.Builder()
.client(okHttpClient)
.baseUrl("https://api-football-standings.azharimm.dev/")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
@Provides
@Singleton
fun provideNetworkService(retrofit: Retrofit): NetworkApi {
return retrofit.create(NetworkApi::class.java)
}
} | 0 | Kotlin | 0 | 0 | 04961794a58fea1e0ee45a5ad5db9974da6da65f | 1,193 | Table | Apache License 2.0 |
clients/kotlin-server/generated/src/main/kotlin/org/openapitools/server/apis/VersionGroupApi.kt | cliffano | 464,411,689 | false | {"C++": 5121151, "Java": 4259235, "TypeScript": 3170746, "HTML": 2401291, "C#": 1569306, "Python": 1470207, "PHP": 1250759, "Scala": 1204291, "Rust": 1144006, "Kotlin": 966686, "JavaScript": 896371, "R": 547831, "Erlang": 504910, "Ada": 495819, "F#": 490032, "Shell": 436186, "Objective-C": 431570, "Go": 402480, "PowerShell": 319730, "Crystal": 313970, "C": 311724, "Swift": 273043, "Eiffel": 250745, "Lua": 225344, "Apex": 203102, "Ruby": 191517, "Clojure": 88385, "Nim": 80342, "Groovy": 75156, "Haskell": 73882, "Elm": 70984, "OCaml": 66631, "Perl": 62597, "Dart": 56824, "CMake": 21408, "Batchfile": 13610, "Makefile": 12176, "Dockerfile": 7307, "CSS": 4873, "QMake": 3807, "Elixir": 2312, "Gherkin": 951, "Emacs Lisp": 191} | /**
*
* No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)
*
* The version of the OpenAPI document: 20220523
* Contact: <EMAIL>
*
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
* https://openapi-generator.tech
* Do not edit the class manually.
*/
package org.openapitools.server.apis
import com.google.gson.Gson
import io.ktor.http.*
import io.ktor.server.application.*
import io.ktor.server.auth.*
import io.ktor.server.response.*
import org.openapitools.server.Paths
import io.ktor.server.resources.options
import io.ktor.server.resources.get
import io.ktor.server.resources.post
import io.ktor.server.resources.put
import io.ktor.server.resources.delete
import io.ktor.server.resources.head
import io.ktor.server.resources.patch
import io.ktor.server.routing.*
import org.openapitools.server.infrastructure.ApiPrincipal
fun Route.MoveBattleStyleApi() {
val gson = Gson()
val empty = mutableMapOf<String, Any?>()
get<Paths.moveBattleStyleList> {
call.respond(HttpStatusCode.NotImplemented)
}
get<Paths.moveBattleStyleRead> {
call.respond(HttpStatusCode.NotImplemented)
}
}
| 1 | C++ | 2 | 4 | d2d9531d4febf5f82411f11ea5779aafd21e1bb9 | 1,240 | pokeapi-clients | MIT License |
plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/ui/toolwindow/ToolWindowUtils.kt | JetBrains | 2,489,216 | false | null | package com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow
import com.intellij.openapi.actionSystem.ActionGroup
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.wm.ToolWindow
import com.intellij.openapi.wm.ex.ToolWindowEx
import com.intellij.ui.content.ContentFactory
import com.intellij.ui.content.ContentManager
import com.intellij.util.castSafelyTo
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.HasToolWindowActions
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.PackageSearchPanelBase
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.SimpleToolWindowWithToolWindowActionsPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.SimpleToolWindowWithTwoToolbarsPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.management.PackageManagementPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.panels.repositories.RepositoryManagementPanel
import com.jetbrains.packagesearch.intellij.plugin.ui.updateAndRepaint
import com.jetbrains.packagesearch.intellij.plugin.util.AppUI
import com.jetbrains.packagesearch.intellij.plugin.util.FeatureFlags
import com.jetbrains.packagesearch.intellij.plugin.util.addSelectionChangedListener
import com.jetbrains.packagesearch.intellij.plugin.util.lifecycleScope
import com.jetbrains.packagesearch.intellij.plugin.util.logInfo
import com.jetbrains.packagesearch.intellij.plugin.util.lookAndFeelFlow
import com.jetbrains.packagesearch.intellij.plugin.util.onEach
import com.jetbrains.packagesearch.intellij.plugin.util.packageSearchDataService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.withContext
import org.jetbrains.annotations.Nls
import javax.swing.JComponent
internal fun ToolWindow.initialize(project: Project) {
title = PackageSearchBundle.message("toolwindow.stripe.Dependencies")
contentManager.addSelectionChangedListener { event ->
if (this is ToolWindowEx) {
setAdditionalGearActions(null)
event.content.component.castSafelyTo<HasToolWindowActions>()
?.also { setAdditionalGearActions(it.gearActions) }
}
setTitleActions(emptyList())
event.content.component.castSafelyTo<HasToolWindowActions>()
?.titleActions
?.also { setTitleActions(it.toList()) }
}
contentManager.removeAllContents(true)
val panels = buildList {
this.add(PackageManagementPanel(project))
if (FeatureFlags.showRepositoriesTab) {
this.add(RepositoryManagementPanel(rootDataModelProvider = project.packageSearchDataService))
}
}
val contentFactory = ContentFactory.SERVICE.getInstance()
for (panel in panels) {
panel.initialize(contentManager, contentFactory)
}
isAvailable = false
project.packageSearchDataService.projectModulesStateFlow
.map { it.isNotEmpty() }
.onEach { logInfo("PackageSearchToolWindowFactory#packageSearchModulesChangesFlow") { "Setting toolWindow.isAvailable = $it" } }
.onEach(Dispatchers.AppUI) { isAvailable = it }
.launchIn(project.lifecycleScope)
combine(
project.lookAndFeelFlow,
project.packageSearchDataService.projectModulesStateFlow.filter { it.isNotEmpty() }
) { _, _ -> withContext(Dispatchers.AppUI) { contentManager.component.updateAndRepaint() } }
.launchIn(project.lifecycleScope)
}
internal fun PackageSearchPanelBase.initialize(
contentManager: ContentManager,
contentFactory: ContentFactory,
) {
val panelContent = content // should be executed before toolbars
val toolbar = toolbar
val topToolbar = topToolbar
val gearActions = gearActions
val titleActions = titleActions
if (topToolbar == null) {
contentManager.addTab(title, panelContent, toolbar, gearActions, titleActions, contentFactory)
} else {
val content = contentFactory.createContent(
toolbar?.let {
SimpleToolWindowWithTwoToolbarsPanel(
it,
topToolbar,
gearActions,
titleActions,
panelContent
)
},
title,
false
)
content.isCloseable = false
contentManager.addContent(content)
content.component.updateAndRepaint()
}
}
internal fun ContentManager.addTab(
@Nls title: String,
content: JComponent,
toolbar: JComponent?,
gearActions: ActionGroup?,
titleActions: Array<AnAction>?,
contentFactory: ContentFactory
) {
addContent(
contentFactory.createContent(null, title, false).apply {
component = SimpleToolWindowWithToolWindowActionsPanel(gearActions, titleActions, false).apply {
setProvideQuickActions(true)
setContent(content)
toolbar?.let { setToolbar(it) }
isCloseable = false
}
}
)
}
| 191 | null | 4372 | 13,319 | 4d19d247824d8005662f7bd0c03f88ae81d5364b | 5,374 | intellij-community | Apache License 2.0 |
app/src/main/java/tool/xfy9326/schedule/utils/DownloadUtils.kt | XFY9326 | 325,915,275 | false | null | package tool.xfy9326.schedule.utils
import android.app.DownloadManager
import android.content.Context
import android.net.Uri
import android.os.Environment
import androidx.core.content.getSystemService
import androidx.core.net.toUri
import io.github.xfy9326.atools.ui.openUrlInBrowser
import tool.xfy9326.schedule.kt.PROJECT_ID
import java.io.File
object DownloadUtils {
private const val DOWNLOAD_SUB_DIR = PROJECT_ID
fun requestDownloadFileDirectly(
context: Context,
url: String,
fileName: String,
title: String,
description: String,
mimeType: String,
): Long? {
val subPath = DOWNLOAD_SUB_DIR + File.separator + fileName
try {
return context.applicationContext.getSystemService<DownloadManager>()?.enqueue(DownloadManager.Request(Uri.parse(url)).apply {
setTitle(title)
setDescription(description)
setMimeType(mimeType)
setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
try {
setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, subPath)
} catch (e: Exception) {
e.printStackTrace()
setDestinationInExternalFilesDir(context, Environment.DIRECTORY_DOWNLOADS, subPath)
}
})
} catch (e: Exception) {
e.printStackTrace()
}
return null
}
fun requestDownloadFileByBrowser(context: Context, url: String) {
context.openUrlInBrowser(url.toUri())
}
} | 1 | null | 1 | 5 | 6e4c0d01b16a02402c7445c9fc340998cabd5e81 | 1,626 | Schedule | Apache License 2.0 |
compiler/testData/diagnostics/testsWithJsStdLib/name/classAndFunction.kt | JakeWharton | 99,388,807 | false | null | package foo
class <!JS_NAME_CLASH!>A(val x: Int)<!>
<!JS_NAME_CLASH!>fun A()<!> {} | 181 | null | 5748 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 84 | kotlin | Apache License 2.0 |
app/src/main/java/com/abdallah_abdelazim/asteroidradar/MainActivity.kt | Abdallah-Abdelazim | 591,115,654 | false | null | package com.abdallah_abdelazim.asteroidradar
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.navigation.findNavController
import androidx.navigation.fragment.NavHostFragment
import androidx.navigation.ui.AppBarConfiguration
import androidx.navigation.ui.navigateUp
import androidx.navigation.ui.setupActionBarWithNavController
import com.abdallah_abdelazim.asteroidradar.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var appBarConfiguration: AppBarConfiguration
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater, null, false)
setContentView(binding.root)
val navHostFragment = supportFragmentManager
.findFragmentById(R.id.nav_host_fragment) as NavHostFragment
val navController = navHostFragment.navController
appBarConfiguration = AppBarConfiguration(navController.graph)
setupActionBarWithNavController(navController, appBarConfiguration)
}
override fun onSupportNavigateUp(): Boolean {
val navController = findNavController(R.id.nav_host_fragment)
return navController.navigateUp(appBarConfiguration)
|| super.onSupportNavigateUp()
}
}
| 0 | Kotlin | 0 | 1 | 03475e4db5fe71e86774790e4157c3b5f5c6186b | 1,399 | nd940-asteroid-radar-app-android | MIT License |
plugin/src/main/kotlin/ru/astrainteractive/aspekt/event/tc/di/TCDependencies.kt | Astra-Interactive | 588,890,842 | false | {"Kotlin": 145506} | package ru.astrainteractive.aspekt.event.tc.di
import kotlinx.coroutines.CoroutineScope
import ru.astrainteractive.aspekt.AspeKt
import ru.astrainteractive.aspekt.di.CoreModule
import ru.astrainteractive.aspekt.plugin.PluginConfiguration
import ru.astrainteractive.astralibs.async.BukkitDispatchers
import ru.astrainteractive.astralibs.event.EventListener
import ru.astrainteractive.klibs.kdi.Provider
import ru.astrainteractive.klibs.kdi.getValue
interface TCDependencies {
val configuration: PluginConfiguration
val eventListener: EventListener
val plugin: AspeKt
val scope: CoroutineScope
val dispatchers: BukkitDispatchers
class Default(
coreModule: CoreModule
) : TCDependencies {
override val configuration: PluginConfiguration by Provider {
coreModule.pluginConfig.value
}
override val eventListener: EventListener by Provider {
coreModule.eventListener.value
}
override val plugin: AspeKt by Provider {
coreModule.plugin.value
}
override val scope: CoroutineScope by Provider {
coreModule.scope.value
}
override val dispatchers: BukkitDispatchers by Provider {
coreModule.dispatchers.value
}
}
}
| 0 | Kotlin | 0 | 0 | b249dc73f62c7d0d786a0805603550a8c2a03552 | 1,287 | AspeKt | MIT License |
spotlight/src/test/kotlin/no/nav/helse/e2e/AbstractE2ETest.kt | navikt | 767,438,587 | false | {"Kotlin": 49683, "Dockerfile": 118} | package no.nav.helse.e2e
import io.mockk.mockk
import io.mockk.verify
import no.nav.helse.Mediator
import no.nav.helse.TestRapidHelpers.hendelser
import no.nav.helse.Testdata.COMMAND_CONTEXT_ID
import no.nav.helse.Testdata.OPPRETTET
import no.nav.helse.Testmeldinger.halvTime
import no.nav.helse.Testmeldinger.helTime
import no.nav.helse.Testmeldinger.kommandokjedeAvbrutt
import no.nav.helse.Testmeldinger.kommandokjedeFerdigstilt
import no.nav.helse.Testmeldinger.kommandokjedeSuspendert
import no.nav.helse.db.DatabaseIntegrationTest
import no.nav.helse.kafka.Meldingssender
import no.nav.helse.kafka.asUUID
import no.nav.helse.rapids_rivers.testsupport.TestRapid
import no.nav.helse.slack.SlackClient
import org.junit.jupiter.api.BeforeEach
import java.time.LocalDateTime
import kotlin.test.assertEquals
internal abstract class AbstractE2ETest : DatabaseIntegrationTest() {
private val testRapid = TestRapid()
private val slackClientMock = mockk<SlackClient>(relaxed = true)
private val meldingssender = Meldingssender(testRapid)
private val mediator = Mediator(testRapid, slackClientMock, meldingssender, kommandokjedeDao)
@BeforeEach
internal fun resetTestSetup() {
testRapid.reset()
}
protected fun sendKommandokjedeSuspendert(opprettet: LocalDateTime = OPPRETTET) =
testRapid.sendTestMessage(kommandokjedeSuspendert(opprettet))
protected fun sendKommandokjedeFerdigstilt() = testRapid.sendTestMessage(kommandokjedeFerdigstilt())
protected fun sendKommandokjedeAvbrutt() = testRapid.sendTestMessage(kommandokjedeAvbrutt())
protected fun sendHalvTime() = testRapid.sendTestMessage(halvTime())
protected fun sendHelTime() = testRapid.sendTestMessage(helTime())
protected fun assertKommandokjedeLagret() = assertLagret()
protected fun assertKommandokjedeSlettet() = assertSlettet()
protected fun assertPåminnelserSendt() {
assertPåminnet(forventetAntallGangerPåminnet = 1)
assertEquals(
COMMAND_CONTEXT_ID,
testRapid.inspektør.hendelser("kommandokjede_påminnelse").first()["commandContextId"].asUUID()
)
}
protected fun assertPostetPåSlack() {
verify(exactly = 1) { mediator.fortellOmSuspenderteKommandokjeder() }
verify(exactly = 1) { slackClientMock.fortellOmSuspenderteKommandokjeder(any()) }
}
} | 0 | Kotlin | 0 | 0 | 9549a255cb15e832a13722fab0e1db2ceb698d56 | 2,369 | helse-spotlight | MIT License |
app/src/main/java/com/andria/wordcounter/di/wordcounter/WordCounterComponent.kt | AndriaNjoku | 328,239,741 | false | null | package com.andria.wordcounter.di.wordcounter
import android.app.Activity
import com.andria.wordcounter.bookSelectionScreen.BookSelectionActivity
import com.andria.wordcounter.wordCountScreen.WordCountActivity
import dagger.Subcomponent
import dagger.android.AndroidInjector
@Subcomponent(modules = [WordCounterModule::class])
interface WordCounterComponent: AndroidInjector<Activity> {
// Inject this componenet and provide dependencies to our main word count activity
// There are no use cases needed for the book selection activity as its just a UI with buttons essentially
fun inject(activity: WordCountActivity)
fun inject(activity: BookSelectionActivity)
}
| 1 | null | 1 | 1 | 931934004c9b99e9d703a141aa30ec7c2c914bcd | 706 | WordCounter | Apache License 2.0 |
app/src/main/java/com/github/satoshun/example/StackCardExampleActivity.kt | satoshun-android-example | 181,663,736 | false | null | package com.github.satoshun.example
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class StackCardExampleActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.stack_card_act)
}
}
| 0 | Kotlin | 0 | 0 | 19b36dcaf4ec956d83cb25b4ad5f59502c575ce0 | 310 | MotionLayout | Apache License 2.0 |
app/src/main/java/com/github/satoshun/example/StackCardExampleActivity.kt | satoshun-android-example | 181,663,736 | false | null | package com.github.satoshun.example
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class StackCardExampleActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.stack_card_act)
}
}
| 0 | Kotlin | 0 | 0 | 19b36dcaf4ec956d83cb25b4ad5f59502c575ce0 | 310 | MotionLayout | Apache License 2.0 |
app/src/main/java/com/lighttigerxiv/simple/mp/compose/screens/main/artist/artist_select_cover/SelectArtistCoverScreen.kt | lighttigerXIV | 547,473,082 | false | null | package com.lighttigerxiv.simple.mp.compose.screens.main.artist.artist_select_cover
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.drawable.Drawable
import android.util.Base64
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.ColorFilter
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.transition.Transition
import com.lighttigerxiv.simple.mp.compose.R
import com.lighttigerxiv.simple.mp.compose.ui.composables.CustomText
import com.lighttigerxiv.simple.mp.compose.ui.composables.CustomToolbar
import com.lighttigerxiv.simple.mp.compose.activities.main.MainVM
import com.lighttigerxiv.simple.mp.compose.data.variables.SCREEN_PADDING
import com.lighttigerxiv.simple.mp.compose.data.variables.SMALL_SPACING
import com.lighttigerxiv.simple.mp.compose.ui.composables.spacers.MediumHeightSpacer
import com.lighttigerxiv.simple.mp.compose.ui.composables.spacers.SmallHeightSpacer
import com.lighttigerxiv.simple.mp.compose.functions.getAppString
import com.lighttigerxiv.simple.mp.compose.functions.getBitmapFromVector
import com.lighttigerxiv.simple.mp.compose.screens.main.artist.ArtistScreenVM
import java.io.ByteArrayOutputStream
@Composable
fun SelectArtistCoverScreen(
mainVM: MainVM,
selectArtistCoverVM: SelectArtistCoverScreenVM,
artistVM: ArtistScreenVM,
artistName: String,
artistID: Long,
onGoBack: () -> Unit,
onGetArtistCover: () -> Unit
){
val context = LocalContext.current
val surfaceColor = mainVM.surfaceColor.collectAsState().value
val screenLoaded = selectArtistCoverVM.screenLoaded.collectAsState().value
val covers = selectArtistCoverVM.covers.collectAsState().value
selectArtistCoverVM.onGoBack = {
onGoBack()
}
if(!screenLoaded){
selectArtistCoverVM.loadScreen(artistName, artistID, artistVM)
}
Column(
modifier = Modifier
.fillMaxSize()
.background(surfaceColor)
.padding(SCREEN_PADDING)
) {
CustomToolbar(
backText = remember { getAppString(context, R.string.Artist) },
onBackClick = {onGoBack()},
)
MediumHeightSpacer()
if(screenLoaded){
Column(
modifier = Modifier
.fillMaxSize()
) {
Row(
modifier = Modifier
.fillMaxWidth()
.border(width = 1.dp, color = MaterialTheme.colorScheme.primary, shape = RoundedCornerShape(percent = 100))
.clip(RoundedCornerShape(percent = 100))
.clickable {
selectArtistCoverVM.clearArtistCover()
}
.padding(SMALL_SPACING),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
){
CustomText(
text = remember{ getAppString(context, R.string.UseDefault) },
color = MaterialTheme.colorScheme.primary
)
}
SmallHeightSpacer()
Row(
modifier = Modifier
.fillMaxWidth()
.border(width = 1.dp, color = MaterialTheme.colorScheme.primary, shape = RoundedCornerShape(percent = 100))
.clip(RoundedCornerShape(percent = 100))
.clickable {
onGetArtistCover()
}
.padding(SMALL_SPACING),
horizontalArrangement = Arrangement.Center,
verticalAlignment = Alignment.CenterVertically
){
CustomText(
text = remember{ getAppString(context, R.string.SelectLocalCover) },
color = MaterialTheme.colorScheme.primary
)
}
MediumHeightSpacer()
if(covers != null){
CustomText(
text = remember{ getAppString(context, R.string.OnlineResults) },
weight = FontWeight.Bold,
size = 20.sp
)
androidx.compose.foundation.lazy.grid.LazyVerticalGrid(
columns = GridCells.Fixed(2),
verticalArrangement = Arrangement.spacedBy(5.dp),
horizontalArrangement = Arrangement.spacedBy(5.dp),
content = {
items(
items = covers,
key = {it.id}
){ result ->
val artistPicture = remember{ mutableStateOf<Bitmap?>(null) }
Image(
modifier = Modifier
.fillMaxWidth()
.aspectRatio(1f)
.clip(RoundedCornerShape(14.dp))
.clickable {
if(artistPicture.value != null){
val baos = ByteArrayOutputStream()
artistPicture.value!!.compress(Bitmap.CompressFormat.PNG, 100, baos)
val b = baos.toByteArray()
val encodedImage = Base64.encodeToString(b, Base64.DEFAULT)
selectArtistCoverVM.updateArtistCover(encodedImage)
}
},
bitmap = if(artistPicture.value == null)
remember{ getBitmapFromVector(context, R.drawable.loading).asImageBitmap()}
else
artistPicture.value!!.asImageBitmap(),
contentDescription = null,
contentScale = ContentScale.Crop,
colorFilter = if(artistPicture.value == null) ColorFilter.tint(MaterialTheme.colorScheme.primary) else null
)
try {
val imageUrl = result.cover_image
Glide.with(context)
.asBitmap()
.load(imageUrl)
.into(object : CustomTarget<Bitmap>() {
override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) {
artistPicture.value = resource
}
override fun onLoadCleared(placeholder: Drawable?) {}
})
} catch (ignore: Exception) {}
}
}
)
}
}
}
}
} | 2 | null | 3 | 98 | 0700d0a6618da48a94b73a4633f8c7582af7a387 | 8,384 | SimpleMP-Compose | MIT License |
plugin/src/main/kotlin/org/gradle/github/dependency/extractor/internal/GitHubRepositorySnapshotBuilder.kt | gradle | 434,412,403 | false | null | package org.gradle.github.dependency.extractor.internal
import org.gradle.github.dependency.extractor.internal.json.BaseGitHubManifest
import org.gradle.github.dependency.extractor.internal.json.GitHubDetector
import org.gradle.github.dependency.extractor.internal.json.GitHubJob
import org.gradle.github.dependency.extractor.internal.json.GitHubManifest
import org.gradle.github.dependency.extractor.internal.json.GitHubManifestFile
import org.gradle.github.dependency.extractor.internal.json.GitHubRepositorySnapshot
import java.nio.file.Path
import java.nio.file.Paths
import java.util.concurrent.ConcurrentHashMap
class GitHubRepositorySnapshotBuilder(
private val gitHubJobName: String,
private val gitHubRunNumber: String,
private val gitSha: String,
private val gitRef: String,
private val gitWorkspaceDirectory: Path
) {
private val detector by lazy { GitHubDetector() }
private val job by lazy {
GitHubJob(
id = gitHubRunNumber,
name = gitHubJobName
)
}
/**
* Map of the project identifier to the relative path of the git workspace directory [gitWorkspaceDirectory].
*/
private val projectToRelativeBuildFile = ConcurrentHashMap<SimpleProjectIdentifier, String>()
private val bundledManifests: MutableMap<String, BundledManifest> = ConcurrentHashMap()
fun addManifest(
name: String,
buildPath: String,
projectPath: String,
manifest: BaseGitHubManifest
) {
bundledManifests[name] = BundledManifest(
projectIdentifier = SimpleProjectIdentifier(
buildPath = buildPath,
projectPath = projectPath
),
manifest = manifest
)
}
fun addProject(buildPath: String, projectPath: String, buildFileAbsolutePath: String) {
val projectIdentifier = SimpleProjectIdentifier(buildPath, projectPath)
val buildFilePath = Paths.get(buildFileAbsolutePath)
projectToRelativeBuildFile[projectIdentifier] = gitWorkspaceDirectory.relativize(buildFilePath).toString()
}
fun build(): GitHubRepositorySnapshot {
val manifests = bundledManifests.mapValues { (_, value) ->
GitHubManifest(
base = value.manifest,
file = projectToRelativeBuildFile[value.projectIdentifier]?.let {
// Cleanup the path for Windows systems
val sourceLocation = it.replace('\\', '/')
GitHubManifestFile(sourceLocation = sourceLocation)
}
)
}
return GitHubRepositorySnapshot(
job = job,
sha = gitSha,
ref = gitRef,
detector = detector,
manifests = manifests
)
}
private data class BundledManifest(
/**
* Used to look up the file path of the build file in the [projectToRelativeBuildFile] map.
*/
val projectIdentifier: SimpleProjectIdentifier,
val manifest: BaseGitHubManifest
)
private data class SimpleProjectIdentifier(
val buildPath: String,
val projectPath: String
)
}
| 4 | Kotlin | 7 | 22 | 2062217b62d6b11965464f433889c1ee93ca3e4e | 3,196 | github-dependency-extractor | Apache License 2.0 |
examples/todo/src/jvmMain/kotlin/todo/api/Add.kt | varabyte | 389,223,226 | false | null | package todo.api
import com.varabyte.kobweb.api.Api
import com.varabyte.kobweb.api.ApiContext
import com.varabyte.kobweb.api.data.getValue
import com.varabyte.kobweb.api.http.HttpMethod
import todo.model.TodoStore
@Api
fun addTodo(ctx: ApiContext) {
if (ctx.req.method != HttpMethod.POST) return
val ownerId = ctx.req.params["owner"]
val todo = ctx.req.params["todo"]
if (ownerId == null || todo == null) {
return
}
ctx.data.getValue<TodoStore>().add(ownerId, todo)
ctx.res.status = 200
} | 80 | null | 19 | 446 | 95f455fdff15a61af083d72f2a8c758d7c502bfd | 528 | kobweb | Apache License 2.0 |
app/src/main/java/com/bluelock/realdownloader/util/BroadcastService.kt | thezayin | 671,003,290 | false | {"Kotlin": 145430, "Java": 27329} | package com.bluelock.realdownloader.util
import android.app.DownloadManager
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Environment
import android.os.IBinder
import android.util.Log
import android.widget.Toast
import com.bluelock.realdownloader.db.Database
import com.bluelock.realdownloader.models.FVideo
class BroadcastService : Service() {
var db: Database? = null
override fun onBind(intent: Intent): IBinder? {
return null
}
override fun onCreate() {
Log.d(TAG, "onCreate: broadcastService")
db = Database.init(applicationContext)
registerBroadcastRecerver()
}
private fun registerBroadcastRecerver() {
Log.d(TAG, "registerBroadcastRecerver: broadcast service")
val downloadComplete: BroadcastReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
val id = intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)
if (Constants.downloadVideos.containsKey(id)) {
Log.d("receiver", "onReceive: download complete")
val fVideo = db!!.getVideo(id)
var videoPath: String? = null
if (fVideo.videoSource == FVideo.FACEBOOK) {
videoPath = Environment.getExternalStorageDirectory().toString() +
"/Download" + Utils.RootDirectoryFacebook + fVideo.fileName
} else if (fVideo.videoSource == FVideo.INSTAGRAM) {
videoPath = Environment.getExternalStorageDirectory().toString() +
"/Download" + Utils.RootDirectoryInsta + fVideo.fileName
} else if ((fVideo as FVideo).videoSource == FVideo.SNAPCHAT) {
videoPath = Environment.getExternalStorageDirectory().toString() +
"/Download" + Utils.RootDirectorySnapchat + fVideo.fileName
} else if (fVideo.videoSource == FVideo.LIKEE) {
videoPath = Environment.getExternalStorageDirectory().toString() +
"/Download" + Utils.RootDirectoryLikee + fVideo.fileName
} else if (fVideo.videoSource == FVideo.MOZ) {
videoPath = Environment.getExternalStorageDirectory().toString() +
"/Download" + Utils.RootDirectoryMoz + fVideo.fileName
}
Toast.makeText(applicationContext, "Download complete", Toast.LENGTH_SHORT)
.show()
db!!.updateState(id, FVideo.COMPLETE)
if (videoPath != null) db!!.setUri(id, videoPath)
Constants.downloadVideos.remove(id)
}
}
}
registerReceiver(
downloadComplete,
IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
)
}
companion object {
private const val TAG = "BroadcastService"
}
} | 0 | Kotlin | 0 | 1 | ff273008c433f11770c9d41f1435854dbfa477e8 | 3,204 | Instagram-Video-Downloader | The Unlicense |
src/main/kotlin/org/bibletranslationtools/scriptureburrito/flavor/XFlavorSchema.kt | Bible-Translation-Tools | 804,953,693 | false | {"Kotlin": 157326} | package org.bibletranslationtools.scriptureburrito.flavor
import com.fasterxml.jackson.annotation.JsonInclude
import com.fasterxml.jackson.annotation.JsonProperty
import com.fasterxml.jackson.annotation.JsonPropertyOrder
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder(
"name"
)
class XFlavorSchema {
@get:JsonProperty("name")
@set:JsonProperty("name")
@JsonProperty("name")
var name: String? = null
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is XFlavorSchema) return false
if (name != other.name) return false
return true
}
override fun hashCode(): Int {
return name?.hashCode() ?: 0
}
override fun toString(): String {
return "XFlavorSchema(name=$name)"
}
}
| 0 | Kotlin | 0 | 1 | 71170bc16a35ba4e5a69f80f1a68dc162260ad48 | 818 | kotlin-scripture-burrito | MIT License |
syftlib/src/test/java/org/openmined/syft/integration/AuthenticationTest.kt | menzi101 | 277,331,168 | true | {"Kotlin": 300127} | package org.openmined.syft.integration
import android.net.NetworkCapabilities
import com.nhaarman.mockitokotlin2.any
import com.nhaarman.mockitokotlin2.argumentCaptor
import com.nhaarman.mockitokotlin2.never
import com.nhaarman.mockitokotlin2.spy
import com.nhaarman.mockitokotlin2.verify
import org.junit.Test
import org.openmined.syft.Syft
import org.openmined.syft.domain.SyftConfiguration
import org.openmined.syft.execution.JobStatusSubscriber
import org.openmined.syft.integration.clients.HttpClientMock
import org.openmined.syft.integration.clients.SocketClientMock
import org.openmined.syft.integration.execution.ShadowPlan
import org.robolectric.annotation.Config
@ExperimentalUnsignedTypes
class AuthenticationTest : AbstractSyftWorkerTest() {
@Test
@Config(shadows = [ShadowPlan::class])
fun `Test success workflow`() {
val socketClient = SocketClientMock(
authenticateSuccess = true,
cycleSuccess = true
)
val httpClient = HttpClientMock(
pingSuccess = true, downloadSpeedSuccess = true,
uploadSuccess = true, downloadPlanSuccess = true, downloadModelSuccess = true
)
val syftConfiguration = SyftConfiguration(
context,
networkingSchedulers,
computeSchedulers,
context.filesDir,
true,
networkConstraints,
NetworkCapabilities.TRANSPORT_WIFI,
0,
1,
socketClient.getMockedClient(),
httpClient.getMockedClient(),
SyftConfiguration.NetworkingClients.SOCKET
)
val syftWorker = Syft.getInstance(syftConfiguration, "test token")
val job = syftWorker.newJob("test", "1")
val jobStatusSubscriber = spy<JobStatusSubscriber>()
job.start(jobStatusSubscriber)
verify(jobStatusSubscriber).onReady(any(), any(), any())
syftWorker.dispose()
verify(jobStatusSubscriber).onComplete()
}
@Test
@Config(shadows = [ShadowPlan::class])
fun `Test workflow with no auth token`() {
val socketClient = SocketClientMock(
authenticateSuccess = true,
cycleSuccess = true
)
val httpClient = HttpClientMock(
pingSuccess = true, downloadSpeedSuccess = true,
uploadSuccess = true, downloadPlanSuccess = true, downloadModelSuccess = true
)
val syftConfiguration = SyftConfiguration(
context,
networkingSchedulers,
computeSchedulers,
context.filesDir,
true,
networkConstraints,
NetworkCapabilities.TRANSPORT_WIFI,
0,
1,
socketClient.getMockedClient(),
httpClient.getMockedClient(),
SyftConfiguration.NetworkingClients.SOCKET
)
val syftWorker = Syft.getInstance(syftConfiguration)
val job = syftWorker.newJob("test", "1")
val jobStatusSubscriber = spy<JobStatusSubscriber>()
job.start(jobStatusSubscriber)
verify(jobStatusSubscriber).onReady(any(), any(), any())
syftWorker.dispose()
verify(jobStatusSubscriber).onComplete()
}
@Test
@Config(shadows = [ShadowPlan::class])
fun `Test workflow with authentication failure`() {
val socketClient = SocketClientMock(
authenticateSuccess = false,
cycleSuccess = true
)
val httpClient = HttpClientMock(
pingSuccess = true, downloadSpeedSuccess = true,
uploadSuccess = true, downloadPlanSuccess = true, downloadModelSuccess = true
)
val syftConfiguration = SyftConfiguration(
context,
networkingSchedulers,
computeSchedulers,
context.filesDir,
true,
networkConstraints,
NetworkCapabilities.TRANSPORT_WIFI,
0,
1,
socketClient.getMockedClient(),
httpClient.getMockedClient(),
SyftConfiguration.NetworkingClients.SOCKET
)
val syftWorker = Syft.getInstance(syftConfiguration)
val job = syftWorker.newJob("test", "1")
val jobStatusSubscriber = spy<JobStatusSubscriber>()
job.start(jobStatusSubscriber)
argumentCaptor<Throwable>().apply {
verify(jobStatusSubscriber).onError(capture())
assert(firstValue is SecurityException)
}
syftWorker.dispose()
verify(jobStatusSubscriber, never()).onComplete()
}
@Test
@Config(shadows = [ShadowPlan::class])
fun `Test workflow with cycle rejected`() {
val socketClient = SocketClientMock(
authenticateSuccess = true,
cycleSuccess = false
)
val httpClient = HttpClientMock(
pingSuccess = true, downloadSpeedSuccess = true,
uploadSuccess = true, downloadPlanSuccess = true, downloadModelSuccess = true
)
val syftConfiguration = SyftConfiguration(
context,
networkingSchedulers,
computeSchedulers,
context.filesDir,
true,
networkConstraints,
NetworkCapabilities.TRANSPORT_WIFI,
0,
1,
socketClient.getMockedClient(),
httpClient.getMockedClient(),
SyftConfiguration.NetworkingClients.SOCKET
)
val syftWorker = Syft.getInstance(syftConfiguration)
val job = syftWorker.newJob("test", "1")
val jobStatusSubscriber = spy<JobStatusSubscriber>()
job.start(jobStatusSubscriber)
verify(jobStatusSubscriber).onRejected(any())
syftWorker.dispose()
verify(jobStatusSubscriber).onComplete()
}
} | 0 | Kotlin | 0 | 0 | 24f2567ef4a2ec96dd6d6d9f0c17b117c1577b96 | 5,818 | KotlinSyft | Apache License 2.0 |
src/main/kotlin/ink/ptms/chemdah/core/conversation/ConversationLoader.kt | TabooLib | 338,114,548 | false | null | package ink.ptms.chemdah.core.conversation
import ink.ptms.chemdah.api.ChemdahAPI
import ink.ptms.chemdah.api.event.collect.ConversationEvents
import ink.ptms.chemdah.core.conversation.AgentType.Companion.toAgentType
import ink.ptms.chemdah.core.conversation.theme.ThemeChat
import ink.ptms.chemdah.core.conversation.theme.ThemeChest
import ink.ptms.chemdah.util.asMap
import taboolib.common.LifeCycle
import taboolib.common.platform.Awake
import taboolib.common.platform.function.getDataFolder
import taboolib.common.platform.function.info
import taboolib.common.platform.function.releaseResourceFile
import taboolib.common.platform.function.warning
import taboolib.common.util.asList
import taboolib.library.configuration.ConfigurationSection
import taboolib.module.configuration.Configuration
import java.io.File
/**
* Chemdah
* ink.ptms.chemdah.core.conversation.ConversationLoader
*
* @author sky
* @since 2021/2/9 6:34 下午
*/
object ConversationLoader {
init {
ChemdahAPI.addConversationTheme("chat", ThemeChat)
ChemdahAPI.addConversationTheme("chest", ThemeChest)
}
@Awake(LifeCycle.ACTIVE)
fun loadAll() {
val file = File(getDataFolder(), "core/conversation")
if (!file.exists()) {
releaseResourceFile("core/conversation/example.yml", true)
}
val conversations = load(file)
ChemdahAPI.conversation.clear()
ChemdahAPI.conversation.putAll(conversations.map { it.id to it })
ChemdahAPI.conversationTheme.values.forEach { it.reloadConfig() }
info("${ChemdahAPI.conversation.size} conversations loaded.")
// 重复检查
conversations.groupBy { it.id }.forEach { (id, c) ->
if (c.size > 1) {
warning("${c.size} conversations use duplicate id: $id")
}
}
}
fun load(file: File): List<Conversation> {
return when {
file.isDirectory -> {
file.listFiles()?.flatMap { load(it) }?.toList() ?: emptyList()
}
file.extension == "yml" || file.extension == "json" -> {
load(Configuration.loadFromFile(file))
}
else -> {
emptyList()
}
}
}
fun load(file: Configuration): List<Conversation> {
val option = if (file.isConfigurationSection("__option__")) {
Option(file.getConfigurationSection("__option__")!!)
} else {
Option.default
}
return file.getKeys(false).filter { it != "__option__" && file.isConfigurationSection(it) }.mapNotNull {
load(null, option, file.getConfigurationSection(it)!!)
}
}
private fun load(file: File?, option: Option, root: ConfigurationSection): Conversation? {
if (ConversationEvents.Load(file, option, root).call()) {
val id = root["npc id"]
val trigger = if (id != null) {
Trigger(id.asList().map { it.split(" ") }.filter { it.size == 2 }.map { Trigger.Id(it[0], it[1]) })
} else {
Trigger(emptyList())
}
return Conversation(
root.name,
file,
root,
trigger,
root["npc"]?.asList()?.flatMap { it.lines() }?.toMutableList() ?: ArrayList(), // 兼容 Chemdah Lab
root.getList("player")?.run {
PlayerSide(mapNotNull { it.asMap() }.map {
PlayerReply(
it.toMutableMap(),
it["if"]?.toString(),
it["reply"].toString(),
it["then"]?.asList()?.flatMap { i -> i.lines() }?.toMutableList() ?: ArrayList() // 兼容 Chemdah Lab
)
}.toMutableList())
} ?: PlayerSide(ArrayList()),
root.getString("condition"),
root.getConfigurationSection("agent")?.getKeys(false)?.map {
val args = it.split("@").map { a -> a.trim() }
Agent(
args[0].toAgentType(),
root["agent.$it"]!!.asList(),
args.getOrNull(1) ?: "self"
)
}?.toMutableList() ?: ArrayList(),
option
)
}
return null
}
} | 4 | Kotlin | 28 | 37 | 47e61f162650a7a1fc48d4832fe1bf5f5e54cb6e | 4,414 | Chemdah | MIT License |
js/js.translator/testData/box/propertyAccess/defaultAccessorsWithJsName.kt | JakeWharton | 99,388,807 | false | null | // IGNORE_BACKEND: JS_IR
// EXPECTED_REACHABLE_NODES: 1288
package foo
class A {
@get:JsName("getX_") val x = 23
@get:JsName("getY_") @set:JsName("setY_") var y = 0
@JsName("z_") var z = 0
}
fun box(): String {
val a = A()
assertEquals(23, a.x)
assertEquals(0, a.y)
a.y = 42
assertEquals(42, a.y)
a.z = 99
assertEquals(99, a.z)
val d: dynamic = A()
assertEquals(23, d.getX_())
assertEquals(0, d.getY_())
d.setY_(42)
assertEquals(42, d.getY_())
d.z_ = 99
assertEquals(99, d.z_)
return "OK"
} | 184 | null | 5691 | 83 | 4383335168338df9bbbe2a63cb213a68d0858104 | 570 | kotlin | Apache License 2.0 |
server/src/main/com/broll/gainea/server/core/goals/impl/all/G_MoveUnit.kt | Rolleander | 253,573,579 | false | {"Kotlin": 522423, "Java": 322590, "HTML": 1714, "CSS": 1069, "Shell": 104, "Batchfile": 100, "JavaScript": 24} | package com.broll.gainea.server.core.goals.impl.all
import com.broll.gainea.server.core.Game
import com.broll.gainea.server.core.bot.strategy.GoalStrategy
import com.broll.gainea.server.core.goals.CustomOccupyGoal
import com.broll.gainea.server.core.goals.GoalDifficulty
import com.broll.gainea.server.core.map.Area
import com.broll.gainea.server.core.map.Location
import com.broll.gainea.server.core.objects.Unit
import com.broll.gainea.server.core.player.Player
import com.broll.gainea.server.core.utils.getUnits
import com.broll.gainea.server.core.utils.getWalkingDistance
open class G_MoveUnit(
difficulty: GoalDifficulty = GoalDifficulty.EASY,
private val distance: Int = 6
) : CustomOccupyGoal(difficulty, "") {
init {
libraryText = text("X", "Y") + " ($distance Felder Abstand)"
}
private lateinit var from: Area
private lateinit var to: Area
private val walkingUnits = mutableListOf<Unit>()
private fun findPath(): Area? {
var step = 0
val visited: MutableList<Location?> = ArrayList()
val remaining = from.walkableNeighbours.toMutableList()
do {
step++
if (step == distance) {
remaining.shuffle()
val target = remaining.filterIsInstance(Area::class.java).firstOrNull()
if (target != null) {
return target
}
}
visited.addAll(remaining)
remaining += remaining.flatMap { it.walkableNeighbours }.distinct().toMutableList()
remaining.removeAll(visited)
} while (remaining.isNotEmpty())
return null
}
override fun init(game: Game, player: Player): Boolean {
this.game = game
this.player = player
val startingPoints = game.map.allAreas.shuffled().toMutableList()
var target: Area? = null
while (startingPoints.isNotEmpty() && target == null) {
from = startingPoints.removeAt(0)
target = findPath()
}
if (target == null) {
return false
}
to = target
locations.add(from)
locations.add(to)
text = text(from.name, to.name)
progressionGoal = distance
return super.init(game, player)
}
private fun text(from: String, to: String) =
"Bewege eine Einheit von $from nach $to"
override fun check() {
walkingUnits.removeIf { it.dead }
walkingUnits.addAll(player.getUnits(from))
if (walkingUnits.any { it.location === to }) {
updateProgression(distance)
success()
} else {
val closestDistance = walkingUnits.minOfOrNull {
it.getWalkingDistance(it.location, to) ?: distance
}
if (closestDistance != null) {
updateProgression(Math.max(0, distance - closestDistance))
} else {
updateProgression(0)
}
}
}
override fun botStrategy(strategy: GoalStrategy) {
strategy.setRequiredUnits(1)
strategy.isSpreadUnits = false
strategy.updateTargets(setOf(from))
strategy.setPrepareStrategy {
strategy.units.filter { walkingUnits.contains(it) }
.forEach { strategy.botStrategy.moveTargets[it] = to }
}
}
}
| 0 | Kotlin | 1 | 3 | ab47587c08ce2884269653a49c8fd8351cc4349f | 3,361 | Gainea | MIT License |
Corona-Warn-App/src/test/java/de/rki/coronawarnapp/util/DataBindingAdaptersTest.kt | covid-be-app | 281,650,940 | false | null | package de.rki.coronawarnapp.util
import android.content.Context
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.widget.Switch
import com.airbnb.lottie.LottieAnimationView
import com.airbnb.lottie.LottieDrawable
import de.rki.coronawarnapp.R
import de.rki.coronawarnapp.util.ContextExtensions.getDrawableCompat
import io.mockk.MockKAnnotations
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.spyk
import io.mockk.verify
import io.mockk.verifySequence
import org.junit.Before
import org.junit.Test
import testhelpers.BaseTest
class DataBindingAdaptersTest : BaseTest() {
@MockK
private lateinit var context: Context
@MockK
private lateinit var drawable: Drawable
@Before
fun setUp() {
MockKAnnotations.init(this)
mockkObject(ContextExtensions)
}
private fun setChecked(status: Boolean?) {
val switch = spyk(Switch(context))
setChecked(switch, status)
if (status != null) {
verifySequence {
switch.tag = IGNORE_CHANGE_TAG
switch.isChecked = status
switch.tag = null
}
} else {
verify(exactly = 0) {
switch.tag = IGNORE_CHANGE_TAG
switch.isChecked = any()
switch.tag = null
}
}
}
@Test
fun setCheckedTrue() {
setChecked(true)
}
@Test
fun setCheckedFalse() {
setChecked(false)
}
@Test
fun setCheckedNull() {
setChecked(false)
}
private fun setAnimation(animation: Int?) {
val animationView = mockk<LottieAnimationView>(relaxUnitFun = true).apply {
every { context } returns mockk<Context>().apply {
every { resources } returns mockk<Resources>().apply {
every { getResourceTypeName(any()) } returns "raw"
}
}
}
setAnimation(animationView, animation)
verify(exactly = 0) {
animationView.setImageDrawable(any())
}
if (animation != null) {
verifySequence {
animationView.context
animationView.setAnimation(animation)
animationView.repeatCount = LottieDrawable.INFINITE
animationView.repeatMode = LottieDrawable.RESTART
animationView.playAnimation()
}
} else {
verify(exactly = 0) {
animationView.setAnimation(any<Int>())
animationView.repeatCount = any()
animationView.repeatMode = any()
animationView.playAnimation()
}
}
}
@Test
fun setAnimationIcon() {
setAnimation(R.raw.ic_settings_tracing_animated)
}
@Test
fun setAnimationNull() {
setAnimation(null)
}
private fun setDrawable(drawableId: Int?) {
val animationView = mockk<LottieAnimationView>(relaxUnitFun = true).apply {
every { context } returns mockk<Context>().apply {
every { resources } returns mockk<Resources>().apply {
every { getResourceTypeName(any()) } returns DRAWABLE_TYPE
}
every { getDrawableCompat(any()) } returns [email protected]
}
}
setAnimation(animationView, drawableId)
verify(exactly = 0) {
animationView.setAnimation(any<Int>())
animationView.repeatCount = any()
animationView.repeatMode = any()
animationView.playAnimation()
}
if (drawableId != null) {
verifySequence {
animationView.context
animationView.setImageDrawable(any())
}
} else {
verify(exactly = 0) {
animationView.setImageDrawable(any())
}
}
}
@Test
fun setDrawableIcon() {
setDrawable(R.drawable.ic_settings_tracing_inactive)
}
@Test
fun setDrawableNull() {
setDrawable(null)
}
private fun setAnimationColor(color: Int?) {
val animationView = mockk<LottieAnimationView>(relaxUnitFun = true)
setAnimationColor(animationView, color)
if (color != null) {
verify {
animationView.setColorFilter(color)
}
} else {
verify(exactly = 0) {
animationView.setColorFilter(any<Int>())
}
}
}
@Test
fun setAnimationColorColor() {
setAnimationColor(R.color.colorTextSemanticRed)
}
@Test
fun setAnimationColorNull() {
setAnimationColor(null)
}
}
| 6 | null | 8 | 55 | d556b0b9f29e76295b59be2a1ba89bc4cf6ec33b | 4,845 | cwa-app-android | Apache License 2.0 |
app/src/main/java/com/opsc/timesync/ui/report/ReportFragment.kt | johanngeustyn | 648,824,203 | false | null | package com.opsc.timesync.ui.report
import android.app.DatePickerDialog
import android.os.Build
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.google.firebase.Timestamp
import com.opsc.timesync.databinding.FragmentReportBinding
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale
class ReportFragment : Fragment() {
private var _binding: FragmentReportBinding? = null
private val binding get() = _binding!!
private val timeEntryAdapter = TimeEntryAdapter()
private val categoryTotalAdapter = CategoryTotalAdapter()
private var selectedStartDate: Timestamp? = null
private var selectedEndDate: Timestamp? = null
@RequiresApi(Build.VERSION_CODES.O)
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val reportViewModel = ViewModelProvider(this).get(ReportViewModel::class.java)
_binding = FragmentReportBinding.inflate(inflater, container, false)
val root: View = binding.root
// Setup RecyclerView for time entries
binding.timeEntriesRecyclerView.layoutManager = LinearLayoutManager(requireContext())
binding.timeEntriesRecyclerView.adapter = timeEntryAdapter
// Setup RecyclerView for category totals
binding.categoryTotalsRecyclerView.layoutManager = LinearLayoutManager(requireContext())
binding.categoryTotalsRecyclerView.adapter = categoryTotalAdapter
// Observe changes in time entries
reportViewModel.timeEntries.observe(viewLifecycleOwner, Observer { timeEntries ->
// Update RecyclerView with new time entries data
timeEntryAdapter.submitList(timeEntries)
})
// Observe changes in category totals
reportViewModel.categoryTotals.observe(viewLifecycleOwner, Observer { categoryTotals ->
// Update RecyclerView with new category totals data
categoryTotalAdapter.submitList(categoryTotals)
})
val startDateButton: Button = binding.startDateButton
startDateButton.setOnClickListener {
val datePickerDialog = DatePickerDialog(
requireContext(),
{ _, year, month, dayOfMonth ->
val calendar = Calendar.getInstance()
calendar.set(year, month, dayOfMonth)
selectedStartDate = Timestamp(calendar.time)
startDateButton.text = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(calendar.time)
},
Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH),
Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
)
datePickerDialog.datePicker.maxDate = System.currentTimeMillis()
datePickerDialog.show()
}
val endDateButton: Button = binding.endDateButton
endDateButton.setOnClickListener {
val datePickerDialog = DatePickerDialog(
requireContext(),
{ _, year, month, dayOfMonth ->
val calendar = Calendar.getInstance()
calendar.set(year, month, dayOfMonth)
selectedEndDate = Timestamp(calendar.time)
endDateButton.text = SimpleDateFormat("dd/MM/yyyy", Locale.getDefault()).format(calendar.time)
},
Calendar.getInstance().get(Calendar.YEAR),
Calendar.getInstance().get(Calendar.MONTH),
Calendar.getInstance().get(Calendar.DAY_OF_MONTH)
)
datePickerDialog.datePicker.maxDate = System.currentTimeMillis()
datePickerDialog.show()
}
val filterButton: Button = binding.filterButton
filterButton.setOnClickListener {
if (selectedStartDate != null && selectedEndDate != null) {
if (!selectedStartDate!!.toDate().after(selectedEndDate!!.toDate())) {
reportViewModel.getReport(selectedStartDate!!, selectedEndDate!!)
} else {
Toast.makeText(requireContext(), "End date cannot be before start date.", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(requireContext(), "Please select both start and end dates.", Toast.LENGTH_SHORT).show()
}
}
return root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
} | 0 | Kotlin | 0 | 0 | 3d93f597b803c66247b16d1ea7a06efb6d50c9da | 4,950 | TimeSync | MIT License |
app/src/main/java/io/horizontalsystems/bankwallet/core/managers/AppConfigProvider.kt | WaltonChain | 263,802,120 | false | null | package io.horizontalsystems.bankwallet.core.managers
import io.horizontalsystems.bankwallet.BuildConfig
import io.horizontalsystems.bankwallet.R
import io.horizontalsystems.bankwallet.core.App
import io.horizontalsystems.bankwallet.core.IAppConfigProvider
import io.horizontalsystems.bankwallet.entities.Coin
import io.horizontalsystems.bankwallet.entities.CoinType
import io.horizontalsystems.bankwallet.entities.Currency
import java.math.BigDecimal
class AppConfigProvider : IAppConfigProvider {
override val companyWebPageLink: String = "https://horizontalsystems.io"
override val appWebPageLink: String = "https://unstoppable.money"
override val reportEmail = "<EMAIL>"
override val reportTelegramGroup = "unstoppable_wallet"
override val ipfsId = "QmXTJZBMMRmBbPun6HFt3tmb3tfYF2usLPxFoacL7G5uMX"
override val ipfsMainGateway = "ipfs-ext.horizontalsystems.xyz"
override val ipfsFallbackGateway = "ipfs.io"
override val infuraProjectId = "2a1306f1d12f4c109a4d4fb9be46b02e"
override val infuraProjectSecret = "fc479a9290b64a84a15fa6544a130218"
// Bitcoin-Core RPC config
override val btcCoreRpcUrl: String = "https://damp-old-pond.quiknode.io/38708434-ee69-4c9a-84d7-cb0f7f45f2cc/YiBzRob3cfnxTRSvByiyFh2bU93pKzxeyyTHpacaaPF0YnCg9u_cxvvoPIC-3wh6eaQAPyZh5Hd-fDjLGFXCIA==/"
override val btcCoreRpcUser: String? = null
override val btcCoreRpcPassword: String? = null
override val fiatDecimal: Int = 2
override val maxDecimal: Int = 8
override val testMode: Boolean = BuildConfig.testMode
override val currencies: List<Currency> = listOf(
Currency(code = "USD", symbol = "\u0024"),
Currency(code = "EUR", symbol = "\u20AC"),
Currency(code = "GBP", symbol = "\u00A3"),
Currency(code = "JPY", symbol = "\u00A5")
)
override val localizations: List<String>
get() {
val coinsString = App.instance.getString(R.string.localizations)
return coinsString.split(",")
}
override val featuredCoins: List<Coin>
get() = listOf(
coins[0],
coins[1],
coins[2],
coins[3],
coins[4],
coins[5]
)
override val coins: List<Coin> = listOf(
Coin("BTC", "Bitcoin", "BTC", 8, CoinType.Bitcoin),
Coin("ETH", "Ethereum", "ETH", 18, CoinType.Ethereum),
Coin("BCH", "Bitcoin Cash", "BCH", 8, CoinType.BitcoinCash),
Coin("DASH", "Dash", "DASH", 8, CoinType.Dash),
Coin("BNB", "Binance DEX", "BNB", 8, CoinType.Binance("BNB")),
Coin("EOS", "EOS", "EOS", 4, CoinType.Eos("eosio.token", "EOS")),
Coin("ZRX", "0x Protocol", "ZRX", 18, CoinType.Erc20("0xE41d2489571d322189246DaFA5ebDe1F4699F498")),
Coin("ELF", "Aelf", "ELF", 18, CoinType.Erc20("0xbf2179859fc6D5BEE9Bf9158632Dc51678a4100e")),
Coin("AURA", "Aurora DAO", "AURA", 18, CoinType.Erc20("0xCdCFc0f66c522Fd086A1b725ea3c0Eeb9F9e8814")),
Coin("ANKR", "Ankr Network", "ANKR", 8, CoinType.Binance("ANKR-E97")),
Coin("BNT", "Bancor", "BNT", 18, CoinType.Erc20("0x1F573D6Fb3F13d689FF844B4cE37794d79a7FF1C")),
Coin("BAT", "Basic Attention Token", "BAT", 18, CoinType.Erc20("0x0D8775F648430679A709E98d2b0Cb6250d2887EF")),
Coin("BNB-ERC20", "Binance ERC20", "BNB", 18, CoinType.Erc20("0xB8c77482e45F1F44dE1745F52C74426C631bDD52")),
Coin("BUSD", "Binance USD", "BUSD", 8, CoinType.Binance("BUSD-BD1")),
Coin("BTCB", "Bitcoin BEP2", "BTCB", 8, CoinType.Binance("BTCB-1DE")),
Coin("CAS", "Cashaaa", "CAS", 8, CoinType.Binance("CAS-167")),
Coin("LINK", "Chainlink", "LINK", 18, CoinType.Erc20("0x514910771AF9Ca656af840dff83E8264EcF986CA")),
Coin("MCO", "MCO", "MCO", 8, CoinType.Erc20("0xB63B606Ac810a52cCa15e44bB630fd42D8d1d83d")),
Coin("CRO", "Crypto.com Coin", "CRO", 8, CoinType.Erc20("0xA0b73E1Ff0B80914AB6fe0444E65848C4C34450b")),
Coin("CRPT", "Crypterium", "CRPT", 8, CoinType.Binance("CRPT-8C9")),
Coin("DAI", "Dai", "DAI", 18, CoinType.Erc20("0x6b175474e89094c44da98b954eedeac495271d0f")),
Coin("MANA", "Decentraland", "MANA", 18, CoinType.Erc20("0x0F5D2fB29fb7d3CFeE444a200298f468908cC942")),
Coin("DGD", "DigixDAO", "DGD", 9, CoinType.Erc20("0xE0B7927c4aF23765Cb51314A0E0521A9645F0E2A")),
Coin("DGX", "Digix Gold Token", "DGX", 9, CoinType.Erc20("0x4f3AfEC4E5a3F2A6a1A411DEF7D7dFe50eE057bF", gasLimit = 300_000, minimumSendAmount = BigDecimal("0.001"))),
Coin("ENJ", "EnjinCoin", "ENJ", 18, CoinType.Erc20("0xF629cBd94d3791C9250152BD8dfBDF380E2a3B9c")),
Coin("EOSDT", "EOSDT", "EOSDT", 9, CoinType.Eos("eosdtsttoken", "EOSDT")),
Coin("IQ", "Everipedia", "IQ", 3, CoinType.Eos("everipediaiq", "IQ")),
Coin("GUSD", "Gemini Dollar", "GUSD", 2, CoinType.Erc20("0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd")),
Coin("GNT", "Golem", "GNT", 18, CoinType.Erc20("0xa74476443119A942dE498590Fe1f2454d7D4aC0d")),
Coin("GTO", "Gifto", "GTO", 8, CoinType.Binance("GTO-908")),
Coin("HOT", "Holo", "HOT", 18, CoinType.Erc20("0x6c6EE5e31d828De241282B9606C8e98Ea48526E2")),
Coin("HT", "Huobi Token", "HT", 18, CoinType.Erc20("0x6f259637dcD74C767781E37Bc6133cd6A68aa161")),
Coin("IDEX", "IDEX", "IDEX", 18, CoinType.Erc20("0xB705268213D593B8FD88d3FDEFF93AFF5CbDcfAE")),
Coin("IDXM", "IDEX Membership", "IDXM", 8, CoinType.Erc20("0xCc13Fc627EFfd6E35D2D2706Ea3C4D7396c610ea")),
Coin("KCS", "KuCoin Shares", "KCS", 6, CoinType.Erc20("0x039B5649A59967e3e936D7471f9c3700100Ee1ab", minimumRequiredBalance = BigDecimal("0.001"))),
Coin("KNC", "Kyber Network", "KNC", 18, CoinType.Erc20("0xdd974D5C2e2928deA5F71b9825b8b646686BD200")),
Coin("LOOM", "Loom Network", "LOOM", 18, CoinType.Erc20("0xA4e8C3Ec456107eA67d3075bF9e3DF3A75823DB0")),
Coin("LRC", "Loopring", "LRC", 18, CoinType.Erc20("0xEF68e7C694F40c8202821eDF525dE3782458639f")),
Coin("MKR", "Maker", "MKR", 18, CoinType.Erc20("0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2")),
Coin("MEETONE", "MEET.ONE", "MEETONE", 4, CoinType.Eos("eosiomeetone", "MEETONE")),
Coin("MITH", "Mithril", "MITH", 18, CoinType.Erc20("0x3893b9422Cd5D70a81eDeFfe3d5A1c6A978310BB")),
Coin("NEXO", "Nexo", "NEXO", 18, CoinType.Erc20("0xB62132e35a6c13ee1EE0f84dC5d40bad8d815206")),
Coin("NDX", "Newdex", "NDX", 4, CoinType.Eos("newdexissuer", "NDX")),
Coin("NUT", "Native Utility Token", "NUT", 9, CoinType.Eos("eosdtnutoken", "NUT")),
Coin("OMG", "OmiseGO", "OMG", 18, CoinType.Erc20("0xd26114cd6EE289AccF82350c8d8487fedB8A0C07")),
Coin("ORBS", "Orbs", "ORBS", 18, CoinType.Erc20("0xff56Cc6b1E6dEd347aA0B7676C85AB0B3D08B0FA")),
Coin("PGL", "Prospectors Gold", "PGL", 4, CoinType.Eos("prospectorsg", "PGL")),
Coin("PAX", "Paxos Standard", "PAX", 18, CoinType.Erc20("0x8E870D67F660D95d5be530380D0eC0bd388289E1")),
Coin("PAXG", "PAX Gold", "PAXG", 18, CoinType.Erc20("0x45804880De22913dAFE09f4980848ECE6EcbAf78")),
Coin("POLY", "Polymath", "POLY", 18, CoinType.Erc20("0x9992eC3cF6A55b00978cdDF2b27BC6882d88D1eC")),
Coin("PPT", "Populous", "PPT", 8, CoinType.Erc20("0xd4fa1460F537bb9085d22C7bcCB5DD450Ef28e3a")),
Coin("PTI", "Paytomat", "PTI", 4, CoinType.Eos("ptitokenhome", "PTI")),
Coin("NPXS", "Pundi X", "NPXS", 18, CoinType.Erc20("0xA15C7Ebe1f07CaF6bFF097D8a589fb8AC49Ae5B3")),
Coin("REP", "Augur", "REP", 18, CoinType.Erc20("0x1985365e9f78359a9B6AD760e32412f4a445E862")),
Coin("R", "Revain", "R", 0, CoinType.Erc20("0x48f775EFBE4F5EcE6e0DF2f7b5932dF56823B990")),
Coin("XRP", "Ripple BEP2", "XRP", 8, CoinType.Binance("XRP-BF2")),
Coin("EURS", "STASIS EURO", "EURS", 2, CoinType.Erc20("0xdB25f211AB05b1c97D595516F45794528a807ad8")),
Coin("SAI", "Sai", "SAI", 18, CoinType.Erc20("0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359")),
Coin("SNT", "Status", "SNT", 18, CoinType.Erc20("0x744d70FDBE2Ba4CF95131626614a1763DF805B9E")),
Coin("TUSD", "TrueUSD", "TUSD", 18, CoinType.Erc20("0x0000000000085d4780B73119b644AE5ecd22b376")),
Coin("USDT", "Tether USD", "USDT", 6, CoinType.Erc20("0xdAC17F958D2ee523a2206206994597C13D831ec7")),
Coin("USDC", "USD Coin", "USDC", 6, CoinType.Erc20("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48")),
Coin("WTC", "Waltonchain", "WTC", 18, CoinType.Erc20("0xb7cB1C96dB6B22b0D3d9536E0108d062BD488F74"))
)
}
| 4 | null | 2 | 4 | ec877434f12db879faabcfbd69d8647f8c2eefdc | 10,860 | waltonchain-wallet-android | MIT License |
src/commonMain/kotlin/data/items/VindicatorsBandOfTriumph.kt | marisa-ashkandi | 332,658,265 | false | null | package `data`.items
import `data`.Constants
import `data`.buffs.Buffs
import `data`.model.Item
import `data`.model.ItemSet
import `data`.model.Socket
import `data`.model.SocketBonus
import character.Buff
import character.Stats
import kotlin.Array
import kotlin.Boolean
import kotlin.Double
import kotlin.Int
import kotlin.String
import kotlin.collections.List
import kotlin.js.JsExport
@JsExport
public class VindicatorsBandOfTriumph : Item() {
public override var isAutoGenerated: Boolean = true
public override var id: Int = 33919
public override var name: String = "Vindicator's Band of Triumph"
public override var itemLevel: Int = 141
public override var quality: Int = 4
public override var icon: String = "inv_jewelry_ring_60.jpg"
public override var inventorySlot: Int = 11
public override var itemSet: ItemSet? = null
public override var itemClass: Constants.ItemClass? = Constants.ItemClass.ARMOR
public override var itemSubclass: Constants.ItemSubclass? = Constants.ItemSubclass.MISC
public override var allowableClasses: Array<Constants.AllowableClass>? = null
public override var minDmg: Double = 0.0
public override var maxDmg: Double = 0.0
public override var speed: Double = 0.0
public override var stats: Stats = Stats(
stamina = 34,
meleeCritRating = 26.0,
rangedCritRating = 26.0,
resilienceRating = 22.0
)
public override var sockets: Array<Socket> = arrayOf()
public override var socketBonus: SocketBonus? = null
public override var phase: Int = 4
public override val buffs: List<Buff> by lazy {
listOfNotNull(
Buffs.byIdOrName(15810, "Attack Power 44", this),
Buffs.byIdOrName(44474, "Armor Penetration 56", this)
)}
}
| 21 | null | 11 | 25 | 9cb6a0e51a650b5d04c63883cb9bf3f64057ce73 | 1,763 | tbcsim | MIT License |
project-system-gradle-models/src/com/android/tools/idea/gradle/model/impl/IdeVariantImpl.kt | JetBrains | 60,701,247 | false | {"Kotlin": 53054415, "Java": 43443054, "Starlark": 1332164, "HTML": 1218044, "C++": 507658, "Python": 191041, "C": 71660, "Lex": 70302, "NSIS": 58238, "AIDL": 35382, "Shell": 29838, "CMake": 27103, "JavaScript": 18437, "Smali": 7580, "Batchfile": 7357, "RenderScript": 4411, "Clean": 3522, "Makefile": 2495, "IDL": 19} | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.gradle.model.impl
import com.android.tools.idea.gradle.model.IdeAndroidArtifact
import com.android.tools.idea.gradle.model.IdeBasicVariant
import com.android.tools.idea.gradle.model.IdeJavaArtifact
import com.android.tools.idea.gradle.model.IdeLibraryModelResolver
import com.android.tools.idea.gradle.model.IdeVariant
import com.android.tools.idea.gradle.model.IdeVariantCore
import java.io.File
import java.io.Serializable
data class IdeBasicVariantImpl(
override val name: String,
override val applicationId: String?,
override val testApplicationId: String?
) : IdeBasicVariant, Serializable
data class IdeVariantCoreImpl(
override val name: String,
override val displayName: String,
override val mainArtifact: IdeAndroidArtifactCoreImpl,
override val unitTestArtifact: IdeJavaArtifactCoreImpl?,
override val androidTestArtifact: IdeAndroidArtifactCoreImpl?,
override val testFixturesArtifact: IdeAndroidArtifactCoreImpl?,
override val buildType: String,
override val productFlavors: List<String>,
override val minSdkVersion: IdeApiVersionImpl,
override val targetSdkVersion: IdeApiVersionImpl?,
override val maxSdkVersion: Int?,
override val versionCode: Int?,
override val versionNameWithSuffix: String?,
override val versionNameSuffix: String?,
override val instantAppCompatible: Boolean,
override val vectorDrawablesUseSupportLibrary: Boolean,
override val resourceConfigurations: Collection<String>,
override val resValues: Map<String, IdeClassFieldImpl>,
override val proguardFiles: Collection<File>,
override val consumerProguardFiles: Collection<File>,
override val manifestPlaceholders: Map<String, String>,
override val testInstrumentationRunner: String?,
override val testInstrumentationRunnerArguments: Map<String, String>,
override val testedTargetVariants: List<IdeTestedTargetVariantImpl>,
// TODO(b/178961768); Review usages and replace with the correct alternatives or rename.
override val deprecatedPreMergedApplicationId: String?,
override val deprecatedPreMergedTestApplicationId: String?,
override val desugaredMethodsFiles: Collection<File>
) : IdeVariantCore, Serializable
data class IdeVariantImpl(
private val core: IdeVariantCore,
private val resolver: IdeLibraryModelResolver
) : IdeVariant, IdeVariantCore by core {
override val mainArtifact: IdeAndroidArtifact = IdeAndroidArtifactImpl(core.mainArtifact, resolver)
override val androidTestArtifact: IdeAndroidArtifact? = core.androidTestArtifact?.let { IdeAndroidArtifactImpl(it, resolver) }
override val testFixturesArtifact: IdeAndroidArtifact? = core.testFixturesArtifact?.let { IdeAndroidArtifactImpl(it, resolver) }
override val unitTestArtifact: IdeJavaArtifact? = core.unitTestArtifact?.let { IdeJavaArtifactImpl(it, resolver) }
} | 5 | Kotlin | 227 | 948 | 10110983c7e784122d94c7467e9d243aba943bf4 | 3,448 | android | Apache License 2.0 |
src/main/kotlin/uk/gov/justice/digital/hmpps/prisonertonomisupdate/helpers/WebClientHelpers.kt | ministryofjustice | 445,140,246 | false | {"Kotlin": 1130745, "Mustache": 1803, "Dockerfile": 1118} | package uk.gov.justice.digital.hmpps.prisonertonomisupdate.helpers
import kotlinx.coroutines.reactor.awaitSingle
import kotlinx.coroutines.reactor.awaitSingleOrNull
import org.springframework.http.HttpStatus
import org.springframework.web.reactive.function.client.WebClient
import org.springframework.web.reactive.function.client.WebClientResponseException
import org.springframework.web.reactive.function.client.bodyToMono
import reactor.core.publisher.Mono
import uk.gov.justice.digital.hmpps.prisonertonomisupdate.nomissync.model.ErrorResponse
suspend inline fun <reified T : Any> WebClient.ResponseSpec.awaitBodyOrNullForNotFound(): T? =
this.bodyToMono<T>()
.onErrorResume(WebClientResponseException.NotFound::class.java) { Mono.empty() }
.awaitSingleOrNull()
suspend inline fun <reified T : Any> WebClient.ResponseSpec.awaitBodyOrNullForStatus(vararg status: HttpStatus): T? =
this.bodyToMono<T>()
.onErrorResume(WebClientResponseException::class.java) {
if (it.statusCode in status) Mono.empty() else Mono.error(it)
}
.awaitSingleOrNull()
suspend inline fun <reified T : Any> WebClient.ResponseSpec.awaitBodyOrUpsertAttendanceError(): T =
this.bodyToMono<T>()
.onErrorResume(WebClientResponseException.BadRequest::class.java) {
val errorResponse = it.getResponseBodyAs(ErrorResponse::class.java) as ErrorResponse
UpsertAttendanceError.entries.find { error -> error.errorCode == errorResponse.errorCode }
?.let { err -> Mono.error(err.exception(errorResponse)) }
?: Mono.error(it)
}
.awaitSingle()
enum class UpsertAttendanceError(val errorCode: Int, val exception: (ErrorResponse) -> UpsertAttendanceException) {
ATTENDANCE_PAID(1001, { AttendancePaidException(it) }),
PRISONER_MOVED_ALLOCATION_ENDED(1002, { PrisonerMovedAllocationEndedException(it) }),
}
sealed class UpsertAttendanceException(errorResponse: ErrorResponse) : RuntimeException(errorResponse.userMessage)
class AttendancePaidException(errorResponse: ErrorResponse) : UpsertAttendanceException(errorResponse)
class PrisonerMovedAllocationEndedException(errorResponse: ErrorResponse) : UpsertAttendanceException(errorResponse)
suspend fun WebClient.ResponseSpec.awaitBodilessEntityOrThrowOnConflict() =
this.toBodilessEntity()
.onErrorResume(WebClientResponseException.Conflict::class.java) {
Mono.error(DuplicateMappingException(it.getResponseBodyAs(DuplicateErrorResponse::class.java)!!))
}
.awaitSingleOrNull()
class DuplicateMappingException(val error: DuplicateErrorResponse) : RuntimeException("message")
class DuplicateErrorResponse(
val moreInfo: DuplicateErrorContent,
)
data class DuplicateErrorContent(
val duplicate: Map<String, *>,
val existing: Map<String, *>? = null,
)
| 1 | Kotlin | 0 | 2 | e168c734a06480b70bd771581ef2692e83f4fc1b | 2,769 | hmpps-prisoner-to-nomis-update | MIT License |
kotlin/samples/tictactoe/app/src/main/java/com/squareup/sample/mainactivity/MainActivity.kt | arriolac | 208,501,497 | true | {"Gemfile.lock": 1, "Ruby": 5, "Markdown": 22, "Text": 1, "Ignore List": 1, "Swift": 44, "YAML": 1, "XML": 40, "JSON": 2, "OpenStep Property List": 5, "Shell": 2, "Gradle": 20, "Java Properties": 10, "Batchfile": 1, "EditorConfig": 1, "Kotlin": 167, "INI": 1, "Java": 1} | /*
* Copyright 2017 Square Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.squareup.sample.mainactivity
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.squareup.sample.authworkflow.AuthViewBindings
import com.squareup.sample.gameworkflow.TicTacToeViewBindings
import com.squareup.sample.panel.PanelContainer
import com.squareup.workflow.ui.ExperimentalWorkflowUi
import com.squareup.workflow.ui.ViewRegistry
import com.squareup.workflow.ui.WorkflowRunner
import com.squareup.workflow.ui.setContentWorkflow
import com.squareup.workflow.ui.workflowOnBackPressed
import io.reactivex.disposables.Disposables
import timber.log.Timber
@UseExperimental(ExperimentalWorkflowUi::class)
class MainActivity : AppCompatActivity() {
private var loggingSub = Disposables.disposed()
private lateinit var component: MainComponent
private lateinit var workflowRunner: WorkflowRunner<*>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
component = lastCustomNonConfigurationInstance as? MainComponent
?: MainComponent()
workflowRunner = setContentWorkflow(viewRegistry, component.mainWorkflow, savedInstanceState)
.apply {
loggingSub = renderings.subscribe { Timber.d("rendering: %s", it) }
}
}
override fun onBackPressed() {
if (!workflowOnBackPressed()) super.onBackPressed()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
workflowRunner.onSaveInstanceState(outState)
}
override fun onRetainCustomNonConfigurationInstance(): Any = component
override fun onDestroy() {
loggingSub.dispose()
super.onDestroy()
}
private companion object {
val viewRegistry = ViewRegistry(PanelContainer) + AuthViewBindings + TicTacToeViewBindings
}
}
| 0 | Kotlin | 0 | 1 | 8acff486c2fc80b1de2e1956170819f03fa0eafd | 2,375 | workflow | Apache License 2.0 |
xof-rest-api/src/main/kotlin/com/github/danzx/xof/entrypoint/rest/controller/HealthRestController.kt | dan-zx | 220,341,123 | false | null | package com.github.danzx.xof.entrypoint.rest.controller
import com.github.danzx.xof.entrypoint.rest.controller.BaseRestController.Companion.BASE_PATH
import com.github.danzx.xof.entrypoint.rest.response.SuccessResponse
import io.swagger.annotations.Api
import io.swagger.annotations.ApiOperation
import io.swagger.annotations.ApiResponse
import io.swagger.annotations.ApiResponses
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RestController
@RestController
@RequestMapping("$BASE_PATH/health")
@Api(tags=["Health API"], description="Health endpoints")
class HealthRestController {
@GetMapping
@ApiOperation("Health check")
@ApiResponses(ApiResponse(code = 200, message = "OK - Services are up and running"))
fun check() = SuccessResponse(true)
}
| 0 | Kotlin | 0 | 5 | 379eebd63fde5c645f822fb6d816f82d58d44b83 | 889 | xof-api | Apache License 2.0 |
src/main/no/nav/pto/veilarbfilter/service/MetricsReporter.kt | navikt | 207,477,352 | false | null | package no.nav.pto.veilarbfilter.service
import no.nav.common.metrics.Event
import no.nav.common.metrics.InfluxClient
import no.nav.common.metrics.MetricsClient
import no.nav.pto.veilarbfilter.config.dbQuery
import no.nav.pto.veilarbfilter.db.MetricsReporterInfo
import org.apache.commons.codec.digest.DigestUtils
import org.jetbrains.exposed.sql.select
import org.jetbrains.exposed.sql.update
import org.slf4j.LoggerFactory
import java.time.LocalDate
import java.time.LocalDateTime
class MetricsReporterService {
private var mineLagredeFilterServiceImpl: MineLagredeFilterServiceImpl
private var metricsClient: MetricsClient
private val log = LoggerFactory.getLogger("MetricsReporterService")
private val REPORT_ID: Int = 1;
constructor(mineLagredeFilterServiceImpl: MineLagredeFilterServiceImpl) {
this.mineLagredeFilterServiceImpl = mineLagredeFilterServiceImpl
metricsClient = InfluxClient()
}
private suspend fun shouldReport(): Boolean {
var lastReportedTime = lastReportedTime();
if (lastReportedTime!!.toLocalDate().isEqual(LocalDate.now())) {
return false;
}
return true
}
private suspend fun saveLastReportingTime() {
dbQuery {
MetricsReporterInfo
.update({ MetricsReporterInfo.reporterId eq REPORT_ID }) {
it[opprettetDato] = LocalDateTime.now()
}
}
}
private suspend fun lastReportedTime(): LocalDateTime? = dbQuery {
(MetricsReporterInfo).slice(
MetricsReporterInfo.opprettetDato,
).select { (MetricsReporterInfo.reporterId eq REPORT_ID) }
.mapNotNull { row -> row[MetricsReporterInfo.opprettetDato] }
.singleOrNull()
}
suspend fun reportLagradeFilter() {
if (!shouldReport()) {
return;
}
saveLastReportingTime();
log.info("Reporting metrics...")
mineLagredeFilterServiceImpl.hentAllLagredeFilter().forEach {
val metrikk = Event("portefolje.metrikker.lagredefilter.veileder-filter-counter")
metrikk.addFieldToReport("navn-lengde", it.filterNavn.length)
metrikk.addTagToReport("id", getHash(it.veilederId))
metrikk.addFieldToReport("filterId", it.filterId)
val filterValg = it.filterValg
var antallFiltre = 0
if (filterValg.aktiviteter != null) {
metrikk.addTagToReport("aktiviteter", "1")
if (filterValg.aktiviteter.BEHANDLING != "NA") {
metrikk.addTagToReport("BEHANDLING", "1")
antallFiltre++
}
if (filterValg.aktiviteter.EGEN != "NA") {
metrikk.addTagToReport("EGEN", "1")
antallFiltre++
}
if (filterValg.aktiviteter.GRUPPEAKTIVITET != "NA") {
metrikk.addTagToReport("GRUPPEAKTIVITET", "1")
antallFiltre++
}
if (filterValg.aktiviteter.IJOBB != "NA") {
metrikk.addTagToReport("IJOBB", "1")
antallFiltre++
}
if (filterValg.aktiviteter.MOTE != "NA") {
metrikk.addTagToReport("MOTE", "1")
antallFiltre++
}
if (filterValg.aktiviteter.SOKEAVTALE != "NA") {
metrikk.addTagToReport("SOKEAVTALE", "1")
antallFiltre++
}
if (filterValg.aktiviteter.STILLING != "NA") {
metrikk.addTagToReport("STILLING", "1")
antallFiltre++
}
if (filterValg.aktiviteter.TILTAK != "NA") {
metrikk.addTagToReport("TILTAK", "1")
antallFiltre++
}
if (filterValg.aktiviteter.UTDANNINGAKTIVITET != "NA") {
metrikk.addTagToReport("UTDANNINGAKTIVITET", "1")
antallFiltre++
}
}
if (filterValg.alder.isNotEmpty()) {
metrikk.addTagToReport("alder", "1")
addValuesAsTags(metrikk, filterValg.alder)
antallFiltre += filterValg.alder.size
}
if (filterValg.ferdigfilterListe.isNotEmpty()) {
metrikk.addTagToReport("ferdigfilterListe", "1")
addValuesAsTags(metrikk, filterValg.ferdigfilterListe)
antallFiltre += filterValg.ferdigfilterListe.size
}
if (filterValg.fodselsdagIMnd.isNotEmpty()) {
metrikk.addTagToReport("fodselsdagIMnd", "1")
antallFiltre += filterValg.fodselsdagIMnd.size
}
if (filterValg.formidlingsgruppe.isNotEmpty()) {
metrikk.addTagToReport("formidlingsgruppe", "1")
addValuesAsTags(metrikk, filterValg.formidlingsgruppe)
antallFiltre += filterValg.formidlingsgruppe.size
}
if (filterValg.hovedmal.isNotEmpty()) {
metrikk.addTagToReport("hovedmal", "1")
addValuesAsTags(metrikk, filterValg.hovedmal)
antallFiltre += filterValg.hovedmal.size
}
if (filterValg.innsatsgruppe.isNotEmpty()) {
metrikk.addTagToReport("innsatsgruppe", "1")
addValuesAsTags(metrikk, filterValg.innsatsgruppe)
antallFiltre += filterValg.innsatsgruppe.size
}
if (filterValg.kjonn != null && filterValg.kjonn.isNotEmpty()) {
metrikk.addTagToReport("kjonn", "1")
metrikk.addTagToReport(filterValg.kjonn, "1")
antallFiltre++
}
if (filterValg.manuellBrukerStatus.isNotEmpty()) {
metrikk.addTagToReport("manuellBrukerStatus", "1")
addValuesAsTags(metrikk, filterValg.manuellBrukerStatus)
antallFiltre += filterValg.manuellBrukerStatus.size
}
if (filterValg.rettighetsgruppe.isNotEmpty()) {
metrikk.addTagToReport("rettighetsgruppe", "1")
addValuesAsTags(metrikk, filterValg.rettighetsgruppe)
antallFiltre += filterValg.rettighetsgruppe.size
}
if (filterValg.servicegruppe.isNotEmpty()) {
metrikk.addTagToReport("servicegruppe", "1")
addValuesAsTags(metrikk, filterValg.servicegruppe)
antallFiltre += filterValg.servicegruppe.size
}
if (filterValg.tiltakstyper.isNotEmpty()) {
metrikk.addTagToReport("tiltakstyper", "1")
addValuesAsTags(metrikk, filterValg.tiltakstyper)
antallFiltre += filterValg.tiltakstyper.size
}
if (filterValg.veilederNavnQuery.isNotEmpty()) {
metrikk.addTagToReport("veilederNavnQuery", "1")
antallFiltre++
}
if (filterValg.veiledere.isNotEmpty()) {
metrikk.addTagToReport("veiledere", "1")
antallFiltre += filterValg.veiledere.size
}
if (filterValg.ytelse != null && filterValg.ytelse.isNotEmpty()) {
metrikk.addTagToReport("ytelse", "1")
metrikk.addTagToReport(filterValg.ytelse, "1")
antallFiltre++
}
if (filterValg.registreringstype != null && filterValg.registreringstype.isNotEmpty()) {
metrikk.addTagToReport("registreringstype", "1")
addValuesAsTags(metrikk, filterValg.registreringstype)
antallFiltre += filterValg.registreringstype.size
}
if (filterValg.cvJobbprofil != null && filterValg.cvJobbprofil.isNotEmpty()) {
metrikk.addTagToReport("cvJobbprofil", "1")
metrikk.addTagToReport(filterValg.cvJobbprofil, "1")
antallFiltre++
}
if (filterValg.arbeidslisteKategori != null && filterValg.arbeidslisteKategori.isNotEmpty()) {
metrikk.addTagToReport("arbeidslisteKategori", "1")
antallFiltre += filterValg.arbeidslisteKategori.size
}
metrikk.addFieldToReport("antallFiltre", antallFiltre)
metricsClient.report(metrikk)
}
}
private fun addValuesAsTags(metrikk: Event, listValues: List<String>) {
listValues.forEach { metrikk.addTagToReport(it, "1") }
}
private fun getHash(veilederId: String): String {
return DigestUtils.md5Hex(veilederId)
};
} | 7 | Kotlin | 0 | 0 | d1bd1580d40e3cc248c51cf0c35d5cb6e85b62a7 | 8,734 | veilarbfilter | MIT License |
src/main/kotlin/xyz/jmullin/drifter/assets/PlaceholderSound.kt | JustinMullin | 65,239,521 | false | null | package xyz.jmullin.drifter.assets
import com.badlogic.gdx.audio.Sound
/**
* Used as a placeholder noop implementation of [Sound] for [DrifterAssets].
*/
class PlaceholderSound : Sound {
val PlaceholderMessage = "This is a placeholder asset; this method should never have been called!"
override fun pause() = throw UnsupportedOperationException(PlaceholderMessage)
override fun pause(soundId: Long) = throw UnsupportedOperationException(PlaceholderMessage)
override fun setPitch(soundId: Long, pitch: Float) = throw UnsupportedOperationException(PlaceholderMessage)
override fun setPan(soundId: Long, pan: Float, volume: Float) = throw UnsupportedOperationException(PlaceholderMessage)
override fun setLooping(soundId: Long, looping: Boolean) = throw UnsupportedOperationException(PlaceholderMessage)
override fun play(): Long = throw UnsupportedOperationException(PlaceholderMessage)
override fun play(volume: Float): Long = throw UnsupportedOperationException(PlaceholderMessage)
override fun play(volume: Float, pitch: Float, pan: Float): Long = throw UnsupportedOperationException(PlaceholderMessage)
override fun stop() = throw UnsupportedOperationException(PlaceholderMessage)
override fun stop(soundId: Long) = throw UnsupportedOperationException(PlaceholderMessage)
override fun setVolume(soundId: Long, volume: Float) = throw UnsupportedOperationException(PlaceholderMessage)
override fun resume() = throw UnsupportedOperationException(PlaceholderMessage)
override fun resume(soundId: Long) = throw UnsupportedOperationException(PlaceholderMessage)
override fun loop(): Long = throw UnsupportedOperationException(PlaceholderMessage)
override fun loop(volume: Float): Long = throw UnsupportedOperationException(PlaceholderMessage)
override fun loop(volume: Float, pitch: Float, pan: Float): Long = throw UnsupportedOperationException(PlaceholderMessage)
override fun dispose() = throw UnsupportedOperationException(PlaceholderMessage)
} | 0 | Kotlin | 0 | 0 | df40d709d57861053e2c17b3ec8bb115ad2a377d | 2,021 | drifter-kotlin | MIT License |
libraries/tools/kotlin-gradle-plugin-integration-tests/src/test/kotlin/org/jetbrains/kotlin/gradle/native/CocoaPodsIT.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.gradle.native
import org.jetbrains.kotlin.gradle.BaseGradleIT
import org.jetbrains.kotlin.gradle.GradleVersionRequired
import org.jetbrains.kotlin.gradle.plugin.cocoapods.KotlinCocoapodsPlugin
import org.jetbrains.kotlin.gradle.plugin.cocoapods.KotlinCocoapodsPlugin.Companion.DUMMY_FRAMEWORK_TASK_NAME
import org.jetbrains.kotlin.gradle.plugin.cocoapods.KotlinCocoapodsPlugin.Companion.POD_BUILD_TASK_NAME
import org.jetbrains.kotlin.gradle.plugin.cocoapods.KotlinCocoapodsPlugin.Companion.POD_DOWNLOAD_TASK_NAME
import org.jetbrains.kotlin.gradle.plugin.cocoapods.KotlinCocoapodsPlugin.Companion.POD_GEN_TASK_NAME
import org.jetbrains.kotlin.gradle.plugin.cocoapods.KotlinCocoapodsPlugin.Companion.POD_IMPORT_TASK_NAME
import org.jetbrains.kotlin.gradle.plugin.cocoapods.KotlinCocoapodsPlugin.Companion.POD_INSTALL_TASK_NAME
import org.jetbrains.kotlin.gradle.plugin.cocoapods.KotlinCocoapodsPlugin.Companion.POD_SETUP_BUILD_TASK_NAME
import org.jetbrains.kotlin.gradle.plugin.cocoapods.KotlinCocoapodsPlugin.Companion.POD_SPEC_TASK_NAME
import org.jetbrains.kotlin.gradle.transformProjectWithPluginsDsl
import org.jetbrains.kotlin.gradle.util.modify
import org.jetbrains.kotlin.gradle.util.runProcess
import org.jetbrains.kotlin.konan.target.HostManager
import org.junit.Assume.assumeTrue
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test
import java.io.File
import java.util.concurrent.TimeUnit
import kotlin.test.assertEquals
import kotlin.test.assertTrue
import kotlin.test.fail
private val String.validFrameworkName: String
get() = replace('-', '_')
private val invalidTaskNameCharacters = "[/\\\\:<>\"?*|]".toRegex()
private val String.validTaskName
get() = replace(invalidTaskNameCharacters, "_")
class CocoaPodsIT : BaseGradleIT() {
override val defaultGradleVersion: GradleVersionRequired
get() = GradleVersionRequired.FOR_MPP_SUPPORT
// We use Kotlin DSL. Earlier Gradle versions fail at accessors codegen.
private val gradleVersion = GradleVersionRequired.FOR_MPP_SUPPORT
val PODFILE_IMPORT_DIRECTIVE_PLACEHOLDER = "<import_mode_directive>"
private val cocoapodsSingleKtPod = "native-cocoapods-single"
private val cocoapodsMultipleKtPods = "native-cocoapods-multiple"
private val templateProjectName = "native-cocoapods-template"
private val groovyTemplateProjectName = "native-cocoapods-template-groovy"
private val dummyTaskName = ":$DUMMY_FRAMEWORK_TASK_NAME"
private val podspecTaskName = ":$POD_SPEC_TASK_NAME"
private val podDownloadTaskName = ":$POD_DOWNLOAD_TASK_NAME"
private val podGenTaskName = ":$POD_GEN_TASK_NAME"
private val podBuildTaskName = ":$POD_BUILD_TASK_NAME"
private val podSetupBuildTaskName = ":$POD_SETUP_BUILD_TASK_NAME"
private val podImportTaskName = ":$POD_IMPORT_TASK_NAME"
private val podInstallTaskName = ":$POD_INSTALL_TASK_NAME"
private val cinteropTaskName = ":cinterop"
private val defaultPodRepo = "https://github.com/AFNetworking/AFNetworking"
private val defaultPodName = "AFNetworking"
private val defaultLibraryPodName = "YandexMapKit"
private val downloadUrlPodName = "podspecWithFilesExample"
private val downloadUrlRepoName = "https://github.com/alozhkin/podspecWithFilesExample/raw/master"
private val defaultTarget = "IOS"
private val defaultFamily = "IOS"
private val defaultSDK = "iphonesimulator"
private val defaultPodDownloadTaskName = podDownloadFullTaskName()
private val defaultPodGenTaskName = podGenFullTaskName()
private val defaultBuildTaskName = podBuildFullTaskName()
private val defaultSetupBuildTaskName = podSetupBuildFullTaskName()
private val defaultCinteropTaskName = cinteropTaskName + defaultPodName + defaultTarget
private val downloadUrlTaskName = podDownloadTaskName + downloadUrlPodName.capitalize()
private fun podDownloadFullTaskName(podName: String = defaultPodName) = podDownloadTaskName + podName.capitalize()
private fun podGenFullTaskName(familyName: String = defaultFamily) = podGenTaskName + familyName.capitalize()
private fun podSetupBuildFullTaskName(podName: String = defaultPodName, sdkName: String = defaultSDK) =
podSetupBuildTaskName + podName.capitalize() + sdkName.capitalize()
private fun podBuildFullTaskName(podName: String = defaultPodName, sdkName: String = defaultSDK) =
podBuildTaskName + podName.capitalize() + sdkName.capitalize()
private fun cinteropFullTaskName(podName: String = defaultPodName, targetName: String = defaultTarget) =
cinteropTaskName + podName.capitalize() + targetName.capitalize()
private lateinit var hooks: CustomHooks
private lateinit var project: BaseGradleIT.Project
@Before
fun configure() {
hooks = CustomHooks()
project = getProjectByName(templateProjectName)
}
@Test
fun testPodspecSingle() = doTestPodspec(
cocoapodsSingleKtPod,
mapOf("kotlin-library" to null),
mapOf("kotlin-library" to kotlinLibraryPodspecContent())
)
@Test
fun testPodspecCustomFrameworkNameSingle() = doTestPodspec(
cocoapodsSingleKtPod,
mapOf("kotlin-library" to "MultiplatformLibrary"),
mapOf("kotlin-library" to kotlinLibraryPodspecContent("MultiplatformLibrary"))
)
@Test
fun testXcodeUseFrameworksSingle() = doTestXcode(
cocoapodsSingleKtPod,
ImportMode.FRAMEWORKS,
"ios-app", mapOf("kotlin-library" to null)
)
@Test
fun testXcodeUseFrameworksWithCustomFrameworkNameSingle() = doTestXcode(
cocoapodsSingleKtPod,
ImportMode.FRAMEWORKS,
"ios-app",
mapOf("kotlin-library" to "MultiplatformLibrary")
)
@Test
fun testXcodeUseModularHeadersSingle() = doTestXcode(
cocoapodsSingleKtPod,
ImportMode.MODULAR_HEADERS,
"ios-app",
mapOf("kotlin-library" to null)
)
@Test
fun testXcodeUseModularHeadersWithCustomFrameworkNameSingle() = doTestXcode(
cocoapodsSingleKtPod,
ImportMode.MODULAR_HEADERS,
"ios-app",
mapOf("kotlin-library" to "MultiplatformLibrary")
)
@Test
fun testPodImportSingle() = doTestImportSingle()
@Test
fun testPodImportMultiple() = doTestImportMultiple()
@Test
fun testPodspecMultiple() = doTestPodspec(
cocoapodsMultipleKtPods,
mapOf("kotlin-library" to null, "second-library" to null),
mapOf("kotlin-library" to kotlinLibraryPodspecContent(), "second-library" to secondLibraryPodspecContent()),
)
@Test
fun testPodspecCustomFrameworkNameMultiple() = doTestPodspec(
cocoapodsMultipleKtPods,
mapOf("kotlin-library" to "FirstMultiplatformLibrary", "second-library" to "SecondMultiplatformLibrary"),
mapOf(
"kotlin-library" to kotlinLibraryPodspecContent("FirstMultiplatformLibrary"),
"second-library" to secondLibraryPodspecContent("SecondMultiplatformLibrary")
)
)
@Test
fun testXcodeUseFrameworksMultiple() = doTestXcode(
cocoapodsMultipleKtPods,
ImportMode.FRAMEWORKS,
null,
mapOf("kotlin-library" to null, "second-library" to null)
)
@Test
fun testXcodeUseFrameworksWithCustomFrameworkNameMultiple() = doTestXcode(
cocoapodsMultipleKtPods,
ImportMode.FRAMEWORKS,
null,
mapOf("kotlin-library" to "FirstMultiplatformLibrary", "second-library" to "SecondMultiplatformLibrary")
)
@Test
fun testXcodeUseModularHeadersMultiple() = doTestXcode(
cocoapodsMultipleKtPods,
ImportMode.MODULAR_HEADERS,
null,
mapOf("kotlin-library" to null, "second-library" to null)
)
@Test
fun testXcodeUseModularHeadersWithCustomFrameworkNameMultiple() = doTestXcode(
cocoapodsMultipleKtPods,
ImportMode.MODULAR_HEADERS,
null,
mapOf("kotlin-library" to "FirstMultiplatformLibrary", "second-library" to "SecondMultiplatformLibrary")
)
@Test
fun testSpecReposImport() {
val podName = "example"
val podRepo = "https://github.com/alozhkin/spec_repo"
with(project.gradleBuildScript()) {
addPod(podName)
addSpecRepo(podRepo)
}
project.testImportWithAsserts(listOf(podRepo))
}
@Test
fun testPodDownloadGitNoTagNorCommit() {
doTestGit()
}
@Test
fun testPodDownloadGitTag() {
doTestGit(tag = "4.0.0")
}
@Test
fun testPodDownloadGitCommit() {
doTestGit(commit = "9c07ac0a5645abb58850253eeb109ed0dca515c1")
}
@Test
fun testPodDownloadGitBranch() {
doTestGit(branch = "2974")
}
@Test
fun testPodDownloadGitSubspec() {
doTestGit(
repo = "https://github.com/SDWebImage/SDWebImage.git",
pod = "SDWebImage/MapKit",
tag = "5.9.2"
)
}
@Test
fun testPodDownloadGitBranchAndCommit() {
val branch = "2974"
val commit = "21637dd6164c0641e414bdaf3885af6f1ef15aee"
with(project.gradleBuildScript()) {
addPod(defaultPodName, produceGitBlock(defaultPodRepo, branchName = branch, commitName = commit))
}
hooks.addHook {
checkGitRepo(commitName = commit)
}
project.testDownload(listOf(defaultPodRepo))
}
// tag priority is bigger than branch priority
@Test
fun testPodDownloadGitBranchAndTag() {
val branch = "2974"
val tag = "4.0.0"
with(project.gradleBuildScript()) {
addPod(defaultPodName, produceGitBlock(defaultPodRepo, branchName = branch, tagName = tag))
}
hooks.addHook {
checkGitRepo(tagName = tag)
}
project.testDownload(listOf(defaultPodRepo))
}
@Test
fun testPodDownloadUrlZip() = doTestPodDownloadUrl("zip")
@Test
fun testPodDownloadUrlTar() = doTestPodDownloadUrl("tar")
@Test
fun testPodDownloadUrlGZ() = doTestPodDownloadUrl("tar.gz")
@Test
fun testPodDownloadUrlBZ2() = doTestPodDownloadUrl("tar.bz2")
@Test
fun testPodDownloadUrlJar() = doTestPodDownloadUrl("jar")
@Test
fun testPodDownloadUrlWrongName() = doTestPodDownloadUrl(fileExtension = "zip", archiveName = "wrongName")
@Test
fun testDownloadAndImport() {
val tag = "4.0.0"
with(project.gradleBuildScript()) {
addPod(defaultPodName, produceGitBlock(defaultPodRepo, tagName = tag))
}
hooks.addHook {
checkGitRepo(tagName = tag)
}
project.testImportWithAsserts(listOf(defaultPodRepo))
}
@Test
fun warnIfDeprecatedPodspecPathIsUsed() {
project = getProjectByName(cocoapodsSingleKtPod)
hooks.addHook {
assertContains(
listOf("Deprecated DSL found on ${project.projectDir.absolutePath}", "kotlin-library", "build.gradle.kts")
.joinToString(separator = File.separator)
)
}
project.test(":kotlin-library:podDownload")
}
// up-to-date tests
@Test
fun testDummyUTD() {
hooks.addHook {
assertTasksExecuted(dummyTaskName)
}
project.testWithWrapper(dummyTaskName)
hooks.rewriteHooks {
assertTasksUpToDate(dummyTaskName)
}
project.testWithWrapper(dummyTaskName)
}
@Test
fun testPodDownloadUTDWithoutPods() {
hooks.addHook {
assertTasksUpToDate(podDownloadTaskName)
}
project.testWithWrapper(podDownloadTaskName)
}
@Test
fun basicUTDTest() {
val tasks = listOf(
podspecTaskName,
defaultPodDownloadTaskName,
defaultPodGenTaskName,
defaultSetupBuildTaskName,
defaultBuildTaskName,
defaultCinteropTaskName
)
with(project.gradleBuildScript()) {
addPod(defaultPodName, produceGitBlock(defaultPodRepo))
}
hooks.addHook {
assertTasksExecuted(tasks)
}
project.testImportWithAsserts(listOf(defaultPodRepo))
hooks.rewriteHooks {
assertTasksUpToDate(tasks)
}
project.testImport(listOf(defaultPodRepo))
}
@Test
fun testSpecReposUTD() {
with(project.gradleBuildScript()) {
addPod("AFNetworking")
}
hooks.addHook {
assertTasksExecuted(defaultPodGenTaskName)
}
project.testSynthetic(defaultPodGenTaskName)
with(project.gradleBuildScript()) {
addSpecRepo("https://github.com/alozhkin/spec_repo_example.git")
}
project.testSynthetic(defaultPodGenTaskName)
hooks.rewriteHooks {
assertTasksUpToDate(defaultPodGenTaskName)
}
project.testSynthetic(defaultPodGenTaskName)
}
@Test
fun testUTDPodAdded() {
with(project.gradleBuildScript()) {
addPod(defaultPodName, produceGitBlock(defaultPodRepo))
}
project.testImport(listOf(defaultPodRepo))
val anotherPodName = "Alamofire"
val anotherPodRepo = "https://github.com/Alamofire/Alamofire"
with(project.gradleBuildScript()) {
addPod(anotherPodName, produceGitBlock(anotherPodRepo))
}
hooks.rewriteHooks {
assertTasksExecuted(
podspecTaskName,
podDownloadFullTaskName(anotherPodName),
defaultPodGenTaskName,
podSetupBuildFullTaskName(anotherPodName),
podBuildFullTaskName(anotherPodName),
cinteropFullTaskName(anotherPodName)
)
assertTasksUpToDate(
defaultPodDownloadTaskName,
defaultSetupBuildTaskName,
defaultBuildTaskName,
defaultCinteropTaskName
)
}
project.testImport(listOf(defaultPodRepo, anotherPodRepo))
with(project.gradleBuildScript()) {
removePod(anotherPodName)
}
hooks.rewriteHooks {
assertTasksNotRegisteredByPrefix(
listOf(
podDownloadFullTaskName(anotherPodName),
podBuildFullTaskName(anotherPodName),
cinteropFullTaskName(anotherPodName)
)
)
assertTasksUpToDate(
defaultBuildTaskName,
defaultPodDownloadTaskName,
defaultSetupBuildTaskName,
defaultCinteropTaskName
)
}
project.testImport(listOf(defaultPodRepo))
}
@Test
fun testImportSubspecs() {
with(project.gradleBuildScript()) {
addPod("SDWebImage/Core")
addPod("SDWebImage/MapKit")
}
project.testImport(listOf(defaultPodRepo))
}
@Test
fun testUTDTargetAdded() {
with(project.gradleBuildScript()) {
addPod(defaultPodName, produceGitBlock(defaultPodRepo))
appendToCocoapodsBlock("osx.deploymentTarget = \"13.5\"")
}
project.testImport(listOf(defaultPodRepo))
val anotherTarget = "MacosX64"
val anotherSdk = "macosx"
val anotherFamily = "OSX"
with(project.gradleBuildScript()) {
appendToKotlinBlock(anotherTarget.decapitalize() + "()")
}
hooks.rewriteHooks {
assertTasksExecuted(
podGenFullTaskName(anotherFamily),
podSetupBuildFullTaskName(sdkName = anotherSdk),
podBuildFullTaskName(sdkName = anotherSdk),
cinteropFullTaskName(targetName = anotherTarget)
)
assertTasksUpToDate(
podspecTaskName,
defaultPodDownloadTaskName,
defaultPodGenTaskName,
defaultSetupBuildTaskName,
defaultBuildTaskName,
defaultCinteropTaskName
)
}
project.testImport(listOf(defaultPodRepo))
with(project.gradleBuildScript()) {
var text = readText()
text = text.replace(anotherTarget.decapitalize() + "()", "")
writeText(text)
}
hooks.rewriteHooks {
assertTasksNotRegisteredByPrefix(
listOf(
podGenFullTaskName(anotherFamily),
podSetupBuildFullTaskName(sdkName = anotherSdk),
podBuildFullTaskName(sdkName = anotherSdk),
cinteropFullTaskName(targetName = anotherTarget)
)
)
assertTasksUpToDate(
podspecTaskName,
defaultPodDownloadTaskName,
defaultPodGenTaskName,
defaultSetupBuildTaskName,
defaultBuildTaskName,
defaultCinteropTaskName
)
}
project.testImport(listOf(defaultPodRepo))
}
@Test
fun testUTDPodspec() {
project.testWithWrapper(podspecTaskName)
hooks.addHook {
assertTasksExecuted(podspecTaskName)
}
with(project.gradleBuildScript()) {
appendToCocoapodsBlock("license = \"new license name\"")
}
project.testWithWrapper(podspecTaskName)
with(project.gradleBuildScript()) {
appendToCocoapodsBlock("license = \"new license name\"")
}
hooks.rewriteHooks {
assertTasksUpToDate(podspecTaskName)
}
project.testWithWrapper(podspecTaskName)
}
@Test
fun testUTDPodspecDeploymentTarget() {
project.testWithWrapper(podspecTaskName)
hooks.addHook {
assertTasksExecuted(podspecTaskName)
}
with(project.gradleBuildScript()) {
appendToCocoapodsBlock("ios.deploymentTarget = \"12.5\"")
}
project.testWithWrapper(podspecTaskName)
hooks.rewriteHooks {
assertTasksUpToDate(podspecTaskName)
}
project.testWithWrapper(podspecTaskName)
}
@Test
fun testUTDDownload() {
val gitRepo = downloadUrlRepoName.substringBeforeLast("/").substringBeforeLast("/")
with(project.gradleBuildScript()) {
addPod(downloadUrlPodName, produceGitBlock(repo = gitRepo))
}
hooks.addHook {
assertTasksExecuted(downloadUrlTaskName)
}
project.testDownload(listOf(gitRepo))
with(project.gradleBuildScript()) {
changePod(downloadUrlPodName, produceGitBlock(repo = gitRepo, commitName = "f52f035018b4f3fe253d50ce85a7e0652a62ee9b"))
}
project.testDownload(listOf(gitRepo))
hooks.rewriteHooks {
assertTasksUpToDate(downloadUrlTaskName)
}
project.testDownload(listOf(gitRepo))
val podArchivePath = "$downloadUrlRepoName/$downloadUrlPodName.tar.gz"
with(project.gradleBuildScript()) {
changePod(downloadUrlPodName, "source = url(\"$podArchivePath\")")
}
hooks.rewriteHooks {
assertTasksExecuted(downloadUrlTaskName)
}
project.testDownload(listOf(podArchivePath))
}
@Test
fun testUTDPodGen() {
with(project.gradleBuildScript()) {
addPod(defaultPodName)
}
val repos = listOf(
"https://github.com/alozhkin/spec_repo_example",
"https://github.com/alozhkin/spec_repo_example_2"
)
for (repo in repos) {
assumeTrue(isRepoAvailable(repo))
}
hooks.addHook {
assertTasksExecuted(defaultPodGenTaskName)
}
project.testSynthetic(defaultPodGenTaskName)
with(project.gradleBuildScript()) {
addSpecRepo("https://github.com/alozhkin/spec_repo_example")
}
project.testSynthetic(defaultPodGenTaskName)
with(project.gradleBuildScript()) {
addSpecRepo("https://github.com/alozhkin/spec_repo_example_2")
}
project.testSynthetic(defaultPodGenTaskName)
hooks.rewriteHooks {
assertTasksUpToDate(defaultPodGenTaskName)
}
project.testSynthetic(defaultPodGenTaskName)
}
@Test
fun testUTDBuild() {
with(project.gradleBuildScript()) {
addPod(defaultPodName, produceGitBlock())
}
hooks.addHook {
assertTasksExecuted(defaultBuildTaskName)
}
project.testImport()
val repo = "$downloadUrlRepoName/$downloadUrlPodName.tar.gz"
with(project.gradleBuildScript()) {
addPod(downloadUrlPodName, "source = url(\"$repo\")")
}
val urlTaskName = podBuildFullTaskName(downloadUrlPodName)
hooks.rewriteHooks {
assertTasksUpToDate(defaultBuildTaskName)
assertTasksExecuted(urlTaskName)
}
project.testImport()
val anotherTarget = "MacosX64"
val anotherSdk = "macosx"
with(project.gradleBuildScript()) {
appendToCocoapodsBlock("osx.deploymentTarget = \"13.5\"")
appendToKotlinBlock(anotherTarget.decapitalize() + "()")
}
val anotherSdkDefaultPodTaskName = podBuildFullTaskName(sdkName = anotherSdk)
val anotherTargetUrlTaskName = podBuildFullTaskName(downloadUrlPodName, anotherSdk)
hooks.rewriteHooks {
assertTasksUpToDate(defaultBuildTaskName, urlTaskName)
assertTasksExecuted(anotherSdkDefaultPodTaskName, anotherTargetUrlTaskName)
}
project.testImport()
hooks.rewriteHooks {
assertTasksUpToDate(defaultBuildTaskName, urlTaskName, anotherSdkDefaultPodTaskName, anotherTargetUrlTaskName)
}
project.testImport()
}
@Test
fun testPodBuildUTDClean() {
with(project.gradleBuildScript()) {
addPod(defaultPodName, produceGitBlock())
}
hooks.addHook {
assertTasksExecuted(defaultBuildTaskName)
}
project.testImport()
hooks.rewriteHooks {}
project.test(":clean")
hooks.addHook {
assertTasksExecuted(defaultBuildTaskName)
}
project.testImport()
}
@Test
fun testPodInstallWithoutPodFile() {
project.testSynthetic(podInstallTaskName)
}
// groovy tests
@Test
fun testGroovyDownloadAndImport() {
val project = getProjectByName(groovyTemplateProjectName)
val tag = "4.0.0"
with(project.gradleBuildScript()) {
addPod(defaultPodName, produceGitBlock(defaultPodRepo, tagName = tag))
}
hooks.addHook {
checkGitRepo(tagName = tag)
}
project.testImportWithAsserts(listOf(defaultPodRepo))
}
// other tests
@Test
fun testDownloadUrlTestSupportDashInNames() {
val fileExtension = "tar.gz"
val podName = "Pod-with-dashes"
val repoPath = "https://github.com/alozhkin/Pod-with-dashes/raw/master"
val flatten = true
val repo = "$repoPath/$podName.$fileExtension"
with(project.gradleBuildScript()) {
addPod(
podName,
"""source = url("$repo", $flatten)
|moduleName = "Pod_with_dashes"
""".trimMargin()
)
}
hooks.addHook {
assertTrue(url().resolve(podName).exists())
}
project.testImportWithAsserts(listOf(repo))
}
@Test
fun supportPodsWithDependencies() {
with(project.gradleBuildScript()) {
addPod("AlamofireImage")
}
project.testImportWithAsserts()
}
@Test
fun testCustomPackageName() {
with(project.gradleBuildScript()) {
addPod("AFNetworking", "packageName = \"AFNetworking\"")
}
with(project) {
File(projectDir, "src/iosMain/kotlin/A.kt").modify {
it.replace(
"fun foo() {", """
import AFNetworking
fun foo() {
""".trimIndent()
)
it.replace("println(\"hi!\")", "println(AFNetworking.AFNetworkingReachabilityNotificationStatusItem)")
}
testWithWrapper("assemble")
}
}
@Test
fun testCinteropExtraOpts() {
with(project) {
gradleBuildScript().addPod("AFNetworking", "extraOpts = listOf(\"-help\")")
hooks.addHook {
assertContains("Usage: cinterop options_list")
}
testWithWrapper("cinteropAFNetworkingIOS")
}
}
@Test
fun testUseLibrariesMode() {
with(project) {
gradleBuildScript().appendToCocoapodsBlock("useLibraries()")
gradleBuildScript().addPod(defaultLibraryPodName)
testImport()
}
}
@Test
fun testCommaSeparatedTargets() {
with(project) {
gradleBuildScript().modify {
// Replace a single target with a pair (iosX64 + iosArm64) to test building a fat framework.
it.replace("iosX64(\"iOS\")", "ios()")
}
hooks.addHook {
// Check that a built universal framework includes both device and simulator architectures.
val framework = fileInWorkingDir("build/cocoapods/framework/cocoapods.framework/cocoapods")
with(runProcess(listOf("file", framework.absolutePath), projectDir)) {
assertTrue(isSuccessful)
assertTrue(output.contains("\\(for architecture x86_64\\):\\s+current ar archive".toRegex()))
assertTrue(output.contains("\\(for architecture arm64\\):\\s+current ar archive".toRegex()))
}
}
// Run the build.
test(
"syncFramework",
"-Pkotlin.native.cocoapods.target=ios_x64,ios_arm64",
"-Pkotlin.native.cocoapods.configuration=DEBUG"
)
}
}
// paths
private fun CompiledProject.url() = externalSources().resolve("url")
private fun CompiledProject.git() = externalSources().resolve("git")
private fun CompiledProject.externalSources() =
fileInWorkingDir("build").resolve("cocoapods").resolve("externalSources")
// test configuration phase
private class CustomHooks {
private val hooks = mutableSetOf<CompiledProject.() -> Unit>()
fun addHook(hook: CompiledProject.() -> Unit) {
hooks.add(hook)
}
fun rewriteHooks(hook: CompiledProject.() -> Unit) {
hooks.clear()
hooks.add(hook)
}
fun trigger(project: CompiledProject) {
hooks.forEach { function ->
project.function()
}
}
}
private fun doTestImportSingle() {
val project = getProjectByName(cocoapodsSingleKtPod)
val subprojects = listOf("kotlin-library")
doTestPodImport(project, subprojects)
}
private fun doTestImportMultiple() {
val project = getProjectByName(cocoapodsMultipleKtPods)
val subprojects = listOf("kotlin-library", "second-library")
doTestPodImport(project, subprojects)
}
private fun doTestPodImport(project: BaseGradleIT.Project, subprojects: List<String>) {
with(project) {
preparePodfile("ios-app", ImportMode.FRAMEWORKS)
}
project.testImportWithAsserts()
subprojects.forEach {
hooks.rewriteHooks {
podImportAsserts(it)
}
project.testSynthetic(":$it:podImport")
}
}
private fun doTestGit(
repo: String = defaultPodRepo,
pod: String = defaultPodName,
branch: String? = null,
commit: String? = null,
tag: String? = null
) {
with(project.gradleBuildScript()) {
addPod(pod, produceGitBlock(repo, branch, commit, tag))
}
hooks.addHook {
checkGitRepo(branch, commit, tag, pod)
}
project.testDownload(listOf(repo))
}
private fun doTestPodDownloadUrl(
fileExtension: String,
podName: String = downloadUrlPodName,
repoPath: String = downloadUrlRepoName,
archiveName: String = podName,
flatten: Boolean = false
) {
val repo = "$repoPath/$archiveName.$fileExtension"
with(project.gradleBuildScript()) {
addPod(podName, "source = url(\"$repo\", $flatten)")
}
hooks.addHook {
assertTrue(url().resolve(podName).exists())
}
project.testImportWithAsserts(listOf(repo))
}
private fun Project.testImportWithAsserts(
repos: List<String> = listOf(),
vararg args: String
) {
hooks.addHook {
podImportAsserts()
}
testImport(repos, *args)
}
private fun Project.testImport(
repos: List<String> = listOf(),
vararg args: String
) {
for (repo in repos) {
assumeTrue(isRepoAvailable(repo))
}
testSynthetic(podImportTaskName, *args)
}
private fun Project.testDownload(
repos: List<String>,
vararg args: String
) {
for (repo in repos) {
assumeTrue(isRepoAvailable(repo))
}
test(podDownloadTaskName, *args)
}
private fun Project.testSynthetic(
taskName: String,
vararg args: String
) {
assumeTrue(KotlinCocoapodsPlugin.isAvailableToProduceSynthetic)
testWithWrapper(taskName, *args)
}
private fun Project.testWithWrapper(
taskName: String,
vararg args: String
) {
test(taskName, "-Pkotlin.native.cocoapods.generate.wrapper=true", *args)
}
private fun Project.test(
taskName: String,
vararg args: String
) {
// check that test executable
build(taskName, *args) {
//base checks
assertSuccessful()
hooks.trigger(this)
}
}
private fun getProjectByName(projectName: String) = transformProjectWithPluginsDsl(projectName, gradleVersion)
// build script configuration phase
private fun File.addPod(podName: String, configuration: String? = null) {
val pod = "pod(\"$podName\")"
val podBlock = configuration?.wrap(pod) ?: pod
appendToCocoapodsBlock(podBlock)
}
private fun File.removePod(podName: String) {
val text = readText()
val begin = text.indexOf("""pod("$podName")""")
require(begin != -1) { "Pod doesn't exist in file" }
var index = begin + """pod("$podName")""".length - 1
if (text.indexOf("""pod("$podName") {""", startIndex = begin) != -1) {
index += 2
var bracket = 1
while (bracket != 0) {
if (text[++index] == '{') {
bracket++
} else if (text[index] == '}') {
bracket--
}
}
}
writeText(text.removeRange(begin..index))
}
private fun File.changePod(podName: String, newConfiguration: String? = null) {
removePod(podName)
addPod(podName, newConfiguration)
}
private fun File.addSpecRepo(specRepo: String) = appendToCocoapodsBlock("url(\"$specRepo\")".wrap("specRepos"))
private fun File.appendToKotlinBlock(str: String) = appendLine(str.wrap("kotlin"))
private fun File.appendToCocoapodsBlock(str: String) = appendToKotlinBlock(str.wrap("cocoapods"))
private fun String.wrap(s: String): String = """
|$s {
| $this
|}
""".trimMargin()
private fun File.appendLine(s: String) = appendText("\n$s")
private fun produceGitBlock(
repo: String = defaultPodRepo,
branchName: String? = null,
commitName: String? = null,
tagName: String? = null
): String {
val branch = if (branchName != null) "branch = \"$branchName\"" else ""
val commit = if (commitName != null) "commit = \"$commitName\"" else ""
val tag = if (tagName != null) "tag = \"$tagName\"" else ""
return """source = git("$repo") {
| $branch
| $commit
| $tag
|}
""".trimMargin()
}
// proposition phase
private fun CompiledProject.checkGitRepo(
branchName: String? = null,
commitName: String? = null,
tagName: String? = null,
aPodDownloadName: String = defaultPodName,
podspecName: String = aPodDownloadName.split("/")[0]
) {
val gitDir = git().resolve(aPodDownloadName.validTaskName)
val podspecFile = gitDir.resolve("$podspecName.podspec")
assertTrue(podspecFile.exists())
if (tagName != null) {
checkTag(gitDir, tagName)
}
checkPresentCommits(gitDir, commitName)
if (branchName != null) {
checkBranch(gitDir, branchName)
}
}
private fun checkTag(gitDir: File, tagName: String) {
runCommand(
gitDir,
"git", "name-rev",
"--tags",
"--name-only",
"HEAD"
) {
val (retCode, out, errorMessage) = this
assertEquals(0, retCode, errorMessage)
assertTrue(out.contains(tagName), errorMessage)
}
}
private fun checkPresentCommits(gitDir: File, commitName: String?) {
runCommand(
gitDir,
"git", "log", "--pretty=oneline"
) {
val (retCode, out, _) = this
assertEquals(0, retCode)
// get rid of '\n' at the end
assertEquals(1, out.trimEnd().lines().size)
if (commitName != null) {
assertEquals(commitName, out.substringBefore(" "))
}
}
}
private fun checkBranch(gitDir: File, branchName: String) {
runCommand(
gitDir,
"git", "show-branch"
) {
val (retCode, out, errorMessage) = this
assertEquals(0, retCode)
// get rid of '\n' at the end
assertEquals(1, out.trimEnd().lines().size, errorMessage)
assertEquals("[$branchName]", out.substringBefore(" "), errorMessage)
}
}
private fun isRepoAvailable(repo: String): Boolean {
var responseCode = 0
runCommand(
File("/"),
"curl",
"-s",
"-o",
"/dev/null",
"-w",
"%{http_code}",
"-L",
repo,
"--retry", "2"
) {
val (retCode, out, errorMessage) = this
assertEquals(0, retCode, errorMessage)
responseCode = out.toInt()
}
return responseCode == 200
}
private fun CompiledProject.podImportAsserts(projectName: String? = null) {
val buildScriptText = project.gradleBuildScript(projectName).readText()
val taskPrefix = projectName?.let { ":$it" } ?: ""
val podspec = "podspec"
val podInstall = "podInstall"
assertSuccessful()
if ("noPodspec()" in buildScriptText) {
assertTasksSkipped("$taskPrefix:$podspec")
}
if ("podfile" in buildScriptText) {
assertTasksExecuted("$taskPrefix:$podInstall")
} else {
assertTasksSkipped("$taskPrefix:$podInstall")
}
assertTasksRegisteredByPrefix(listOf("$taskPrefix:$POD_GEN_TASK_NAME"))
if (buildScriptText.matches("pod\\(.*\\)".toRegex())) {
assertTasksExecutedByPrefix(listOf("$taskPrefix:$POD_GEN_TASK_NAME"))
}
with(listOf(POD_SETUP_BUILD_TASK_NAME, POD_BUILD_TASK_NAME).map { "$taskPrefix:$it" }) {
if (buildScriptText.matches("pod\\(.*\\)".toRegex())) {
assertTasksRegisteredByPrefix(this)
assertTasksExecutedByPrefix(this)
}
}
}
private fun Project.useCustomFrameworkName(subproject: String, frameworkName: String, iosAppLocation: String? = null) {
// Change the name at the Gradle side.
gradleBuildScript(subproject).appendText(
"""
|kotlin {
| cocoapods {
| frameworkName = "$frameworkName"
| }
|}
""".trimMargin()
)
// Change swift sources import if needed.
if (iosAppLocation != null) {
val iosAppDir = projectDir.resolve(iosAppLocation)
iosAppDir.resolve("ios-app/ViewController.swift").modify {
it.replace("import ${subproject.validFrameworkName}", "import $frameworkName")
}
}
}
private fun doTestPodspec(
projectName: String,
subprojectsToFrameworkNamesMap: Map<String, String?>,
subprojectsToPodspecContentMap: Map<String, String?>
) {
val gradleProject = transformProjectWithPluginsDsl(projectName, gradleVersion)
for ((subproject, frameworkName) in subprojectsToFrameworkNamesMap) {
frameworkName?.let {
gradleProject.useCustomFrameworkName(subproject, it)
}
// Check that we can generate the wrapper along with the podspec if the corresponding property specified
gradleProject.build(":$subproject:podspec", "-Pkotlin.native.cocoapods.generate.wrapper=true") {
assertSuccessful()
assertTasksExecuted(":$subproject:podspec")
// Check that the podspec file is correctly generated.
val podspecFileName = "$subproject/${subproject.validFrameworkName}.podspec"
assertFileExists(podspecFileName)
val actualPodspecContentWithoutBlankLines = fileInWorkingDir(podspecFileName).readText()
.lineSequence()
.filter { it.isNotBlank() }
.joinToString("\n")
assertEquals(subprojectsToPodspecContentMap[subproject], actualPodspecContentWithoutBlankLines)
}
}
}
private enum class ImportMode(val directive: String) {
FRAMEWORKS("use_frameworks!"),
MODULAR_HEADERS("use_modular_headers!")
}
private data class CommandResult(
val exitCode: Int,
val stdOut: String,
val stdErr: String
)
private fun runCommand(
workingDir: File,
command: String,
vararg args: String,
timeoutSec: Long = 120,
inheritIO: Boolean = false,
block: CommandResult.() -> Unit
) {
val process = ProcessBuilder(command, *args).apply {
directory(workingDir)
if (inheritIO) {
inheritIO()
}
}.start()
val isFinished = process.waitFor(timeoutSec, TimeUnit.SECONDS)
val stdOut = process.inputStream.bufferedReader().use { it.readText() }
val stdErr = process.errorStream.bufferedReader().use { it.readText() }
if (!isFinished) {
process.destroyForcibly()
println("Stdout:\n$stdOut")
println("Stderr:\n$stdErr")
fail("Command '$command ${args.joinToString(" ")}' killed by timeout.".trimIndent())
}
CommandResult(process.exitValue(), stdOut, stdErr).block()
}
private fun doTestXcode(
projectName: String,
mode: ImportMode,
iosAppLocation: String?,
subprojectsToFrameworkNamesMap: Map<String, String?>
) {
val gradleProject = transformProjectWithPluginsDsl(projectName, gradleVersion)
with(gradleProject) {
setupWorkingDir()
for ((subproject, frameworkName) in subprojectsToFrameworkNamesMap) {
// Add property with custom framework name
frameworkName?.let {
useCustomFrameworkName(subproject, it, iosAppLocation)
}
// Generate podspec.
build(":$subproject:podspec", "-Pkotlin.native.cocoapods.generate.wrapper=true") {
assertSuccessful()
}
iosAppLocation?.also {
// Set import mode for Podfile.
preparePodfile(it, mode)
// Install pods.
build(":$subproject:podInstall", "-Pkotlin.native.cocoapods.generate.wrapper=true") {
assertSuccessful()
}
projectDir.resolve(it).apply {
// Run Xcode build.
runCommand(
this, "xcodebuild",
"-sdk", "iphonesimulator",
"-arch", "x86_64",
"-configuration", "Release",
"-workspace", "$name.xcworkspace",
"-scheme", name,
inheritIO = true // Xcode doesn't finish the process if the PIPE redirect is used.
) {
assertEquals(
0, exitCode, """
|Exit code mismatch for `xcodebuild`.
|stdout:
|$stdOut
|
|stderr:
|$stdErr
""".trimMargin()
)
}
}
}
}
}
}
private fun Project.preparePodfile(iosAppLocation: String, mode: ImportMode) {
val iosAppDir = projectDir.resolve(iosAppLocation)
// Set import mode for Podfile.
iosAppDir.resolve("Podfile").takeIf { it.exists() }?.modify {
it.replace(PODFILE_IMPORT_DIRECTIVE_PLACEHOLDER, mode.directive)
}
}
private fun kotlinLibraryPodspecContent(frameworkName: String? = null) = """
Pod::Spec.new do |spec|
spec.name = 'kotlin_library'
spec.version = '1.0'
spec.homepage = 'https://github.com/JetBrains/kotlin'
spec.source = { :git => "Not Published", :tag => "Cocoapods/#{spec.name}/#{spec.version}" }
spec.authors = ''
spec.license = ''
spec.summary = 'CocoaPods test library'
spec.static_framework = true
spec.vendored_frameworks = "build/cocoapods/framework/${frameworkName ?: "kotlin_library"}.framework"
spec.libraries = "c++"
spec.module_name = "#{spec.name}_umbrella"
spec.dependency 'pod_dependency', '1.0'
spec.dependency 'subspec_dependency/Core', '1.0'
spec.pod_target_xcconfig = {
'KOTLIN_TARGET[sdk=iphonesimulator*]' => 'ios_x64',
'KOTLIN_TARGET[sdk=iphoneos*]' => 'ios_arm',
'KOTLIN_TARGET[sdk=watchsimulator*]' => 'watchos_x64',
'KOTLIN_TARGET[sdk=watchos*]' => 'watchos_arm',
'KOTLIN_TARGET[sdk=appletvsimulator*]' => 'tvos_x64',
'KOTLIN_TARGET[sdk=appletvos*]' => 'tvos_arm64',
'KOTLIN_TARGET[sdk=macosx*]' => 'macos_x64'
}
spec.script_phases = [
{
:name => 'Build kotlin_library',
:execution_position => :before_compile,
:shell_path => '/bin/sh',
:script => <<-SCRIPT
set -ev
REPO_ROOT="${'$'}PODS_TARGET_SRCROOT"
"${'$'}REPO_ROOT/../gradlew" -p "${'$'}REPO_ROOT" :kotlin-library:syncFramework \
-Pkotlin.native.cocoapods.target=${'$'}KOTLIN_TARGET \
-Pkotlin.native.cocoapods.configuration=${'$'}CONFIGURATION \
-Pkotlin.native.cocoapods.cflags="${'$'}OTHER_CFLAGS" \
-Pkotlin.native.cocoapods.paths.headers="${'$'}HEADER_SEARCH_PATHS" \
-Pkotlin.native.cocoapods.paths.frameworks="${'$'}FRAMEWORK_SEARCH_PATHS"
SCRIPT
}
]
end
""".trimIndent()
private fun secondLibraryPodspecContent(frameworkName: String? = null) = """
Pod::Spec.new do |spec|
spec.name = 'second_library'
spec.version = '1.0'
spec.homepage = 'https://github.com/JetBrains/kotlin'
spec.source = { :git => "Not Published", :tag => "Cocoapods/#{spec.name}/#{spec.version}" }
spec.authors = ''
spec.license = ''
spec.summary = 'CocoaPods test library'
spec.static_framework = true
spec.vendored_frameworks = "build/cocoapods/framework/${frameworkName ?: "second_library"}.framework"
spec.libraries = "c++"
spec.module_name = "#{spec.name}_umbrella"
spec.pod_target_xcconfig = {
'KOTLIN_TARGET[sdk=iphonesimulator*]' => 'ios_x64',
'KOTLIN_TARGET[sdk=iphoneos*]' => 'ios_arm',
'KOTLIN_TARGET[sdk=watchsimulator*]' => 'watchos_x64',
'KOTLIN_TARGET[sdk=watchos*]' => 'watchos_arm',
'KOTLIN_TARGET[sdk=appletvsimulator*]' => 'tvos_x64',
'KOTLIN_TARGET[sdk=appletvos*]' => 'tvos_arm64',
'KOTLIN_TARGET[sdk=macosx*]' => 'macos_x64'
}
spec.script_phases = [
{
:name => 'Build second_library',
:execution_position => :before_compile,
:shell_path => '/bin/sh',
:script => <<-SCRIPT
set -ev
REPO_ROOT="${'$'}PODS_TARGET_SRCROOT"
"${'$'}REPO_ROOT/../gradlew" -p "${'$'}REPO_ROOT" :second-library:syncFramework \
-Pkotlin.native.cocoapods.target=${'$'}KOTLIN_TARGET \
-Pkotlin.native.cocoapods.configuration=${'$'}CONFIGURATION \
-Pkotlin.native.cocoapods.cflags="${'$'}OTHER_CFLAGS" \
-Pkotlin.native.cocoapods.paths.headers="${'$'}HEADER_SEARCH_PATHS" \
-Pkotlin.native.cocoapods.paths.frameworks="${'$'}FRAMEWORK_SEARCH_PATHS"
SCRIPT
}
]
end
""".trimIndent()
companion object {
@BeforeClass
@JvmStatic
fun assumeItsMac() {
assumeTrue(HostManager.hostIsMac)
}
}
} | 7 | null | 5478 | 44,267 | 7545472dd3b67d2ac5eb8024054e3e6ff7795bf6 | 48,209 | kotlin | Apache License 2.0 |
compiler/ir/backend.jvm/lower/src/org/jetbrains/kotlin/backend/jvm/lower/PropertyReferenceLowering.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.backend.jvm.lower
import org.jetbrains.kotlin.backend.common.FileLoweringPass
import org.jetbrains.kotlin.backend.common.IrElementTransformerVoidWithContext
import org.jetbrains.kotlin.backend.common.lower.createIrBuilder
import org.jetbrains.kotlin.backend.common.phaser.makeIrFilePhase
import org.jetbrains.kotlin.backend.jvm.*
import org.jetbrains.kotlin.backend.jvm.ir.*
import org.jetbrains.kotlin.backend.jvm.lower.FunctionReferenceLowering.Companion.calculateOwner
import org.jetbrains.kotlin.backend.jvm.lower.FunctionReferenceLowering.Companion.calculateOwnerKClass
import org.jetbrains.kotlin.codegen.inline.loadCompiledInlineFunction
import org.jetbrains.kotlin.codegen.optimization.nullCheck.usesLocalExceptParameterNullCheck
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.descriptors.Modality
import org.jetbrains.kotlin.ir.IrStatement
import org.jetbrains.kotlin.ir.UNDEFINED_OFFSET
import org.jetbrains.kotlin.ir.builders.*
import org.jetbrains.kotlin.ir.builders.declarations.*
import org.jetbrains.kotlin.ir.declarations.*
import org.jetbrains.kotlin.ir.expressions.*
import org.jetbrains.kotlin.ir.expressions.impl.IrConstImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrFunctionReferenceImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrGetObjectValueImpl
import org.jetbrains.kotlin.ir.expressions.impl.IrInstanceInitializerCallImpl
import org.jetbrains.kotlin.ir.symbols.*
import org.jetbrains.kotlin.ir.types.IrSimpleType
import org.jetbrains.kotlin.ir.types.IrTypeProjection
import org.jetbrains.kotlin.ir.types.createType
import org.jetbrains.kotlin.ir.types.impl.IrSimpleTypeImpl
import org.jetbrains.kotlin.ir.types.impl.makeTypeProjection
import org.jetbrains.kotlin.ir.types.typeWith
import org.jetbrains.kotlin.ir.util.*
import org.jetbrains.kotlin.load.java.JavaDescriptorVisibilities
import org.jetbrains.kotlin.load.java.JvmAbi
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.name.SpecialNames
import org.jetbrains.kotlin.types.Variance
import java.util.concurrent.ConcurrentHashMap
internal val propertyReferencePhase = makeIrFilePhase(
::PropertyReferenceLowering,
name = "PropertyReference",
description = "Construct KProperty instances returned by expressions such as A::x and A()::x",
// This must be done after contents of functions are extracted into separate classes, or else the `$$delegatedProperties`
// field will end up in the wrong class (not the one that declares the delegated property).
prerequisite = setOf(functionReferencePhase, suspendLambdaPhase, propertyReferenceDelegationPhase)
)
internal class PropertyReferenceLowering(val context: JvmBackendContext) : IrElementTransformerVoidWithContext(), FileLoweringPass {
// Marking a property reference with this origin causes it to not generate a class.
object REFLECTED_PROPERTY_REFERENCE : IrStatementOriginImpl("REFLECTED_PROPERTY_REFERENCE")
// TODO: join IrLocalDelegatedPropertyReference and IrPropertyReference via the class hierarchy?
private val IrMemberAccessExpression<*>.getter: IrSimpleFunctionSymbol?
get() = (this as? IrPropertyReference)?.getter ?: (this as? IrLocalDelegatedPropertyReference)?.getter
private val IrMemberAccessExpression<*>.setter: IrSimpleFunctionSymbol?
get() = (this as? IrPropertyReference)?.setter ?: (this as? IrLocalDelegatedPropertyReference)?.setter
private val IrMemberAccessExpression<*>.field: IrFieldSymbol?
get() = (this as? IrPropertyReference)?.field
private val arrayItemGetter =
context.ir.symbols.array.owner.functions.single { it.name.asString() == "get" }
private val signatureStringIntrinsic = context.ir.symbols.signatureStringIntrinsic
private val kPropertyStarType = IrSimpleTypeImpl(
context.irBuiltIns.kPropertyClass,
false,
listOf(makeTypeProjection(context.irBuiltIns.anyNType, Variance.OUT_VARIANCE)),
emptyList()
)
private val kPropertiesFieldType =
context.ir.symbols.array.createType(false, listOf(makeTypeProjection(kPropertyStarType, Variance.OUT_VARIANCE)))
private val useOptimizedSuperClass =
context.state.generateOptimizedCallableReferenceSuperClasses
private val IrMemberAccessExpression<*>.propertyContainer: IrDeclarationParent
get() = if (this is IrLocalDelegatedPropertyReference)
currentClassData?.localPropertyOwner(getter)
?: throw AssertionError("local property reference before declaration: ${render()}")
else
getter?.owner?.parent ?: field?.owner?.parent ?: error("Property without getter or field: ${dump()}")
// Plain Java fields do not have a getter, but can be referenced nonetheless. The signature should be the one
// that a getter would have, if it existed.
private val IrField.fakeGetterSignature: String
get() = "${JvmAbi.getterName(name.asString())}()${context.defaultMethodSignatureMapper.mapReturnType(this)}"
private fun IrBuilderWithScope.computeSignatureString(expression: IrMemberAccessExpression<*>): IrExpression {
if (expression is IrLocalDelegatedPropertyReference) {
// Local delegated properties are stored as a plain list, and the runtime library extracts the index from this string:
val index = currentClassData?.localPropertyIndex(expression.getter)
?: throw AssertionError("local property reference before declaration: ${expression.render()}")
return irString("<v#$index>")
}
val getter = expression.getter ?: return irString(expression.field!!.owner.fakeGetterSignature)
// Work around for differences between `RuntimeTypeMapper.KotlinProperty` and the real Kotlin type mapper.
// Most notably, the runtime type mapper does not perform inline class name mangling. This is usually not
// a problem, since we will produce a getter signature as part of the Kotlin metadata, except when there
// is no getter method in the bytecode. In that case we need to avoid inline class mangling for the
// function reference used in the <signature-string> intrinsic.
//
// Note that we cannot compute the signature at this point, since we still need to mangle the names of
// private properties in multifile-part classes.
val needsDummySignature = getter.owner.correspondingPropertySymbol?.owner?.needsAccessor(getter.owner) == false ||
// Internal underlying vals of inline classes have no getter method
getter.owner.isInlineClassFieldGetter && getter.owner.visibility == DescriptorVisibilities.INTERNAL
val origin = if (needsDummySignature) InlineClassAbi.UNMANGLED_FUNCTION_REFERENCE else null
val reference = IrFunctionReferenceImpl.fromSymbolOwner(
startOffset, endOffset, expression.type, getter, getter.owner.typeParameters.size, getter, origin
)
for ((index, parameter) in getter.owner.typeParameters.withIndex()) {
reference.putTypeArgument(index, parameter.erasedUpperBound.defaultType)
}
return irCall(signatureStringIntrinsic).apply { putValueArgument(0, reference) }
}
private fun IrClass.addOverride(method: IrSimpleFunction, buildBody: JvmIrBuilder.(List<IrValueParameter>) -> IrExpression) =
addFunction {
setSourceRange(this@addOverride)
name = method.name
returnType = method.returnType
visibility = method.visibility
modality = Modality.OPEN
origin = JvmLoweredDeclarationOrigin.GENERATED_MEMBER_IN_CALLABLE_REFERENCE
}.apply {
overriddenSymbols += method.symbol
dispatchReceiverParameter = thisReceiver!!.copyTo(this)
valueParameters = method.valueParameters.map { it.copyTo(this) }
body = context.createJvmIrBuilder(symbol, startOffset, endOffset).run {
irExprBody(buildBody(listOf(dispatchReceiverParameter!!) + valueParameters))
}
}
private fun IrClass.addFakeOverride(method: IrSimpleFunction) =
addFunction {
name = method.name
returnType = method.returnType
visibility = method.visibility
isFakeOverride = true
origin = IrDeclarationOrigin.FAKE_OVERRIDE
}.apply {
overriddenSymbols += method.symbol
dispatchReceiverParameter = thisReceiver!!.copyTo(this)
valueParameters = method.valueParameters.map { it.copyTo(this) }
}
private class PropertyReferenceKind(
val interfaceSymbol: IrClassSymbol,
val implSymbol: IrClassSymbol,
val wrapper: IrFunction
)
private fun propertyReferenceKind(expression: IrCallableReference<*>, mutable: Boolean, i: Int): PropertyReferenceKind {
check(i in 0..2) { "Incorrect number of receivers ($i) for property reference: ${expression.render()}" }
val symbols = context.ir.symbols
return PropertyReferenceKind(
symbols.getPropertyReferenceClass(mutable, i, false),
symbols.getPropertyReferenceClass(mutable, i, true),
symbols.reflection.owner.functions.single {
it.name.asString() == (if (mutable) "mutableProperty$i" else "property$i")
}
)
}
private fun propertyReferenceKindFor(expression: IrCallableReference<*>): PropertyReferenceKind =
expression.getter?.owner?.let {
val boundReceivers = listOfNotNull(expression.dispatchReceiver, expression.extensionReceiver).size
val needReceivers = listOfNotNull(it.dispatchReceiverParameter, it.extensionReceiverParameter).size
// PropertyReference1 will swap the receivers if bound with the extension one, and PropertyReference0
// has no way to bind two receivers at once.
check(boundReceivers < 2 && (expression.extensionReceiver == null || needReceivers < 2)) {
"Property reference with two receivers is not supported: ${expression.render()}"
}
propertyReferenceKind(expression, expression.setter != null, needReceivers - boundReceivers)
} ?: expression.field?.owner?.let {
propertyReferenceKind(expression, !it.isFinal, if (it.isStatic || expression.dispatchReceiver != null) 0 else 1)
} ?: throw AssertionError("property has no getter and no field: ${expression.dump()}")
private data class PropertyInstance(val initializer: IrExpression, val index: Int)
private inner class ClassData(val irClass: IrClass, val parent: ClassData?) {
val kProperties = mutableMapOf<IrSymbol, PropertyInstance>()
val kPropertiesField = context.irFactory.buildField {
name = Name.identifier(JvmAbi.DELEGATED_PROPERTIES_ARRAY_NAME)
type = kPropertiesFieldType
origin = JvmLoweredDeclarationOrigin.GENERATED_PROPERTY_REFERENCE
isFinal = true
isStatic = true
visibility =
if (irClass.isInterface && context.state.jvmDefaultMode.forAllMethodsWithBody) DescriptorVisibilities.PUBLIC else JavaDescriptorVisibilities.PACKAGE_VISIBILITY
}
val localProperties = mutableListOf<IrLocalDelegatedPropertySymbol>()
val localPropertyIndices = mutableMapOf<IrSymbol, Int>()
val isSynthetic = irClass.metadata !is MetadataSource.File && irClass.metadata !is MetadataSource.Class &&
irClass.metadata !is MetadataSource.Script
fun localPropertyIndex(getter: IrSymbol): Int? =
localPropertyIndices[getter] ?: parent?.localPropertyIndex(getter)
fun localPropertyOwner(getter: IrSymbol): IrClass? =
if (getter in localPropertyIndices) irClass else parent?.localPropertyOwner(getter)
fun rememberLocalProperty(property: IrLocalDelegatedProperty) {
// Prefer to attach metadata to non-synthetic classes, because it won't be serialized otherwise;
// if not possible, though, putting it right here will at least allow non-reflective uses.
val metadataOwner = generateSequence(this) { it.parent }.find { !it.isSynthetic } ?: this
metadataOwner.localPropertyIndices[property.getter.symbol] = metadataOwner.localProperties.size
metadataOwner.localProperties.add(property.symbol)
}
}
private var currentClassData: ClassData? = null
override fun lower(irFile: IrFile) =
irFile.transformChildrenVoid()
override fun visitClassNew(declaration: IrClass): IrStatement {
val data = ClassData(declaration, currentClassData)
currentClassData = data
declaration.transformChildrenVoid()
currentClassData = data.parent
// Put the new field at the beginning so that static delegated properties with initializers work correctly.
// Since we do not cache property references with bound receivers, the new field does not reference anything else.
if (data.kProperties.isNotEmpty()) {
declaration.declarations.add(0, data.kPropertiesField.apply {
parent = declaration
initializer = context.createJvmIrBuilder(data.kPropertiesField.symbol).run {
val initializers = data.kProperties.values.sortedBy { it.index }.map { it.initializer }
irExprBody(irArrayOf(kPropertiesFieldType, initializers))
}
})
}
if (data.localProperties.isNotEmpty()) {
context.localDelegatedProperties[declaration.attributeOwnerId] = data.localProperties
}
return declaration
}
override fun visitLocalDelegatedProperty(declaration: IrLocalDelegatedProperty): IrStatement {
currentClassData!!.rememberLocalProperty(declaration)
return super.visitLocalDelegatedProperty(declaration)
}
override fun visitPropertyReference(expression: IrPropertyReference): IrExpression =
cachedKProperty(expression)
override fun visitLocalDelegatedPropertyReference(expression: IrLocalDelegatedPropertyReference): IrExpression =
cachedKProperty(expression)
private fun IrSimpleFunction.usesParameter(index: Int): Boolean {
parentClassId?.let { containerId ->
// This function was imported from a jar. Didn't run the inline class lowering yet though - have to map manually.
val replaced = context.inlineClassReplacements.getReplacementFunction(this) ?: this
val signature = context.defaultMethodSignatureMapper.mapSignatureSkipGeneric(replaced)
val localIndex = signature.valueParameters.take(index + if (replaced.extensionReceiverParameter != null) 1 else 0)
.sumOf { it.asmType.size } + (if (replaced.dispatchReceiverParameter != null) 1 else 0)
// Null checks are removed during inlining, so we can ignore them.
return loadCompiledInlineFunction(containerId, signature.asmMethod, isSuspend, hasMangledReturnType, context.state)
.node.usesLocalExceptParameterNullCheck(localIndex)
}
return hasChild { it is IrGetValue && it.symbol == valueParameters[index].symbol }
}
// Assuming that the only functions that take PROPERTY_REFERENCE_FOR_DELEGATE-kind references are getValue,
// setValue, and provideDelegate, there is only one valid index for each symbol, so we don't need it in the key.
private val usesPropertyParameterCache = ConcurrentHashMap<IrSymbol, Boolean>()
override fun visitCall(expression: IrCall): IrExpression {
// Don't generate entries in `$$delegatedProperties` if they won't be used for anything. This is only possible
// for inline functions, since for non-inline ones we need to provide some non-null value, and if they're not
// in the same file, they can start using it without forcing a recompilation of this file.
if (!expression.symbol.owner.isInline) return super.visitCall(expression)
for (index in expression.symbol.owner.valueParameters.indices) {
val value = expression.getValueArgument(index)
if (value is IrCallableReference<*> && value.origin == IrStatementOrigin.PROPERTY_REFERENCE_FOR_DELEGATE) {
val resolved = expression.symbol.owner.resolveFakeOverride() ?: expression.symbol.owner
if (!usesPropertyParameterCache.getOrPut(resolved.symbol) { resolved.usesParameter(index) }) {
expression.putValueArgument(index, IrConstImpl.constNull(value.startOffset, value.endOffset, value.type))
}
}
}
return super.visitCall(expression)
}
private fun cachedKProperty(expression: IrCallableReference<*>): IrExpression {
expression.transformChildrenVoid()
if (expression.origin == REFLECTED_PROPERTY_REFERENCE)
return createReflectedKProperty(expression)
if (expression.origin != IrStatementOrigin.PROPERTY_REFERENCE_FOR_DELEGATE)
return createSpecializedKProperty(expression)
val data = currentClassData ?: throw AssertionError("property reference not in class: ${expression.render()}")
// For delegated properties, the getter and setter contain a reference each as the second argument to getValue
// and setValue. Since it's highly unlikely that anyone will call get/set on these, optimize for space.
return context.createIrBuilder(currentScope!!.scope.scopeOwnerSymbol, expression.startOffset, expression.endOffset).run {
val (_, index) = data.kProperties.getOrPut(expression.symbol) {
PropertyInstance(createReflectedKProperty(expression), data.kProperties.size)
}
irCall(arrayItemGetter).apply {
dispatchReceiver = irGetField(null, data.kPropertiesField)
putValueArgument(0, irInt(index))
}
}
}
// Create an instance of KProperty that uses Java reflection to locate the getter and the setter. This kind of reference
// does not support local variables and is slower, but takes up less space in the output binary.
// Example: `C::property` -> `Reflection.property1(PropertyReference1Impl(C::class, "property", "getProperty()LType;"))`.
private fun createReflectedKProperty(expression: IrCallableReference<*>): IrExpression {
val boundReceiver = expression.getBoundReceiver()
if (boundReceiver != null && !useOptimizedSuperClass) {
// Pre-1.4 reflected property reference constructors do not allow bound receivers.
return createSpecializedKProperty(expression)
}
val referenceKind = propertyReferenceKindFor(expression)
return context.createJvmIrBuilder(currentScope!!, expression).run {
val arity = when {
boundReceiver != null -> 5 // (receiver, jClass, name, desc, flags)
useOptimizedSuperClass -> 4 // (jClass, name, desc, flags)
else -> 3 // (kClass, name, desc)
}
val instance = irCall(referenceKind.implSymbol.constructors.single { it.owner.valueParameters.size == arity }).apply {
fillReflectedPropertyArguments(this, expression, boundReceiver)
}
irCall(referenceKind.wrapper).apply { putValueArgument(0, instance) }
}
}
private fun JvmIrBuilder.fillReflectedPropertyArguments(
call: IrFunctionAccessExpression,
expression: IrCallableReference<*>,
receiver: IrExpression?,
) {
val container = expression.propertyContainer
val containerClass = if (useOptimizedSuperClass) kClassToJavaClass(calculateOwnerKClass(container)) else calculateOwner(container)
var index = 0
receiver?.let { call.putValueArgument(index++, it) }
call.putValueArgument(index++, containerClass)
call.putValueArgument(index++, irString((expression.symbol.owner as IrDeclarationWithName).name.asString()))
call.putValueArgument(index++, computeSignatureString(expression))
if (useOptimizedSuperClass) {
val isPackage = (container is IrClass && container.isFileClass) || container is IrPackageFragment
call.putValueArgument(index, irInt((if (isPackage) 1 else 0) or (if (expression.isJavaSyntheticPropertyReference) 2 else 0)))
}
}
private val IrCallableReference<*>.isJavaSyntheticPropertyReference: Boolean
get() =
symbol.owner.let {
it is IrProperty && it.backingField == null &&
(it.origin == IrDeclarationOrigin.SYNTHETIC_JAVA_PROPERTY_DELEGATE
|| it.origin == IrDeclarationOrigin.IR_EXTERNAL_JAVA_DECLARATION_STUB)
}
// Create an instance of KProperty that overrides the get() and set() methods to directly call getX() and setX() on the object.
// This is (relatively) fast, but space-inefficient. Also, the instances can store bound receivers in their fields. Example:
//
// class C$property$0 : PropertyReference0Impl {
// constructor(boundReceiver: C) : super(boundReceiver, C::class.java, "property", "getProperty()LType;", 0)
// override fun get(): T = receiver.property
// override fun set(value: T) { receiver.property = value }
// }
//
// and then `C()::property` -> `C$property$0(C())`.
//
private fun createSpecializedKProperty(expression: IrCallableReference<*>): IrExpression {
// We do not reuse classes for non-reflective property references because they would not have
// a valid enclosing method if the same property is referenced at many points.
val referenceClass = createKPropertySubclass(expression)
return context.createIrBuilder(currentScope!!.scope.scopeOwnerSymbol, expression.startOffset, expression.endOffset).irBlock {
+referenceClass
+irCall(referenceClass.constructors.single()).apply {
expression.getBoundReceiver()?.let { putValueArgument(0, it) }
}
}
}
private fun createKPropertySubclass(expression: IrCallableReference<*>): IrClass {
val kind = propertyReferenceKindFor(expression)
val superClass = if (useOptimizedSuperClass) kind.implSymbol.owner else kind.interfaceSymbol.owner
val referenceClass = context.irFactory.buildClass {
setSourceRange(expression)
name = SpecialNames.NO_NAME_PROVIDED
origin = JvmLoweredDeclarationOrigin.GENERATED_PROPERTY_REFERENCE
visibility = DescriptorVisibilities.LOCAL
}.apply {
parent = currentDeclarationParent!!
superTypes = listOf(superClass.defaultType)
createImplicitParameterDeclarationWithWrappedDescriptor()
}.copyAttributes(expression)
addConstructor(expression, referenceClass, superClass)
if (!useOptimizedSuperClass) {
val getName = superClass.functions.single { it.name.asString() == "getName" }
val getOwner = superClass.functions.single { it.name.asString() == "getOwner" }
val getSignature = superClass.functions.single { it.name.asString() == "getSignature" }
referenceClass.addOverride(getName) { irString((expression.symbol.owner as IrDeclarationWithName).name.asString()) }
referenceClass.addOverride(getOwner) { calculateOwner(expression.propertyContainer) }
referenceClass.addOverride(getSignature) { computeSignatureString(expression) }
}
val boundReceiver = expression.getBoundReceiver()
val get = superClass.functions.find { it.name.asString() == "get" }
val set = superClass.functions.find { it.name.asString() == "set" }
val invoke = superClass.functions.find { it.name.asString() == "invoke" }
val field = expression.field?.owner
if (field == null) {
fun IrBuilderWithScope.setCallArguments(call: IrCall, arguments: List<IrValueParameter>) {
val backingField =
with(FunctionReferenceLowering) { referenceClass.getReceiverField([email protected]) }
val receiverFromField = boundReceiver?.let { irImplicitCast(irGetField(irGet(arguments[0]), backingField), it.type) }
if (expression.isJavaSyntheticPropertyReference) {
assert(call.typeArgumentsCount == 0) { "Unexpected type arguments: ${call.typeArgumentsCount}" }
} else {
call.copyTypeArgumentsFrom(expression)
}
call.dispatchReceiver = call.symbol.owner.dispatchReceiverParameter?.let {
receiverFromField ?: irImplicitCast(irGet(arguments[1]), expression.receiverType)
}
call.extensionReceiver = call.symbol.owner.extensionReceiverParameter?.let {
if (call.symbol.owner.dispatchReceiverParameter == null)
receiverFromField ?: irImplicitCast(irGet(arguments[1]), it.type)
else
irImplicitCast(irGet(arguments[if (receiverFromField != null) 1 else 2]), it.type)
}
}
expression.getter?.owner?.let { getter ->
referenceClass.addOverride(get!!) { arguments ->
irGet(getter.returnType, null, getter.symbol).apply {
setCallArguments(this, arguments)
}
}
referenceClass.addFakeOverride(invoke!!)
}
expression.setter?.owner?.let { setter ->
referenceClass.addOverride(set!!) { arguments ->
irSet(setter.returnType, null, setter.symbol, irGet(arguments.last())).apply {
setCallArguments(this, arguments)
}
}
}
} else {
fun IrBuilderWithScope.fieldReceiver(arguments: List<IrValueParameter>) = when {
field.isStatic ->
null
expression.dispatchReceiver != null -> {
val backingField =
with(FunctionReferenceLowering) { referenceClass.getReceiverField([email protected]) }
irImplicitCast(irGetField(irGet(arguments[0]), backingField), expression.receiverType)
}
else ->
irImplicitCast(irGet(arguments[1]), expression.receiverType)
}
referenceClass.addOverride(get!!) { arguments ->
irGetField(fieldReceiver(arguments), field)
}
if (!field.isFinal) {
referenceClass.addOverride(set!!) { arguments ->
irSetField(fieldReceiver(arguments), field, irGet(arguments.last()))
}
}
}
return referenceClass
}
private fun addConstructor(expression: IrCallableReference<*>, referenceClass: IrClass, superClass: IrClass) {
val hasBoundReceiver = expression.getBoundReceiver() != null
val numOfSuperArgs =
(if (hasBoundReceiver) 1 else 0) + (if (useOptimizedSuperClass) 4 else 0)
val superConstructor = superClass.constructors.single { it.valueParameters.size == numOfSuperArgs }
if (!useOptimizedSuperClass) {
referenceClass.addSimpleDelegatingConstructor(superConstructor, context.irBuiltIns, isPrimary = true)
return
}
referenceClass.addConstructor {
origin = JvmLoweredDeclarationOrigin.GENERATED_MEMBER_IN_CALLABLE_REFERENCE
isPrimary = true
}.apply {
val receiverParameter = if (hasBoundReceiver) addValueParameter("receiver", context.irBuiltIns.anyNType) else null
body = context.createJvmIrBuilder(symbol).run {
irBlockBody(startOffset, endOffset) {
+irDelegatingConstructorCall(superConstructor).apply {
fillReflectedPropertyArguments(this, expression, receiverParameter?.let(::irGet))
}
+IrInstanceInitializerCallImpl(startOffset, endOffset, referenceClass.symbol, context.irBuiltIns.unitType)
}
}
}
}
// In `value::x`, using `value`'s type is fine; but in `C::x`, the type of the receiver has to be `C`.
// This is *not* the type of `x`'s dispatch receiver if `x` is declared in a superclass of `C`, so we
// extract `C` from the reference's type, which is either `KProperty1<C, R>` or `KProperty2<C, Extension, R>`.
private val IrCallableReference<*>.receiverType
get() = dispatchReceiver?.type ?: ((type as IrSimpleType).arguments.first() as IrTypeProjection).type
private fun IrCallableReference<*>.getBoundReceiver(): IrExpression? {
val callee = symbol.owner
return if (callee is IrDeclaration && callee.isJvmStaticInObject()) {
// See FunctionReferenceLowering.FunctionReferenceBuilder.createFakeBoundReceiverForJvmStaticInObject.
val objectClass = callee.parentAsClass
IrGetObjectValueImpl(UNDEFINED_OFFSET, UNDEFINED_OFFSET, objectClass.typeWith(), objectClass.symbol)
} else dispatchReceiver ?: extensionReceiver
}
}
| 7 | null | 5771 | 49,172 | 33eb9cef3d146062c103f9853d772f0a1da0450e | 29,809 | kotlin | Apache License 2.0 |
src/main/java/ru/hollowhorizon/hollowengine/common/scripting/mod/ModScriptBase.kt | HollowHorizon | 586,593,959 | false | {"Kotlin": 945627, "Java": 23246, "GLSL": 2628} | /*
* MIT License
*
* Copyright (c) 2024 HollowHorizon
*
* 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 ru.hollowhorizon.hollowengine.common.scripting.mod
import net.minecraftforge.common.MinecraftForge
import net.minecraftforge.eventbus.api.IEventBus
import net.minecraftforge.fml.loading.FMLEnvironment
import ru.hollowhorizon.hollowengine.HollowEngine
import ru.hollowhorizon.hollowengine.common.scripting.story.ForgeEvent
import ru.hollowhorizon.hollowengine.common.scripting.story.IForgeEventScriptSupport
abstract class ModScriptBase : IForgeEventScriptSupport {
override val forgeEvents = HashSet<ForgeEvent<*>>()
val FORGE_BUS: IEventBus = MinecraftForge.EVENT_BUS
val MOD_BUS: IEventBus = HollowEngine.MOD_BUS
val dist = FMLEnvironment.dist
abstract fun init()
} | 0 | Kotlin | 6 | 27 | a81eb9337c22e97c950528d2e5b638ff81ce2d2e | 1,835 | HollowEngine | MIT License |
baseKit/src/main/java/me/shetj/base/tools/app/Tim.kt | SheTieJun | 137,007,462 | false | {"Kotlin": 841510, "Java": 165162} | package me.shetj.base.tools.app
import android.util.Log
import timber.log.Timber
import java.io.File
object Tim {
private val LOG_FILE_PATH = Utils.app.externalCacheDir?.path + File.separator + "baseLog.test"
/**
* 设置log自动在debug打开,在release关闭
* @param isDebug
*/
fun setLogAuto(isDebug: Boolean) {
Timber.uprootAll()
// 打印关,同时gradle中的release的debuggable要设置为false
if (isDebug) {
Timber.plant(Timber.DebugTree())
} else { // release版本
Timber.plant(CrashReportingTree())
}
}
/**
* 设置log自动,并且想在release时仅在测试时有打印,
* 在release版本时增加判断磁盘目录下是否存在文件 baseLog.test,
* 测试时让测试人员在磁盘目录下建立这么个文件。
* 注意,如果读取存储需要权限申请的话,需要先获得权限,才能调用
*/
fun setLogAutoEx(isDebug: Boolean) {
if (isDebug) { // debug版本
Timber.plant(Timber.DebugTree())
} else { // release版本
val logFile = File(LOG_FILE_PATH)
if (logFile.exists()) {
// 打印开
Timber.plant(Timber.DebugTree())
} else {
// 打印关,同时gradle中的release的debuggable要设置为false
Timber.plant(CrashReportingTree())
}
}
}
private class CrashReportingTree : Timber.Tree() {
override fun log(priority: Int, tag: String?, message: String, t: Throwable?) {
if (priority == Log.VERBOSE || priority == Log.DEBUG) {
return
}
if (t != null) {
when (priority) {
Log.ERROR -> {
Log.e(tag, message)
}
Log.WARN -> {
// FakeCrashLibrary.logWarning(t);
}
else -> {
}
}
}
}
}
fun getTag(o: Any): String {
return if (o is Class<*>) o.simpleName else o.javaClass.simpleName
}
}
| 1 | Kotlin | 1 | 7 | b6935cc5983d32b51dc7c4850dd1e8f63a38a75b | 1,951 | BaseKit | MIT License |
src/main/kotlin/com/wutsi/flutter/sdui/Chip.kt | wutsi | 415,658,640 | false | null | package com.wutsi.flutter.sdui
import com.wutsi.flutter.sdui.enums.WidgetType
class Chip(
val color: String? = null,
val backgroundColor: String? = null,
val caption: String? = null,
val shadowColor: String? = null,
val padding: Double? = null,
val elevation: Double? = null,
val fontSize: Double? = null,
val id: String? = null,
) : WidgetAware {
override fun toWidget() = Widget(
type = WidgetType.Chip,
attributes = mapOf(
"id" to id,
"color" to color,
"padding" to padding,
"elevation" to elevation,
"shadowColor" to shadowColor,
"backgroundColor" to backgroundColor,
"caption" to caption,
"fontSize" to fontSize,
),
)
}
| 1 | Kotlin | 1 | 2 | 0e39b6120b9cb6e8acf35c5d4d86cf95e75ebfae | 787 | sdui-kotlin | MIT License |
wasi-emscripten-host/src/commonMain/kotlin/wasi/preview1/type/EventFdReadwrite.kt | illarionov | 769,429,996 | false | null | /*
* Copyright 2024, the wasm-sqlite-open-helper project authors and contributors. Please see the AUTHORS file
* for details. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
* SPDX-License-Identifier: Apache-2.0
*/
package ru.pixnews.wasm.sqlite.open.helper.host.wasi.preview1.type
import ru.pixnews.wasm.sqlite.open.helper.host.WasmValueType
/**
* The type for the `dirent::d_namlen` field of `dirent` struct.
*/
@JvmInline
public value class Dirnamlen(
public val rawValue: UInt,
) {
public companion object : WasiTypename {
public override val wasmValueType: WasmValueType = WasiValueTypes.U32
}
}
| 0 | null | 0 | 3 | 546dc6fce69d2d3704ddf34939ab498931b2d047 | 683 | wasm-sqlite-open-helper | Apache License 2.0 |
camera/integration-tests/extensionstestapp/src/main/java/androidx/camera/integration/extensions/utils/PermissionUtil.kt | androidx | 256,589,781 | false | {"Kotlin": 112114129, "Java": 66594571, "C++": 9132142, "AIDL": 635065, "Python": 325169, "Shell": 194520, "TypeScript": 40647, "HTML": 35176, "Groovy": 27178, "ANTLR": 26700, "Svelte": 20397, "CMake": 15512, "C": 15043, "GLSL": 3842, "Swift": 3153, "JavaScript": 3019} | /*
* Copyright 2024 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.camera.integration.extensions.utils
import android.Manifest
import android.app.Activity
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Build
import android.util.Log
import android.util.Pair
import androidx.camera.integration.extensions.PERMISSIONS_REQUEST_CODE
import androidx.concurrent.futures.CallbackToFutureAdapter
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.common.util.concurrent.ListenableFuture
private const val TAG = "PermissionUtil"
/** Permissions setup utility. */
object PermissionUtil {
/** Setup required permissions. */
@JvmStatic
fun setupPermissions(
activity: Activity
): Pair<ListenableFuture<Boolean>, CallbackToFutureAdapter.Completer<Boolean>> {
var permissionCompleter: CallbackToFutureAdapter.Completer<Boolean>? = null
val future =
CallbackToFutureAdapter.getFuture {
completer: CallbackToFutureAdapter.Completer<Boolean> ->
permissionCompleter = completer
if (!allPermissionsGranted(activity)) {
makePermissionRequest(activity)
} else {
permissionCompleter!!.set(true)
}
"get_permissions"
}
return Pair.create(future, permissionCompleter!!)
}
private fun makePermissionRequest(activity: Activity) {
ActivityCompat.requestPermissions(
activity,
getRequiredPermissions(activity),
PERMISSIONS_REQUEST_CODE
)
}
/** Returns true if all the necessary permissions have been granted already. */
private fun allPermissionsGranted(activity: Activity): Boolean {
for (permission in getRequiredPermissions(activity)) {
if (
ContextCompat.checkSelfPermission(activity, permission!!) !=
PackageManager.PERMISSION_GRANTED
) {
return false
}
}
return true
}
/** Tries to acquire all the necessary permissions through a dialog. */
private fun getRequiredPermissions(activity: Activity): Array<String?> {
val info: PackageInfo
try {
info =
activity.packageManager.getPackageInfo(
activity.packageName,
PackageManager.GET_PERMISSIONS
)
} catch (exception: PackageManager.NameNotFoundException) {
Log.e(TAG, "Failed to obtain all required permissions.", exception)
return arrayOfNulls(0)
}
if (info.requestedPermissions == null || info.requestedPermissions.isEmpty()) {
return arrayOfNulls(0)
}
val requiredPermissions: MutableList<String?> = mutableListOf()
// From Android T, skips the permission check of WRITE_EXTERNAL_STORAGE since it won't be
// granted any more. When querying the requested permissions from PackageManager,
// READ_EXTERNAL_STORAGE will also be included if we specify WRITE_EXTERNAL_STORAGE
// requirement in AndroidManifest.xml. Therefore, also need to skip the permission check
// of READ_EXTERNAL_STORAGE.
for (permission in info.requestedPermissions) {
if (
Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
(Manifest.permission.WRITE_EXTERNAL_STORAGE == permission ||
Manifest.permission.READ_EXTERNAL_STORAGE == permission)
) {
continue
}
requiredPermissions.add(permission)
}
val permissions = requiredPermissions.toTypedArray<String?>()
return if (permissions.isNotEmpty()) {
permissions
} else {
arrayOfNulls(0)
}
}
}
| 29 | Kotlin | 1011 | 5,321 | 98b929d303f34d569e9fd8a529f022d398d1024b | 4,540 | androidx | Apache License 2.0 |
app/src/main/java/com/sakebook/android/nexustimer/model/Week.kt | sakebook | 60,192,310 | false | null | package com.sakebook.android.nexustimer.model
/**
* Created by sakemotoshinya on 16/06/08.
*/
enum class Week(val id: Long) {
Sun(10),
Mon(11),
Tue(12),
Wed(13),
Thu(14),
Fri(15),
Sat(16),
;
var enable = false
fun label(): String {
return when(enable) {
true -> "ON"
false -> "OFF"
}
}
} | 1 | Kotlin | 0 | 0 | c4a583de795c4c4c2127fbc0148bd3c58024642c | 376 | NexusTimer | Apache License 2.0 |
fxgl/src/main/kotlin/com/almasb/fxgl/scene/ProgressDialog.kt | Ravanla | 205,673,093 | false | null | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB (<EMAIL>).
* See LICENSE for details.
*/
package com.almasb.fxgl.app
import com.almasb.fxgl.core.concurrent.IOTask
import com.almasb.fxgl.dsl.FXGL
import com.almasb.fxgl.ui.DialogBox
/**
*
*
* @author <NAME> (<EMAIL>)
*/
class ProgressDialog(val message: String) : IOTask.UIDialogHandler {
private lateinit var dialog: DialogBox
override fun show() {
dialog = FXGL.getDisplay().showProgressBox(message)
}
override fun dismiss() {
dialog.close()
}
} | 0 | null | 0 | 1 | 25433dbdebb4c358eabe622063fac0ccc8a910f6 | 577 | FXGL | MIT License |
noty-android/app/composeapp/src/androidTest/java/dev/shreyaspatil/noty/composeapp/component/ConnectivityStatusTest.kt | PatilShreyas | 303,164,275 | false | {"Kotlin": 494618, "Procfile": 59} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shreyaspatil.noty.composeapp.component
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.onNodeWithText
import dev.shreyaspatil.noty.composeapp.NotyComposableTest
import org.junit.Test
class ConnectivityStatusTest : NotyComposableTest() {
@Test
fun testNoConnectivity() = runTest {
setContent {
ConnectivityStatus(isConnected = false)
}
onNodeWithText("No Internet Connection!").assertIsDisplayed()
}
@Test
fun testConnectivityBackAfterNoConnectivity() = runTest {
var isConnected by mutableStateOf(false)
setContent {
ConnectivityStatus(isConnected = isConnected)
}
// First, no connectivity should be displayed
onNodeWithText("No Internet Connection!").assertIsDisplayed()
// Bring connectivity back
isConnected = true
onNodeWithText("No Internet Connection!").assertDoesNotExist()
onNodeWithText("Back Online!").assertIsDisplayed()
// Wait for 2 seconds
mainClock.advanceTimeBy(2000)
// Status should be vanished
onNodeWithText("Back Online!").assertDoesNotExist()
}
}
| 16 | Kotlin | 243 | 1,705 | 35d18480fe22904e68c25233eb704f97ae9b6200 | 1,920 | NotyKT | Apache License 2.0 |
noty-android/app/composeapp/src/androidTest/java/dev/shreyaspatil/noty/composeapp/component/ConnectivityStatusTest.kt | PatilShreyas | 303,164,275 | false | {"Kotlin": 494618, "Procfile": 59} | /*
* Copyright 2020 <NAME>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.shreyaspatil.noty.composeapp.component
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.compose.ui.test.assertIsDisplayed
import androidx.compose.ui.test.onNodeWithText
import dev.shreyaspatil.noty.composeapp.NotyComposableTest
import org.junit.Test
class ConnectivityStatusTest : NotyComposableTest() {
@Test
fun testNoConnectivity() = runTest {
setContent {
ConnectivityStatus(isConnected = false)
}
onNodeWithText("No Internet Connection!").assertIsDisplayed()
}
@Test
fun testConnectivityBackAfterNoConnectivity() = runTest {
var isConnected by mutableStateOf(false)
setContent {
ConnectivityStatus(isConnected = isConnected)
}
// First, no connectivity should be displayed
onNodeWithText("No Internet Connection!").assertIsDisplayed()
// Bring connectivity back
isConnected = true
onNodeWithText("No Internet Connection!").assertDoesNotExist()
onNodeWithText("Back Online!").assertIsDisplayed()
// Wait for 2 seconds
mainClock.advanceTimeBy(2000)
// Status should be vanished
onNodeWithText("Back Online!").assertDoesNotExist()
}
}
| 16 | Kotlin | 243 | 1,705 | 35d18480fe22904e68c25233eb704f97ae9b6200 | 1,920 | NotyKT | Apache License 2.0 |
dd-sdk-android/src/main/kotlin/com/datadog/android/rum/internal/instrumentation/GesturesTrackingStrategy.kt | slicelife | 366,814,258 | false | null | /*
* Unless explicitly stated otherwise all files in this repository are licensed under the Apache License Version 2.0.
* This product includes software developed at Datadog (https://www.datadoghq.com/).
* Copyright 2016-Present Datadog, Inc.
*/
package com.datadog.android.rum.internal.instrumentation
import android.app.Activity
import com.datadog.android.rum.internal.instrumentation.gestures.GesturesTracker
import com.datadog.android.rum.internal.tracking.UserActionTrackingStrategy
import com.datadog.android.rum.tracking.ActivityLifecycleTrackingStrategy
internal class GesturesTrackingStrategy(
internal val gesturesTracker: GesturesTracker
) :
ActivityLifecycleTrackingStrategy(),
UserActionTrackingStrategy {
override fun onActivityResumed(activity: Activity) {
super.onActivityResumed(activity)
gesturesTracker.startTracking(activity.window, activity)
}
override fun onActivityPaused(activity: Activity) {
super.onActivityPaused(activity)
gesturesTracker.stopTracking(activity.window, activity)
}
}
| 0 | Kotlin | 0 | 0 | e2b11f61f57f7a6e55a4d1de299e30f6c4e8d237 | 1,078 | dd-sdk-android-1.8.0-maven | Apache License 2.0 |
core/designsystem/src/test/kotlin/com/merxury/blocker/core/designsystem/BackgroundScreenshotTests.kt | lihenggui | 115,417,337 | false | null | /*
* Copyright 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.google.samples.apps.nowinandroid.core.designsystem
import androidx.activity.ComponentActivity
import androidx.compose.foundation.layout.size
import androidx.compose.material3.Text
import androidx.compose.ui.Modifier
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import androidx.compose.ui.unit.dp
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaBackground
import com.google.samples.apps.nowinandroid.core.designsystem.component.NiaGradientBackground
import com.google.samples.apps.nowinandroid.core.testing.util.captureMultiTheme
import dagger.hilt.android.testing.HiltTestApplication
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
import org.robolectric.annotation.LooperMode
@RunWith(RobolectricTestRunner::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(application = HiltTestApplication::class, qualifiers = "480dpi")
@LooperMode(LooperMode.Mode.PAUSED)
class BackgroundScreenshotTests {
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@Test
fun niaBackground_multipleThemes() {
composeTestRule.captureMultiTheme("Background") { description ->
NiaBackground(Modifier.size(100.dp)) {
Text("$description background")
}
}
}
@Test
fun niaGradientBackground_multipleThemes() {
composeTestRule.captureMultiTheme("Background", "GradientBackground") { description ->
NiaGradientBackground(Modifier.size(100.dp)) {
Text("$description background")
}
}
}
}
| 25 | null | 54 | 988 | 9696c391c64d1aa4a74384d22b4433fb7c67c890 | 2,372 | blocker | Apache License 2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.