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
matrix-sdk-android/src/main/java/org/matrix/android/sdk/api/session/room/model/message/MessageVerificationReadyContent.kt
matrix-org
287,466,066
false
null
/* * Copyright 2020 The Matrix.org Foundation C.I.C. * * 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.wormhole.android.sdk.api.session.room.model.message import com.squareup.moshi.Json import com.squareup.moshi.JsonClass import org.wormhole.android.sdk.api.session.events.model.RelationType import org.wormhole.android.sdk.api.session.events.model.toContent import org.wormhole.android.sdk.api.session.room.model.relation.RelationDefaultContent import org.wormhole.android.sdk.internal.crypto.verification.MessageVerificationReadyFactory import org.wormhole.android.sdk.internal.crypto.verification.VerificationInfoReady @JsonClass(generateAdapter = true) internal data class MessageVerificationReadyContent( @Json(name = "from_device") override val fromDevice: String? = null, @Json(name = "methods") override val methods: List<String>? = null, @Json(name = "m.relates_to") val relatesTo: RelationDefaultContent? ) : VerificationInfoReady { override val transactionId: String? get() = relatesTo?.eventId override fun toEventContent() = toContent() companion object : MessageVerificationReadyFactory { override fun create(tid: String, methods: List<String>, fromDevice: String): VerificationInfoReady { return MessageVerificationReadyContent( fromDevice = fromDevice, methods = methods, relatesTo = RelationDefaultContent( RelationType.REFERENCE, tid ) ) } } }
75
null
27
97
55cc7362de34a840c67b4bbb3a14267bc8fd3b9c
2,112
matrix-android-sdk2
Apache License 2.0
triad-core/src/test/java/com/nhaarman/triad/TriadDelegateTest.kt
nhaarman
31,015,663
false
null
/* * Copyright 2016 <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.nhaarman.triad import android.app.Activity import android.app.Application import android.view.ViewGroup import com.nhaarman.mockito_kotlin.any import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.never import com.nhaarman.mockito_kotlin.whenever import org.junit.Before import org.junit.Test import org.mockito.Mock import org.mockito.Mockito import org.mockito.Mockito.verify import org.mockito.MockitoAnnotations.initMocks class TriadDelegateTest { @Mock private lateinit var activity: Activity private var mApplication: Application? = null @Mock private lateinit var mListener: Triad.Listener<Any> @Mock private lateinit var mScreen1: Screen<Any> @Mock private lateinit var mScreen2: Screen<Any> @Before fun setup() { initMocks(this) mApplication = Mockito.mock(Application::class.java, Mockito.withSettings().extraInterfaces(TriadProvider::class.java, ApplicationComponentProvider::class.java)) whenever(activity.application).thenReturn(mApplication) whenever(activity.findViewById(any())).thenReturn(mock<ViewGroup>()) whenever(mScreen2.createView(any())).thenReturn(mock()) } @Test fun onDestroy_finishing_notifiesBackstackScreenPopped() { /* Given */ whenever(activity.isFinishing).thenReturn(true) val delegate = TriadDelegate<Any>(activity, mock()) whenever((mApplication as TriadProvider).triad).thenReturn(TriadFactory.newInstance(Backstack.of(mScreen1, mScreen2), mListener)) delegate.onCreate() /* When */ delegate.onDestroy() /* Then */ verify(mScreen2).onDestroy() verify(mScreen1).onDestroy() } @Test fun onDestroy_notFinishing_doesNotNotifyScreens() { /* Given */ whenever(activity.isFinishing).thenReturn(false) val delegate = TriadDelegate<Any>(activity, mock()) whenever((mApplication as TriadProvider).triad).thenReturn(TriadFactory.newInstance(Backstack.of(mScreen1, mScreen2), mListener)) delegate.onCreate() /* When */ delegate.onDestroy() /* Then */ verify(mScreen2, never()).onDestroy() verify(mScreen1, never()).onDestroy() } }
2
null
6
88
83753e0d6421e12b516e76feaba37224d456f467
2,869
Triad
Apache License 2.0
vico/core/src/main/java/com/patrykandpatrick/vico/core/common/shape/Shape.kt
patrykandpatrick
338,848,755
false
null
/* * Copyright 2024 by <NAME> and <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.patrykandpatrick.vico.core.common.shape import android.graphics.Path import com.patrykandpatrick.vico.core.common.MeasuringContext /** Defines a shape. */ public fun interface Shape { /** * Adds an outline of the [Shape] to [path]. [left], [top], [right], and [bottom] define the * outline bounds. */ public fun outline( context: MeasuringContext, path: Path, left: Float, top: Float, right: Float, bottom: Float, ) public companion object { /** A rectangle with sharp corners. */ public val Rectangle: Shape = Shape { _, path, left, top, right, bottom -> path.moveTo(left, top) path.lineTo(right, top) path.lineTo(right, bottom) path.lineTo(left, bottom) path.close() } } }
12
null
130
2,132
7066e4bf88cdd1e4c57e1ab03d10354e5f640928
1,381
vico
Apache License 2.0
compiler/tests-common-new/tests/org/jetbrains/kotlin/test/frontend/AbstractFailingTestSuppressor.kt
JetBrains
3,432,266
false
null
/* * Copyright 2010-2022 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.test.frontend import org.jetbrains.kotlin.test.WrappedException import org.jetbrains.kotlin.test.model.AfterAnalysisChecker import org.jetbrains.kotlin.test.services.TestServices import java.io.File abstract class AbstractFailingTestSuppressor(testServices: TestServices) : AfterAnalysisChecker(testServices) { protected abstract fun testFile(): File protected abstract fun hasFailure(failedAssertions: List<WrappedException>): Boolean override fun suppressIfNeeded(failedAssertions: List<WrappedException>): List<WrappedException> { val failFile = testFile().parentFile.resolve("${testFile().nameWithoutExtension}.fail").takeIf { it.exists() } ?: return failedAssertions val failReason = failFile.readText().trim() if (hasFailure(failedAssertions) || failReason == INCONSISTENT_DIAGNOSTICS) return emptyList() return failedAssertions + AssertionError("Fail file exists but no exception was thrown. Please remove ${failFile.name}").wrap() } companion object { const val INCONSISTENT_DIAGNOSTICS = "INCONSISTENT_DIAGNOSTICS" } }
181
null
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
1,349
kotlin
Apache License 2.0
app-home/src/main/java/xiaobo0113/xiaobo/com/app_home/AppHomePipeLineImp.kt
xiaobo0113
146,252,895
false
null
package xiaobo0113.xiaobo.com.app_home import android.content.Context import android.content.Intent import android.os.Bundle class AppHomePipeLineImp : AppHomePipeLine { override fun startAppHomeMainActivity(context: Context, bundle: Bundle) { val intent = Intent(context, AppHomeMainActivity::class.java) intent.putExtras(bundle) startActivity(context, intent) } }
0
Kotlin
0
0
46239891af6077afffe46ae68e9c4e5943c70503
400
SingleEntry
Apache License 2.0
src/test/kotlin/io/articulus/fhir/model/dstu3/ClaimResponseDataTest.kt
Articulus-Tech
160,540,104
false
null
package io.articulus.fhir.model.dstu3 import java.io.File import java.lang.SuppressWarnings import kotlin.test.assertEquals import kotlin.test.assertTrue import org.junit.jupiter.api.Test class ClaimResponseDataTest : DataTests() { @Test fun `claimresponse-example 538 Test`() { val json = File("./src/test/resources/model/sample_data/dstu3/claimresponse-example.json").readTextAndClose() val obj = mapper.fromJson(json, ClaimResponse::class.java) assertTrue(stringMatch("ClaimResponse", obj.resourceType)) assertTrue(stringMatch("R3500", obj.id)) assertTrue(stringMatch("generated", obj.text!!.status)) assertTrue(stringMatch("<div xmlns=\"http://www.w3.org", obj.text!!.div)) assertTrue(stringMatch("http://www.BenefitsInc.com/fh", obj.identifier[0].system)) assertTrue(stringMatch("R3500", obj.identifier[0].value)) assertTrue(stringMatch("active", obj.status)) assertTrue(stringMatch("Patient/1", obj.patient!!.reference)) assertTrue(stringMatch("2014-08-16", obj.created)) assertTrue(stringMatch("http://www.jurisdiction.org/i", obj.insurer!!.identifier!!.system)) assertTrue(stringMatch("555123", obj.insurer!!.identifier!!.value)) assertTrue(stringMatch("Practitioner/1", obj.requestProvider!!.reference)) assertTrue(stringMatch("Organization/1", obj.requestOrganization!!.reference)) assertTrue(stringMatch("http://www.BenefitsInc.com/fh", obj.request!!.reference)) assertTrue(stringMatch("http://hl7.org/fhir/remittanc", obj.outcome!!.coding[0].system)) assertTrue(stringMatch("complete", obj.outcome!!.coding[0].code)) assertTrue(stringMatch("Claim settled as per contract", obj.disposition)) assertTrue(stringMatch("http://hl7.org/fhir/payeetype", obj.payeeType!!.coding[0].system)) assertTrue(stringMatch("provider", obj.payeeType!!.coding[0].code)) assertEquals(1, obj.item[0].sequenceLinkId) assertTrue(stringMatch("eligible", obj.item[0].adjudication[0].category.coding[0].code)) assertTrue(stringMatch("%.2f".format(135.57f), "%.2f".format(obj.item[0].adjudication[0].amount!!.value))) assertTrue(stringMatch("urn:iso:std:iso:4217", obj.item[0].adjudication[0].amount!!.system)) assertTrue(stringMatch("USD", obj.item[0].adjudication[0].amount!!.code)) assertTrue(stringMatch("copay", obj.item[0].adjudication[1].category.coding[0].code)) assertTrue(stringMatch("%.2f".format(10.00f), "%.2f".format(obj.item[0].adjudication[1].amount!!.value))) assertTrue(stringMatch("urn:iso:std:iso:4217", obj.item[0].adjudication[1].amount!!.system)) assertTrue(stringMatch("USD", obj.item[0].adjudication[1].amount!!.code)) assertTrue(stringMatch("eligpercent", obj.item[0].adjudication[2].category.coding[0].code)) assertTrue(stringMatch("%.2f".format(80.00f), "%.2f".format(obj.item[0].adjudication[2].value))) assertTrue(stringMatch("benefit", obj.item[0].adjudication[3].category.coding[0].code)) assertTrue(stringMatch("%.2f".format(100.47f), "%.2f".format(obj.item[0].adjudication[3].amount!!.value))) assertTrue(stringMatch("urn:iso:std:iso:4217", obj.item[0].adjudication[3].amount!!.system)) assertTrue(stringMatch("USD", obj.item[0].adjudication[3].amount!!.code)) assertTrue(stringMatch("%.2f".format(135.57f), "%.2f".format(obj.totalCost!!.value))) assertTrue(stringMatch("urn:iso:std:iso:4217", obj.totalCost!!.system)) assertTrue(stringMatch("USD", obj.totalCost!!.code)) assertTrue(stringMatch("%.2f".format(100.47f), "%.2f".format(obj.totalBenefit!!.value))) assertTrue(stringMatch("urn:iso:std:iso:4217", obj.totalBenefit!!.system)) assertTrue(stringMatch("USD", obj.totalBenefit!!.code)) assertTrue(stringMatch("http://hl7.org/fhir/ex-paymen", obj.payment!!.type!!.coding[0].system)) assertTrue(stringMatch("complete", obj.payment!!.type!!.coding[0].code)) assertTrue(stringMatch("2014-08-31", obj.payment!!.date)) assertTrue(stringMatch("%.2f".format(100.47f), "%.2f".format(obj.payment!!.amount!!.value))) assertTrue(stringMatch("urn:iso:std:iso:4217", obj.payment!!.amount!!.system)) assertTrue(stringMatch("USD", obj.payment!!.amount!!.code)) assertTrue(stringMatch("http://www.BenefitsInc.com/fh", obj.payment!!.identifier!!.system)) assertTrue(stringMatch("201408-2-1569478", obj.payment!!.identifier!!.value)) } fun `claimresponse-example Init`(@SuppressWarnings("unused") obj: Bundle) { obj.identifier // No-Op to suprress unused warnings } }
0
Kotlin
0
3
90b7b912048fc61ad3696497d1ceaf76459852cb
4,705
kotlin-fhir-model
Apache License 2.0
harmony-kotlin/src/commonMain/kotlin/com/harmony/kotlin/data/datasource/flow/VoidFlowDataSources.kt
mobilejazz
193,985,847
false
null
package com.harmony.kotlin.data.datasource.flow import com.harmony.kotlin.data.query.Query import kotlinx.coroutines.flow.Flow class VoidFlowDataSource<V> : FlowGetDataSource<V>, FlowPutDataSource<V>, FlowDeleteDataSource { override fun get(query: Query): Flow<V> = throw UnsupportedOperationException() @Deprecated("Use get instead") override fun getAll(query: Query): Flow<List<V>> = throw UnsupportedOperationException() override fun put(query: Query, value: V?): Flow<V> = throw UnsupportedOperationException() @Deprecated("Use put instead") override fun putAll(query: Query, value: List<V>?): Flow<List<V>> = throw UnsupportedOperationException() override fun delete(query: Query) = throw UnsupportedOperationException() } class VoidFlowGetDataSource<V> : FlowGetDataSource<V> { override fun get(query: Query): Flow<V> = throw UnsupportedOperationException() @Deprecated("Use get instead") override fun getAll(query: Query): Flow<List<V>> = throw UnsupportedOperationException() } class VoidFlowPutDataSource<V> : FlowPutDataSource<V> { override fun put(query: Query, value: V?): Flow<V> = throw UnsupportedOperationException() @Deprecated("Use put instead") override fun putAll(query: Query, value: List<V>?): Flow<List<V>> = throw UnsupportedOperationException() } class VoidFlowDeleteDataSource : FlowDeleteDataSource { override fun delete(query: Query) = throw UnsupportedOperationException() }
1
Kotlin
1
12
77fe72f1e62afeac68e28e0a6121b97655b7e3ad
1,443
harmony-kotlin
Apache License 2.0
schema-server-core/src/main/java/com/orbitalhq/schemaServer/core/repositories/FileWorkspaceConfigLoader.kt
orbitalapi
541,496,668
false
{"TypeScript": 9344934, "Kotlin": 5669840, "HTML": 201985, "SCSS": 170620, "HCL": 55741, "Java": 29373, "JavaScript": 24697, "Shell": 8800, "Dockerfile": 7001, "Smarty": 4741, "CSS": 2966, "Mustache": 1392, "Batchfile": 983, "MDX": 884, "PLpgSQL": 337}
package com.orbitalhq.schemaServer.core.repositories import com.google.common.annotations.VisibleForTesting import com.google.common.base.Throwables import com.google.common.collect.Sets import com.orbitalhq.PackageIdentifier import com.orbitalhq.config.ChangeWatchingConfigFileRepository import com.orbitalhq.config.toHocon import com.orbitalhq.schema.publisher.ProjectLoaderManager import com.orbitalhq.schema.publisher.loaders.LoaderStatus import com.orbitalhq.schema.publisher.loaders.ProjectTransportConfig import com.orbitalhq.schemaServer.core.adaptors.InstantHoconSupport import com.orbitalhq.schemaServer.core.adaptors.PackageLoaderSpecHoconSupport import com.orbitalhq.schemaServer.core.adaptors.UriHoconSupport import com.orbitalhq.schemaServer.core.file.FileProjectSpec import com.orbitalhq.schemaServer.core.file.WorkspaceFileProjectConfig import com.orbitalhq.schemaServer.core.git.GitProjectSpec import com.orbitalhq.schemaServer.core.git.WorkspaceGitProjectConfig import com.orbitalhq.schemaServer.core.repositories.lifecycle.FileSpecAddedEvent import com.orbitalhq.schemaServer.core.repositories.lifecycle.FileSpecRemovedEvent import com.orbitalhq.schemaServer.core.repositories.lifecycle.GitSpecAddedEvent import com.orbitalhq.schemaServer.core.repositories.lifecycle.GitSpecRemovedEvent import com.orbitalhq.schemaServer.core.repositories.lifecycle.ProjectSpecLifecycleEventDispatcher import com.orbitalhq.schemaServer.packages.OpenApiPackageLoaderSpec import com.orbitalhq.schemaServer.packages.TaxiPackageLoaderSpec import com.orbitalhq.schemaServer.repositories.FileProjectStoreTestRequest import com.orbitalhq.schemaServer.repositories.FileProjectTestResponse import com.orbitalhq.toPackageMetadata import com.orbitalhq.toVynePackageIdentifier import com.orbitalhq.utils.concat import com.typesafe.config.Config import com.typesafe.config.ConfigFactory import io.github.config4k.extract import io.github.config4k.registerCustomType import lang.taxi.packages.ProjectName import lang.taxi.packages.TaxiPackageLoader import lang.taxi.packages.TaxiPackageProject import lang.taxi.writers.ConfigWriter import mu.KotlinLogging import reactor.core.publisher.Flux import reactor.core.publisher.Mono import reactor.core.publisher.Sinks import reactor.core.publisher.Sinks.EmissionException import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.time.Duration import kotlin.io.path.createDirectories import kotlin.io.path.exists import kotlin.io.path.isDirectory import kotlin.io.path.isRegularFile import kotlin.io.path.writeText class FileWorkspaceConfigLoader( val configFilePath: Path, fallback: Config = ConfigFactory.systemEnvironment(), private val eventDispatcher: ProjectSpecLifecycleEventDispatcher, private val projectManager: ProjectLoaderManager, emitStateOnInit: Boolean = true ) : ChangeWatchingConfigFileRepository<WorkspaceConfig>( configFilePath, fallback ), WorkspaceConfigLoader { private val logger = KotlinLogging.logger {} private var lastConfig: WorkspaceConfig? = null private val stateSink = Sinks.many().replay().latest<LoaderStatus>() override val loaderStatus: Flux<LoaderStatus> = stateSink.asFlux() // .distinctUntilChanged() .doOnNext { status -> logger.info { "File workspace loader at $configFilePath changed state: $status" } } init { registerCustomType(PackageLoaderSpecHoconSupport) registerCustomType(UriHoconSupport) registerCustomType(InstantHoconSupport) stateSink.emitNext(LoaderStatus.STARTING, Sinks.EmitFailureHandler.FAIL_FAST) if (emitStateOnInit) { readCurrentStateAndEmit() } watchForChanges() } override val isReadOnly: Boolean = false override fun filePathChanged(changedPath: Path) { super.filePathChanged(changedPath) readCurrentStateAndEmit() } /** * Reads the current state of the workspace config from disk, and emits * the relevant updates */ fun readCurrentStateAndEmit(): WorkspaceConfig? { val oldConfig = lastConfig try { val workspaceConfig = load() logger.info { "Repository config at $configFilePath loaded with ${workspaceConfig.repoCountDescription()}" } emitUpdateEvents(oldConfig, workspaceConfig) lastConfig = workspaceConfig } catch (e: Exception) { // load() handles the errors in case there is an error in workspace.config and reports these errors back to UI. // However, it re-throws the caught error, we re-catch it over here so that Orbital doesn't fall over during // start-up val rootCause = Throwables.getRootCause(e) if (rootCause is EmissionException) { // This isn't a config issue, it's an application issue logger.error(rootCause) { "Failed to send update to changes to workspace" } throw rootCause } logger.error(rootCause) { "error in emitting workspace specs" } lastConfig = null } return lastConfig } private fun emitUpdateEvents(oldConfig: WorkspaceConfig?, workspaceConfig: WorkspaceConfig) { val oldFileSpecs = oldConfig?.fileConfigOrDefault?.projects?.toSet() ?: emptySet() val newFileSpecs = workspaceConfig.fileConfigOrDefault.projects.toSet() val removedPackages = mutableListOf<PackageIdentifier>() val fileSpecsRemoved = Sets.difference(oldFileSpecs, newFileSpecs) fileSpecsRemoved.forEach { removedFileSpec -> removedPackages.addAll(getPackageIdentifierForTransport(removedFileSpec)) eventDispatcher.fileRepositorySpecRemoved(FileSpecRemovedEvent(removedFileSpec)) } val fileSpecsAdded = Sets.difference(newFileSpecs, oldFileSpecs) fileSpecsAdded.forEach { addedFileSpec -> eventDispatcher.fileRepositorySpecAdded(FileSpecAddedEvent(addedFileSpec, workspaceConfig.fileConfigOrDefault)) } val oldGitSpecs = oldConfig?.gitConfigOrDefault?.repositories?.toSet() ?: emptySet() val newGitSpecs = workspaceConfig.gitConfigOrDefault.repositories.toSet() val gitSpecsRemoved = Sets.difference(oldGitSpecs, newGitSpecs) gitSpecsRemoved.forEach { removedGitSpec -> removedPackages.addAll(getPackageIdentifierForTransport(removedGitSpec)) eventDispatcher.gitRepositorySpecRemoved(GitSpecRemovedEvent(removedGitSpec)) } val addedGitSpecs = Sets.difference(newGitSpecs, oldGitSpecs) addedGitSpecs.forEach { addedGitSpec -> eventDispatcher.gitRepositorySpecAdded(GitSpecAddedEvent(addedGitSpec, workspaceConfig.gitConfigOrDefault)) } eventDispatcher.schemaSourceRemoved(removedPackages) } /** * Looks up the package identifier(s) for the transport. * Although some transports expose the package identifier directly (like file transports), * others - like git - need to defer to their loader, since the identifier isn't known until * we fetch the actual package. * So, we consistently leverage the projectManager to find the package identifier */ private fun getPackageIdentifierForTransport(transport: ProjectTransportConfig): List<PackageIdentifier> { val packages = this.projectManager.loaders.filter { it.config == transport }.map { it.packageIdentifier } if (packages.isEmpty()) { logger.warn { "Could not find a corresponding package for transport $transport - sources from the package may not be updated" } } return packages } override fun extract(config: Config): WorkspaceConfig = config.extract() override fun emptyConfig(): WorkspaceConfig = WorkspaceConfig(null, null) override fun safeConfigJson(): String { return getSafeConfigString(unresolvedConfig(), asJson = true) } @VisibleForTesting public override fun invalidateCache() { super.invalidateCache() } override fun load(createDefaultIfAbsent: Boolean): WorkspaceConfig { try { if (!createDefaultIfAbsent && !configFilePath.exists()) { throw IllegalStateException("No workspace file exists at $configFilePath") } val original = typedConfig() val config = resolveRelativePaths(original) // Use busy loop here, otherwise we get errors about non-serialized event emmission stateSink.emitNext(LoaderStatus.OK, Sinks.EmitFailureHandler.busyLooping(Duration.ofSeconds(2L))) this.lastConfig = config return config } catch (e: Exception) { val rootCause = Throwables.getRootCause(e) val message = "Error when loading workspace config file at $configFilePath: ${rootCause.message ?: rootCause::class.simpleName}" logger.warn { message } stateSink.emitNext(LoaderStatus.error(message), Sinks.EmitFailureHandler.FAIL_FAST) throw e } } private fun makeRelativeToConfigFile(path: Path): Path { return if (path.isAbsolute) { path } else { configFilePath.toAbsolutePath().parent.resolve(path) } } private fun resolveRelativePaths(original: WorkspaceConfig): WorkspaceConfig { // MP: 06-Sep-24: Changed from original.file -> original.fileConfigOrDefault // We need to make newPaths relative to the location of the file, and this is the // only / best place to do it. val updatedFileConfig = original.fileConfigOrDefault.let { fileConfig -> val resolvedPaths = fileConfig.projects .map { packageSpec -> val relativePath = makeRelativeToConfigFile(packageSpec.path) if (packageSpec.loader is TaxiPackageLoaderSpec) { val packageMetadata = try { // If we were passed a file, use it. Otherwise, if it's a dir, resolve taxi.conf file. val pathToLoad = when { !Files.exists(relativePath) -> error("No file or directory exists at ${relativePath.toFile().canonicalPath}") relativePath.isDirectory() -> relativePath.resolve("taxi.conf") relativePath.isRegularFile() -> relativePath else -> error("Provided path is neither a file not a directory - not sure what to do") } TaxiPackageLoader(pathToLoad).load()?.toPackageMetadata() } catch (e: Exception) { val rootCause = Throwables.getRootCause(e) logger.warn(e) { "Failed to read package metadata for project at $relativePath ${rootCause.message}" } null } packageSpec.copy(path = relativePath, packageIdentifier = packageMetadata?.identifier) } else { packageSpec.copy(path = relativePath) } } fileConfig.copy(projects = resolvedPaths, newProjectsPath = makeRelativeToConfigFile(fileConfig.newProjectsPath)) } return original.copy(file = updatedFileConfig) } override fun addFileSpec(fileSpec: FileProjectSpec): ModifyWorkspaceResponse { val current = this.typedConfig() // Don't call load, as we want the original, not the one we resolve paths with val currentFileConfig = current.file ?: WorkspaceFileProjectConfig() if (currentFileConfig.projects.any { it.path == fileSpec.path }) { return ModifyWorkspaceResponse(ModifyProjectResponseStatus.Failed, "${fileSpec.path} already exists") } if (fileSpec.loader is TaxiPackageLoaderSpec) { if (fileSpec.packageIdentifier != null) { createProjectIfNotExists(fileSpec) } else { verifyProjectExists(fileSpec) } } val updated = current.copy( file = currentFileConfig.copy( projects = currentFileConfig.projects.concat(fileSpec) ) ) save(updated) val fileSpecWithAbsolutePath = fileSpec.copy(path = makeRelativeToConfigFile(fileSpec.path)) eventDispatcher.fileRepositorySpecAdded(FileSpecAddedEvent(fileSpecWithAbsolutePath, updated.file!!)) return ModifyWorkspaceResponse(ModifyProjectResponseStatus.Ok) } private fun verifyProjectExists(fileSpec: FileProjectSpec): PackageIdentifier { return when (fileSpec.loader) { is TaxiPackageLoaderSpec -> verifyTaxiProjectExists(fileSpec) is OpenApiPackageLoaderSpec -> verifyOpenApiProjectExists(fileSpec) else -> error("No package verification built for loader type ${fileSpec.loader::class.simpleName}") } } private fun verifyOpenApiProjectExists(fileSpec: FileProjectSpec): PackageIdentifier { require(fileSpec.path.exists()) { "No OpenAPI spec found at ${fileSpec.path}" } // What else do we need to check? return (fileSpec.loader as OpenApiPackageLoaderSpec).identifier } private fun verifyTaxiProjectExists(fileSpec: FileProjectSpec): PackageIdentifier { val projectPath = makeRelativeToConfigFile(fileSpec.path) val project = TaxiPackageLoader.forDirectoryContainingTaxiFile(projectPath).load() if (fileSpec.packageIdentifier != null && project.identifier.toVynePackageIdentifier() != fileSpec.packageIdentifier) { error("The provided package identifier (${fileSpec.packageIdentifier!!.id} does not match the package identifier found at ${fileSpec.path} - ${project.identifier.id}") } return project.identifier.toVynePackageIdentifier() } private fun createProjectIfNotExists(fileSpec: FileProjectSpec): PackageIdentifier { // We don't create openAPI projects if (fileSpec.loader is OpenApiPackageLoaderSpec) { return verifyOpenApiProjectExists(fileSpec) } val taxiProjectPath = makeRelativeToConfigFile(fileSpec.path) if (!taxiProjectPath.createDirectories().exists()) { logger.warn { "Failed to create directory $taxiProjectPath for taxi project" } error("Failed to create directory $taxiProjectPath for taxi project") } val taxiPackageLoader = TaxiPackageLoader.forDirectoryContainingTaxiFile(taxiProjectPath) val taxiConfPath = taxiPackageLoader.taxiConfFilePath!! if (!taxiConfPath.exists()) { if (fileSpec.packageIdentifier == null) { error("There is no Taxi project at ${fileSpec.path}, however cannot create an empty one as a package identifier wasn't provided") } logger.info { "No taxi.conf exists at $taxiConfPath - creating one" } val project = TaxiPackageProject( name = ProjectName(fileSpec.packageIdentifier.organisation, fileSpec.packageIdentifier.name).id, version = fileSpec.packageIdentifier.version, sourceRoot = "src/" ) val taxiConf = ConfigWriter().writeMinimal(project) taxiConfPath.writeText(taxiConf) taxiProjectPath.resolve(project.sourceRoot).createDirectories() } return taxiPackageLoader.load().identifier.toVynePackageIdentifier() } override fun addGitSpec(gitSpec: GitProjectSpec): ModifyWorkspaceResponse { val current = this.typedConfig() // Don't call load, as we want the original, not the one we resolve paths with val currentGitConfig = current.git ?: WorkspaceGitProjectConfig() if (currentGitConfig.repositories.any { it.name == gitSpec.name }) { return ModifyWorkspaceResponse( ModifyProjectResponseStatus.Failed, "A git repository with the name ${gitSpec.name} already exists" ) } if (currentGitConfig.repositories.any { it.uri == gitSpec.uri }) { return ModifyWorkspaceResponse( ModifyProjectResponseStatus.Failed, "A git repository already exists for ${gitSpec.uri}" ) } val updated = current.copy( git = currentGitConfig.copy( repositories = currentGitConfig.repositories.concat(gitSpec) ) ) save(updated) eventDispatcher.gitRepositorySpecAdded(GitSpecAddedEvent(gitSpec, updated.git!!)) return ModifyWorkspaceResponse( ModifyProjectResponseStatus.Ok, "${gitSpec.name} added as a new project, you need to commit and push your workspace.conf" ) } override fun removeGitRepository( repositoryName: String, packageIdentifier: PackageIdentifier ): List<PackageIdentifier> { val original = load() val matchedProjects = original.git?.repositories?.filter { it.name == repositoryName } require(matchedProjects?.size == 1) { "Could not find git repository with name $repositoryName" } val updatedProjectList = original.git!!.repositories.toMutableList() updatedProjectList.removeIf { it.name == repositoryName } val updatedConfig = original.copy( git = original.git!!.copy(repositories = updatedProjectList), ) save(updatedConfig) logger.info { "Removed git repository $repositoryName and saved to disk" } val affectedPackages = listOf(packageIdentifier) eventDispatcher.schemaSourceRemoved(affectedPackages) return affectedPackages } override fun removeFileRepository( repositoryPath: Path, packageIdentifier: PackageIdentifier ): List<PackageIdentifier> { val original = this.load() val matchedProjects = original.file?.projects?.filter { it.packageIdentifier?.uriSafeId == packageIdentifier.uriSafeId } require(matchedProjects?.size == 1) { "Could not find file repository for package $packageIdentifier" } val updatedProjectList = original.file!!.projects.toMutableList() updatedProjectList.removeIf { it.packageIdentifier!!.uriSafeId == packageIdentifier.uriSafeId } val updatedConfig = original.copy( file = original.file!!.copy(projects = updatedProjectList), ) save(updatedConfig) logger.info { "Removed file repository for $packageIdentifier and saved to disk" } matchedProjects!!.map { it.packageIdentifier } val removedPackages = listOf(packageIdentifier) eventDispatcher.schemaSourceRemoved(removedPackages) return removedPackages } override fun removePushedRepository(identifier: PackageIdentifier): List<PackageIdentifier> { val identifiers = listOf(identifier) eventDispatcher.schemaSourceRemoved(identifiers) return identifiers } override fun validateProjectExists(request: FileProjectStoreTestRequest): Mono<FileProjectTestResponse> { return Mono.fromCallable { val path = Paths.get(request.path) val projectHome = makeRelativeToConfigFile(path) try { val project = TaxiPackageLoader.forDirectoryContainingTaxiFile(projectHome).load() FileProjectTestResponse(request.path, true, project.identifier.toVynePackageIdentifier()) } catch (e: Exception) { logger.info { "Could not find a package at ${request.path} - maybe it doesn't exist? Error: ${e.message}" } FileProjectTestResponse(request.path, false, null) } } } @VisibleForTesting internal fun getSavableHocon(workspaceConfig: WorkspaceConfig): Config { val newConfig = workspaceConfig.toHocon() // Use the existing unresolvedConfig to ensure that when we're // writing back out, that tokens that have been resolved // aren't accidentally written with their real values back out val existingValues = unresolvedConfig() val updated = ConfigFactory.empty() .withFallback(newConfig) .withFallback(existingValues) return updated } @VisibleForTesting internal fun getHoconString(workspaceConfig: WorkspaceConfig): String { return getSafeConfigString(getSavableHocon(workspaceConfig)) } fun save(workspaceConfig: WorkspaceConfig) { val saveable = getSavableHocon(workspaceConfig) saveConfig(saveable) } }
9
TypeScript
10
292
2be59abde0bd93578f12fc1e2ecf1f458a0212ec
20,035
orbital
Apache License 2.0
example/mastodon/src/main/java/com/wcaokaze/vue/android/example/mastodon/infrastructure/oauth/getAuthorizeUrl.kt
wcaokaze
233,875,665
false
null
/* * Copyright 2020 wcaokaze * * 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.wcaokaze.vue.android.example.mastodon.infrastructure.oauth import io.ktor.http.* internal fun getAuthorizeUrl( instanceUrl: String, clientId: String, responseType: String, redirectUri: String, scopes: List<String> ): String { val urlBuilder = URLBuilder(instanceUrl) urlBuilder.path("oauth/authorize") urlBuilder.parameters.append("client_id", clientId) urlBuilder.parameters.append("response_type", responseType) urlBuilder.parameters.append("redirect_uri", redirectUri) urlBuilder.parameters.append("scope", scopes.joinToString(separator = " ")) return urlBuilder.buildString() }
8
Kotlin
0
3
e5401d4ffd04e059b13da3923583171db49b7737
1,225
Vue.android
Apache License 2.0
app/src/main/java/wannabit/io/cosmostaion/ui/tx/info/StakeInfoFragment.kt
cosmostation
418,314,439
false
null
package wannabit.io.cosmostaion.ui.tx.info import android.os.Build import android.os.Bundle import android.os.Handler import android.os.Looper import android.os.Parcelable import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.fragment.app.Fragment import androidx.lifecycle.lifecycleScope import androidx.recyclerview.widget.LinearLayoutManager import com.cosmos.staking.v1beta1.StakingProto import com.google.android.material.bottomsheet.BottomSheetDialogFragment import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.parcelize.Parcelize import wannabit.io.cosmostaion.chain.CosmosLine import wannabit.io.cosmostaion.databinding.FragmentStakeInfoBinding import wannabit.io.cosmostaion.ui.option.tx.general.ChangeRewardAddressWarnFragment import wannabit.io.cosmostaion.ui.option.tx.general.StakingOptionFragment import wannabit.io.cosmostaion.ui.tx.step.StakingFragment import wannabit.io.cosmostaion.ui.viewmodel.ApplicationViewModel class StakeInfoFragment : Fragment() { private var _binding: FragmentStakeInfoBinding? = null private val binding get() = _binding!! private lateinit var selectedChain: CosmosLine private lateinit var stakingInfoAdapter: StakingInfoAdapter private var isClickable = true companion object { @JvmStatic fun newInstance(selectedChain: CosmosLine): StakeInfoFragment { val args = Bundle().apply { putParcelable("selectedChain", selectedChain) } val fragment = StakeInfoFragment() fragment.arguments = args return fragment } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View { _binding = FragmentStakeInfoBinding.inflate(layoutInflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) initView() setUpClickAction() setUpStakeInfo() } private fun initView() { binding.apply { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) { arguments?.getParcelable("selectedChain", CosmosLine::class.java) ?.let { selectedChain = it } } else { (arguments?.getParcelable("selectedChain") as? CosmosLine)?.let { selectedChain = it } } lifecycleScope.launch(Dispatchers.IO) { val rewardAddress = selectedChain.rewardAddress var delegations = selectedChain.cosmosDelegations val validators = selectedChain.cosmosValidators val unBondings = selectedChain.cosmosUnbondings.flatMap { unbonding -> unbonding.entriesList.map { entry -> UnBondingEntry(unbonding.validatorAddress, entry) } }.sortedBy { it.entry?.creationHeight }.toMutableList() val cosmostationValAddress = validators.firstOrNull { it.description.moniker == "Cosmostation" }?.operatorAddress val tempDelegations = delegations.toMutableList() tempDelegations.sortWith { o1, o2 -> when { o1.delegation.validatorAddress == cosmostationValAddress -> -1 o2.delegation.validatorAddress == cosmostationValAddress -> 1 o1.balance.amount.toDouble() > o2.balance.amount.toDouble() -> -1 else -> 1 } } delegations = tempDelegations val stakingInfoList = delegations + unBondings withContext(Dispatchers.Main) { recycler.visibility = if (stakingInfoList.isNotEmpty()) View.VISIBLE else View.GONE emptyStake.visibility = if (stakingInfoList.isEmpty()) View.VISIBLE else View.GONE if (stakingInfoList.isNotEmpty()) { stakingInfoAdapter = StakingInfoAdapter( selectedChain, rewardAddress, validators, delegations, unBondings, selectClickAction ) recycler.setHasFixedSize(true) recycler.layoutManager = LinearLayoutManager(requireContext()) recycler.adapter = stakingInfoAdapter } } } } } private fun setUpClickAction() { binding.apply { btnBack.setOnClickListener { requireActivity().supportFragmentManager.popBackStack() } btnChangeRewardAddress.setOnClickListener { handleOneClickWithDelay(ChangeRewardAddressWarnFragment.newInstance(selectedChain)) } btnStake.setOnClickListener { StakingFragment.newInstance(selectedChain, null).show( requireActivity().supportFragmentManager, StakingFragment::class.java.name ) } } } private val selectClickAction = object : StakingInfoAdapter.ClickListener { override fun selectStakingAction(validator: StakingProto.Validator?) { handleOneClickWithDelay( StakingOptionFragment.newInstance( selectedChain, validator, null, OptionType.STAKE ) ) } override fun selectUnStakingCancelAction(unBondingEntry: UnBondingEntry?) { handleOneClickWithDelay( StakingOptionFragment.newInstance( selectedChain, null, unBondingEntry, OptionType.UNSTAKE ) ) } } private fun handleOneClickWithDelay(bottomSheetDialogFragment: BottomSheetDialogFragment) { if (isClickable) { isClickable = false bottomSheetDialogFragment.show( requireActivity().supportFragmentManager, bottomSheetDialogFragment::class.java.name ) Handler(Looper.getMainLooper()).postDelayed({ isClickable = true }, 300) } } private fun setUpStakeInfo() { ApplicationViewModel.shared.txFetchedResult.observe(viewLifecycleOwner) { initView() } } override fun onDestroyView() { _binding = null super.onDestroyView() } } @Parcelize data class UnBondingEntry( val validatorAddress: String?, val entry: StakingProto.UnbondingDelegationEntry? ) : Parcelable enum class OptionType { STAKE, UNSTAKE }
1
null
43
79
2da146a88290210e56f6d49f7a764b95dd262fbf
7,043
cosmostation-android
MIT License
app/src/main/java/com/nicoqueijo/android/currencyconverter/kotlin/view/DecimalNumberKeyboard.kt
nicoqueijo
136,773,306
false
{"Kotlin": 160859}
package com.nicoqueijo.android.currencyconverter.kotlin.view import android.content.Context import android.util.AttributeSet import android.view.LayoutInflater import android.view.View import android.widget.Button import android.widget.ImageButton import androidx.constraintlayout.widget.ConstraintLayout import com.nicoqueijo.android.currencyconverter.R import java.text.DecimalFormatSymbols /** * Custom keyboard that includes buttons: digits 0-9, decimal separator, backspace. */ class DecimalNumberKeyboard(context: Context, attrs: AttributeSet) : ConstraintLayout(context, attrs), View.OnClickListener, View.OnLongClickListener { private var onClickCallback: KeyboardCallback? = null private var onLongClickCallback: KeyboardCallback? = null private val buttonOne: Button private val buttonTwo: Button private val buttonThree: Button private val buttonFour: Button private val buttonFive: Button private val buttonSix: Button private val buttonSeven: Button private val buttonEight: Button private val buttonNine: Button private val buttonDecimalSeparator: Button private val buttonZero: Button private val buttonBackspace: ImageButton init { LayoutInflater.from(context).inflate(R.layout.decimal_number_keyboard, this) buttonOne = findViewById(R.id.button_one) buttonTwo = findViewById(R.id.button_two) buttonThree = findViewById(R.id.button_three) buttonFour = findViewById(R.id.button_four) buttonFive = findViewById(R.id.button_five) buttonSix = findViewById(R.id.button_six) buttonSeven = findViewById(R.id.button_seven) buttonEight = findViewById(R.id.button_eight) buttonNine = findViewById(R.id.button_nine) buttonDecimalSeparator = findViewById(R.id.button_decimal_separator) buttonZero = findViewById(R.id.button_zero) buttonBackspace = findViewById(R.id.button_backspace) buttonDecimalSeparator.text = DecimalFormatSymbols.getInstance().decimalSeparator.toString() setListeners(buttonOne, buttonTwo, buttonThree, buttonFour, buttonFive, buttonSix, buttonSeven, buttonEight, buttonNine, buttonDecimalSeparator, buttonZero, buttonBackspace) } private fun setListeners(vararg buttons: View) { buttons.forEach { button -> button.setOnClickListener(this) if (button is ImageButton) { button.setOnLongClickListener(this) } } } fun onKeyClickedListener(listener: KeyboardCallback) { onClickCallback = listener } fun onKeyLongClickedListener(listener: KeyboardCallback) { onLongClickCallback = listener } override fun onClick(button: View?) { onClickCallback?.invoke(button) } override fun onLongClick(button: View?): Boolean { onLongClickCallback?.invoke(button) return true } } /** * Credit: https://stackoverflow.com/a/60906741/5906793 */ typealias KeyboardCallback = (View?) -> Unit
5
Kotlin
22
42
9b459d0701d3f981ff0067c494be69d1cc4b04da
3,097
Android-Currency-Converter
Apache License 2.0
app/src/main/java/com/josenaves/iddog/data/remote/api/dto/AuthRequest.kt
josenaves
203,216,578
false
null
package com.josenaves.iddog.data.remote.api.dto data class AuthRequest(val email: String)
0
Kotlin
0
0
f6193bc2ecd549dfdfb2b3ea6dfe0fe510aff437
90
idDog
MIT License
app/src/main/java/ru/rznnike/eyehealthmanager/app/di/DatabaseModule.kt
RznNike
207,148,781
false
null
package ru.rznnike.eyehealthmanager.app.di import org.koin.android.ext.koin.androidContext import org.koin.dsl.module import ru.rznnike.eyehealthmanager.data.storage.entity.MyObjectBox import ru.rznnike.eyehealthmanager.domain.storage.repository.TestRepository import ru.rznnike.eyehealthmanager.data.storage.repository.TestRepositoryImpl val databaseModule = module { single { MyObjectBox.builder().androidContext(androidContext()).build() } single<TestRepository> { TestRepositoryImpl(get()) } }
0
null
0
1
64cb90237029e498c4f1484daa1023f0302b4a0f
508
EyeHealthManager
MIT License
PrinterApp/app/src/main/java/de/domes_muc/printerappkotlin/library/LibraryModelCreation.kt
frado1
171,032,287
true
{"Kotlin": 813558, "Java": 569834}
package de.domes_muc.printerappkotlin.library import android.app.AlertDialog import de.domes_muc.printerappkotlin.Log import de.domes_muc.printerappkotlin.R import de.domes_muc.printerappkotlin.viewer.DataStorage import de.domes_muc.printerappkotlin.viewer.GcodeFile import de.domes_muc.printerappkotlin.viewer.StlFile import de.domes_muc.printerappkotlin.viewer.ViewerMainFragment import de.domes_muc.printerappkotlin.viewer.ViewerSurfaceView import android.content.Context import android.content.DialogInterface import android.content.Intent import android.graphics.Bitmap import android.os.Handler import androidx.localbroadcastmanager.content.LocalBroadcastManager import android.view.LayoutInflater import android.view.View import android.widget.FrameLayout import com.afollestad.materialdialogs.MaterialDialog import com.afollestad.materialdialogs.customview.customView import java.io.File import java.io.FileInputStream import java.io.FileOutputStream import java.io.IOException import java.io.InputStream import java.io.OutputStream import java.nio.ByteBuffer import java.nio.ShortBuffer import java.util.ArrayList import kotlin.experimental.and /** * * this method will create a new folder structure from a file in our system * @author alberto-baeza */ class LibraryModelCreation { companion object { private lateinit var mAlert: MaterialDialog internal lateinit var mName: String lateinit var mSnapshotSurface: ViewerSurfaceView lateinit var mSnapshotLayout: FrameLayout private val mHandler = Handler() private val WAIT_TIME = 2000 private var mContext: Context? = null private var mFile: File? = null private var mFileQueue: ArrayList<File>? = null private var mCount = 0 //Static method to create a folder structure fun createFolderStructure(context: Context?, source: File?) { //Catch null pointer because file browser buttons aren't implemented if (source != null) { mName = source.name.substring(0, source.name.lastIndexOf('.')) mContext = context mFile = source /*File root = new File(LibraryController.getParentFolder().getAbsolutePath() + "/Files/" + mName);*/ val root = File(LibraryController.currentPath.toString() + "/" + mName) val mainFolder: File val secondaryFolder: File Log.i("OUT", "File " + root.getAbsolutePath() + " source " + mFile!!.name) //root folder if (root.mkdirs()) { if (mFile!!.name.contains(".stl") || mFile!!.name.contains(".STL")) { mainFolder = File(root.getAbsolutePath() + "/_stl") secondaryFolder = File(root.getAbsolutePath() + "/_gcode") } else { mainFolder = File(root.getAbsolutePath() + "/_gcode") secondaryFolder = File(root.getAbsolutePath() + "/_stl") } //gcode folder if (secondaryFolder.mkdir()) { } //stl folder if (mainFolder.mkdir()) { try { val target = File(mainFolder.absolutePath + "/" + mFile!!.name) if (mFile!!.exists()) { val fileStreamIn = FileInputStream(mFile) val out = FileOutputStream(target) // Copy the bits from instream to outstream val buf = ByteArray(1024) var len: Int while (fileStreamIn.read(buf)?.let { out.write(buf, 0, it); it } > 0); fileStreamIn.close() out.close() } else { } openModel(mContext, target.absolutePath) } catch (e: IOException) { e.printStackTrace() } } } } } /** * Open model to take screenshot * @param context * @param path */ private fun openModel(context: Context?, path: String) { val generatingProjectDialog = LayoutInflater.from(context).inflate(R.layout.dialog_loading_project, null) mSnapshotLayout = generatingProjectDialog.findViewById<View>(R.id.framesnapshot) as FrameLayout Log.i("OUT", "Opening to snap $path") var count = context!!.getString(R.string.generating_project) if (mFileQueue != null) count += " (" + (mCount - (mFileQueue!!.size - 1)) + "/" + mCount + ")" mAlert = MaterialDialog(mContext!!) .title(text = count) .customView(view = generatingProjectDialog, scrollable = true) .cancelable(false) .noAutoDismiss() //We need the alertdialog instance to dismiss it mAlert.show() val file = File(path) val list = ArrayList<DataStorage>() val data = DataStorage() if (StlFile.checkFileSize(file, mContext!!)) { if (LibraryController.hasExtension(0, path)) { StlFile.openStlFile(context, file, data, ViewerMainFragment.DO_SNAPSHOT) } else if (LibraryController.hasExtension(1, path)) { GcodeFile.openGcodeFile(context, file, data, ViewerMainFragment.DO_SNAPSHOT) } mSnapshotSurface = ViewerSurfaceView(context, list, ViewerSurfaceView.NORMAL, ViewerMainFragment.DO_SNAPSHOT, null) list.add(data) } else mAlert.dismiss() } /** * This method is called from STlFile or GcodeFile when data is ready to render. Add the view to the layout. */ fun takeSnapshot() { mSnapshotSurface.setZOrderOnTop(true) mSnapshotLayout.addView(mSnapshotSurface) } /** * Creates the snapshot of the model */ fun saveSnapshot(width: Int, height: Int, bb: ByteBuffer) { val screenshotSize = width * height var pixelsBuffer: IntArray? = IntArray(screenshotSize) bb.asIntBuffer().get(pixelsBuffer) val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565) bitmap.setPixels(pixelsBuffer, screenshotSize - width, -width, 0, 0, width, height) pixelsBuffer = null val sBuffer = ShortArray(screenshotSize) val sb = ShortBuffer.wrap(sBuffer) bitmap.copyPixelsToBuffer(sb) //Making created bitmap (from OpenGL points) compatible with Android bitmap for (i in 0 until screenshotSize) { val v = sBuffer[i] //FD20190101 @TODO sBuffer[i] = ((v and 0x1f).toInt() shl 11 or (v and 0x7e0).toInt() or ((v.toLong() and 0xf800L).toInt() shr 11)).toShort() } sb.rewind() bitmap.copyPixelsFromBuffer(sb) try { val fos = FileOutputStream(LibraryController.currentPath.toString() + "/" + mName + "/" + mName + ".thumb") bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos) fos.flush() fos.close() } catch (e: Exception) { e.printStackTrace() } dismissSnapshotAlert() } /** * Dismiss the loading project dialog after a few seconds. */ private fun dismissSnapshotAlert() { mHandler.postDelayed({ mAlert.dismiss() //Only show delete dialog if there is no queue //TODO if (mFileQueue == null) deleteFileDialog() else checkQueue() val intent = Intent("notify") intent.putExtra("message", "Files") LocalBroadcastManager.getInstance(mContext!!).sendBroadcast(intent) }, WAIT_TIME.toLong()) } private fun deleteFileDialog() { val adb = AlertDialog.Builder(mContext) adb.setTitle(R.string.library_delete_dialog_original) adb.setPositiveButton(R.string.ok) { dialogInterface, i -> LibraryController.deleteFiles(mFile!!) } adb.setNegativeButton(R.string.cancel, null) adb.show() /** * Use an intent because it's an asynchronous static method without any reference (yet) */ val intent = Intent("notify") intent.putExtra("message", "Files") LocalBroadcastManager.getInstance(mContext!!).sendBroadcast(intent) } /************************************************************ * * JOB QUEUE * */ //Send a file list to enqueue jobs fun enqueueJobs(context: Context, q: ArrayList<File>) { mFileQueue = q mCount = mFileQueue!!.size createFolderStructure(context, mFileQueue!![0]) } //Check if there are more files in the queue fun checkQueue() { if (mFileQueue != null) { mFileQueue!!.removeAt(0) //Remove last file if (mFileQueue!!.size > 0) { //If there are more createFolderStructure(mContext, mFileQueue!![0]) //Create folder again } else { mFileQueue = null //Remove queue mCount = 0 } } } } }
0
Kotlin
0
0
91f440d7b699fd6754b937f8afaf36973bef750d
10,032
OctoPrint-AndroidApp
Apache License 2.0
glance/glance-testing/src/main/java/androidx/glance/testing/GlanceNodeSelector.kt
androidx
256,589,781
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 * * 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.glance.testing import androidx.annotation.RestrictTo /** A chainable selector that allows specifying how to select nodes from a collection. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class GlanceNodeSelector<R>( val description: String, private val previousChainedSelector: GlanceNodeSelector<R>? = null, private val selector: (Iterable<GlanceNode<R>>) -> SelectionResult<R> ) { /** Returns nodes selected by previous chained selectors followed by the current selector. */ fun map(nodes: Iterable<GlanceNode<R>>): SelectionResult<R> { val previousSelectionResult = previousChainedSelector?.map(nodes) val inputNodes = previousSelectionResult?.selectedNodes ?: nodes return selector(inputNodes) } } @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) class SelectionResult<R>( val selectedNodes: List<GlanceNode<R>>, val errorMessageOnNoMatch: String? = null ) /** * Constructs an entry-point selector that selects nodes satisfying the matcher condition. Used at * the entry points such as [GlanceNodeAssertionsProvider.onNode] and * [GlanceNodeAssertionsProvider.onAllNodes] where there is no previous chained selector. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun <R> GlanceNodeMatcher<R>.matcherToSelector(): GlanceNodeSelector<R> { return GlanceNodeSelector(description = description, previousChainedSelector = null) { glanceNodes -> SelectionResult(selectedNodes = glanceNodes.filter { matches(it) }) } } /** * Wraps the current selector with a chained selector that selects a node at a given index from the * the result of current selection. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun <R> GlanceNodeSelector<R>.addIndexedSelector(index: Int): GlanceNodeSelector<R> { return GlanceNodeSelector( description = "(${this.description})[$index]", previousChainedSelector = this ) { nodes -> val nodesList = nodes.toList() val minimumExpectedCount = index + 1 if (index >= 0 && index < nodesList.size) { SelectionResult(selectedNodes = listOf(nodesList[index])) } else { SelectionResult( selectedNodes = emptyList(), errorMessageOnNoMatch = buildErrorReasonForIndexOutOfMatchedNodeBounds( description, requestedIndex = minimumExpectedCount, actualCount = nodesList.size ) ) } } } /** * Wraps the current selector with a chained matcher-based selector that filters the list of nodes * to return ones matched by the matcher. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun <R> GlanceNodeSelector<R>.addMatcherSelector( selectorName: String, matcher: GlanceNodeMatcher<R> ): GlanceNodeSelector<R> { return GlanceNodeSelector( description = "(${this.description}).$selectorName(${matcher.description})", previousChainedSelector = this ) { nodes -> SelectionResult(selectedNodes = nodes.filter { matcher.matches(it) }) } } /** * Wraps the current selector with a chained matcher-based selector that ensures only one node is * returned by current selector and selects children of that node. */ @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) fun <R> GlanceNodeSelector<R>.addChildrenSelector(): GlanceNodeSelector<R> { return GlanceNodeSelector( description = "($description).children()", previousChainedSelector = this ) { nodes -> if (nodes.count() != 1) { SelectionResult( selectedNodes = emptyList(), errorMessageOnNoMatch = buildErrorReasonForCountMismatch( matcherDescription = description, expectedCount = 1, actualCount = nodes.count() ) ) } else { SelectionResult(selectedNodes = nodes.single().children()) } } }
29
null
937
5,321
98b929d303f34d569e9fd8a529f022d398d1024b
4,682
androidx
Apache License 2.0
kroto-plus-coroutines/src/main/kotlin/com/github/marcoferrer/krotoplus/coroutines/client/ClientChannels.kt
qsona
165,782,677
true
{"Kotlin": 196181}
package com.github.marcoferrer.krotoplus.coroutines.client import com.github.marcoferrer.krotoplus.coroutines.FlowControlledObserver import com.github.marcoferrer.krotoplus.coroutines.enableManualFlowControl import io.grpc.stub.ClientCallStreamObserver import io.grpc.stub.ClientResponseObserver import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Deferred import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.channels.ReceiveChannel import kotlinx.coroutines.channels.SendChannel import java.util.concurrent.atomic.AtomicBoolean import kotlin.coroutines.CoroutineContext data class ClientBidiCallChannel<ReqT, RespT>( val requestChannel: SendChannel<ReqT>, val responseChannel: ReceiveChannel<RespT> ) : SendChannel<ReqT> by requestChannel, ReceiveChannel<RespT> by responseChannel data class ClientStreamingCallChannel<ReqT, RespT>( val requestChannel: SendChannel<ReqT> = Channel(), val response: Deferred<RespT> ) : SendChannel<ReqT> by requestChannel class ClientResponseObserverChannel<ReqT, RespT>( override val coroutineContext: CoroutineContext, private val responseChannelDelegate: Channel<RespT> = Channel(capacity = 1) ) : ClientResponseObserver<ReqT, RespT>, FlowControlledObserver, ReceiveChannel<RespT> by responseChannelDelegate, CoroutineScope { private val isMessagePreloaded = AtomicBoolean() lateinit var requestStream: ClientCallStreamObserver<ReqT> @ExperimentalCoroutinesApi override fun beforeStart(requestStream: ClientCallStreamObserver<ReqT>) { this.requestStream = requestStream.apply { enableManualFlowControl(responseChannelDelegate,isMessagePreloaded) } } @ExperimentalCoroutinesApi override fun onNext(value: RespT) = nextValueWithBackPressure( value = value, channel = responseChannelDelegate, callStreamObserver = requestStream, isMessagePreloaded = isMessagePreloaded ) override fun onError(t: Throwable) { responseChannelDelegate.close(t) } override fun onCompleted() { responseChannelDelegate.close() } }
0
Kotlin
0
0
b690acc2da2abb17be1c44b2004fc07bd86bddad
2,201
kroto-plus
Apache License 2.0
app/src/main/kotlin/dev/aaa1115910/bv/screen/VideoInfoScreen.kt
aaa1115910
571,702,700
false
null
package dev.aaa1115910.bv.screen import android.app.Activity import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.animateContentSize import androidx.compose.animation.core.animateFloatAsState import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.clickable import androidx.compose.foundation.focusable import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.material.icons.Icons import androidx.compose.material.icons.rounded.Add import androidx.compose.material.icons.rounded.Done import androidx.compose.material.icons.rounded.ViewModule import androidx.compose.material.icons.rounded.Warning import androidx.compose.material3.AlertDialog import androidx.compose.material3.Scaffold import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.derivedStateOf import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableIntStateOf import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.draw.rotate import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color import androidx.compose.ui.layout.ContentScale import androidx.compose.ui.layout.onGloballyPositioned import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalDensity import androidx.compose.ui.platform.LocalLifecycleOwner import androidx.compose.ui.platform.LocalView import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import androidx.compose.ui.window.DialogProperties import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleEventObserver import androidx.lifecycle.LifecycleOwner import androidx.tv.foundation.lazy.grid.TvGridCells import androidx.tv.foundation.lazy.grid.TvLazyVerticalGrid import androidx.tv.foundation.lazy.grid.itemsIndexed import androidx.tv.foundation.lazy.grid.rememberTvLazyGridState import androidx.tv.foundation.lazy.list.TvLazyColumn import androidx.tv.foundation.lazy.list.TvLazyRow import androidx.tv.foundation.lazy.list.items import androidx.tv.foundation.lazy.list.itemsIndexed import androidx.tv.material3.Border import androidx.tv.material3.ClickableSurfaceDefaults import androidx.tv.material3.ExperimentalTvMaterial3Api import androidx.tv.material3.Icon import androidx.tv.material3.LocalContentColor import androidx.tv.material3.MaterialTheme import androidx.tv.material3.Surface import androidx.tv.material3.Tab import androidx.tv.material3.TabRow import androidx.tv.material3.Text import coil.compose.AsyncImage import coil.compose.rememberAsyncImagePainter import coil.request.ImageRequest import coil.transform.BlurTransformation import dev.aaa1115910.biliapi.BiliApi import dev.aaa1115910.biliapi.entity.user.FollowAction import dev.aaa1115910.biliapi.entity.user.FollowActionSource import dev.aaa1115910.biliapi.entity.user.RelationData import dev.aaa1115910.biliapi.entity.user.RelationType import dev.aaa1115910.biliapi.entity.user.favorite.UserFavoriteFoldersData import dev.aaa1115910.biliapi.entity.video.Dimension import dev.aaa1115910.biliapi.entity.video.Tag import dev.aaa1115910.biliapi.entity.video.UgcSeason import dev.aaa1115910.biliapi.entity.video.VideoInfo import dev.aaa1115910.biliapi.entity.video.VideoPage import dev.aaa1115910.bv.R import dev.aaa1115910.bv.activities.video.SeasonInfoActivity import dev.aaa1115910.bv.activities.video.TagActivity import dev.aaa1115910.bv.activities.video.UpInfoActivity import dev.aaa1115910.bv.component.SurfaceWithoutClickable import dev.aaa1115910.bv.component.UpIcon import dev.aaa1115910.bv.component.buttons.FavoriteButton import dev.aaa1115910.bv.component.videocard.VideosRow import dev.aaa1115910.bv.entity.carddata.VideoCardData import dev.aaa1115910.bv.repository.VideoInfoRepository import dev.aaa1115910.bv.repository.VideoListItem import dev.aaa1115910.bv.ui.theme.BVTheme import dev.aaa1115910.bv.util.Prefs import dev.aaa1115910.bv.util.fDebug import dev.aaa1115910.bv.util.fException import dev.aaa1115910.bv.util.fInfo import dev.aaa1115910.bv.util.fWarn import dev.aaa1115910.bv.util.focusedBorder import dev.aaa1115910.bv.util.formatPubTimeString import dev.aaa1115910.bv.util.launchPlayerActivity import dev.aaa1115910.bv.util.requestFocus import dev.aaa1115910.bv.util.swapList import dev.aaa1115910.bv.util.toast import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import mu.KotlinLogging import org.koin.compose.getKoin import java.util.Date import kotlin.math.ceil @Composable fun VideoInfoScreen( modifier: Modifier = Modifier, lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current, videoInfoRepository: VideoInfoRepository = getKoin().get() ) { val context = LocalContext.current val scope = rememberCoroutineScope() val intent = (context as Activity).intent val logger = KotlinLogging.logger { } var videoInfo: VideoInfo? by remember { mutableStateOf(null) } val relatedVideos = remember { mutableStateListOf<VideoCardData>() } var relations: RelationData? by remember { mutableStateOf(null) } val tags = remember { mutableStateListOf<Tag>() } var lastPlayedCid by remember { mutableIntStateOf(0) } var lastPlayedTime by remember { mutableIntStateOf(0) } var tip by remember { mutableStateOf("Loading") } var fromSeason by remember { mutableStateOf(false) } var paused by remember { mutableStateOf(false) } val containsVerticalScreenVideo by remember { derivedStateOf { videoInfo?.pages?.any { page -> page.dimension.height > page.dimension.width } ?: false || videoInfo?.ugcSeason?.sections?.any { section -> section.episodes.any { episode -> episode.page.dimension.height > episode.page.dimension.width } } ?: false } } var favorited by remember { mutableStateOf(false) } val favoriteFolders = remember { mutableStateListOf<UserFavoriteFoldersData.UserFavoriteFolder>() } val videoInFavoriteFolderIds = remember { mutableStateListOf<Long>() } val updateV2Data: () -> Unit = { scope.launch(Dispatchers.Default) { runCatching { logger.fInfo { "Get video more info" } val moreInfoResponse = BiliApi.getVideoMoreInfo( avid = videoInfo!!.aid, cid = videoInfo!!.cid, sessData = Prefs.sessData ).getResponseData() lastPlayedCid = moreInfoResponse.lastPlayCid lastPlayedTime = moreInfoResponse.lastPlayTime }.onFailure { logger.fInfo { "Get video more info failed: ${it.stackTraceToString()}" } } } } val updateRelationVideos: (avid: Long) -> Unit = { avid -> scope.launch(Dispatchers.Default) { runCatching { val response = BiliApi.getRelatedVideos(avid = avid) relatedVideos.swapList(response.data.map { VideoCardData( avid = it.aid, title = it.title, cover = it.pic, upName = it.owner.name, time = it.duration * 1000L, play = it.stat.view, danmaku = it.stat.danmaku ) }) }.onFailure { withContext(Dispatchers.Main) { "获取相关视频失败:${it.localizedMessage}".toast(context) } logger.fException(it) { "Get related videos failed" } } } } val updateRelationData: () -> Unit = { scope.launch(Dispatchers.Default) { runCatching { logger.fInfo { "Get relation data with user ${videoInfo?.owner?.mid}" } relations = BiliApi.getRelations( mid = videoInfo?.owner?.mid ?: -1, sessData = Prefs.sessData ).getResponseData() }.onFailure { logger.fInfo { "Get relation data failed: ${it.stackTraceToString()}" } } } } val updateTags: (avid: Int) -> Unit = { avid -> scope.launch(Dispatchers.Default) { runCatching { logger.fInfo { "Getting tags" } tags.swapList(BiliApi.getVideoTags(avid = avid).getResponseData()) }.onFailure { logger.fInfo { "Get tags failed: ${it.stackTraceToString()}" } } } } val modifyRelation: (action: FollowAction, afterModify: () -> Unit) -> Unit = { action, afterModify -> scope.launch(Dispatchers.Default) { runCatching { logger.fInfo { "Modify relation: $action" } BiliApi.modifyFollow( mid = videoInfo?.owner?.mid ?: -1, action = action, actionSource = FollowActionSource.Video, csrf = Prefs.biliJct, sessData = Prefs.sessData ) afterModify() }.onFailure { logger.fInfo { "Modify relation failed: ${it.stackTraceToString()}" } } } } val updateFavoriteData: (Int) -> Unit = { avid -> scope.launch(Dispatchers.IO) { runCatching { favorited = BiliApi.checkVideoFavoured(avid = avid, sessData = Prefs.sessData) logger.fDebug { "Update video is favorite: $favorited" } } } scope.launch(Dispatchers.IO) { runCatching { val userFavoriteFoldersDataBiliResponse = BiliApi.getAllFavoriteFoldersInfo(mid = Prefs.uid, sessData = Prefs.sessData) favoriteFolders.swapList(userFavoriteFoldersDataBiliResponse.getResponseData().list) logger.fDebug { "Update favoriteFolders: ${userFavoriteFoldersDataBiliResponse.getResponseData().list.map { it.title }}" } } } scope.launch(Dispatchers.IO) { runCatching { val favoriteFoldersResponse = BiliApi.getAllFavoriteFoldersInfo( mid = Prefs.uid, rid = avid, sessData = Prefs.sessData ) val list = favoriteFoldersResponse.getResponseData().list.filter { it.favState == 1 } videoInFavoriteFolderIds.swapList(list.map { it.id }) logger.fDebug { "Update videoInFavoriteFolderIds: ${list.map { it.title }}" } } } } val addVideoToFavoriteFolder: (List<Long>) -> Unit = { folderIds -> scope.launch(Dispatchers.IO) { runCatching { require(favoriteFolders.isNotEmpty()) { "Not found favorite folder" } require(videoInfo?.aid != null) { "Video info is null" } logger.info { "Update video av${videoInfo?.aid} to favorite folder $folderIds" } BiliApi.setVideoToFavorite( avid = videoInfo!!.aid, addMediaIds = folderIds, delMediaIds = favoriteFolders.map { it.id } - folderIds.toSet(), csrf = Prefs.biliJct, sessData = Prefs.sessData ) }.onFailure { logger.fInfo { "Add video to favorite folder failed: ${it.stackTraceToString()}" } withContext(Dispatchers.Main) { it.message ?: "unknown error".toast(context) } }.onSuccess { logger.fInfo { "Add video to favorite folder success" } videoInFavoriteFolderIds.swapList(folderIds) } } } val addVideoToDefaultFavoriteFolder: () -> Unit = { runCatching { val defaultFavoriteFolder = favoriteFolders.firstOrNull { it.title == "默认收藏夹" } require(defaultFavoriteFolder != null) { "Not found default favorite folder" } addVideoToFavoriteFolder(listOf(defaultFavoriteFolder.id)) }.onFailure { logger.fInfo { "Add video to default favorite folder failed: ${it.stackTraceToString()}" } it.message ?: "unknown error".toast(context) } } LaunchedEffect(Unit) { if (intent.hasExtra("aid")) { val aid = intent.getIntExtra("aid", 170001) fromSeason = intent.getBooleanExtra("fromSeason", false) //获取视频信息 scope.launch(Dispatchers.Default) { runCatching { val response = BiliApi.getVideoInfo(av = aid, sessData = Prefs.sessData) videoInfo = response.getResponseData() updateV2Data() if (Prefs.isLogin) updateFavoriteData(aid) //如果是从剧集跳转过来的,就直接播放 P1 if (fromSeason) { val playPart = videoInfo!!.pages.first() launchPlayerActivity( context = context, avid = videoInfo!!.aid, cid = playPart.cid, title = videoInfo!!.title, partTitle = videoInfo!!.pages.find { it.cid == playPart.cid }!!.part, played = if (playPart.cid == lastPlayedCid) lastPlayedTime else 0, fromSeason = true, isVerticalVideo = containsVerticalScreenVideo ) context.finish() } else if (videoInfo?.isSeasonDisplay == true) { //如果不是剧集,则设置分p数据,以便播放器读取(合集) val partVideoList = videoInfo!!.ugcSeason!!.sections[0].episodes.mapIndexed { index, episode -> VideoListItem( aid = episode.aid, cid = episode.cid, title = episode.title, index = index, isEpisode = false ) } videoInfoRepository.videoList.clear() videoInfoRepository.videoList.addAll(partVideoList) } else { //如果不是剧集,则设置分p数据,以便播放器读取(分P) val partVideoList = videoInfo!!.pages.mapIndexed { index, videoPage -> VideoListItem( aid = aid, cid = videoPage.cid, title = videoPage.part, index = index, isEpisode = false ) } videoInfoRepository.videoList.clear() videoInfoRepository.videoList.addAll(partVideoList) } }.onFailure { tip = it.localizedMessage ?: "未知错误" logger.fInfo { "Get video info failed: ${it.stackTraceToString()}" } } } //如果是从剧集跳转过来的,就不需要获取相关视频等信息,因为页面一直都是 Loading if (!fromSeason) { updateRelationVideos(aid.toLong()) updateTags(aid) } } } LaunchedEffect(videoInfo) { //如果是从剧集页跳转回来的,那就不需要再跳转到剧集页了 if (fromSeason) return@LaunchedEffect videoInfo?.let { logger.fInfo { "Redirect url: ${videoInfo?.redirectUrl}" } if (it.redirectUrl?.contains("ep") == true) { runCatching { //redirectUrl example https://www.bilibili.com/bangumi/play/ep706549?theme=movie val epid = videoInfo!!.redirectUrl!!.split("ep", "?")[1].toInt() logger.fInfo { "Redirect to season activity: ep${epid}" } SeasonInfoActivity.actionStart(context, epid) context.finish() }.onFailure { logger.fWarn { "Redirect failed: ${it.stackTraceToString()}" } } } else { logger.fInfo { "No redirection required" } } if (!fromSeason) updateRelationData() } } DisposableEffect(lifecycleOwner) { val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_PAUSE) { paused = true } else if (event == Lifecycle.Event.ON_RESUME) { // 如果 pause==true 那可能是从播放页返回回来的,此时更新历史记录 if (paused) updateV2Data() } } lifecycleOwner.lifecycle.addObserver(observer) onDispose { lifecycleOwner.lifecycle.removeObserver(observer) } } if (videoInfo == null || videoInfo?.redirectUrl?.contains("ep") == true || fromSeason) { Box( modifier = Modifier .fillMaxSize() .background(Color.Black) ) { Text( modifier = Modifier.align(Alignment.Center), text = tip ) } } else { Scaffold( containerColor = Color.Black ) { innerPadding -> Box( modifier.padding(innerPadding) ) { Image( modifier = Modifier.fillMaxSize(), painter = rememberAsyncImagePainter( model = ImageRequest.Builder(LocalContext.current) .data(if (videoInfo!!.isSeasonDisplay) videoInfo!!.ugcSeason!!.cover else videoInfo!!.pic) .transformations(BlurTransformation(LocalContext.current, 20f, 5f)) .build() ), contentDescription = null, contentScale = ContentScale.FillBounds, alpha = 0.6f ) TvLazyColumn( contentPadding = PaddingValues(top = 16.dp, bottom = 32.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { item { Column( verticalArrangement = Arrangement.spacedBy(8.dp) ) { if (containsVerticalScreenVideo) { ArgueTip(text = stringResource(R.string.video_info_argue_tip_vertical_screen)) } if ((videoInfo?.stat?.argueMsg ?: "") != "") { ArgueTip(text = videoInfo!!.stat.argueMsg) } } } item { VideoInfoData( videoInfo = videoInfo!!, relations = relations, tags = tags, isFavorite = favorited, userFavoriteFolders = favoriteFolders, favoriteFolderIds = videoInFavoriteFolderIds, onClickCover = { logger.fInfo { "Click video cover" } launchPlayerActivity( context = context, avid = videoInfo!!.aid, cid = videoInfo!!.pages.first().cid, title = videoInfo!!.title, partTitle = videoInfo!!.pages.first().part, played = if (videoInfo!!.cid == lastPlayedCid) lastPlayedTime else 0, fromSeason = false, isVerticalVideo = containsVerticalScreenVideo ) }, onClickUp = { UpInfoActivity.actionStart( context, mid = videoInfo!!.owner.mid, name = videoInfo!!.owner.name ) }, onAddFollow = { modifyRelation(FollowAction.AddFollow) { updateRelationData() } }, onDelFollow = { modifyRelation(FollowAction.DelFollow) { updateRelationData() } }, onClickTip = { tag -> TagActivity.actionStart( context = context, tagId = tag.tagId, tagName = tag.tagName ) }, onAddToDefaultFavoriteFolder = { addVideoToDefaultFavoriteFolder() favorited = true }, onUpdateFavoriteFolders = { addVideoToFavoriteFolder(it) favorited = it.isNotEmpty() videoInFavoriteFolderIds.swapList(it) } ) } item { VideoDescription( description = videoInfo?.desc ?: "no desc" ) } if (videoInfo?.isSeasonDisplay != true) { item { VideoPartRow( pages = videoInfo?.pages ?: emptyList(), lastPlayedCid = lastPlayedCid, lastPlayedTime = lastPlayedTime, enablePartListDialog = videoInfo?.pages?.size ?: 0 > 5, onClick = { cid -> logger.fInfo { "Click video part: [av:${videoInfo?.aid}, bv:${videoInfo?.bvid}, cid:$cid]" } launchPlayerActivity( context = context, avid = videoInfo!!.aid, cid = cid, title = videoInfo!!.title, partTitle = videoInfo!!.pages.find { it.cid == cid }!!.part, played = if (cid == lastPlayedCid) lastPlayedTime else 0, fromSeason = false, isVerticalVideo = containsVerticalScreenVideo ) } ) } } else { item { VideoUgcSeasonRow( episodes = videoInfo?.ugcSeason?.sections?.get(0)?.episodes ?: emptyList(), lastPlayedCid = lastPlayedCid, lastPlayedTime = lastPlayedTime, enableUgcListDialog = videoInfo?.ugcSeason?.sections?.get(0)?.episodes?.size ?: 0 > 5, onClick = { aid, cid -> logger.fInfo { "Click ugc season part: [av:${videoInfo?.aid}, bv:${videoInfo?.bvid}, cid:$cid]" } launchPlayerActivity( context = context, avid = aid, cid = cid, title = videoInfo!!.title, partTitle = videoInfo!!.ugcSeason!!.sections[0].episodes.find { it.cid == cid }!!.title, played = if (cid == lastPlayedCid) lastPlayedTime else 0, fromSeason = false, isVerticalVideo = containsVerticalScreenVideo ) } ) } } item { VideosRow( header = stringResource(R.string.video_info_related_video_title), videos = relatedVideos, showMore = {} ) } } } } } } @OptIn(ExperimentalTvMaterial3Api::class) @Composable fun ArgueTip( modifier: Modifier = Modifier, text: String ) { SurfaceWithoutClickable( modifier = modifier .fillMaxWidth() .padding(horizontal = 50.dp), color = Color.Yellow.copy(alpha = 0.2f), contentColor = Color.Yellow, shape = MaterialTheme.shapes.small ) { Row( modifier = Modifier.padding( horizontal = 16.dp, vertical = 8.dp ), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalAlignment = Alignment.CenterVertically ) { Icon( imageVector = Icons.Rounded.Warning, contentDescription = null, tint = Color.Yellow ) Text(text = text) } } } @OptIn(ExperimentalTvMaterial3Api::class) @Composable fun VideoInfoData( modifier: Modifier = Modifier, videoInfo: VideoInfo, relations: RelationData?, tags: List<Tag>, isFavorite: Boolean, userFavoriteFolders: List<UserFavoriteFoldersData.UserFavoriteFolder> = emptyList(), favoriteFolderIds: List<Long> = emptyList(), onClickCover: () -> Unit, onClickUp: () -> Unit, onAddFollow: () -> Unit, onDelFollow: () -> Unit, onClickTip: (Tag) -> Unit, onAddToDefaultFavoriteFolder: () -> Unit, onUpdateFavoriteFolders: (List<Long>) -> Unit ) { val scope = rememberCoroutineScope() val localDensity = LocalDensity.current val focusRequester = remember { FocusRequester() } var heightIs by remember { mutableStateOf(0.dp) } LaunchedEffect(Unit) { focusRequester.requestFocus(scope) } Row( modifier = modifier .padding(horizontal = 50.dp, vertical = 16.dp), ) { AsyncImage( modifier = Modifier .focusRequester(focusRequester) .weight(3f) .aspectRatio(1.6f) .clip(MaterialTheme.shapes.large) .onGloballyPositioned { coordinates -> heightIs = with(localDensity) { coordinates.size.height.toDp() } } .focusedBorder(MaterialTheme.shapes.large) .clickable { onClickCover() }, model = if (videoInfo.isSeasonDisplay) videoInfo.ugcSeason!!.cover else videoInfo.pic, contentDescription = null, contentScale = ContentScale.FillBounds ) Spacer(modifier = Modifier.width(16.dp)) Column( modifier = Modifier .weight(7f) .height(heightIs), verticalArrangement = Arrangement.SpaceBetween ) { Text( text = videoInfo.title, style = MaterialTheme.typography.titleLarge, maxLines = 1, overflow = TextOverflow.Ellipsis, color = Color.White ) Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically ) { Row( modifier = Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically ) { UpButton( name = videoInfo.owner.name, followed = listOf( RelationType.Followed, RelationType.FollowedQuietly, RelationType.BothFollowed ).contains(relations?.relation?.attribute), showFollowButton = relations != null, onClickUp = onClickUp, onAddFollow = onAddFollow, onDelFollow = onDelFollow ) } Text( modifier = Modifier.weight(1f), text = stringResource( R.string.video_info_time, Date(videoInfo.ctime.toLong() * 1000).formatPubTimeString() ), maxLines = 1, color = Color.White ) } Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween ) { Row { Box(modifier = Modifier.focusable(true)) {} FavoriteButton( isFavorite = isFavorite, userFavoriteFolders = userFavoriteFolders, favoriteFolderIds = favoriteFolderIds, onAddToDefaultFavoriteFolder = onAddToDefaultFavoriteFolder, onUpdateFavoriteFolders = onUpdateFavoriteFolders ) Box(modifier = Modifier.focusable(true)) {} } Text( text = "点赞:${videoInfo.stat.like}", color = Color.White ) Text( text = "投币:${videoInfo.stat.coin}", color = Color.White ) Text( text = "收藏:${videoInfo.stat.favorite}", color = Color.White ) } Row( verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp) ) { Text( text = stringResource(R.string.video_info_tags), color = Color.White ) TvLazyRow( contentPadding = PaddingValues(horizontal = 8.dp), horizontalArrangement = Arrangement.spacedBy(4.dp) ) { items(tags) { tag -> Surface( modifier = Modifier, colors = ClickableSurfaceDefaults.colors( containerColor = Color.White.copy(alpha = 0.2f), focusedContainerColor = Color.White.copy(alpha = 0.2f), pressedContainerColor = Color.White.copy(alpha = 0.2f) ), shape = ClickableSurfaceDefaults.shape(shape = MaterialTheme.shapes.small), border = ClickableSurfaceDefaults.border( focusedBorder = Border( border = BorderStroke(width = 3.dp, color = Color.White), shape = MaterialTheme.shapes.small ) ), scale = ClickableSurfaceDefaults.scale(focusedScale = 1f), onClick = { onClickTip(tag) } ) { Text( modifier = Modifier.padding(8.dp, 4.dp), text = tag.tagName, color = Color.White ) } } } } } } } @OptIn(ExperimentalTvMaterial3Api::class) @Composable private fun UpButton( modifier: Modifier = Modifier, name: String, followed: Boolean, showFollowButton: Boolean = false, onClickUp: () -> Unit, onAddFollow: () -> Unit, onDelFollow: () -> Unit ) { val view = LocalView.current val isLogin by remember { mutableStateOf(if (!view.isInEditMode) Prefs.isLogin else true) } Row( modifier = modifier, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(2.dp) ) { Row( modifier = Modifier .clip(MaterialTheme.shapes.small) .background(Color.White.copy(alpha = 0.2f)) .focusedBorder(MaterialTheme.shapes.small) .padding(4.dp) .clickable { onClickUp() } ) { UpIcon(color = Color.White) Text(text = name, color = Color.White) } AnimatedVisibility(visible = isLogin && showFollowButton) { Row( modifier = Modifier .clip(MaterialTheme.shapes.small) .background(Color.White.copy(alpha = 0.2f)) .focusedBorder(MaterialTheme.shapes.small) .padding(horizontal = 4.dp, vertical = 3.dp) .clickable { if (followed) onDelFollow() else onAddFollow() } .animateContentSize() ) { if (followed) { Icon( imageVector = Icons.Rounded.Done, contentDescription = null, tint = Color.White ) Text(text = stringResource(R.string.video_info_followed), color = Color.White) } else { Icon( imageVector = Icons.Rounded.Add, contentDescription = null, tint = Color.White ) Text(text = stringResource(R.string.video_info_follow), color = Color.White) } } } } } @Composable fun VideoDescription( modifier: Modifier = Modifier, description: String ) { var hasFocus by remember { mutableStateOf(false) } val titleColor = if (hasFocus) Color.White else Color.White.copy(alpha = 0.6f) val titleFontSize by animateFloatAsState(if (hasFocus) 30f else 14f) var showDescriptionDialog by remember { mutableStateOf(false) } Column( modifier = modifier .padding(horizontal = 50.dp), ) { Text( text = stringResource(R.string.video_info_description_title), fontSize = titleFontSize.sp, color = titleColor ) Box( modifier = Modifier .padding(top = 15.dp) .onFocusChanged { hasFocus = it.hasFocus } .clip(MaterialTheme.shapes.medium) .focusedBorder(MaterialTheme.shapes.medium) .padding(8.dp) .clickable { showDescriptionDialog = true } ) { Text( text = description, maxLines = 2, overflow = TextOverflow.Ellipsis, color = Color.White ) } } VideoDescriptionDialog( show = showDescriptionDialog, onHideDialog = { showDescriptionDialog = false }, description = description ) } @Composable fun VideoDescriptionDialog( modifier: Modifier = Modifier, show: Boolean, onHideDialog: () -> Unit, description: String ) { if (show) { AlertDialog( modifier = modifier, onDismissRequest = { onHideDialog() }, title = { Text( text = stringResource(R.string.video_info_description_title), color = Color.White ) }, text = { TvLazyColumn { item { Text(text = description) } } }, confirmButton = {} ) } } @OptIn(ExperimentalTvMaterial3Api::class) @Composable fun VideoPartButton( modifier: Modifier = Modifier, index: Int, title: String, duration: Int, played: Int = 0, onClick: () -> Unit ) { Surface( modifier = modifier, colors = ClickableSurfaceDefaults.colors( containerColor = MaterialTheme.colorScheme.primary, focusedContainerColor = MaterialTheme.colorScheme.primary, pressedContainerColor = MaterialTheme.colorScheme.primary ), shape = ClickableSurfaceDefaults.shape(shape = MaterialTheme.shapes.medium), border = ClickableSurfaceDefaults.border( focusedBorder = Border( border = BorderStroke(width = 3.dp, color = Color.White), shape = MaterialTheme.shapes.large ) ), onClick = { onClick() } ) { Box( modifier = Modifier .size(200.dp, 64.dp) ) { Box( modifier = Modifier .background(Color.Black.copy(alpha = 0.2f)) .fillMaxHeight() .fillMaxWidth(if (played < 0) 1f else (played / (duration * 1000f))) ) {} Text( modifier = Modifier .padding(8.dp), text = "P$index $title", maxLines = 2, overflow = TextOverflow.Ellipsis ) } } } @OptIn(ExperimentalTvMaterial3Api::class) @Composable private fun VideoPartRowButton( modifier: Modifier = Modifier, onClick: () -> Unit ) { Surface( modifier = modifier.height(64.dp), colors = ClickableSurfaceDefaults.colors( containerColor = MaterialTheme.colorScheme.primary, focusedContainerColor = MaterialTheme.colorScheme.primary, pressedContainerColor = MaterialTheme.colorScheme.primary ), shape = ClickableSurfaceDefaults.shape(shape = MaterialTheme.shapes.medium), border = ClickableSurfaceDefaults.border( focusedBorder = Border( border = BorderStroke(width = 3.dp, color = Color.White), shape = MaterialTheme.shapes.medium ) ), onClick = onClick ) { Box( modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center ) { Icon( modifier = Modifier .size(48.dp) .rotate(90f), imageVector = Icons.Rounded.ViewModule, contentDescription = null ) } } } @Composable fun VideoPartRow( modifier: Modifier = Modifier, pages: List<VideoPage>, lastPlayedCid: Int = 0, lastPlayedTime: Int = 0, enablePartListDialog: Boolean = false, onClick: (cid: Int) -> Unit ) { var hasFocus by remember { mutableStateOf(false) } var showPartListDialog by remember { mutableStateOf(false) } val titleColor = if (hasFocus) Color.White else Color.White.copy(alpha = 0.6f) val titleFontSize by animateFloatAsState(if (hasFocus) 30f else 14f) Column( modifier = modifier .padding(start = 50.dp) .onFocusChanged { hasFocus = it.hasFocus }, verticalArrangement = Arrangement.SpaceBetween ) { Text( text = stringResource(R.string.video_info_part_row_title), fontSize = titleFontSize.sp, color = titleColor ) TvLazyRow( modifier = Modifier.padding(top = 15.dp), contentPadding = PaddingValues(12.dp), horizontalArrangement = Arrangement.spacedBy(16.dp) ) { if (enablePartListDialog) { item { VideoPartRowButton( onClick = { showPartListDialog = true } ) } } itemsIndexed(items = pages, key = { _, page -> page.cid }) { index, page -> VideoPartButton( index = index + 1, title = page.part, played = if (page.cid == lastPlayedCid) lastPlayedTime else 0, duration = page.duration, onClick = { onClick(page.cid) } ) } } } VideoPartListDialog( show = showPartListDialog, onHideDialog = { showPartListDialog = false }, pages = pages, title = "分 P 列表", onClick = onClick ) } @Composable fun VideoUgcSeasonRow( modifier: Modifier = Modifier, episodes: List<UgcSeason.Section.Episode>, lastPlayedCid: Int = 0, lastPlayedTime: Int = 0, enableUgcListDialog: Boolean = false, onClick: (avid: Int, cid: Int) -> Unit ) { var hasFocus by remember { mutableStateOf(false) } var showUgcListDialog by remember { mutableStateOf(false) } val titleColor = if (hasFocus) Color.White else Color.White.copy(alpha = 0.6f) val titleFontSize by animateFloatAsState(if (hasFocus) 30f else 14f) Column( modifier = modifier .padding(start = 50.dp) .onFocusChanged { hasFocus = it.hasFocus }, verticalArrangement = Arrangement.SpaceBetween ) { Text( text = stringResource(R.string.video_info_ugc_season_row_title), fontSize = titleFontSize.sp, color = titleColor ) TvLazyRow( modifier = Modifier.padding(top = 15.dp), contentPadding = PaddingValues(12.dp), horizontalArrangement = Arrangement.spacedBy(16.dp) ) { if (enableUgcListDialog) { item { VideoPartRowButton( onClick = { showUgcListDialog = true } ) } } itemsIndexed(items = episodes) { index, episode -> VideoPartButton( index = index + 1, title = episode.title, played = if (episode.cid == lastPlayedCid) lastPlayedTime else 0, duration = episode.arc.duration, onClick = { onClick(episode.aid, episode.cid) } ) } } } VideoUgcListDialog( show = showUgcListDialog, onHideDialog = { showUgcListDialog = false }, episodes = episodes, title = "合集列表", onClick = onClick ) } @OptIn(ExperimentalTvMaterial3Api::class) @Composable private fun VideoPartListDialog( modifier: Modifier = Modifier, show: Boolean, title: String, pages: List<VideoPage>, onHideDialog: () -> Unit, onClick: (cid: Int) -> Unit ) { val scope = rememberCoroutineScope() var selectedTabIndex by remember { mutableIntStateOf(0) } val tabCount by remember { mutableIntStateOf(ceil(pages.size / 20.0).toInt()) } val selectedVideoPart = remember { mutableStateListOf<VideoPage>() } val tabRowFocusRequester = remember { FocusRequester() } val videoListFocusRequester = remember { FocusRequester() } val listState = rememberTvLazyGridState() LaunchedEffect(selectedTabIndex) { val fromIndex = selectedTabIndex * 20 var toIndex = (selectedTabIndex + 1) * 20 if (toIndex >= pages.size) { toIndex = pages.size } selectedVideoPart.swapList(pages.subList(fromIndex, toIndex)) } LaunchedEffect(show) { if (show && tabCount > 1) tabRowFocusRequester.requestFocus(scope) if (show && tabCount == 1) videoListFocusRequester.requestFocus(scope) } if (show) { AlertDialog( modifier = modifier, title = { Text(text = title) }, onDismissRequest = { onHideDialog() }, confirmButton = {}, properties = DialogProperties(usePlatformDefaultWidth = false), text = { Column( modifier = Modifier.size(600.dp, 330.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { TabRow( modifier = Modifier .onFocusChanged { if (it.hasFocus) { scope.launch(Dispatchers.Main) { listState.scrollToItem(0) } } }, selectedTabIndex = selectedTabIndex, separator = { Spacer(modifier = Modifier.width(12.dp)) }, ) { for (i in 0 until tabCount) { Tab( modifier = if (i == 0) Modifier.focusRequester( tabRowFocusRequester ) else Modifier, selected = i == selectedTabIndex, onFocus = { selectedTabIndex = i }, ) { Text( text = "P${i * 20 + 1}-${(i + 1) * 20}", fontSize = 12.sp, color = LocalContentColor.current, modifier = Modifier.padding( horizontal = 16.dp, vertical = 6.dp ) ) } } } TvLazyVerticalGrid( state = listState, columns = TvGridCells.Fixed(2), contentPadding = PaddingValues(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp) ) { itemsIndexed( items = selectedVideoPart, key = { _, video -> video.cid } ) { index, page -> val buttonModifier = if (index == 0) Modifier.focusRequester(videoListFocusRequester) else Modifier VideoPartButton( modifier = buttonModifier, index = index + 1, title = page.part, played = 0, duration = page.duration, onClick = { onClick(page.cid) } ) } } } } ) } } @OptIn(ExperimentalTvMaterial3Api::class) @Composable private fun VideoUgcListDialog( modifier: Modifier = Modifier, show: Boolean, title: String, episodes: List<UgcSeason.Section.Episode>, onHideDialog: () -> Unit, onClick: (avid: Int, cid: Int) -> Unit ) { val scope = rememberCoroutineScope() var selectedTabIndex by remember { mutableIntStateOf(0) } val tabCount by remember { mutableIntStateOf(ceil(episodes.size / 20.0).toInt()) } val selectedVideoPart = remember { mutableStateListOf<UgcSeason.Section.Episode>() } val tabRowFocusRequester = remember { FocusRequester() } val videoListFocusRequester = remember { FocusRequester() } val listState = rememberTvLazyGridState() LaunchedEffect(selectedTabIndex) { val fromIndex = selectedTabIndex * 20 var toIndex = (selectedTabIndex + 1) * 20 if (toIndex >= episodes.size) { toIndex = episodes.size } selectedVideoPart.swapList(episodes.subList(fromIndex, toIndex)) } LaunchedEffect(show) { if (show && tabCount > 1) tabRowFocusRequester.requestFocus(scope) if (show && tabCount == 1) videoListFocusRequester.requestFocus(scope) } if (show) { AlertDialog( modifier = modifier, title = { Text(text = title) }, onDismissRequest = { onHideDialog() }, confirmButton = {}, properties = DialogProperties(usePlatformDefaultWidth = false), text = { Column( modifier = Modifier.size(600.dp, 330.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { TabRow( modifier = Modifier .onFocusChanged { if (it.hasFocus) { scope.launch(Dispatchers.Main) { listState.scrollToItem(0) } } }, selectedTabIndex = selectedTabIndex, separator = { Spacer(modifier = Modifier.width(12.dp)) }, ) { for (i in 0 until tabCount) { Tab( modifier = if (i == 0) Modifier.focusRequester( tabRowFocusRequester ) else Modifier, selected = i == selectedTabIndex, onFocus = { selectedTabIndex = i }, ) { Text( text = "P${i * 20 + 1}-${(i + 1) * 20}", fontSize = 12.sp, color = LocalContentColor.current, modifier = Modifier.padding( horizontal = 16.dp, vertical = 6.dp ) ) } } } TvLazyVerticalGrid( state = listState, columns = TvGridCells.Fixed(2), contentPadding = PaddingValues(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp) ) { itemsIndexed( items = selectedVideoPart, key = { _, video -> video.cid } ) { index, episode -> val buttonModifier = if (index == 0) Modifier.focusRequester(videoListFocusRequester) else Modifier VideoPartButton( modifier = buttonModifier, index = index + 1, title = episode.title, played = 0, duration = episode.arc.duration, onClick = { onClick(episode.aid, episode.cid) } ) } } } } ) } } @Preview @Composable fun VideoPartButtonShortTextPreview() { BVTheme { VideoPartButton( index = 2, title = "这是一段短文字", duration = 100, onClick = {} ) } } @Preview @Composable fun VideoPartButtonLongTextPreview() { BVTheme { VideoPartButton( index = 2, title = "这可能是我这辈子距离梅西最近的一次", played = 23333, duration = 100, onClick = {} ) } } @Preview @Composable fun VideoPartRowPreview() { val pages = remember { mutableStateListOf<VideoPage>() } for (i in 0..10) { pages.add( VideoPage( 1000 + i, 0, "", "这可能是我这辈子距离梅西最近的一次", 10, "", "", Dimension(0, 0, 0) ) ) } BVTheme { VideoPartRow(pages = pages, onClick = {}) } } @Preview @Composable fun VideoDescriptionPreview() { BVTheme { VideoDescription(description = "12435678") } } @Preview @Composable private fun UpButtonPreview() { var followed by remember { mutableStateOf(false) } BVTheme { UpButton( name = "12435678", followed = followed, onClickUp = { followed = !followed }, onAddFollow = {}, onDelFollow = {} ) } }
27
Kotlin
95
812
f4bdfb9f59f265c2d9e8c9ad99a58b1050885582
55,396
bv
MIT License
src/main/kotlin/org/goodmath/simplex/runtime/values/manifold/SPolygon.kt
MarkChuCarroll
831,231,194
false
{"Kotlin": 333643, "JavaScript": 5595, "ANTLR": 3455, "Emacs Lisp": 1296, "Scheme": 450}
/* * Copyright 2024 <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 org.goodmath.simplex.runtime.values.manifold import manifold3d.manifold.CrossSection import manifold3d.pub.Polygons import manifold3d.pub.SimplePolygon import org.goodmath.simplex.ast.types.Type import org.goodmath.simplex.runtime.Env import org.goodmath.simplex.runtime.values.FunctionSignature import org.goodmath.simplex.runtime.values.MethodSignature import org.goodmath.simplex.runtime.values.Param import org.goodmath.simplex.runtime.values.Value import org.goodmath.simplex.runtime.values.ValueType import org.goodmath.simplex.runtime.values.primitives.VectorValue import org.goodmath.simplex.runtime.values.primitives.VectorValueType import org.goodmath.simplex.runtime.values.primitives.PrimitiveFunctionValue import org.goodmath.simplex.runtime.values.primitives.PrimitiveMethod import org.goodmath.simplex.runtime.values.primitives.Vec2 import org.goodmath.simplex.runtime.values.primitives.Vec2ValueType import org.goodmath.simplex.twist.Twist class SPolygon(val poly: SimplePolygon) : Value { override val valueType: ValueType = SPolygonType override fun twist(): Twist = Twist.obj( "Polygon", Twist.attr("position", poly.position().toString()), Twist.attr("size", poly.size().toString()), ) } object SPolygonType : ValueType() { override val name: String = "Polygon" override val asType: Type by lazy { Type.simple("Polygon") } override fun isTruthy(v: Value): Boolean { return true } override val providesFunctions: List<PrimitiveFunctionValue> by lazy { listOf( object : PrimitiveFunctionValue( "polygon", FunctionSignature.simple(listOf(Param("points", Type.vector(Vec2ValueType.asType))), asType), ) { override fun execute(args: List<Value>): Value { val points = VectorValueType.of(Vec2ValueType).assertIs(args[0]).elements val floatArray = DoubleArray( points.size, { idx -> val halfIdx = idx / 2 val mod = idx % 2 assertIsFloat(points[halfIdx + mod]) }, ) return SPolygon(SimplePolygon.FromArray(floatArray)) } }, object : PrimitiveFunctionValue( "polygons_hull", FunctionSignature.simple( listOf(Param("polygons", Type.vector(asType))), SliceValueType.asType ), ) { override fun execute(args: List<Value>): Value { val polyList = VectorValueType.of(SPolygonType).assertIs(args[0]).elements val polys = Polygons() polys.resize(polyList.size.toLong()) for (p in polyList) { polys.pushBack(assertIs(p).poly) } return Slice(CrossSection.ConvexHull(polys)) } }, ) } override val providesPrimitiveMethods: List<PrimitiveMethod> by lazy { listOf( object : PrimitiveMethod( "points", MethodSignature.simple(asType, emptyList<Param>(), Type.vector(Vec2ValueType.asType)), ) { override fun execute(target: Value, args: List<Value>, env: Env): Value { val self = assertIs(target).poly val result = ArrayList<Value>() for (p in self) { result.add(Vec2(p.x(), p.y())) } return VectorValue(Vec2ValueType, result) } }, object : PrimitiveMethod( "convex_hull", MethodSignature.simple(asType, emptyList<Param>(), SliceValueType.asType), ) { override fun execute(target: Value, args: List<Value>, env: Env): Value { val poly = assertIs(target).poly return Slice(CrossSection.ConvexHull(poly)) } }, ) } override val providesVariables: Map<String, Value> = emptyMap() override fun assertIs(v: Value): SPolygon { if (v is SPolygon) { return v } else { throwTypeError(v) } } }
0
Kotlin
0
0
e593a5a4cb31f8cbad13d16822f8d141e6d5a217
5,265
simplex
Apache License 2.0
app/src/main/kotlin/org/mediasoup/droid/lib/JsonUtils.kt
ow-ro
373,256,601
true
{"Kotlin": 120969}
package org.mediasoup.droid.lib import org.json.JSONArray import org.json.JSONException import org.json.JSONObject object JsonUtils { fun jsonPut(json: JSONObject, key: String, value: Any?) { try { json.put(key, value) } catch (e: JSONException) { e.printStackTrace() } } fun toJsonObject(data: String): JSONObject { return try { JSONObject(data) } catch (e: JSONException) { e.printStackTrace() JSONObject() } } fun toJsonArray(data: String): JSONArray { return try { JSONArray(data) } catch (e: JSONException) { e.printStackTrace() JSONArray() } } }
0
Kotlin
0
0
e7ed9c822e0c63430bfc9d5d3f0081a187850452
747
mediasoup-demo-android
MIT License
app/src/main/java/org/wit/rightcard/helpers/DataGenerator.kt
sveggen
251,733,790
false
null
package org.wit.rightcard.helpers import org.wit.rightcard.persistence.models.BenefitModel import org.wit.rightcard.persistence.models.CardBenefitsModel import org.wit.rightcard.persistence.models.CardModel import org.wit.rightcard.persistence.models.ShopModel import org.wit.rightcard.persistence.stores.BenefitStore import org.wit.rightcard.persistence.stores.CardBenefitsStore import org.wit.rightcard.persistence.stores.CardStore import org.wit.rightcard.persistence.stores.ShopStore /** * Contains functions to generate data that is not generated in other ways in the app. */ fun createBenefit(){ val benefitModel = BenefitModel("", "5% Trumf-bonus on mondays", "Grocery", "5%") BenefitStore().create(benefitModel) } fun createCardBenefit(){ val shopid = "51672797-153b-4cea-be57-5bb7431c538a" val benefitid = "40708937-0c2a-408a-8003-8f7fa9dec039" val creditcardid = "720f3839-fd89-416c-9537-83a28e5899d1" val cardBenefitModel = CardBenefitsModel(shopid + benefitid + creditcardid, shopid, benefitid, creditcardid) CardBenefitsStore().create(cardBenefitModel) } fun createStore(){ val shopModel = ShopModel("", "") ShopStore().create(shopModel) } fun createCard(){ val cardModel = CardModel() CardStore().create(cardModel) }
0
Kotlin
0
1
8a0361eff431235ee26027e1c53636b3da9653b4
1,283
RightCard
MIT License
app/src/main/java/com/wavesplatform/wallet/v2/injection/module/ApplicationModule.kt
wavesplatform
98,419,999
false
null
/* * Created by <NAME> on 1/4/2019 * Copyright © 2019 Waves Platform. All rights reserved. */ package com.wavesplatform.wallet.v2.injection.module import android.content.Context import com.wavesplatform.wallet.App import com.wavesplatform.wallet.v2.injection.qualifier.ApplicationContext import dagger.Binds import dagger.Module @Module abstract class ApplicationModule { @Binds @ApplicationContext internal abstract fun application(app: App): Context }
2
null
52
55
5f4106576dc4fe377a355d045f638e7469cd6abe
473
WavesWallet-android
MIT License
core/ui/components/src/main/kotlin/top/chengdongqing/weui/core/ui/components/swiper/Swiper.kt
chengdongqing
782,566,304
false
{"Kotlin": 894390}
package top.chengdongqing.weui.core.ui.components.swiper import androidx.compose.animation.core.animateDpAsState import androidx.compose.foundation.background import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.BoxScope import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.offset import androidx.compose.foundation.layout.width import androidx.compose.foundation.pager.HorizontalPager import androidx.compose.foundation.pager.PagerScope import androidx.compose.foundation.pager.PagerState import androidx.compose.foundation.pager.rememberPagerState import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip import androidx.compose.ui.graphics.Color import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import kotlinx.coroutines.delay @Composable fun <T> WeSwiper( options: List<T>, modifier: Modifier = Modifier, state: PagerState = rememberPagerState { options.size }, contentPadding: PaddingValues = PaddingValues(0.dp), pageSpacing: Dp = 0.dp, autoplay: Boolean = true, interval: Long = 3000, indicator: (@Composable BoxScope.(count: Int, current: Int) -> Unit)? = { count, current -> WeSwiperDefaults.Indicator( count, current, Modifier .align(Alignment.BottomCenter) .offset(y = (-10).dp) ) }, content: @Composable (PagerScope.(Int, T) -> Unit) ) { if (autoplay) { LaunchedEffect(state.settledPage) { delay(interval) val targetPage = (state.currentPage + 1) % state.pageCount state.animateScrollToPage(targetPage) } } Box { HorizontalPager( state, modifier, contentPadding, pageSpacing = pageSpacing ) { index -> content(index, options[index]) } if (indicator != null) { indicator(options.size, state.currentPage) } } } object WeSwiperDefaults { @Composable fun Indicator(count: Int, current: Int, modifier: Modifier = Modifier) { Row( modifier .width((count * 16).dp) .height(3.dp) .clip(RoundedCornerShape(2.dp)) .background(Color.White.copy(0.2f)) ) { val offsetX by animateDpAsState( targetValue = (current * 16).dp, label = "OffsetAnimation" ) Box( Modifier .width(16.dp) .height(3.dp) .offset(x = offsetX) .clip(RoundedCornerShape(2.dp)) .background(Color.White) ) } } }
0
Kotlin
4
8
eb773e75aacb801cb24adb41db9fe17224eb883a
3,146
WeUI
Apache License 2.0
app/src/main/java/link/download/ru/contact.kt
Maxuttta
795,203,771
false
{"Kotlin": 163861}
package link.download.ru import android.annotation.SuppressLint import android.content.Intent import android.os.Bundle import android.provider.ContactsContract import androidx.appcompat.app.AppCompatActivity import androidx.recyclerview.widget.LinearLayoutManager import com.google.firebase.database.DataSnapshot import com.google.firebase.database.DatabaseError import com.google.firebase.database.FirebaseDatabase import com.google.firebase.database.ValueEventListener import link.download.ru.databinding.ActivityContactBinding class contact : AppCompatActivity() { private lateinit var binding: ActivityContactBinding private lateinit var adapter1: ContactAdapter private lateinit var adapter2: ContactAdapter var id = "" var name = "" var phone = "" override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) binding = ActivityContactBinding.inflate(layoutInflater) setContentView(binding.root) adapter1 = ContactAdapter() adapter2 = ContactAdapter() binding.recyclerView1.layoutManager = LinearLayoutManager(this@contact) binding.recyclerView2.layoutManager = LinearLayoutManager(this@contact) binding.recyclerView1.adapter = adapter1 binding.recyclerView2.adapter = adapter2 getContacts() viewAdapter() } private fun viewAdapter() { binding.apply { back.setOnClickListener { val intent = Intent(this@contact, Listdrawer::class.java) startActivity(intent) overridePendingTransition(R.anim.from_right, R.anim.to_right) } } } override fun onBackPressed() { super.onBackPressed() val intent = Intent(this@contact, Listdrawer::class.java) startActivity(intent) overridePendingTransition(R.anim.from_left, R.anim.to_left) } @SuppressLint("Range") private fun getContacts() { val contactsList = mutableListOf<ContactData>() val contentResolver = this.contentResolver val cursor = contentResolver.query( ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC" ) cursor?.use { c -> while (c.moveToNext()) { val id = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)) val name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)) var phone = "" val hasPhone = c.getInt(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)) > 0 if (hasPhone) { val phoneCursor = contentResolver.query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", arrayOf(id), null ) phoneCursor?.use { pc -> if (pc.moveToFirst()) { phone = pc.getString(pc.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)) phone = formatPhoneNumber(phone) } } } val contact = ContactData(id, name, phone) adapter1.addItem(contact) } } } fun formatPhoneNumber(phoneNumber: String): String { return phoneNumber.replace("(", "") .replace(")", "") .replace("-", "") .replace(" ", "") } }
0
Kotlin
0
0
3a773195ee28e0fcb330e33fa149384fc2739836
3,775
Link-Rus-OFFICIAL
Apache License 2.0
app/src/main/java/com/misana/barcodeface/domain/model/Emotion.kt
MisaghM
864,967,262
false
{"Kotlin": 99707}
package com.misana.barcodeface.domain.model enum class Emotion { ANGRY, DISGUST, FEAR, HAPPY, NEUTRAL, SAD, SURPRISE; override fun toString() = when (this) { ANGRY -> "Angry" DISGUST -> "Disgust" FEAR -> "Fear" HAPPY -> "Happy" NEUTRAL -> "Neutral" SAD -> "Sad" SURPRISE -> "Surprise" } }
0
Kotlin
0
0
76a2d6ef2a4527a4ef288ee3a7589003ef253835
383
BarcodeFace
MIT License
core/src/commonTest/kotlin/maryk/core/aggregations/metric/SumTest.kt
marykdb
290,454,412
false
{"Kotlin": 3039791, "JavaScript": 1004}
package maryk.core.aggregations.metric import maryk.checkJsonConversion import maryk.checkProtoBufConversion import maryk.checkYamlConversion import maryk.core.extensions.toUnitLambda import maryk.core.query.RequestContext import maryk.test.models.TestMarykModel import kotlin.test.Test import kotlin.test.expect class SumTest { private val sum = Sum( TestMarykModel { int::ref } ) private val context = RequestContext( mapOf( TestMarykModel.name toUnitLambda { TestMarykModel } ), dataModel = TestMarykModel ) @Test fun convertToProtoBufAndBack() { checkProtoBufConversion(this.sum, Sum, { this.context }) } @Test fun convertToJSONAndBack() { expect( """ { "of": "int" } """.trimIndent() ) { checkJsonConversion(this.sum, Sum, { this.context }) } } @Test fun convertToYAMLAndBack() { expect( """ of: int """.trimIndent() ) { checkYamlConversion(this.sum, Sum, { this.context }) } } }
1
Kotlin
1
8
4c58b04a0189e13e5621a505a5bb82ce5e655ae0
1,166
maryk
Apache License 2.0
dsl/src/main/kotlin/io/cloudshiftdev/awscdkdsl/services/quicksight/CfnTemplateDrillDownFilterPropertyDsl.kt
cloudshiftinc
667,063,030
false
{"Kotlin": 70198112}
@file:Suppress( "RedundantVisibilityModifier", "RedundantUnitReturnType", "RemoveRedundantQualifierName", "unused", "UnusedImport", "ClassName", "REDUNDANT_PROJECTION", "DEPRECATION" ) package cloudshift.awscdk.dsl.services.quicksight import cloudshift.awscdk.common.CdkDslMarker import software.amazon.awscdk.IResolvable import software.amazon.awscdk.services.quicksight.CfnAnalysis /** * The drill down filter for the column hierarchies. * * This is a union type structure. For this structure to be valid, only one of the attributes can be * defined. * * 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.quicksight.*; * DrillDownFilterProperty drillDownFilterProperty = DrillDownFilterProperty.builder() * .categoryFilter(CategoryDrillDownFilterProperty.builder() * .categoryValues(List.of("categoryValues")) * .column(ColumnIdentifierProperty.builder() * .columnName("columnName") * .dataSetIdentifier("dataSetIdentifier") * .build()) * .build()) * .numericEqualityFilter(NumericEqualityDrillDownFilterProperty.builder() * .column(ColumnIdentifierProperty.builder() * .columnName("columnName") * .dataSetIdentifier("dataSetIdentifier") * .build()) * .value(123) * .build()) * .timeRangeFilter(TimeRangeDrillDownFilterProperty.builder() * .column(ColumnIdentifierProperty.builder() * .columnName("columnName") * .dataSetIdentifier("dataSetIdentifier") * .build()) * .rangeMaximum("rangeMaximum") * .rangeMinimum("rangeMinimum") * .timeGranularity("timeGranularity") * .build()) * .build(); * ``` * * [Documentation](http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-quicksight-analysis-drilldownfilter.html) */ @CdkDslMarker public class CfnAnalysisDrillDownFilterPropertyDsl { private val cdkBuilder: CfnAnalysis.DrillDownFilterProperty.Builder = CfnAnalysis.DrillDownFilterProperty.builder() /** * @param categoryFilter The category type drill down filter. This filter is used for string * type columns. */ public fun categoryFilter(categoryFilter: IResolvable) { cdkBuilder.categoryFilter(categoryFilter) } /** * @param categoryFilter The category type drill down filter. This filter is used for string * type columns. */ public fun categoryFilter(categoryFilter: CfnAnalysis.CategoryDrillDownFilterProperty) { cdkBuilder.categoryFilter(categoryFilter) } /** * @param numericEqualityFilter The numeric equality type drill down filter. This filter is used * for number type columns. */ public fun numericEqualityFilter(numericEqualityFilter: IResolvable) { cdkBuilder.numericEqualityFilter(numericEqualityFilter) } /** * @param numericEqualityFilter The numeric equality type drill down filter. This filter is used * for number type columns. */ public fun numericEqualityFilter( numericEqualityFilter: CfnAnalysis.NumericEqualityDrillDownFilterProperty ) { cdkBuilder.numericEqualityFilter(numericEqualityFilter) } /** * @param timeRangeFilter The time range drill down filter. This filter is used for date time * columns. */ public fun timeRangeFilter(timeRangeFilter: IResolvable) { cdkBuilder.timeRangeFilter(timeRangeFilter) } /** * @param timeRangeFilter The time range drill down filter. This filter is used for date time * columns. */ public fun timeRangeFilter(timeRangeFilter: CfnAnalysis.TimeRangeDrillDownFilterProperty) { cdkBuilder.timeRangeFilter(timeRangeFilter) } public fun build(): CfnAnalysis.DrillDownFilterProperty = cdkBuilder.build() }
3
Kotlin
0
3
256ad92aebe2bcf9a4160089a02c76809dbbedba
3,850
awscdk-dsl-kotlin
Apache License 2.0
platform/platform-impl/src/com/intellij/ide/actions/CloseOtherProjectsAction.kt
JetBrains
2,489,216
false
null
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions import com.intellij.openapi.actionSystem.AnActionEvent import com.intellij.openapi.project.Project import com.intellij.openapi.project.ProjectManager import com.intellij.ui.IdeUICustomization /** * @author Konstantin Bulenkov */ class CloseOtherProjectsAction : CloseProjectsActionBase() { init { templatePresentation.setText { IdeUICustomization.getInstance().projectMessage("action.close.other.projects.text") } templatePresentation.setDescription { IdeUICustomization.getInstance().projectMessage("action.close.other.projects.description") } } override fun canClose(project: Project, currentProject: Project) = project !== currentProject override fun shouldShow(e: AnActionEvent) = ProjectManager.getInstance().openProjects.size > 1 }
191
null
4372
13,319
4d19d247824d8005662f7bd0c03f88ae81d5364b
933
intellij-community
Apache License 2.0
native/src/main/kotlin/dev/sanmer/geomag/Geomag.kt
SanmerApps
583,580,288
false
null
package dev.sanmer.geomag import kotlinx.datetime.LocalDateTime object Geomag { init { ImplLibrary.load() } external fun toDecimalYears(year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int): Double external fun wmm(longitude: Double, latitude: Double, altitude: Double, decimalYears: Double): MagneticField external fun igrf(longitude: Double, latitude: Double, altitude: Double, decimalYears: Double): MagneticField fun toDecimalYears(date: LocalDateTime) = toDecimalYears(date.year, date.monthNumber, date.dayOfMonth, date.hour, date.minute, date.second) fun wmm(longitude: Double, latitude: Double, altitude: Double, date: LocalDateTime) = wmm(longitude, latitude, altitude, toDecimalYears(date)) fun igrf(longitude: Double, latitude: Double, altitude: Double, date: LocalDateTime) = igrf(longitude, latitude, altitude, toDecimalYears(date)) }
0
null
3
31
f7f356588494c586faf2a57febd709a2c062afda
932
Geomag
Apache License 2.0
bindk_test/src/main/java/com/mozhimen/bindk/test/MainActivity.kt
mozhimen
353,952,154
false
{"Kotlin": 178443, "AIDL": 964}
package com.mozhimen.bindk.test import android.os.Bundle import androidx.activity.enableEdgeToEdge import androidx.appcompat.app.AppCompatActivity import androidx.core.view.ViewCompat import androidx.core.view.WindowInsetsCompat import com.mozhimen.bindk.bases.viewbinding.activity.BaseActivityVB import com.mozhimen.bindk.test.databinding.ActivityMainBinding import com.mozhimen.bindk.utils.viewBinding class MainActivity : AppCompatActivity() { private val vb :ActivityMainBinding by viewBinding() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(vb.root) } }
1
Kotlin
15
119
3258afee059573e7cac2afa2ffc43ba6d50d73a1
646
SwiftKit
Apache License 2.0
app/src/main/java/com/lsp/view/repository/exception/NetworkUnableConnectException.kt
AnranYus
543,646,685
false
{"Kotlin": 56673}
package com.lsp.view.repository.exception import okhttp3.ResponseBody class NetworkErrorException(override val message: String?) : Exception() { }
0
Kotlin
0
0
c1942d8417e8d038618e6266a81f0c79647ed6ef
148
YandView
MIT License
Kotlin基础-2/src/main/java/com/yey/kotlin2/39-by lazy惰性加载.kt
rgdzh1
266,117,976
false
null
package com.yey.kotlin2 import org.junit.Test // 惰性加载条件 // 1 字段val 不可变值 // 2 by lazy 可以放到成员变量中,也可以单独存在 // 3 by lazy的返回值就是最后一行 // 4 惰性加载是线程安全的. val 惰性加载 :Int by lazy { println("by lazy 加载了几次") 10 } class `39-by lazy惰性加载` { @Test fun 惰性加载(){ // 惰性加载,当用到的时候才会加载到内存中,只加载一次 println(惰性加载) println(惰性加载) println(惰性加载) println(惰性加载) } }
0
Kotlin
0
0
450905528aba3d39f2c98af172c0282ec9b268aa
390
Java-Kotlin-Learning
Apache License 2.0
android-weather-mvp-clean/presentation/src/main/kotlin/io/sametkurumahmut/weather/presentation/main/MainContract.kt
sametkurumahmut
116,595,636
false
{"Text": 1, "Markdown": 1, "Gradle": 11, "Java Properties": 2, "Shell": 1, "Ignore List": 9, "Batchfile": 1, "Proguard": 3, "Kotlin": 117, "XML": 14, "Java": 4}
package io.sametkurumahmut.weather.presentation.main import io.sametkurumahmut.weather.presentation.BasePresenter import io.sametkurumahmut.weather.presentation.BaseView import io.sametkurumahmut.weather.presentation.model.CityWeatherView interface MainContract { interface View : BaseView { var isRefreshingWeather: Boolean fun hideWeatherInfoNotAvailableError() fun hideHotCityWeatherLayout() fun showCityWeather(cityWeatherView: CityWeatherView) fun showHotCityWeatherLayout() fun showNetworkUnavailableError() fun showWeatherInfoNotAvailableError() } interface Presenter : BasePresenter { fun loadCityWeather() fun loadCityWeatherManually() fun loadCityWeatherOnNetConnected() fun openAppSettings() } }
1
null
1
1
329b53e856851d0fd505aa87d4e2aa3d1545ce41
826
weather-mvp-clean
Apache License 2.0
application-model/src/test/kotlin/pl/beone/promena/transformer/pageextractor/pdfbox/applicationmodel/PdfBoxPageExtractorDslTest.kt
BeOne-PL
235,077,961
false
null
package pl.beone.promena.transformer.pageextractor.pdfbox.applicationmodel import io.kotlintest.shouldBe import org.junit.jupiter.api.Test import pl.beone.promena.transformer.applicationmodel.mediatype.MediaTypeConstants.APPLICATION_PDF import pl.beone.promena.transformer.pageextractor.pdfbox.applicationmodel.PdfBoxPageExtractorConstants.TRANSFORMER_ID class PdfBoxPageExtractorDslTest { @Test fun pdfBoxPageExtractorTransformation() { with(pdfBoxPageExtractorTransformation(APPLICATION_PDF, pdfBoxPageExtractorParameters())) { transformerId shouldBe TRANSFORMER_ID targetMediaType shouldBe APPLICATION_PDF parameters.getAll().size shouldBe 0 } } }
1
Kotlin
0
0
f2147f28aa889861d0019f5e1d1cdd9090f86daf
717
promena-transformer-page-extractor-pdfbox
Apache License 2.0
chat-core/src/main/java/com/fzm/chat/core/data/contract/ContractQuery.kt
txchat
507,831,442
false
{"Kotlin": 2234450, "Java": 384844}
package com.fzm.chat.core.data.contract import java.io.Serializable /** * @author zhengjy * @since 2020/02/05 * Description:合约查询接口参数 */ abstract class ContractQuery : Serializable { /** * 执行器 */ var execer: String = "" /** * 方法名 */ var funcName: String = "" var payload: Any? = null }
0
Kotlin
1
1
6a3c6edf6ae341199764d4d08dffd8146877678b
331
ChatPro-Android
MIT License
CodingChallenge/src/main/java/com/test/codingchallenge/data/api/StartWarsApiService.kt
Mayo1122
460,762,963
false
null
package com.test.codingchallenge.data.api import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import com.test.codingchallenge.data.model.BaseResponse import com.test.codingchallenge.data.model.FilmRes import com.test.codingchallenge.data.model.People import com.test.codingchallenge.data.model.Population import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Call import retrofit2.Retrofit import retrofit2.converter.moshi.MoshiConverterFactory import retrofit2.http.* internal interface StartWarsApiService { @GET(ApiTags.PEOPLE_URL) fun getPeopleEyeColor(): Call<BaseResponse<People>> @GET(ApiTags.PLANETS_URL) fun getPopulations(): Call<BaseResponse<Population>> @GET(ApiTags.FILMS_URL) fun getFilms(): Call<BaseResponse<FilmRes>> companion object { /** * Creates object of StartWarsApiService using Retrofit * */ fun create(): StartWarsApiService { // print api logs val interceptor : HttpLoggingInterceptor = HttpLoggingInterceptor().apply { level = HttpLoggingInterceptor.Level.BODY } val client : OkHttpClient = OkHttpClient.Builder().apply { addInterceptor(interceptor) }.build() // for json parsing val moshi = Moshi.Builder() .addLast(KotlinJsonAdapterFactory()) .build() return Retrofit.Builder() .baseUrl(ApiTags.BASE_URL) .addConverterFactory(MoshiConverterFactory.create(moshi)) .client(client) .build() .create(StartWarsApiService::class.java) } } }
0
Kotlin
0
1
247a8f70cc09f95ef5dddfb19b11f30cc64faa53
1,771
CodingChallenge
MIT License
coroutine/src/main/java/com/sys1yagi/android/kotlin/coroutine/coroutine/CoroutineExtensions.kt
sys1yagi
93,977,322
false
{"Kotlin": 15203}
package com.sys1yagi.android.kotlin.coroutine.coroutine import kotlinx.coroutines.experimental.CommonPool import kotlinx.coroutines.experimental.CoroutineScope import kotlinx.coroutines.experimental.CoroutineStart import kotlinx.coroutines.experimental.android.UI import kotlinx.coroutines.experimental.launch import kotlin.coroutines.experimental.CoroutineContext fun <T> CoroutineScope.async(context: CoroutineContext = CommonPool, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> T) = kotlinx.coroutines.experimental.async(this.context + context, start, block) fun ui(start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit) = launch(UI, start, block)
0
Kotlin
0
21
d6552f46c5ce46825780436b09fa24ec9713593e
742
implementation-of-async-request-with-rxjava2-or-coroutine
MIT License
app/src/main/java/com/niyaj/popos/features/product/presentation/details/ProductDetailsViewModel.kt
skniyajali
579,613,644
false
null
package com.niyaj.popos.features.product.presentation.details import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.niyaj.popos.features.cart_order.domain.util.CartOrderType import com.niyaj.popos.features.common.util.Resource import com.niyaj.popos.features.common.util.UiEvent import com.niyaj.popos.features.product.domain.model.Product import com.niyaj.popos.features.product.domain.repository.ProductRepository import com.niyaj.popos.utils.toBarDate import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asSharedFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.collectLatest import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel class ProductDetailsViewModel @Inject constructor( private val productRepository : ProductRepository, savedStateHandle : SavedStateHandle, ): ViewModel() { private val _product = MutableStateFlow(Product()) val product = _product.asStateFlow() private val _orderDetails = MutableStateFlow(ProductOrderState()) val orderDetails = _orderDetails.asStateFlow() private val _totalOrders = MutableStateFlow(ProductTotalOrderDetails()) val totalOrders = _totalOrders.asStateFlow() private val _eventFlow = MutableSharedFlow<UiEvent>() val eventFlow = _eventFlow.asSharedFlow() init { savedStateHandle.get<String>("productId")?.let { productId -> getProductDetails(productId) getOrderDetails(productId) } } private fun getOrderDetails(productId: String) { viewModelScope.launch { productRepository.getProductOrders(productId).collectLatest {result -> when (result) { is Resource.Loading -> { _orderDetails.value = _orderDetails.value.copy(isLoading = result.isLoading) } is Resource.Success -> { result.data?.let { orders -> _orderDetails.value = _orderDetails.value.copy(isLoading = true) val productPrice = _product.value.productPrice val groupByDate = orders.groupBy { it.orderedDate.toBarDate } val grpByOrderType = orders.groupBy { it.orderType } val dineInOrders = grpByOrderType.getOrElse(CartOrderType.DineIn.orderType, defaultValue = { emptyList() }) val dineOutOrders = grpByOrderType.getOrElse(CartOrderType.DineOut.orderType, defaultValue = { emptyList() }) val dineInAmount = dineInOrders.sumOf { it.quantity }.times(productPrice) val dineOutAmount = dineOutOrders.sumOf { it.quantity}.times(productPrice) val totalAmount = dineInAmount + dineOutAmount val startDate = if (orders.isNotEmpty()) orders.first().orderedDate else "" val endDate = if (orders.isNotEmpty()) orders.last().orderedDate else "" val mostOrderItemDate = if (groupByDate.isNotEmpty()) groupByDate.maxBy { it.value.size }.key else "" val mostOrderQtyDate = if (groupByDate.isNotEmpty()) groupByDate.maxBy { entry -> entry.value.sumOf { it.quantity } }.key else "" _totalOrders.value = _totalOrders.value.copy( totalAmount = totalAmount.toString(), dineInAmount = dineInAmount.toString(), dineInQty = dineInOrders.size, dineOutAmount = dineOutAmount.toString(), dineOutQty = dineOutOrders.size, mostOrderItemDate = mostOrderItemDate, mostOrderQtyDate = mostOrderQtyDate, datePeriod = Pair(startDate, endDate) ) _orderDetails.value = _orderDetails.value.copy( productOrders = orders, productPrice = productPrice, isLoading = false ) } } is Resource.Error -> { _orderDetails.value = _orderDetails.value.copy(hasError = result.message) } } } } } private fun getProductDetails(productId: String) { viewModelScope.launch { when(val result = productRepository.getProductById(productId)) { is Resource.Loading -> {} is Resource.Success -> { result.data?.let { _product.value = it } } is Resource.Error -> { _eventFlow.emit(UiEvent.Error(result.message ?: "Unable to get product details")) } } } } }
4
Kotlin
0
1
6e00bd5451336314b99f6ae1f1f43eea0f2079ad
5,295
POS-Application
MIT License
src/test/kotlin/com/askrepps/advent/advent2021/day14/Advent2021Day14Test.kt
askrepps
726,566,200
false
{"Kotlin": 302802}
/* * MIT License * * Copyright (c) 2021-2023 <NAME> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package com.askrepps.advent.advent2021.day14 import com.askrepps.advent.util.getInputLines import kotlin.test.assertEquals import kotlin.test.Test private const val TEST_DATA = """ NNCB CH -> B HH -> N CB -> H NH -> C HB -> C HC -> B HN -> C NN -> C BH -> H NC -> B NB -> B BN -> B BB -> N BC -> B CC -> N CN -> C """ class Advent2021Day14Test { @Test fun test2021Day14() { val (initialState, rules) = TEST_DATA.getInputLines().toPolymerDescription() assertEquals(1588L, getPart1Answer(initialState, rules)) assertEquals(2188189693529L, getPart2Answer(initialState, rules)) } }
0
Kotlin
0
0
5ce2228b0951db49a5cf2a6d974112f57e70030c
1,754
advent-of-code-kotlin
MIT License
app/src/main/java/ru/vlarkin/translatekeyboardapp/MainActivity.kt
NetherQuartz
288,578,412
false
null
package ru.vlarkin.translatekeyboardapp import android.content.ClipData import android.content.ClipboardManager import android.content.Context import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.text.Editable import android.text.TextWatcher import android.util.Log import android.widget.EditText import android.widget.ImageButton import android.widget.Toast class MainActivity : AppCompatActivity() { private var clipboardManager: ClipboardManager? = null private var clipData: ClipData? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val keysRuUp = resources.getString(R.string.ru_up) val keysRuLow = resources.getString(R.string.ru_low) val keysEnUp = resources.getString(R.string.en_up) val keysEnLow = resources.getString(R.string.en_low) val keysRuUpperRow = resources.getString(R.string.ru_upperRow) val keysEnUpperRow = resources.getString(R.string.en_upperRow) val keysEn = keysEnLow + keysEnUp + keysEnUpperRow val keysRu = keysRuLow + keysRuUp + keysRuUpperRow val input = findViewById<EditText>(R.id.input) val output = findViewById<EditText>(R.id.output) Log.d("keys", keysRuUp) Log.d("keys", keysRuLow) Log.d("keys", keysEnUp) Log.d("keys", keysEnLow) input.addTextChangedListener(object : TextWatcher { override fun afterTextChanged(text: Editable?) { if (text == null || input.text.isEmpty()) { output.setText("") output.hint = "" return } var layout: Layouts = Layouts.Any for (c in text) { layout = when { c in keysEn && c in keysRu -> Layouts.Any c in keysEn -> Layouts.En c in keysRu -> Layouts.Ru else -> Layouts.Any } if (layout != Layouts.Any) break } Log.d("Layout", "$layout $text") when (layout) { Layouts.Any -> { output.setText("") output.hint = resources.getString(R.string.ambiguous_text) } Layouts.En -> { var s = "" for (c in text) { val i = keysEn.indexOfFirst { it == c} s += if (i != -1) { keysRu[i] } else { c } } output.setText(s) } Layouts.Ru -> { var s = "" for (c in text) { val i = keysRu.indexOfFirst { it == c } s += if (i != -1) { keysEn[i] } else { c } } output.setText(s) } } } override fun beforeTextChanged(text: CharSequence?, p1: Int, p2: Int, p3: Int) {} override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {} }) val copy = findViewById<ImageButton>(R.id.copy) val paste = findViewById<ImageButton>(R.id.paste) clipboardManager = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager? copy.setOnClickListener { clipData = ClipData.newPlainText("TranslatedText", output.text) if (clipData == null) return@setOnClickListener clipboardManager?.setPrimaryClip(clipData!!) Toast.makeText(this, resources.getString(R.string.copied), Toast.LENGTH_SHORT).show() } paste.setOnClickListener { val text = clipboardManager?.primaryClip?.getItemAt(0)?.text ?: return@setOnClickListener input.setTextKeepState(text) } } } enum class Layouts { Any, Ru, En }
0
Kotlin
0
1
8214d448edc8ef1976058af3feacff897ce75bcb
4,378
TranslateKeyboardApp
MIT License
vector/src/main/java/im/vector/app/features/home/InitSyncStepFormatter.kt
vector-im
151,282,063
false
null
/* * Copyright (c) 2021 New Vector Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package im.vector.app.features.home import im.vector.app.R import im.vector.app.core.resources.StringProvider import org.matrix.android.sdk.api.session.initsync.InitSyncStep import javax.inject.Inject class InitSyncStepFormatter @Inject constructor( private val stringProvider: StringProvider ) { fun format(initSyncStep: InitSyncStep): String { return stringProvider.getString( when (initSyncStep) { InitSyncStep.ServerComputing -> R.string.initial_sync_start_server_computing InitSyncStep.Downloading -> R.string.initial_sync_start_downloading InitSyncStep.ImportingAccount -> R.string.initial_sync_start_importing_account InitSyncStep.ImportingAccountCrypto -> R.string.initial_sync_start_importing_account_crypto InitSyncStep.ImportingAccountRoom -> R.string.initial_sync_start_importing_account_rooms InitSyncStep.ImportingAccountGroups -> R.string.initial_sync_start_importing_account_groups InitSyncStep.ImportingAccountData -> R.string.initial_sync_start_importing_account_data InitSyncStep.ImportingAccountJoinedRooms -> R.string.initial_sync_start_importing_account_joined_rooms InitSyncStep.ImportingAccountInvitedRooms -> R.string.initial_sync_start_importing_account_invited_rooms InitSyncStep.ImportingAccountLeftRooms -> R.string.initial_sync_start_importing_account_left_rooms } ) } }
55
null
418
1,995
abe07c73a4f21e476e4eb1fd40fb84638177cff6
2,244
element-android
Apache License 2.0
app/src/main/java/com/zigis/paleontologas/main/views/MainMenuView.kt
edgar-zigis
240,962,785
false
null
package com.zigis.paleontologas.main.views import android.content.Context import android.view.animation.AlphaAnimation import android.view.animation.AnimationUtils import android.widget.FrameLayout import androidx.core.content.ContextCompat import androidx.recyclerview.widget.DividerItemDecoration import androidx.recyclerview.widget.DividerItemDecoration.VERTICAL import androidx.recyclerview.widget.LinearLayoutManager import com.nightonke.boommenu.BoomButtons.SimpleCircleButton import com.zigis.paleontologas.R import com.zigis.paleontologas.periods.adapters.PeriodListAdapter import com.zigis.paleontologas.periods.data.entities.Period import kotlinx.android.synthetic.main.view_main_menu.view.* interface MainMenuViewDelegate { fun openLanguages() fun openAbout() fun openQuiz() fun openPeriod(period: Period) } class MainMenuView(context: Context) : FrameLayout(context) { var delegate: MainMenuViewDelegate? = null private val adapter = PeriodListAdapter(emptyList()) { delegate?.openPeriod(it) } private var animateLayoutChanges = true init { inflate(context, R.layout.view_main_menu, this) initMenu() initPeriodList() } private fun initMenu() { for (i in 0 until menuButton.piecePlaceEnum.pieceNumber()) { val image = when (i) { 0 -> R.drawable.menu_time_scale 1 -> R.drawable.menu_quiz 2 -> R.drawable.menu_language 3 -> R.drawable.menu_about else -> 0 } val builder = SimpleCircleButton.Builder().listener { index -> when (index) { 1 -> delegate?.openQuiz() 2 -> delegate?.openLanguages() 3 -> delegate?.openAbout() } } .rippleEffect(true) .normalColor(ContextCompat.getColor(context, R.color.colorMenuItem)) .pieceColor(ContextCompat.getColor(context, R.color.white)) .normalImageRes(image) menuButton.addBuilder(builder) } } private fun initPeriodList() { periodList.adapter = adapter periodList.layoutManager = LinearLayoutManager(context) periodList.addItemDecoration(DividerItemDecoration(context, VERTICAL).also { it.setDrawable(ContextCompat.getDrawable(context, R.drawable.list_divider)!!) }) } fun setPeriods(items: List<Period>) { if (animateLayoutChanges) { periodList.layoutAnimation = AnimationUtils.loadLayoutAnimation(context, R.anim.layout_animation_fall_down) periodList.scheduleLayoutAnimation() } adapter.items = items adapter.notifyDataSetChanged() if (animateLayoutChanges) { AlphaAnimation(1f, 0f).apply { duration = 500 fillAfter = true logoImage.startAnimation(this) } animateLayoutChanges = false } } }
0
Kotlin
16
126
4ee09d3c6f29278aa1762e71f7db6a84d0ca3dea
3,076
Paleontologas
Apache License 2.0
app/src/main/java/com/example/starbuy/model/db/AppDatabase.kt
Armin00ilghami
822,999,086
false
{"Kotlin": 57941}
package com.example.starbuy.model.db import androidx.room.Database import androidx.room.RoomDatabase import com.example.starbuy.model.data.Product @Database( entities = [Product::class] , version = 1 , exportSchema = false ) abstract class AppDatabase :RoomDatabase(){ abstract fun productDao(): ProductDao }
0
Kotlin
0
0
dc226586de17e7a2c7ee65214504b021cbdef0f8
317
Star_Buy
MIT License
app/src/main/java/com/sevenexp/craftit/data/source/database/RemoteKeysDao.kt
7exp
809,363,290
false
{"Kotlin": 163764}
package com.sevenexp.craftit.data.source.database import androidx.room.Dao import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query @Dao interface RemoteKeysDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insertAll(remoteKey: List<RemoteKeys>) @Query("SELECT * FROM remote_keys WHERE id = :id AND source = :source") suspend fun getRemoteKeysId(id: String, source: String): RemoteKeys? @Query("DELETE FROM remote_keys") suspend fun deleteRemoteKeys() }
3
Kotlin
1
0
a709aa4ab566dc8af3cbaba74e21794a8e63cf05
536
craftit-android
MIT License
app/src/main/java/nl/rwslinkman/simdeviceble/ui/devices/SupportedDevicesAdapter.kt
rwslinkman
304,111,864
false
null
package nl.rwslinkman.simdeviceble.ui.devices import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.LinearLayout import android.widget.TextView import androidx.recyclerview.widget.RecyclerView import nl.rwslinkman.simdeviceble.R import nl.rwslinkman.simdeviceble.device.model.Device class SupportedDevicesAdapter(private val dataSet: List<Device>): RecyclerView.Adapter<SupportedDevicesAdapter.ViewHolder>() { class ViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) { val nameView: TextView = itemView.findViewById(R.id.item_device_name) val servicesView: LinearLayout = itemView.findViewById(R.id.item_device_services) } private class ServiceViewHolder(inflater: LayoutInflater) { val itemView: View = inflater.inflate(R.layout.list_item_servicedata, null) val nameView: TextView = itemView.findViewById(R.id.item_service_name) val uuidView: TextView = itemView.findViewById(R.id.item_service_uuid) val characteristicsBlock: LinearLayout = itemView.findViewById(R.id.item_service_characteristics) } private class CharacteristicViewHolder(inflater: LayoutInflater) { val itemView: View = inflater.inflate(R.layout.list_item_supported_characteristic, null) val nameView: TextView = itemView.findViewById(R.id.item_characteristic_name) val uuidView: TextView = itemView.findViewById(R.id.item_characteristic_uuid) } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val itemRoot: View = LayoutInflater.from(parent.context) .inflate(R.layout.list_item_supported_device, parent, false) return ViewHolder(itemRoot) } override fun getItemCount(): Int { return dataSet.size } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val deviceItem: Device = dataSet[position] holder.nameView.text = deviceItem.name val inflater = LayoutInflater.from(holder.itemView.context) deviceItem.services.forEach { serviceItem -> val serviceViewHolder = ServiceViewHolder(inflater) serviceViewHolder.nameView.text = serviceItem.name serviceViewHolder.uuidView.text = serviceItem.uuid.toString() serviceItem.characteristics.forEach { val charViewHolder = CharacteristicViewHolder(inflater) charViewHolder.nameView.text = it.name charViewHolder.uuidView.text = it.uuid.toString() serviceViewHolder.characteristicsBlock.addView(charViewHolder.itemView) } holder.servicesView.addView(serviceViewHolder.itemView) } } }
0
Kotlin
0
1
37f0433c94d9245d136cef84ec14ba9efc66b34e
2,753
SimDeviceBLE
Apache License 2.0
idea/tests/testData/structuralsearch/property/functionTypeNamedParameter.kt
JetBrains
278,369,660
false
null
class MyClass { <warning descr="SSR">val funTwo: (s: String) -> Unit = {}</warning> <warning descr="SSR">val funOne: (String) -> Unit = {}</warning> }
0
Kotlin
30
82
cc81d7505bc3e9ad503d706998ae8026c067e838
158
intellij-kotlin
Apache License 2.0
eventsourcing/javers-testing/src/main/kotlin/org/javers/core/RandomCommitGenerator.kt
debop
187,949,869
false
null
package org.javers.core import mu.KLogging import org.javers.core.commit.CommitId import java.util.UUID import java.util.function.Supplier import kotlin.math.abs /** * RandomCommitGenerator * * @author debop * @since 19. 7. 15 */ class RandomCommitGenerator : Supplier<CommitId> { companion object : KLogging() private val commits = hashMapOf<CommitId, Int>() private var counter: Int = 0 fun getSeq(commitId: CommitId): Int = commits[commitId] ?: throw NoSuchElementException("Not found commitId. $commitId") override fun get(): CommitId { synchronized(this) { counter++ val next = CommitId(abs(UUID.randomUUID().leastSignificantBits), 0) commits[next] = counter logger.trace { "Generate randomm CommitId. next commitId=$next, counter=$counter" } return next } } }
1
Kotlin
4
24
b9d1eb5309c6f9eab82dec676bfe6962428f36ce
886
kotlin-workshop
MIT License
src/main/kotlin/com/neighbwang/gradle/transform/retrace/RetraceTransformer.kt
neighbWang
384,454,786
false
null
package com.neighbwang.gradle.transform.retrace import com.didiglobal.booster.kotlinx.asIterable import com.didiglobal.booster.kotlinx.touch import com.didiglobal.booster.transform.TransformContext import com.didiglobal.booster.transform.asm.ClassTransformer import com.google.auto.service.AutoService import org.objectweb.asm.tree.ClassNode import org.objectweb.asm.tree.MethodInsnNode import java.io.PrintWriter import java.util.concurrent.ConcurrentHashMap /** * @author neighbWang */ @AutoService(ClassTransformer::class) class RetraceTransformer : ClassTransformer { private lateinit var logger: PrintWriter private lateinit var searches: Set<String> private val result = ConcurrentHashMap<String, MutableSet<String>>() override fun onPreTransform(context: TransformContext) { logger = getReport(context, "report.txt").touch().printWriter() searches = context.getProperty("booster.transform.retraces", "") .split(',') .filter { it.isNotEmpty() } .map { it.trim() } .toSet() } override fun transform(context: TransformContext, klass: ClassNode): ClassNode { klass.methods.forEach { method -> method.instructions.iterator().asIterable().filterIsInstance<MethodInsnNode>().map { methodIns -> "${methodIns.owner}.${methodIns.name}${methodIns.desc}" }.filter { searches.contains(it) }.forEach { val result = result.getOrPut(it, { mutableSetOf() }) result.add("class : ${klass.name}, method : ${method.name}${method.desc}") } } return klass } override fun onPostTransform(context: TransformContext) { super.onPostTransform(context) result.forEach { logger.println() logger.println(" **** search info => ${it.key}, total size:${it.value.size}") it.value.forEach { location -> logger.println(location) } } this.logger.close() } }
0
Kotlin
0
0
21aadadb3f5a52baeab6eacbb7394b54e1654439
2,104
booster-transform-api-scanner-plugin
Apache License 2.0
app/src/main/java/e/vatsal/kesarwani/gitfit/ui/user/UserActivity.kt
plazzy99
321,106,952
false
null
package code.namanbir.gitfit.app.ui.user import android.content.Context import android.content.Intent import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.databinding.DataBindingUtil import androidx.lifecycle.ViewModelProviders import com.bumptech.glide.Glide import code.namanbir.gitfit.app.R import code.namanbir.gitfit.app.app.ViewModelFactory import code.namanbir.gitfit.app.data.model.RepoCountResponse import code.namanbir.gitfit.app.data.model.ResultModel import code.namanbir.gitfit.app.data.network.ApiHelper import code.namanbir.gitfit.app.data.network.RetrofitBuilder import code.namanbir.gitfit.app.databinding.ActivityUserBinding import code.namanbir.gitfit.app.ui.BattleActivity import code.namanbir.gitfit.app.utils.Status import code.namanbir.gitfit.app.utils.showSnackBar class UserActivity : AppCompatActivity() { companion object{ fun start(context : Context) { context.startActivity(Intent(context, UserActivity::class.java)) } } //private lateinit var sharedPreferences : SharedPreferences private lateinit var viewBinding : ActivityUserBinding lateinit var viewModel : UserViewModel private var score : Int = 0 private var resultModel = ResultModel() override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) overridePendingTransition( android.R.anim.fade_in, android.R.anim.fade_out ); viewBinding = DataBindingUtil.setContentView(this, R.layout.activity_user) //sharedPreferences = getSharedPreferences(SharedPref.SHARED_PREF.name, Context.MODE_PRIVATE) setSupportActionBar(viewBinding.toolUser) setupViewModel() setUpUI() setUpObservers() onclick() } /* override fun onCreateOptionsMenu(menu: Menu?): Boolean { menuInflater.inflate(R.menu.menu_theme, menu) return super.onCreateOptionsMenu(menu) }*/ /*override fun onOptionsItemSelected(item: MenuItem): Boolean { return when(item.itemId){ R.id.themeSwitch -> { sharedPreferences.edit() .putBoolean(SharedPref.IS_DARK_MODE.name, !sharedPreferences.getBoolean(SharedPref.IS_DARK_MODE.name,false)) .apply() showToast("Pressed") changeTheme() true } else -> super.onOptionsItemSelected(item) } }*/ /*private fun changeTheme() { when(sharedPreferences.getBoolean(SharedPref.IS_DARK_MODE.name, true)) { false -> { setTheme(R.style.Light) recreate() } else -> { setTheme(R.style.Dark) recreate() } } }*/ private fun setupViewModel() { viewModel = ViewModelProviders.of( this, ViewModelFactory(ApiHelper(RetrofitBuilder.api)) ).get(UserViewModel::class.java) } private fun setUpUI() { viewBinding.viewModel = viewModel } private fun setUpObservers() { viewModel.user1.observe(this, { when(it.isNotEmpty()){ false -> viewBinding.etUser1.error = null } }) viewModel.user2.observe(this, { when(it.isNotEmpty()){ false -> viewBinding.etUser2.error = null } }) viewModel.flag.observe(this, { when(it==2){ true -> { viewBinding.imageView.visibility = View.GONE viewBinding.btStartBattle.visibility = View.VISIBLE } false -> { viewBinding.imageView.visibility = View.VISIBLE viewBinding.btStartBattle.visibility = View.GONE } } }) } private fun onclick() { viewBinding.btSubmit1.setOnClickListener{ when(viewModel.user1.value.isNullOrEmpty()){ true -> viewBinding.etUser1.error = "Enter username" false -> fetchUser1() } } viewBinding.btSubmit2.setOnClickListener{ when(viewModel.user2.value.isNullOrEmpty()){ true -> viewBinding.etUser2.error = "Enter username" false -> fetchUser2() } } viewBinding.btStartBattle.setOnClickListener { if(viewModel.user1.value == viewModel.user2.value){ showSnackBar("Enter different users") } else { overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out) BattleActivity.start( this, resultModel ) } } viewBinding.imCancel1.setOnClickListener{ viewBinding.group1.visibility = View.VISIBLE viewBinding.card1.visibility = View.GONE viewModel.flag.value = viewModel.flag.value?.minus(1) } viewBinding.imCancel2.setOnClickListener{ viewBinding.group2.visibility = View.VISIBLE viewBinding.card2.visibility = View.GONE viewModel.flag.value = viewModel.flag.value?.minus(1) } } private fun fetchUser1() { viewModel.getUsers(viewModel.user1.value.toString()).observe(this, { it.let { when(it.status) { Status.SUCCESS -> { viewBinding.group1.visibility = View.GONE viewBinding.card1.visibility = View.VISIBLE viewBinding.tvUserName1.text = it.data?.name Glide.with(this) .load(it.data?.avatarUrl) .into(viewBinding.imUserImage1) val model = ResultModel.User() model.name = it.data?.name model.avatarUrl = it.data?.avatarUrl model.followers = it.data?.followers model.following = it.data?.following model.publicRepos = it.data?.publicRepos resultModel.user1 = model it.data?.followers?.let { it1 -> fetchRepo1(it1) } } Status.ERROR -> { it.message?.let { it1 -> showSnackBar(it1) } } Status.LOADING -> { //progressBar } } } }) } private fun fetchUser2() { viewModel.getUsers(viewModel.user2.value.toString()).observe(this, { it.let { when(it.status) { Status.SUCCESS -> { viewBinding.group2.visibility = View.GONE viewBinding.card2.visibility = View.VISIBLE viewBinding.tvUserName2.text = it.data?.name Glide.with(this) .load(it.data?.avatarUrl) .into(viewBinding.imUserImage2) val model = ResultModel.User() model.name = it.data?.name model.avatarUrl = it.data?.avatarUrl model.followers = it.data?.followers model.following = it.data?.following model.publicRepos = it.data?.publicRepos resultModel.user2 = model it.data?.followers?.let { it1 -> fetchRepo2(it1) } } Status.ERROR -> { it.message?.let { it1 -> showSnackBar(it1) } } Status.LOADING -> { //progressBar } } } }) } private fun fetchRepo1(follow : Int) { viewModel.getRepo(viewModel.user1.value.toString()).observe(this, { it.let { when(it.status) { Status.SUCCESS -> { viewModel.flag.value = viewModel.flag.value?.plus(1) scoreCalculate(it.data!!, follow, true) } Status.ERROR -> { it.message?.let { it1 -> showSnackBar(it1) } } Status.LOADING -> { //progressBar } } } }) } private fun fetchRepo2(follow : Int) { viewModel.getRepo(viewModel.user2.value.toString()).observe(this, { it.let { when(it.status) { Status.SUCCESS -> { viewModel.flag.value = viewModel.flag.value?.plus(1) scoreCalculate(it.data!!, follow, false) } Status.ERROR -> { it.message?.let { it1 -> showSnackBar(it1) } } Status.LOADING -> { //progressBar } } } }) } private fun scoreCalculate(list : RepoCountResponse, follow: Int, user : Boolean) { var star = 0 var fork = 0 var publicRepo = 0 for (element in list){ if (element.fork == false) { publicRepo++ star += element.stargazersCount!!*3 /**star gives you 3 points */ fork += element.forksCount!!*5 /**fork gives you 5 points */ } /**follow gives you 1 point */ } /**public repo give 1 point only which you are owner */ score = star+fork+follow+publicRepo if (user) { resultModel.score1 = score }else { resultModel.score2 = score } } }
0
null
2
19
9f0ab86abf639502fafc8d286da5d0e1d0038be3
10,180
GitFit
MIT License
Kotlin/techhub/app/src/main/java/com/example/techhub/MainActivity.kt
mehmoodharis74
655,308,233
false
null
package com.example.techhub import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import com.example.techhub.navigation.NavigationFunction class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { NavigationFunction() } } }
0
Kotlin
0
0
a552470e9ff631ed5da5e94a5ac6d415083a1109
422
Android-Projects
MIT License
src/commonMain/kotlin/com/jeffpdavidson/kotwords/formats/Encodings.kt
jpd236
143,651,464
false
{"Kotlin": 4431127, "HTML": 41941, "Rouge": 3731, "Perl": 1705, "Shell": 744, "JavaScript": 618}
package com.jeffpdavidson.kotwords.formats internal expect object Encodings { /** Decode the given Cp1252 data as a string. */ fun decodeCp1252(bytes: ByteArray): String /** Encode the given string as Cp1252 bytes. Unsupported characters are replaced with '?'. */ fun encodeCp1252(string: String): ByteArray fun decodeUrl(url: String): String fun decodeHtmlEntities(string: String): String fun unescape(string: String): String } /** Unicode values corresponding to bytes 0x80-0x9F in CP1252. */ private val CP1252_DECODE_TABLE = listOf( '\u20ac', '\u0081', '\u201a', '\u0192', '\u201e', '\u2026', '\u2020', '\u2021', '\u02c6', '\u2030', '\u0160', '\u2039', '\u0152', '\u008d', '\u017d', '\u008f', '\u0090', '\u2018', '\u2019', '\u201c', '\u201d', '\u2022', '\u2013', '\u2014', '\u02dc', '\u2122', '\u0161', '\u203a', '\u0153', '\u009d', '\u017e', '\u0178', ) /** Map from supported CP1252 unicode values to their byte value in CP1252. */ private val CP1252_ENCODE_TABLE = CP1252_DECODE_TABLE.withIndex().associate { it.value to it.index } internal fun Encodings.commonDecodeCp1252(bytes: ByteArray): String { return bytes.map { byte -> val intValue = byte.toInt() and 0xFF if (intValue in 0x00..0x7F || intValue in 0xA0..0xFF) { // ISO-8859-1 characters map directly. intValue.toChar() } else { // Between 0x80 and 0x9F - look up the value in the table. CP1252_DECODE_TABLE[intValue - 0x80] } }.joinToString("") } internal fun Encodings.commonEncodeCp1252(string: String): ByteArray { return string.map { ch -> if (ch.code in 0x00..0x7F || ch.code in 0xA0..0xFF) { // ISO-8859-1 characters map directly. ch.code.toByte() } else { val cp1252Byte = CP1252_ENCODE_TABLE[ch] if (cp1252Byte != null) { // One of the supported CP1252 characters. (0x80 + cp1252Byte).toByte() } else { // Unsupported value - use default '?' character. '?'.code.toByte() } } }.toByteArray() } private val UNESCAPE_PATTERN = "%u([0-9A-Fa-f]{4})|%([0-9A-Fa-f]{2})".toRegex() internal fun Encodings.commonUnescape(string: String): String { return UNESCAPE_PATTERN.replace(string) { result -> val code = result.groupValues[1].ifEmpty { result.groupValues[2] } code.toInt(16).toChar().toString() } }
8
Kotlin
6
25
0c94260c3e9472db2e89f6c62ba715e85e1539f4
2,504
kotwords
Apache License 2.0
pleo-antaeus-core/src/main/kotlin/io/pleo/antaeus/core/services/InvoiceService.kt
nlarios
212,889,738
true
{"Kotlin": 51808, "Shell": 861, "Dockerfile": 249}
/* Implements endpoints related to invoices. */ package io.pleo.antaeus.core.services import io.pleo.antaeus.core.exceptions.InvoiceNotFoundException import io.pleo.antaeus.data.InvoiceDal import io.pleo.antaeus.models.Invoice import io.pleo.antaeus.models.InvoiceStatus class InvoiceService(private val dal: InvoiceDal) { fun fetchAll(): List<Invoice> { return dal.fetchInvoices() } fun fetch(id: Int): Invoice { return dal.fetchInvoice(id) ?: throw InvoiceNotFoundException(id) } fun fetchInvoicesByCustomer(id: Int): List<Invoice> { return dal.fetchInvoicesByCustomer(id) } fun fetchInvoicesByCustomerAndStatus(id: Int, status: InvoiceStatus): List<Invoice> { return dal.fetchInvoicesByCostumerAndStatus(id, status) } //not just update, room for more business logic fun payInvoice(invoice: Invoice): Invoice? { invoice.status = InvoiceStatus.PAID return dal.updateInvoice(invoice) } }
0
Kotlin
0
0
0e6a815371bb540f61408e2ac8c2b6af9801cd6f
992
antaeus
Creative Commons Zero v1.0 Universal
save-cloud-common/src/commonMain/kotlin/com/saveourtool/save/entities/TestSuitesSourceSnapshotDto.kt
saveourtool
300,279,336
false
{"Kotlin": 3427815, "SCSS": 86430, "JavaScript": 9061, "HTML": 8852, "Shell": 2770, "Smarty": 2608, "Dockerfile": 1366}
package com.saveourtool.common.entities import kotlinx.datetime.LocalDateTime /** * @property organizationName * @property testSuitesSourceName * @property version * @property creationTime * @property location */ data class TestSuitesSourceSnapshotDto( val organizationName: String, val testSuitesSourceName: String, val version: String, val creationTime: LocalDateTime, val location: String, )
202
Kotlin
3
38
7e126d4fb23f8527c47ca9fa27282379759d154e
424
save-cloud
MIT License
core/android/src/main/kotlin/com/reown/android/utils/Extensions.kt
reown-com
851,466,242
false
{"Kotlin": 2055654, "Java": 4294, "Shell": 1676}
@file:JvmSynthetic package com.reown.android.utils import android.net.Uri import com.reown.android.Core import com.reown.android.internal.common.exception.GenericException import com.reown.android.internal.common.exception.InvalidProjectIdException import com.reown.android.internal.common.exception.ProjectIdDoesNotExistException import com.reown.android.internal.common.exception.UnableToConnectToWebsocketException import com.reown.android.internal.common.exception.WalletConnectException import com.reown.android.internal.common.model.AppMetaData import com.reown.utils.Empty import java.net.HttpURLConnection @JvmSynthetic internal fun String.strippedUrl() = Uri.parse(this).run { this@run.scheme + "://" + this@run.authority } @JvmSynthetic internal fun String.isValidRelayServerUrl(): Boolean { return this.isNotBlank() && Uri.parse(this)?.let { relayUrl -> arrayOf("wss", "ws").contains(relayUrl.scheme) && !relayUrl.getQueryParameter("projectId").isNullOrBlank() } ?: false } // Assumes isValidRelayServerUrl returns true. @JvmSynthetic internal fun String.projectId(): String { return Uri.parse(this)!!.let { relayUrl -> relayUrl.getQueryParameter("projectId")!! } } @get:JvmSynthetic internal val Throwable.toWalletConnectException: WalletConnectException get() = when { this.message?.contains(HttpURLConnection.HTTP_UNAUTHORIZED.toString()) == true -> UnableToConnectToWebsocketException("${this.message}. It's possible that JWT has expired. Try initializing the CoreClient again.") this.message?.contains(HttpURLConnection.HTTP_NOT_FOUND.toString()) == true -> ProjectIdDoesNotExistException("Project ID doesn't exist: ${this.message}") this.message?.contains(HttpURLConnection.HTTP_FORBIDDEN.toString()) == true -> InvalidProjectIdException("Invalid project ID: ${this.message}") else -> GenericException("Error while connecting, please check your Internet connection or contact support: ${this.message}") } @get:JvmSynthetic val Int.Companion.DefaultId get() = -1 fun AppMetaData?.toClient() = Core.Model.AppMetaData( name = this?.name ?: String.Empty, description = this?.description ?: String.Empty, url = this?.url ?: String.Empty, icons = this?.icons ?: emptyList(), redirect = this?.redirect?.native, appLink = this?.redirect?.universal, linkMode = this?.redirect?.linkMode ?: false )
6
Kotlin
1
8
893084b3df91b47daa77f8f964e37f84a02843b1
2,500
reown-kotlin
Apache License 2.0
ktorm-core/src/main/kotlin/me/liuwj/ktorm/schema/SqlTypes.kt
liphis
263,756,535
true
{"Kotlin": 563994, "Shell": 2820, "TSQL": 102}
/* * Copyright 2018-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package me.liuwj.ktorm.schema import java.math.BigDecimal import java.sql.* import java.time.* import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatterBuilder import java.time.format.SignStyle import java.time.temporal.ChronoField import javax.sql.rowset.serial.SerialBlob /** * Define a column typed of [BooleanSqlType]. */ fun <E : Any> BaseTable<E>.boolean(name: String): BaseTable<E>.ColumnRegistration<Boolean> { return registerColumn(name, BooleanSqlType) } /** * [SqlType] implementation represents `boolean` SQL type. */ object BooleanSqlType : SqlType<Boolean>(Types.BOOLEAN, "boolean") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: Boolean) { ps.setBoolean(index, parameter) } override fun doGetResult(rs: ResultSet, index: Int): Boolean? { return rs.getBoolean(index) } } /** * Define a column typed of [IntSqlType]. */ fun <E : Any> BaseTable<E>.int(name: String): BaseTable<E>.ColumnRegistration<Int> { return registerColumn(name, IntSqlType) } /** * [SqlType] implementation represents `int` SQL type. */ object IntSqlType : SqlType<Int>(Types.INTEGER, "int") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: Int) { ps.setInt(index, parameter) } override fun doGetResult(rs: ResultSet, index: Int): Int? { return rs.getInt(index) } } /** * Define a column typed of [LongSqlType]. */ fun <E : Any> BaseTable<E>.long(name: String): BaseTable<E>.ColumnRegistration<Long> { return registerColumn(name, LongSqlType) } /** * [SqlType] implementation represents `long` SQL type. */ object LongSqlType : SqlType<Long>(Types.BIGINT, "bigint") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: Long) { ps.setLong(index, parameter) } override fun doGetResult(rs: ResultSet, index: Int): Long? { return rs.getLong(index) } } /** * Define a column typed of [FloatSqlType]. */ fun <E : Any> BaseTable<E>.float(name: String): BaseTable<E>.ColumnRegistration<Float> { return registerColumn(name, FloatSqlType) } /** * [SqlType] implementation represents `float` SQL type. */ object FloatSqlType : SqlType<Float>(Types.FLOAT, "float") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: Float) { ps.setFloat(index, parameter) } override fun doGetResult(rs: ResultSet, index: Int): Float? { return rs.getFloat(index) } } /** * Define a column typed of [DoubleSqlType]. */ fun <E : Any> BaseTable<E>.double(name: String): BaseTable<E>.ColumnRegistration<Double> { return registerColumn(name, DoubleSqlType) } /** * [SqlType] implementation represents `double` SQL type. */ object DoubleSqlType : SqlType<Double>(Types.DOUBLE, "double") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: Double) { ps.setDouble(index, parameter) } override fun doGetResult(rs: ResultSet, index: Int): Double? { return rs.getDouble(index) } } /** * Define a column typed of [DecimalSqlType]. */ fun <E : Any> BaseTable<E>.decimal(name: String): BaseTable<E>.ColumnRegistration<BigDecimal> { return registerColumn(name, DecimalSqlType) } /** * [SqlType] implementation represents `decimal` SQL type. */ object DecimalSqlType : SqlType<BigDecimal>(Types.DECIMAL, "decimal") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: BigDecimal) { ps.setBigDecimal(index, parameter) } override fun doGetResult(rs: ResultSet, index: Int): BigDecimal? { return rs.getBigDecimal(index) } } /** * Define a column typed of [VarcharSqlType]. */ fun <E : Any> BaseTable<E>.varchar(name: String): BaseTable<E>.ColumnRegistration<String> { return registerColumn(name, VarcharSqlType) } /** * [SqlType] implementation represents `varchar` SQL type. */ object VarcharSqlType : SqlType<String>(Types.VARCHAR, "varchar") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: String) { ps.setString(index, parameter) } override fun doGetResult(rs: ResultSet, index: Int): String? { return rs.getString(index) } } /** * Define a column typed of [TextSqlType]. */ fun <E : Any> BaseTable<E>.text(name: String): BaseTable<E>.ColumnRegistration<String> { return registerColumn(name, TextSqlType) } /** * [SqlType] implementation represents `text` SQL type. */ object TextSqlType : SqlType<String>(Types.LONGVARCHAR, "text") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: String) { ps.setString(index, parameter) } override fun doGetResult(rs: ResultSet, index: Int): String? { return rs.getString(index) } } /** * Define a column typed of [BlobSqlType]. */ fun <E : Any> BaseTable<E>.blob(name: String): BaseTable<E>.ColumnRegistration<ByteArray> { return registerColumn(name, BlobSqlType) } /** * [SqlType] implementation represents `blob` SQL type. */ object BlobSqlType : SqlType<ByteArray>(Types.BLOB, "blob") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: ByteArray) { ps.setBlob(index, SerialBlob(parameter)) } override fun doGetResult(rs: ResultSet, index: Int): ByteArray? { val blob = rs.getBlob(index) ?: return null try { return blob.binaryStream.use { it.readBytes() } } finally { blob.free() } } } /** * Define a column typed of [BytesSqlType]. */ fun <E : Any> BaseTable<E>.bytes(name: String): BaseTable<E>.ColumnRegistration<ByteArray> { return registerColumn(name, BytesSqlType) } /** * [SqlType] implementation represents `bytes` SQL type. */ object BytesSqlType : SqlType<ByteArray>(Types.BINARY, "bytes") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: ByteArray) { ps.setBytes(index, parameter) } override fun doGetResult(rs: ResultSet, index: Int): ByteArray? { return rs.getBytes(index) } } /** * Define a column typed of [TimestampSqlType]. */ fun <E : Any> BaseTable<E>.jdbcTimestamp(name: String): BaseTable<E>.ColumnRegistration<Timestamp> { return registerColumn(name, TimestampSqlType) } /** * [SqlType] implementation represents `timestamp` SQL type. */ object TimestampSqlType : SqlType<Timestamp>(Types.TIMESTAMP, "timestamp") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: Timestamp) { ps.setTimestamp(index, parameter) } override fun doGetResult(rs: ResultSet, index: Int): Timestamp? { return rs.getTimestamp(index) } } /** * Define a column typed of [DateSqlType]. */ fun <E : Any> BaseTable<E>.jdbcDate(name: String): BaseTable<E>.ColumnRegistration<Date> { return registerColumn(name, DateSqlType) } /** * [SqlType] implementation represents `date` SQL type. */ object DateSqlType : SqlType<Date>(Types.DATE, "date") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: Date) { ps.setDate(index, parameter) } override fun doGetResult(rs: ResultSet, index: Int): Date? { return rs.getDate(index) } } /** * Define a column typed of [TimeSqlType]. */ fun <E : Any> BaseTable<E>.jdbcTime(name: String): BaseTable<E>.ColumnRegistration<Time> { return registerColumn(name, TimeSqlType) } /** * [SqlType] implementation represents `time` SQL type. */ object TimeSqlType : SqlType<Time>(Types.TIME, "time") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: Time) { ps.setTime(index, parameter) } override fun doGetResult(rs: ResultSet, index: Int): Time? { return rs.getTime(index) } } /** * Define a column typed of [InstantSqlType]. */ fun <E : Any> BaseTable<E>.timestamp(name: String): BaseTable<E>.ColumnRegistration<Instant> { return registerColumn(name, InstantSqlType) } /** * [SqlType] implementation represents `timestamp` SQL type. */ object InstantSqlType : SqlType<Instant>(Types.TIMESTAMP, "timestamp") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: Instant) { ps.setTimestamp(index, Timestamp.from(parameter)) } override fun doGetResult(rs: ResultSet, index: Int): Instant? { return rs.getTimestamp(index)?.toInstant() } } /** * Define a column typed of [LocalDateTimeSqlType]. */ fun <E : Any> BaseTable<E>.datetime(name: String): BaseTable<E>.ColumnRegistration<LocalDateTime> { return registerColumn(name, LocalDateTimeSqlType) } /** * [SqlType] implementation represents `datetime` SQL type. */ object LocalDateTimeSqlType : SqlType<LocalDateTime>(Types.TIMESTAMP, "datetime") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: LocalDateTime) { ps.setTimestamp(index, Timestamp.valueOf(parameter)) } override fun doGetResult(rs: ResultSet, index: Int): LocalDateTime? { return rs.getTimestamp(index)?.toLocalDateTime() } } /** * Define a column typed of [LocalDateSqlType]. */ fun <E : Any> BaseTable<E>.date(name: String): BaseTable<E>.ColumnRegistration<LocalDate> { return registerColumn(name, LocalDateSqlType) } /** * [SqlType] implementation represents `date` SQL type. */ object LocalDateSqlType : SqlType<LocalDate>(Types.DATE, "date") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: LocalDate) { ps.setDate(index, Date.valueOf(parameter)) } override fun doGetResult(rs: ResultSet, index: Int): LocalDate? { return rs.getDate(index)?.toLocalDate() } } /** * Define a column typed of [LocalTimeSqlType]. */ fun <E : Any> BaseTable<E>.time(name: String): BaseTable<E>.ColumnRegistration<LocalTime> { return registerColumn(name, LocalTimeSqlType) } /** * [SqlType] implementation represents `time` SQL type. */ object LocalTimeSqlType : SqlType<LocalTime>(Types.TIME, "time") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: LocalTime) { ps.setTime(index, Time.valueOf(parameter)) } override fun doGetResult(rs: ResultSet, index: Int): LocalTime? { return rs.getTime(index)?.toLocalTime() } } /** * Define a column typed of [MonthDaySqlType], instances of [MonthDay] are saved as strings in format `MM-dd`. */ fun <E : Any> BaseTable<E>.monthDay(name: String): BaseTable<E>.ColumnRegistration<MonthDay> { return registerColumn(name, MonthDaySqlType) } /** * [SqlType] implementation used to save [MonthDay] instances, formating them to strings with pattern `MM-dd`. */ object MonthDaySqlType : SqlType<MonthDay>(Types.VARCHAR, "varchar") { val formatter: DateTimeFormatter = DateTimeFormatterBuilder() .appendValue(ChronoField.MONTH_OF_YEAR, 2) .appendLiteral('-') .appendValue(ChronoField.DAY_OF_MONTH, 2) .toFormatter() override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: MonthDay) { ps.setString(index, parameter.format(formatter)) } override fun doGetResult(rs: ResultSet, index: Int): MonthDay? { return rs.getString(index)?.let { MonthDay.parse(it, formatter) } } } /** * Define a column typed of [YearMonthSqlType], instances of [YearMonth] are saved as strings in format `yyyy-MM`. */ fun <E : Any> BaseTable<E>.yearMonth(name: String): BaseTable<E>.ColumnRegistration<YearMonth> { return registerColumn(name, YearMonthSqlType) } /** * [SqlType] implementation used to save [YearMonth] instances, formating them to strings with pattern `yyyy-MM`. */ @Suppress("MagicNumber") object YearMonthSqlType : SqlType<YearMonth>(Types.VARCHAR, "varchar") { val formatter: DateTimeFormatter = DateTimeFormatterBuilder() .appendValue(ChronoField.YEAR, 4, 10, SignStyle.EXCEEDS_PAD) .appendLiteral('-') .appendValue(ChronoField.MONTH_OF_YEAR, 2) .toFormatter() override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: YearMonth) { ps.setString(index, parameter.format(formatter)) } override fun doGetResult(rs: ResultSet, index: Int): YearMonth? { return rs.getString(index)?.let { YearMonth.parse(it, formatter) } } } /** * Define a column typed of [YearSqlType], instances of [Year] are saved as integers. */ fun <E : Any> BaseTable<E>.year(name: String): BaseTable<E>.ColumnRegistration<Year> { return registerColumn(name, YearSqlType) } /** * [SqlType] implementation used to save [Year] instances as integers. */ object YearSqlType : SqlType<Year>(Types.INTEGER, "int") { override fun doSetParameter(ps: PreparedStatement, index: Int, parameter: Year) { ps.setInt(index, parameter.value) } override fun doGetResult(rs: ResultSet, index: Int): Year? { return Year.of(rs.getInt(index)) } }
0
Kotlin
0
0
6425edb834f6e5736ddfca8320e67d67e41948ed
13,614
Ktorm
Apache License 2.0
app/src/main/java/com/example/jmb_bms/activities/MainActivity.kt
alarm-clock
701,783,108
false
{"Kotlin": 868333}
/** * @file: MainActivity.kt * @author: <NAME> <<EMAIL>,<EMAIL>> * Description: File containing MainActivity class */ package com.example.jmb_bms.activities import android.content.ComponentName import android.content.Context import android.content.Intent import android.content.ServiceConnection import android.os.Bundle import android.os.IBinder import android.util.Log import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.viewModels import com.example.jmb_bms.LocusVersionHolder import com.example.jmb_bms.connectionService.ConnectionService import com.example.jmb_bms.model.LocationRepo import com.example.jmb_bms.model.menu.MainMenuItems import com.example.jmb_bms.model.database.points.PointDBHelper import com.example.jmb_bms.view.mainMenu import com.example.jmb_bms.viewModel.LiveLocationFromPhone import com.example.jmb_bms.viewModel.LiveTime import locus.api.android.objects.LocusVersion import locus.api.android.utils.IntentHelper import locus.api.objects.extra.Location /** * MainActivity * * This class hosts main activity of whole application. In short, it is main menu of whole app. * It extends ComponentActivity */ class MainActivity : ComponentActivity(){ private val currentTime by viewModels<LiveTime>() private lateinit var locationRepo : LocationRepo private lateinit var menuItems: MainMenuItems private var service : ConnectionService? = null private val serviceConnection = object : ServiceConnection { /** * Method which is called when activity connects to service * * @param name Specifier of application component. Not used * @param serviceBin Service binder */ override fun onServiceConnected(name: ComponentName?, serviceBin: IBinder?) { val binder = serviceBin as ConnectionService.LocalBinder service = binder.getService() } /** * Method which is called when activity disconnects from service * * @param name Specifier of application component. Not used */ override fun onServiceDisconnected(name: ComponentName?) { service = null } } /** * Method called when activity created. Part of its life cycle. It prepares db helper and viewModels for time and location. * Then sets screen content. * * @param savedInstanceState Previous instance state saved in bundle */ override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) bind() val db = PointDBHelper(this,null) db.sendAllPointsToLoc(this) db.close() LocusVersionHolder.checkAndSotreLocVer(this) if( LocusVersionHolder.getLv() == null ) return locationRepo = LocationRepo(applicationContext) val currentLocation by viewModels<LiveLocationFromPhone> { LiveLocationFromPhone.create(locationRepo, this) } menuItems = MainMenuItems(getSharedPreferences("jmb_bms_MainMenu", MODE_PRIVATE),this) if(IntentHelper.isIntentMainFunction(intent)) { IntentHelper.handleIntentMainFunction(this,intent, object : IntentHelper.OnIntentReceived{ override fun onReceived(lv: LocusVersion, locGps: Location?, locMapCenter: Location?) { setContent { mainMenu(currentTime, currentLocation, menuItems){ finish() } } } override fun onFailed() {} }) } else if( IntentHelper.isIntentPointTools(intent)) { //val point = IntentHelper.getPointFromIntent(this,intent); } else if (IntentHelper.isIntentPointsTools(intent)) { finish() } else { setContent { mainMenu(currentTime, currentLocation, menuItems){ finish() } } } } /** * Function for binding to service if it is running */ fun bind() { //service is already bound if(service != null) return val running = this.getSharedPreferences("jmb_bms_Server_Info", Context.MODE_PRIVATE).getBoolean("Service_Running",false) if(!running) return Log.d("MainActivity", "Binding to service") val intent = Intent(this, ConnectionService::class.java).putExtra("Caller","CreatePoint") bindService(intent, serviceConnection, 0) } /** * Function for unbinding from service */ fun unbind() { if( service != null) { unbindService(serviceConnection) } service = null } override fun onStop() { super.onStop() unbind() } override fun onRestart() { super.onRestart() bind() } }
0
Kotlin
0
0
1e3227abcd299188042ba847e7e4a2153334d51e
4,914
PERLA_Android_client
MIT License
ugc-detail-component/src/main/java/com/kotlin/android/ugc/detail/component/bean/TopicFamilyViewBean.kt
R-Gang-H
538,443,254
false
null
package com.kotlin.android.ugc.detail.component.bean import com.kotlin.android.app.data.constant.CommConstant import com.kotlin.android.app.data.entity.community.content.CommunityContent import com.kotlin.android.app.data.entity.community.content.CommunityContent.Companion.GROUP_JOINING import com.kotlin.android.app.data.entity.community.content.CommunityContent.Companion.GROUP_JOIN_BLACK_NAME import com.kotlin.android.app.data.entity.community.content.CommunityContent.Companion.GROUP_JOIN_SUCCESS import com.kotlin.android.app.data.entity.community.content.CommunityContent.Companion.GROUP_JOIN_UNDO import com.kotlin.android.app.data.ProguardRule import com.kotlin.android.mtime.ktx.formatCount import com.kotlin.android.mtime.ktx.getString import com.kotlin.android.ugc.detail.component.R /** * create by lushan on 2020/8/13 * description: 话题,家族标题 */ data class TopicFamilyViewBean(var familyId: Long = 0L,//家族id var familyName: String = "",//家族名称 var familyPic: String = "",//家族头像 var familyCount: Long = 0L,//成员数 var familyRule: String = "",//家族公告 var familyStatus: Long = 0,//当前家族加入状态 当前用户是否加入此群组 0:未加入1:已加入成功2:加入中(待审核)3:黑名单 var familyPostStatus: Long = 0L,//群组的发帖和评论的权限 JOIN_POST_JOIN_COMMENT(1, "加入发帖加入评论"), FREE_POST_FREE_COMMENT(2, "自由发帖自由评论"), ADMIN_POST_FREE_COMMENT(3, "管理员发帖自由评论"); var userPostCommentPmsn: Long? = 0L,//当前用户帖子评论权限 1:可评论2:不可评论 var userGroupRole: Long? = 0L//当前用户家族权限 APPLICANT(-1, "申请者"), OWNER(1, "族长"), ADMINISTRATOR(2, "管理员"), MEMBER(3, "普通成员"), BLACKLIST(4, "黑名单"); ) : ProguardRule { fun setJoinFamilyStatus(status: Long) { familyStatus = if (status == CommConstant.JOIN_FAMILY_RESULT_STATUS_SUCCEED) CommunityContent.GROUP_JOIN_SUCCESS else GROUP_JOINING if (status == CommConstant.JOIN_FAMILY_RESULT_STATUS_SUCCEED) { familyCount++ } } fun setExitFamilyStatus(status: Long) { familyStatus = if (status == 1L) {//退群成功 GROUP_JOIN_UNDO } else { familyStatus } } fun isBlack(): Boolean = familyStatus == GROUP_JOIN_BLACK_NAME /** * 未加入到家族 */ fun isUnJoinFamily(): Boolean = familyStatus == GROUP_JOIN_UNDO /** * 加入成功 */ fun isJoinSuccess(): Boolean = familyStatus == GROUP_JOIN_SUCCESS /** * 加入按钮显示文案 */ fun getJoinContent(): String { return when (familyStatus) { GROUP_JOINING -> getString(R.string.ugc_group_joining)//加入中 else -> getString(R.string.ugc_detail_family_join)//加入或者黑名单显示文案 } } /** * 获取成员数量 */ fun getFamilyCountContent(): String { return getString(R.string.ugc_family_member_count_format).format(formatCount(if (familyCount < 0) 0 else familyCount)) } }
0
Kotlin
0
1
e63b1f9a28c476c1ce4db8d2570d43a99c0cdb28
3,000
Mtime
Apache License 2.0
idea/idea-completion/testData/handlers/smart/DoNotReplaceOnEnter.kt
JakeWharton
99,388,807
false
null
fun foo(p: Int): Int = p fun f(p: Int): Int { return <caret>foo(1) } //ELEMENT: p
0
null
28
83
4383335168338df9bbbe2a63cb213a68d0858104
88
kotlin
Apache License 2.0
app/src/main/kotlin/com/godslew/gcube/infra/api/response/BookListResponse.kt
godslew
196,345,247
false
{"Kotlin": 13401}
package com.godslew.gcube.infra.api.response import com.google.gson.annotations.SerializedName data class BookListResponse ( @SerializedName("items") var items: List<BookResponse>?, @SerializedName("kind") var kind: String, @SerializedName("totalItems") var totalItems: Int )
0
Kotlin
0
0
23a29fa36ac5ae8f3c27a48cd5888672334b53fa
291
g-cube
Apache License 2.0
src/main/kotlin/site/liangbai/lbapi/economy/parser/impl/ContainsItemParser.kt
Liangbai2333
846,688,168
false
{"Kotlin": 107495}
package site.liangbai.lbapi.economy.parser.impl import site.liangbai.lbapi.economy.parser.Parser // containsItem:name:lore:amount class ContainsItemParser : Parser<ItemInfo> { override fun parse(source: String): ItemInfo { val list = source.split(":").dropLastWhile { it.isEmpty() } val name = list[0] val lore = list[1] val amount = list[2].toInt() val material = if (list.size > 3) list[3] else "" val damage = if (list.size > 4) list[4].toInt() else 0 return ItemInfo(name, lore, amount, material, damage) } } class ItemInfo(val name: String, val lore: String, val amount: Int, val material: String, val damage: Int)
0
Kotlin
0
0
531ab68166203693045dc49bf152599877946b4b
686
LBAPI
Creative Commons Zero v1.0 Universal
src/main/kotlin/org/easysql/ast/statement/select/SqlUnionType.kt
wz7982
537,805,512
false
null
package easysql.ast.statement enum class SqlUnionType(val unionType: String) { UNION("UNION"), UNION_ALL("UNION ALL"), EXCEPT("EXCEPT"), EXCEPT_ALL("EXCEPT ALL"), INTERSECT("INTERSECT"), INTERSECT_ALL("INTERSECT ALL") }
0
Kotlin
0
2
d0d4f8c55f9653f07520a73a660ae103f3a21545
244
easysql-kt
Apache License 2.0
app/src/main/java/wannabit/io/cosmostaion/ui/option/tx/validator/OktValidatorAdapter.kt
cosmostation
418,314,439
false
{"Java": 5007328, "Kotlin": 3109600, "Shell": 3941}
package wannabit.io.cosmostaion.ui.option.tx.validator import android.view.LayoutInflater import android.view.ViewGroup import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import com.google.gson.JsonObject import wannabit.io.cosmostaion.chain.BaseChain import wannabit.io.cosmostaion.databinding.ItemOktValidatorBinding class OktValidatorAdapter( private val selectedChain: BaseChain, private val myValidators: MutableList<JsonObject> ) : ListAdapter<JsonObject, OktValidatorViewHolder>(OkValidatorDefaultDiffCallback()) { private var onItemClickListener: ((Int) -> Unit)? = null override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): OktValidatorViewHolder { val binding = ItemOktValidatorBinding.inflate(LayoutInflater.from(parent.context), parent, false) return OktValidatorViewHolder(parent.context, binding) } override fun onBindViewHolder(holder: OktValidatorViewHolder, position: Int) { val validator = currentList[position] holder.bind(selectedChain, validator, myValidators) holder.itemView.setOnClickListener { onItemClickListener?.let { it(position) } } } private class OkValidatorDefaultDiffCallback : DiffUtil.ItemCallback<JsonObject>() { override fun areItemsTheSame( oldItem: JsonObject, newItem: JsonObject ): Boolean { return oldItem == newItem } override fun areContentsTheSame( oldItem: JsonObject, newItem: JsonObject ): Boolean { return oldItem == newItem } } fun setOnItemClickListener(listener: (Int) -> Unit) { onItemClickListener = listener } }
0
Java
43
83
b04f3615c7c7b4407d719e160155a8c03fbae3a9
1,748
cosmostation-android
MIT License
db/src/main/java/jp/kaleidot725/easycalc/db/dao/TodayStatsDao.kt
kaleidot725
727,725,457
false
{"Kotlin": 288088, "Ruby": 106}
package jp.kaleidot725.easycalc.db.dao import androidx.room.Dao import androidx.room.Delete import androidx.room.Insert import androidx.room.OnConflictStrategy import androidx.room.Query import jp.kaleidot725.easycalc.db.entity.TodayStatsEntity @Dao interface TodayStatsDao { @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun insert(stats: TodayStatsEntity) @Delete suspend fun delete(stats: TodayStatsEntity) @Query("select * from today_stats order by id") suspend fun getAll(): List<TodayStatsEntity> @Query("select * from today_stats where id = :id") suspend fun getById(id: String): TodayStatsEntity? @Query("select count(id) from today_stats") suspend fun getCount(): Long @Query("select sum(elapsedTime) from today_stats") suspend fun getTotalElapsedSeconds(): Long @Query("select sum(solvedQuizCount) from today_stats") suspend fun getTotalSolvedQuizCount(): Long }
0
Kotlin
0
0
e6ed3eb42b6fad739e42be77eebd9619874ae548
948
EasyCalc
MIT License
src/app/src/test/kotlin/org/vaccineimpact/reporting_api/tests/unit_tests/controllers/ArtefactControllerTests.kt
vimc
96,883,583
false
{"Git Config": 1, "Ignore List": 2, "Dockerfile": 2, "Text": 1, "Markdown": 2, "Shell": 8, "YAML": 1, "Gradle": 7, "Batchfile": 1, "INI": 2, "Java Properties": 3, "Java": 46, "Kotlin": 121, "JSON": 22, "XML": 4}
package org.vaccineimpact.reporting_api.tests.unit_tests.controllers import com.google.gson.JsonParser import com.nhaarman.mockito_kotlin.doReturn import com.nhaarman.mockito_kotlin.doThrow import com.nhaarman.mockito_kotlin.mock import com.nhaarman.mockito_kotlin.verify import org.assertj.core.api.Assertions.assertThat import org.assertj.core.api.Assertions.assertThatThrownBy import org.junit.Test import org.vaccineimpact.reporting_api.ActionContext import org.vaccineimpact.reporting_api.FileSystem import org.vaccineimpact.reporting_api.controllers.ArtefactController import org.vaccineimpact.reporting_api.db.Config import org.vaccineimpact.reporting_api.db.OrderlyClient import org.vaccineimpact.reporting_api.errors.UnknownObjectError class ArtefactControllerTests : ControllerTest() { private val mockConfig = mock<Config> { on { this.get("orderly.root") } doReturn "root/" } @Test fun `gets artefacts for report`() { val name = "testname" val version = "testversion" val artefacts = mapOf("test.png" to "hjkdasjkldas6762i1j") val orderly = mock<OrderlyClient> { on { this.getArtefactHashes(name, version) } doReturn artefacts } val actionContext = mock<ActionContext> { on { this.params(":name") } doReturn name on { this.params(":version") } doReturn version } val sut = ArtefactController(actionContext, orderly, mock<FileSystem>(), mockConfig) assertThat(sut.get()).isEqualTo(artefacts) } @Test fun `downloads artefact for report`() { val name = "testname" val version = "testversion" val artefact = "testartefact" val orderly = mock<OrderlyClient> { on { this.getArtefactHash(name, version, artefact) } doReturn "" } val actionContext = mock<ActionContext> { on { this.params(":name") } doReturn name on { this.params(":version") } doReturn version on { this.params(":artefact") } doReturn artefact on { this.getSparkResponse() } doReturn mockSparkResponse } val fileSystem = mock<FileSystem>() { on { this.fileExists("root/archive/$name/$version/$artefact") } doReturn true } val sut = ArtefactController(actionContext, orderly, fileSystem, mockConfig) sut.download() verify(actionContext).addResponseHeader("Content-Disposition", "attachment; filename=\"testname/testversion/testartefact\"") } @Test fun `throws unknown object error if artefact does not exist for report`() { val name = "testname" val version = "testversion" val artefact = "test.png" val orderly = mock<OrderlyClient> { on { this.getArtefactHash(name, version, artefact) } doThrow UnknownObjectError("", "") } val actionContext = mock<ActionContext> { on { this.params(":name") } doReturn name on { this.params(":version") } doReturn version on { this.params(":artefact") } doReturn artefact } val sut = ArtefactController(actionContext, orderly, mock<FileSystem>(), mockConfig) assertThatThrownBy { sut.download() } .isInstanceOf(UnknownObjectError::class.java) } }
1
null
1
1
2a1f1ecd1fdcf7fdc4669834d5329837cb1139db
3,350
montagu-reporting-api
MIT License
FilePicker/src/main/java/com/linkdev/filepicker/utils/file/ScalingUtils.kt
linkdevelopment
309,077,085
false
null
/* * Copyright (C) 2020 Link Development * * 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.linkdev.filepicker.utils.file import android.graphics.Bitmap import android.graphics.BitmapFactory /** * Class containing static utility methods for bitmap decoding and scaling */ object ScalingUtils { /** * Decode a file path into a sample bitmap * @param path file path to be decoded * @param dstWidth desired width * @param dstHeight desired height * @return The decoded bitmap, or null if the image data could not be decoded * */ fun decodeFile(path: String?, dstWidth: Int, dstHeight: Int): Bitmap { val options = BitmapFactory.Options().apply { inJustDecodeBounds = true BitmapFactory.decodeFile(path, this) } return if (options.outWidth <= dstWidth || options.outHeight <= dstHeight) { BitmapFactory.decodeFile(path) } else { options.inJustDecodeBounds = false options.inSampleSize = calculateSampleSize(options.outWidth, options.outHeight, dstWidth, dstHeight) BitmapFactory.decodeFile(path, options) } } /** * Calculate optimal down-sampling factor given the dimensions of a source * image, the dimensions of a destination area and a scaling logic. * * @param srcWidth Width of source image * @param srcHeight Height of source image * @param dstWidth Width of destination area * @param dstHeight Height of destination area * @return Optimal down scaling sample size for decoding */ private fun calculateSampleSize( srcWidth: Int, srcHeight: Int, dstWidth: Int, dstHeight: Int ): Int { var inSampleSize = 1 if (srcHeight > dstHeight || srcWidth > dstWidth) { val halfHeight: Int = srcHeight / 2 val halfWidth: Int = srcWidth / 2 while (halfHeight / inSampleSize >= dstHeight && halfWidth / inSampleSize >= dstWidth) { inSampleSize *= 2 } } return inSampleSize } }
0
Kotlin
1
5
ed8c62fb2220f3e0eb61272a2d8c86fa1ac16aad
2,625
FilePicker_Android
Apache License 2.0
app/src/main/java/io/github/ch8n/compose97/ui/components/windowscaffold/WindowScaffold.kt
ch8n
403,836,527
false
{"Kotlin": 83109}
package io.github.ch8n.compose97.ui.components.windowscaffold import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.gestures.scrollable import androidx.compose.foundation.layout.* import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.material.Divider import androidx.compose.material.Icon import androidx.compose.material.MaterialTheme import androidx.compose.material.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.shadow import androidx.compose.ui.graphics.Brush import androidx.compose.ui.graphics.Color import androidx.compose.ui.res.painterResource import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp import io.github.ch8n.compose97.R import io.github.ch8n.compose97.ui.theme.* data class WindowProps( val statusBar: StatusBarProps, val toolbar: List<ToolbarGroupProp>, val navToolbar: List<NavToolbarProp>, val addressBar: WindowAddressProps, val isMinimised: Boolean = false, val isMaximised: Boolean = false, ) { companion object { val NoWindow = WindowProps( statusBar = StatusBarProps.Empty, toolbar = listOf(ToolbarGroupProp.Empty), navToolbar = listOf(NavToolbarProp.Empty), addressBar = WindowAddressProps.Empty ) } } @Composable fun WindowScaffold( props: WindowProps, modifier: Modifier = Modifier, onMinimiseClicked: () -> Unit, onMaximiseClicked: () -> Unit, onCloseClicked: () -> Unit, content: @Composable () -> Unit, ) { if (props.isMinimised) { return } Column( modifier = modifier .fillMaxWidth(if (props.isMaximised) 1f else 0.75f) .fillMaxHeight(if (props.isMaximised) 1f else 0.65f) .border(2.dp, Silver), horizontalAlignment = Alignment.CenterHorizontally ) { WindowStatusBar( props = props.statusBar, modifier = Modifier.fillMaxWidth(), onMinimiseClicked = onMinimiseClicked, onMaximiseClicked = onMaximiseClicked, onCloseClicked = onCloseClicked ) Divider( modifier = Modifier.fillMaxWidth(), color = Gray, ) WindowToolbar( menuGroup = props.toolbar, modifier = Modifier.fillMaxWidth() ) Divider( modifier = Modifier.fillMaxWidth(), color = Gray, ) WindowNavToolbar( modifier = Modifier.fillMaxWidth(), toolbarOptions = props.navToolbar ) Divider( modifier = Modifier.fillMaxWidth(), color = Gray, ) WindowAddressBar( props = props.addressBar, modifier = Modifier.fillMaxWidth() ) Divider( modifier = Modifier.fillMaxWidth(), color = Gray, ) Box( modifier = Modifier .background(Silver) .padding(top = 8.dp) .fillMaxWidth() .fillMaxHeight() .padding(start = 8.dp, end = 8.dp, bottom = 8.dp) .background(White) .border(1.dp, Black) .shadow(2.dp) ) { Column( modifier = Modifier .fillMaxSize() .background( Brush.linearGradient( 0.15f to RoyalBlue, 0.30f to White, ) ) ) { Column( modifier = Modifier .fillMaxWidth() .padding(top = 48.dp, start = 16.dp), verticalArrangement = Arrangement.spacedBy(8.dp) ) { Icon( painter = painterResource(id = props.statusBar.mainIcon), modifier = Modifier .padding(start = 16.dp) .size(56.dp), contentDescription = null, tint = Color.Unspecified ) Text( text = props.statusBar.title, style = MaterialTheme.typography.h2, ) Box( modifier = Modifier .fillMaxWidth(0.8f) .height(2.5.dp) .background( Brush.horizontalGradient( colors = listOf( Color.Red, Color.Yellow, Color.Green, Color.Blue ) ) ) ) } Spacer(modifier = Modifier.height(16.dp)) Column( modifier = Modifier .fillMaxWidth() .verticalScroll(state = rememberScrollState()) ) { content.invoke() } } } } } @Preview @Composable fun WindowScaffoldPreview() { WindowScaffold( props = WindowProps( statusBar = StatusBarProps( title = """C:\\""", mainIcon = R.drawable.my_computer_32x32, ), toolbar = listOf( ToolbarGroupProp( groupName = "File", onGroupClicked = {} ), ToolbarGroupProp( groupName = "Edit", onGroupClicked = {} ), ToolbarGroupProp( groupName = "View", onGroupClicked = {} ), ToolbarGroupProp( groupName = "Help", onGroupClicked = {} ), ), navToolbar = listOf( NavToolbarProp( name = "Back", iconRes = R.drawable.ic_back_navtool, onOptionClicked = {} ), NavToolbarProp( name = "Forward", iconRes = R.drawable.ic_forward_navtool, onOptionClicked = {} ), NavToolbarProp( name = "Up", iconRes = R.drawable.ic_up_navtool, onOptionClicked = {} ), NavToolbarProp( name = "Delete", iconRes = R.drawable.ic_delete_navtool, isExtra = true, onOptionClicked = {} ), ), addressBar = WindowAddressProps( iconRes = R.drawable.my_computer_32x32, path = """C:\\""", name = "C:" ), isMaximised = true ), onMinimiseClicked = {}, onMaximiseClicked = {}, onCloseClicked = {}, ) { } }
0
Kotlin
1
25
a41af28865814b89cf1519f0a749c1d22f2e4753
7,614
Compose97
MIT License
jwt-core/src/commonMain/kotlin/tz/co/asoft/KeyInfo.ktx.kt
aSoft-Ltd
320,982,927
false
null
package tz.co.asoft val KeyInfo.privateKey: SecurityKey get() = when (this) { is SecurityKey -> this is SecurityKeyPair -> privateSecurityKey else -> error("Unkown key") }
0
Kotlin
1
1
ae27cc251d42c913a252541ec93253416219974f
204
jwt
MIT License
kairo-rest-feature/src/main/kotlin/kairo/rest/exception/MissingJwtClaim.kt
hudson155
836,940,978
false
{"Kotlin": 486567, "HCL": 1700}
package kairo.rest.exception import kairo.exception.UnauthorizedException public class MissingJwtClaim(name: String) : UnauthorizedException( message = "The $name claim is missing from the JWT", )
0
Kotlin
1
9
da21d969005c51aa6d30ac20b1e682452494c50c
201
kairo
Apache License 2.0
app/src/main/java/org/stepic/droid/storage/dao/CourseDaoImpl.kt
abhirocks1211
205,717,847
false
null
package org.stepic.droid.storage.dao import android.content.ContentValues import android.database.Cursor import org.stepic.droid.storage.operations.DatabaseOperations import org.stepic.droid.storage.structure.DbStructureCourse import org.stepic.droid.util.DbParseHelper import org.stepic.droid.util.getBoolean import org.stepic.droid.util.getDouble import org.stepic.droid.util.getLong import org.stepic.droid.util.getString import org.stepik.android.cache.video.dao.VideoDao import org.stepik.android.model.Course import org.stepik.android.model.Video import javax.inject.Inject class CourseDaoImpl @Inject constructor( databaseOperations: DatabaseOperations, private val videoDao: VideoDao ) : DaoBase<Course>(databaseOperations) { public override fun getDbName() = DbStructureCourse.TABLE_NAME public override fun getDefaultPrimaryColumn() = DbStructureCourse.Columns.ID public override fun getDefaultPrimaryValue(persistentObject: Course) = persistentObject.id.toString() public override fun parsePersistentObject(cursor: Cursor): Course = Course( id = cursor.getLong(DbStructureCourse.Columns.ID), title = cursor.getString(DbStructureCourse.Columns.TITLE), description = cursor.getString(DbStructureCourse.Columns.DESCRIPTION), cover = cursor.getString(DbStructureCourse.Columns.COVER), certificate = cursor.getString(DbStructureCourse.Columns.CERTIFICATE), requirements = cursor.getString(DbStructureCourse.Columns.REQUIREMENTS), summary = cursor.getString(DbStructureCourse.Columns.SUMMARY), workload = cursor.getString(DbStructureCourse.Columns.WORKLOAD), intro = cursor.getString(DbStructureCourse.Columns.INTRO), introVideo = Video(id = cursor.getLong(DbStructureCourse.Columns.INTRO_VIDEO_ID)), language = cursor.getString(DbStructureCourse.Columns.LANGUAGE), authors = DbParseHelper.parseStringToLongArray(cursor.getString(DbStructureCourse.Columns.AUTHORS)), instructors = DbParseHelper.parseStringToLongArray(cursor.getString(DbStructureCourse.Columns.INSTRUCTORS)), sections = DbParseHelper.parseStringToLongArray(cursor.getString(DbStructureCourse.Columns.SECTIONS)), courseFormat = cursor.getString(DbStructureCourse.Columns.COURSE_FORMAT), targetAudience = cursor.getString(DbStructureCourse.Columns.TARGET_AUDIENCE), certificateFooter = cursor.getString(DbStructureCourse.Columns.CERTIFICATE_FOOTER), certificateCoverOrg = cursor.getString(DbStructureCourse.Columns.CERTIFICATE_COVER_ORG), totalUnits = cursor.getLong(DbStructureCourse.Columns.TOTAL_UNITS), enrollment = cursor.getLong(DbStructureCourse.Columns.ENROLLMENT), progress = cursor.getString(DbStructureCourse.Columns.PROGRESS), owner = cursor.getLong(DbStructureCourse.Columns.OWNER), readiness = cursor.getDouble(DbStructureCourse.Columns.READINESS), isContest = cursor.getBoolean(DbStructureCourse.Columns.IS_CONTEST), isFeatured = cursor.getBoolean(DbStructureCourse.Columns.IS_FEATURED), isActive = cursor.getBoolean(DbStructureCourse.Columns.IS_ACTIVE), isPublic = cursor.getBoolean(DbStructureCourse.Columns.IS_PUBLIC), certificateDistinctionThreshold = cursor.getLong(DbStructureCourse.Columns.CERTIFICATE_DISTINCTION_THRESHOLD), certificateRegularThreshold = cursor.getLong(DbStructureCourse.Columns.CERTIFICATE_REGULAR_THRESHOLD), certificateLink = cursor.getString(DbStructureCourse.Columns.CERTIFICATE_LINK), isCertificateAutoIssued = cursor.getBoolean(DbStructureCourse.Columns.IS_CERTIFICATE_AUTO_ISSUED), lastDeadline = cursor.getString(DbStructureCourse.Columns.LAST_DEADLINE), beginDate = cursor.getString(DbStructureCourse.Columns.BEGIN_DATE), endDate = cursor.getString(DbStructureCourse.Columns.END_DATE), slug = cursor.getString(DbStructureCourse.Columns.SLUG), scheduleLink = cursor.getString(DbStructureCourse.Columns.SCHEDULE_LINK), scheduleLongLink = cursor.getString(DbStructureCourse.Columns.SCHEDULE_LONG_LINK), scheduleType = cursor.getString(DbStructureCourse.Columns.SCHEDULE_TYPE), lastStepId = cursor.getString(DbStructureCourse.Columns.LAST_STEP), learnersCount = cursor.getLong(DbStructureCourse.Columns.LEARNERS_COUNT), reviewSummary = cursor.getLong(DbStructureCourse.Columns.REVIEW_SUMMARY), timeToComplete = cursor.getLong(DbStructureCourse.Columns.TIME_TO_COMPLETE), isPaid = cursor.getBoolean(DbStructureCourse.Columns.IS_PAID), price = cursor.getString(DbStructureCourse.Columns.PRICE), currencyCode = cursor.getString(DbStructureCourse.Columns.CURRENCY_CODE), displayPrice = cursor.getString(DbStructureCourse.Columns.DISPLAY_PRICE), priceTier = cursor.getString(DbStructureCourse.Columns.PRICE_TIER) ) public override fun getContentValues(course: Course): ContentValues { val values = ContentValues() values.put(DbStructureCourse.Columns.ID, course.id) values.put(DbStructureCourse.Columns.TITLE, course.title) values.put(DbStructureCourse.Columns.DESCRIPTION, course.description) values.put(DbStructureCourse.Columns.COVER, course.cover) values.put(DbStructureCourse.Columns.CERTIFICATE, course.certificate) values.put(DbStructureCourse.Columns.REQUIREMENTS, course.requirements) values.put(DbStructureCourse.Columns.SUMMARY, course.summary) values.put(DbStructureCourse.Columns.WORKLOAD, course.workload) values.put(DbStructureCourse.Columns.INTRO, course.intro) values.put(DbStructureCourse.Columns.INTRO_VIDEO_ID, course.introVideo?.id ?: -1) // todo add complete course entity and remove this hack values.put(DbStructureCourse.Columns.LANGUAGE, course.language) values.put(DbStructureCourse.Columns.AUTHORS, DbParseHelper.parseLongArrayToString(course.authors)) values.put(DbStructureCourse.Columns.INSTRUCTORS, DbParseHelper.parseLongArrayToString(course.instructors)) values.put(DbStructureCourse.Columns.SECTIONS, DbParseHelper.parseLongArrayToString(course.sections)) values.put(DbStructureCourse.Columns.COURSE_FORMAT, course.courseFormat) values.put(DbStructureCourse.Columns.TARGET_AUDIENCE, course.targetAudience) values.put(DbStructureCourse.Columns.CERTIFICATE_FOOTER, course.certificateFooter) values.put(DbStructureCourse.Columns.CERTIFICATE_COVER_ORG, course.certificateCoverOrg) values.put(DbStructureCourse.Columns.TOTAL_UNITS, course.totalUnits) values.put(DbStructureCourse.Columns.ENROLLMENT, course.enrollment) values.put(DbStructureCourse.Columns.PROGRESS, course.progress) values.put(DbStructureCourse.Columns.OWNER, course.owner) values.put(DbStructureCourse.Columns.READINESS, course.readiness) values.put(DbStructureCourse.Columns.IS_CONTEST, course.isContest) values.put(DbStructureCourse.Columns.IS_FEATURED, course.isFeatured) values.put(DbStructureCourse.Columns.IS_ACTIVE, course.isActive) values.put(DbStructureCourse.Columns.IS_PUBLIC, course.isPublic) values.put(DbStructureCourse.Columns.CERTIFICATE_DISTINCTION_THRESHOLD, course.certificateDistinctionThreshold) values.put(DbStructureCourse.Columns.CERTIFICATE_REGULAR_THRESHOLD, course.certificateRegularThreshold) values.put(DbStructureCourse.Columns.CERTIFICATE_LINK, course.certificateLink) values.put(DbStructureCourse.Columns.IS_CERTIFICATE_AUTO_ISSUED, course.isCertificateAutoIssued) values.put(DbStructureCourse.Columns.LAST_DEADLINE, course.lastDeadline) values.put(DbStructureCourse.Columns.BEGIN_DATE, course.beginDate) values.put(DbStructureCourse.Columns.END_DATE, course.endDate) values.put(DbStructureCourse.Columns.SLUG, course.slug) values.put(DbStructureCourse.Columns.SCHEDULE_LINK, course.scheduleLink) values.put(DbStructureCourse.Columns.SCHEDULE_LONG_LINK, course.scheduleLongLink) values.put(DbStructureCourse.Columns.SCHEDULE_TYPE, course.scheduleType) values.put(DbStructureCourse.Columns.LAST_STEP, course.lastStepId) values.put(DbStructureCourse.Columns.LEARNERS_COUNT, course.learnersCount) values.put(DbStructureCourse.Columns.REVIEW_SUMMARY, course.reviewSummary) values.put(DbStructureCourse.Columns.TIME_TO_COMPLETE, course.timeToComplete) values.put(DbStructureCourse.Columns.IS_PAID, course.isPaid) values.put(DbStructureCourse.Columns.PRICE, course.price) values.put(DbStructureCourse.Columns.CURRENCY_CODE, course.currencyCode) values.put(DbStructureCourse.Columns.DISPLAY_PRICE, course.displayPrice) values.put(DbStructureCourse.Columns.PRICE_TIER, course.priceTier) return values } override fun populateNestedObjects(course: Course): Course = course.apply { introVideo = videoDao.get(course.introVideo?.id ?: -1) // less overhead vs immutability } override fun storeNestedObjects(persistentObject: Course) { persistentObject.introVideo?.let(videoDao::replace) } }
1
null
1
1
8a2ead7334b6b26a281b3a7842e6502fd96b2cc5
9,678
stepik
Apache License 2.0
analysis/analysis-api-platform-interface/src/org/jetbrains/kotlin/analysis/api/platform/projectStructure/KotlinAnchorModuleProvider.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2023 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.analysis.api.platform.projectStructure import com.intellij.openapi.components.serviceOrNull import com.intellij.openapi.project.Project import org.jetbrains.kotlin.analysis.api.platform.KotlinOptionalPlatformComponent import org.jetbrains.kotlin.analysis.api.projectStructure.KaLibraryModule import org.jetbrains.kotlin.analysis.api.projectStructure.KaSourceModule /** * [KotlinAnchorModuleProvider] provides modules which contain dependencies of libraries. * * In the IJ monorepo, anchor modules are required for navigation from Kotlin compiler library sources to IJ platform sources. The Kotlin * compiler depends on the IJ platform, but this dependency is not represented as JARs in the monorepo, but rather by certain monorepo * source modules, which are made visible to the Kotlin compiler library sources as dependencies via an anchor module. */ public interface KotlinAnchorModuleProvider : KotlinOptionalPlatformComponent { public fun getAnchorModule(libraryModule: KaLibraryModule): KaSourceModule? /** * Returns all anchor modules configured in the project. */ public fun getAllAnchorModules(): Collection<KaSourceModule> /** * Returns all anchor modules configured in the project if they have already been computed and are not invalidated. * This function must only be called from a write action to ensure that they are not being computed from another read action. * * @return The anchor modules if they are computed and the result is the same as [getAllAnchorModules], or `null` otherwise. */ public fun getAllAnchorModulesIfComputed(): Collection<KaSourceModule>? public companion object { public fun getInstance(project: Project): KotlinAnchorModuleProvider? = project.serviceOrNull() } }
182
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
2,024
kotlin
Apache License 2.0
analysis/analysis-api-platform-interface/src/org/jetbrains/kotlin/analysis/api/platform/projectStructure/KotlinAnchorModuleProvider.kt
JetBrains
3,432,266
false
{"Kotlin": 79571273, "Java": 6776465, "Swift": 4063829, "C": 2609744, "C++": 1957654, "Objective-C++": 175279, "JavaScript": 130754, "Python": 59855, "Shell": 34920, "Objective-C": 21463, "Lex": 21452, "Batchfile": 11382, "CSS": 11368, "Ruby": 10470, "Dockerfile": 9907, "Groovy": 7092, "EJS": 5241, "CMake": 4473, "HTML": 2699, "Puppet": 1698, "FreeMarker": 1393, "Roff": 725, "Scala": 80}
/* * Copyright 2010-2023 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.analysis.api.platform.projectStructure import com.intellij.openapi.components.serviceOrNull import com.intellij.openapi.project.Project import org.jetbrains.kotlin.analysis.api.platform.KotlinOptionalPlatformComponent import org.jetbrains.kotlin.analysis.api.projectStructure.KaLibraryModule import org.jetbrains.kotlin.analysis.api.projectStructure.KaSourceModule /** * [KotlinAnchorModuleProvider] provides modules which contain dependencies of libraries. * * In the IJ monorepo, anchor modules are required for navigation from Kotlin compiler library sources to IJ platform sources. The Kotlin * compiler depends on the IJ platform, but this dependency is not represented as JARs in the monorepo, but rather by certain monorepo * source modules, which are made visible to the Kotlin compiler library sources as dependencies via an anchor module. */ public interface KotlinAnchorModuleProvider : KotlinOptionalPlatformComponent { public fun getAnchorModule(libraryModule: KaLibraryModule): KaSourceModule? /** * Returns all anchor modules configured in the project. */ public fun getAllAnchorModules(): Collection<KaSourceModule> /** * Returns all anchor modules configured in the project if they have already been computed and are not invalidated. * This function must only be called from a write action to ensure that they are not being computed from another read action. * * @return The anchor modules if they are computed and the result is the same as [getAllAnchorModules], or `null` otherwise. */ public fun getAllAnchorModulesIfComputed(): Collection<KaSourceModule>? public companion object { public fun getInstance(project: Project): KotlinAnchorModuleProvider? = project.serviceOrNull() } }
182
Kotlin
5748
49,172
33eb9cef3d146062c103f9853d772f0a1da0450e
2,024
kotlin
Apache License 2.0
app-extensions/app-utilities/src/main/java/com/kaleyra/app_utilities/notification/NotificationProxy.kt
Bandyer
153,806,014
false
null
/* * Copyright 2023 Kaleyra @ https://www.kaleyra.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.kaleyra.app_utilities.notification import android.content.Context import com.kaleyra.app_configuration.model.PushProvider import com.kaleyra.app_utilities.storage.ConfigurationPrefsManager import com.kaleyra.app_utilities.storage.LoginManager.isUserLogged import com.kaleyra.app_utilities.activities.BaseActivity /** * This class is a proxy to the different notification services we want to show case * At the moment we implemented the FCM ( standard ) which works everywhere except for China. * For China we show case the Pushy library. */ object NotificationProxy { fun registerDevice(context: Context) { if (!isUserLogged(context)) return val configuration = ConfigurationPrefsManager.getConfiguration(context) when (configuration.pushProvider) { PushProvider.FCM -> { if (FirebaseCompat.isGmsAvailable(context)) FirebaseCompat.registerDevice(context) else if (HuaweiCompat.isHmsAvailable(context)) HuaweiCompat.registerDevice(context) } PushProvider.Pushy -> PushyCompat.registerDevice(context) PushProvider.HMS -> if (HuaweiCompat.isHmsAvailable(context)) HuaweiCompat.registerDevice(context) PushProvider.NONE -> Unit } } fun unregisterDevice(context: Context) { val configuration = ConfigurationPrefsManager.getConfiguration(context) when (configuration.pushProvider) { PushProvider.FCM -> { if (FirebaseCompat.isGmsAvailable(context)) FirebaseCompat.unregisterDevice(context) else if (HuaweiCompat.isHmsAvailable(context)) HuaweiCompat.unregisterDevice(context) } PushProvider.Pushy -> PushyCompat.unregisterDevice(context) PushProvider.HMS -> if (HuaweiCompat.isHmsAvailable(context)) HuaweiCompat.unregisterDevice(context) PushProvider.NONE -> Unit } } @JvmStatic fun listen(context: BaseActivity) { val configuration = ConfigurationPrefsManager.getConfiguration(context) if (configuration.pushProvider != PushProvider.Pushy) return PushyCompat.listen(context) } }
1
null
4
13
46d9cd4215095fe9a95bdd315de2ad21c714504b
2,805
Bandyer-Android-SDK
Apache License 2.0
components/string-utilities/src/main/kotlin/org/cloudfoundry/credhub/utils/ResourceReader.kt
binlab
261,746,796
true
{"Java": 1287999, "Kotlin": 1058614, "TSQL": 44569, "Shell": 22882, "Groovy": 3620, "HTML": 1305, "Dockerfile": 989, "Vim Snippet": 593, "PLSQL": 271}
package org.cloudfoundry.credhub.utils import com.google.common.io.Resources import kotlin.text.Charsets.UTF_8 import org.springframework.stereotype.Component @Component class ResourceReader { fun readFileToString(fileName: String): String { val resource = Resources.getResource(fileName) return Resources.toString(resource, UTF_8) } }
0
null
0
0
936c69204d369089be36ee30d61479ec0a24dfb0
362
credhub
Apache License 2.0
src/test/kotlin/net/corda/option/flow/OptionExerciseFlowTests.kt
R3-Archive
124,871,072
true
{"Kotlin": 93860, "HTML": 12265, "JavaScript": 11056, "CSS": 60}
package net.corda.option.flow import net.corda.core.contracts.Amount import net.corda.core.node.services.queryBy import net.corda.core.transactions.SignedTransaction import net.corda.core.utilities.OpaqueBytes import net.corda.core.utilities.getOrThrow import net.corda.finance.flows.CashIssueFlow import net.corda.option.DUMMY_LINEAR_ID import net.corda.option.base.OPTION_CURRENCY import net.corda.option.base.ORACLE_NAME import net.corda.option.base.contract.OptionContract import net.corda.option.base.state.OptionState import net.corda.option.client.flow.OptionExerciseFlow import net.corda.option.client.flow.OptionIssueFlow import net.corda.option.client.flow.OptionTradeFlow import net.corda.option.createOption import net.corda.option.oracle.flow.QueryOracleHandler import net.corda.option.oracle.flow.RequestOracleSigHandler import net.corda.testing.node.MockNetwork import org.junit.After import org.junit.Before import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertFailsWith class OptionExerciseFlowTests { private val mockNet: MockNetwork = MockNetwork(cordappPackages = listOf("net.corda.option.base.contract", "net.corda.option.oracle.oracle", "net.corda.finance.contracts.asset")) private val issuerNode = mockNet.createPartyNode() private val buyerNode = mockNet.createPartyNode() private val oracleNode = mockNet.createNode(legalName = ORACLE_NAME) private val issuer = issuerNode.info.legalIdentities.first() private val buyer = buyerNode.info.legalIdentities.first() @Before fun setup() { oracleNode.registerInitiatedFlow(QueryOracleHandler::class.java) oracleNode.registerInitiatedFlow(RequestOracleSigHandler::class.java) listOf(issuerNode, buyerNode).forEach { it.registerInitiatedFlow(OptionIssueFlow.Responder::class.java) it.registerInitiatedFlow(OptionTradeFlow.Responder::class.java) } mockNet.runNetwork() } @After fun tearDown() { mockNet.stopNodes() } @Test fun `issue flow records a correctly-formed transaction in both parties' transaction storages`() { issueCashToBuyer() val option = createOption(issuer, buyer) issueOptionToBuyer(option) val stx = exerciseOption() // We check the recorded transaction in both vaults. listOf(issuerNode, buyerNode).forEach { node -> assertEquals(stx, node.services.validatedTransactions.getTransaction(stx.id)) val ltx = node.transaction { stx.toLedgerTransaction(node.services) } // An OptionState input. assertEquals(1, ltx.inputs.size) assertEquals(1, ltx.inputsOfType<OptionState>().size) // An OptionState output. assertEquals(1, ltx.outputs.size) assertEquals(1, ltx.outputsOfType<OptionState>().size) // A single OptionContract.Commands.Exercise command with the correct attributes. assertEquals(1, ltx.commands.size) val optionCmd = ltx.commandsOfType<OptionContract.Commands.Exercise>().single() assert(optionCmd.signers.containsAll(listOf(buyer.owningKey))) } } @Test fun `flow records the option in the vaults of the issuer and owner`() { issueCashToBuyer() val option = createOption(issuer, buyer) issueOptionToBuyer(option) exerciseOption() // We check the recorded option in both vaults. listOf(issuerNode, buyerNode).forEach { node -> val options = node.transaction { node.services.vaultService.queryBy<OptionState>().states } assertEquals(1, options.size) val recordedOption = options.single().state.data assertEquals(option, recordedOption.copy(exercised = false, exercisedOnDate = option.exercisedOnDate)) } } @Test fun `exercise flow can only be run by the current owner`() { issueCashToBuyer() val option = createOption(issuer, buyer) issueOptionToBuyer(option) val flow = OptionExerciseFlow.Initiator(DUMMY_LINEAR_ID) // We are running the flow from the issuer, who doesn't currently own the option. val future = issuerNode.startFlow(flow) mockNet.runNetwork() assertFailsWith<IllegalArgumentException> { future.getOrThrow() } } private fun issueCashToBuyer() { val notary = buyerNode.services.networkMapCache.notaryIdentities.first() val flow = CashIssueFlow(Amount(900, OPTION_CURRENCY), OpaqueBytes.of(0x01), notary) val future = buyerNode.startFlow(flow) mockNet.runNetwork() future.getOrThrow() } private fun issueOptionToBuyer(option: OptionState): SignedTransaction { val flow = OptionIssueFlow.Initiator(option) val future = buyerNode.startFlow(flow) mockNet.runNetwork() return future.getOrThrow() } private fun exerciseOption(): SignedTransaction { val flow = OptionExerciseFlow.Initiator(DUMMY_LINEAR_ID) val future = buyerNode.startFlow(flow) mockNet.runNetwork() return future.getOrThrow() } }
1
Kotlin
6
1
528aab74e2be32782d355a081e4572e5093bebb7
5,250
cordapp-option
Apache License 2.0
mr-clean-processor/src/main/java/com/trello/mrclean/MrCleanProcessor.kt
trello
168,751,198
false
{"Kotlin": 28151, "Shell": 968}
/* * Copyright @ 2018 Atlassian Pty Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.trello.mrclean import com.google.auto.service.AutoService import com.squareup.kotlinpoet.FileSpec import com.trello.mrclean.annotations.Sanitize import kotlinx.metadata.impl.extensions.MetadataExtensions import kotlinx.metadata.jvm.KotlinClassMetadata import net.ltgt.gradle.incap.IncrementalAnnotationProcessor import net.ltgt.gradle.incap.IncrementalAnnotationProcessorType import java.io.File import javax.annotation.processing.AbstractProcessor import javax.annotation.processing.Filer import javax.annotation.processing.Messager import javax.annotation.processing.ProcessingEnvironment import javax.annotation.processing.Processor import javax.annotation.processing.RoundEnvironment import javax.lang.model.SourceVersion import javax.lang.model.element.TypeElement import javax.lang.model.util.Elements import javax.lang.model.util.Types import javax.tools.Diagnostic @AutoService(Processor::class) @IncrementalAnnotationProcessor(IncrementalAnnotationProcessorType.ISOLATING) class MrCleanProcessor : AbstractProcessor() { private lateinit var messager: Messager private lateinit var elementUtils: Elements private lateinit var typeUtils: Types private lateinit var filer: Filer private var generatedDir: File? = null private var isDebug: Boolean = false private var packageName: String? = null private val sanitize = Sanitize::class.java override fun getSupportedAnnotationTypes(): MutableSet<String> = mutableSetOf( sanitize.canonicalName ) override fun getSupportedSourceVersion(): SourceVersion = SourceVersion.latest() override fun getSupportedOptions() = mutableSetOf( OPTION_KAPT_GENERATED, OPTION_DEBUG, OPTION_PACKAGE_NAME ) override fun init(processingEnv: ProcessingEnvironment) { super.init(processingEnv) messager = processingEnv.messager elementUtils = processingEnv.elementUtils typeUtils = processingEnv.typeUtils filer = processingEnv.filer generatedDir = processingEnv.options[OPTION_KAPT_GENERATED]?.let(::File) // load properties applied by MrCleanPlugin isDebug = processingEnv.options[OPTION_DEBUG] == "true" packageName = processingEnv.options[OPTION_PACKAGE_NAME] } override fun process(annotations: MutableSet<out TypeElement>, roundEnv: RoundEnvironment): Boolean { val funs = roundEnv.getElementsAnnotatedWith(sanitize) .map { val classHeader = it.getClassHeader()!! val metadata = classHeader.readKotlinClassMetadata() it to when (metadata) { is KotlinClassMetadata.Class -> metadata.readClassData() else -> error("not a class") } } .map { (element, classData) -> element to SanitizeGenerator.generateSanitizedToString(classData, isDebug) .toBuilder() .addOriginatingElement(element) .build() } if (funs.isNotEmpty() && packageName == null) { messager.printMessage(Diagnostic.Kind.ERROR, "PackageName is not available at processing time. You may be trying to annotate test classes, which is unsupported.") return true } funs.map { (element, funSpec) -> val enclosingElementName = element.enclosingElement.simpleName.toString().capitalize() FileSpec.builder(packageName!!, "SanitizationFor$enclosingElementName${element.simpleName}") .apply { if (isDebug) addComment("Debug") else addComment("Release") } .addFunction(funSpec) .build() } .forEach { it.writeTo(processingEnv.filer) } return true } companion object { /** * Name of the processor option containing the path to the Kotlin generated src dir. */ private const val OPTION_KAPT_GENERATED = "kapt.kotlin.generated" /** * Compiler options that get added by MrCleanPlugin * mrclean.debug - whether the variant's build type is debuggable * mrclean.packagename - the root package name for the project * * Changes here must be reflected in MrCleanPlugin.kt */ private const val OPTION_DEBUG = "mrclean.debug" private const val OPTION_PACKAGE_NAME = "mrclean.packagename" init { // https://youtrack.jetbrains.net/issue/KT-24881 with(Thread.currentThread()) { val classLoader = contextClassLoader contextClassLoader = MetadataExtensions::class.java.classLoader try { MetadataExtensions.INSTANCES } finally { contextClassLoader = classLoader } } } } } fun Messager.note(message: String) { printMessage(Diagnostic.Kind.NOTE, message) }
3
Kotlin
11
228
0eb00d8bf51d6d9fceaecc0c9289748b7b3d3d14
5,248
mr-clean
Apache License 2.0
src/main/kotlin/com/teamclicker/gameservice/game/templates/WaveTemplate.kt
Humberd
140,150,771
false
{"Kotlin": 153182, "Dockerfile": 346}
package com.teamclicker.gameservice.game.templates data class WaveTemplate( val templateId: Long, var creatures: List<CreatureTemplate> )
0
Kotlin
0
0
dfe3c64168e1ff62edd1cc93d86d1b85dabc5eeb
147
TeamClicker-GameService
Apache License 2.0
app/src/main/java/org/stepic/droid/core/presenters/DiscussionPresenter.kt
abhirocks1211
205,717,847
false
{"Gradle": 12, "Java Properties": 2, "Text": 19, "Shell": 2, "Ignore List": 5, "Batchfile": 1, "Git Attributes": 1, "Markdown": 2, "XML": 519, "YAML": 1, "Kotlin": 1311, "Proguard": 3, "Prolog": 1, "Java": 190, "CSS": 2, "SVG": 65, "JSON": 4, "JavaScript": 3}
package org.stepic.droid.core.presenters import io.reactivex.Scheduler import io.reactivex.disposables.CompositeDisposable import io.reactivex.rxkotlin.plusAssign import io.reactivex.rxkotlin.subscribeBy import org.stepic.droid.core.presenters.contracts.DiscussionView import org.stepic.droid.di.comment.CommentsScope import org.stepic.droid.di.qualifiers.BackgroundScheduler import org.stepic.droid.di.qualifiers.MainScheduler import org.stepik.android.domain.discussion_proxy.interactor.DiscussionProxyInteractor import javax.inject.Inject @CommentsScope class DiscussionPresenter @Inject constructor( private val discussionProxyInteractor: DiscussionProxyInteractor, @BackgroundScheduler private val backgroundScheduler: Scheduler, @MainScheduler private val mainScheduler: Scheduler ) : PresenterBase<DiscussionView>() { private val compositeDisposable = CompositeDisposable() fun loadDiscussion(discussionId: String) { compositeDisposable.clear() compositeDisposable += discussionProxyInteractor .getDiscussionProxy(discussionId) .subscribeOn(backgroundScheduler) .observeOn(mainScheduler) .subscribeBy( onSuccess = { discussionProxy -> if (discussionProxy.discussions.isEmpty()) { view?.onEmptyComments(discussionProxy) } else { view?.onLoaded(discussionProxy) } }, onError = { view?.onInternetProblemInComments() } ) } }
1
null
1
1
8a2ead7334b6b26a281b3a7842e6502fd96b2cc5
1,596
stepik
Apache License 2.0
components/remote-controls/core-model/src/commonMain/kotlin/com/flipperdevices/ifrmvp/model/buttondata/PowerButtonData.kt
flipperdevices
288,258,832
false
null
package com.flipperdevices.ifrmvp.model.buttondata import com.flipperdevices.ifrmvp.model.IfrKeyIdentifier import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @Serializable data class PowerButtonData( @SerialName("key_id") override val keyIdentifier: IfrKeyIdentifier = IfrKeyIdentifier.Empty, ) : SingleKeyButtonData { override val type: ButtonData.ButtonType = ButtonData.ButtonType.POWER }
21
null
174
1,528
8f293e596741a6c97409acbc8de10c7ae6e8d8b0
437
Flipper-Android-App
MIT License
entity-browser-app/src/main/kotlin/jetbrains/xodus/browser/web/Transformations.kt
JetBrains
45,294,329
false
null
package jetbrains.xodus.browser.web import jetbrains.exodus.entitystore.Entity import jetbrains.exodus.entitystore.PersistentEntityStoreImpl import jetbrains.xodus.browser.web.search.UIPropertyTypes fun Entity.asView(): EntityView { return asLightView().apply { blobs = blobNames.map { blobView(it) } links = linkNames.asSequence().map { linkView(it) }.toList() } } fun Entity.asLightView(): EntityView { return EntityView( id = id.toString(), typeId = id.typeId, label = label, type = type, properties = propertyNames.map { propertyView(it) } ) } fun Entity.linkView(name: String, skip: Int = 0, top: Int = 100): LinkPager { val links = getLinks(name) return LinkPager( name = name, skip = skip, top = top, totalCount = links.size(), entities = links.asSequence().drop(skip).take(top).map { link -> val linkId = link.id val exists = link.exists() EntityLink( id = link.id.toString(), name = name, typeId = linkId.typeId, label = link.label, type = link.type, notExists = !exists ) }.toList() ) } fun Entity.exists(): Boolean { return try { val currentTransaction = store.currentTransaction!! currentTransaction.getEntity(id) true } catch (e: RuntimeException) { false } } private fun Entity.blobView(name: String): EntityBlob { return EntityBlob( name = name, blobSize = getBlobSize(name) ) } private fun Entity.propertyView(name: String): EntityProperty { val value = this.getProperty(name) val entity = this val store = entity.store as PersistentEntityStoreImpl val clazz: Class<*> = if (value != null) { val propertyType = store.propertyTypes.getPropertyType(value.javaClass) propertyType.clazz } else { String::class.java } val typeVO = PropertyType( readonly = !UIPropertyTypes.isSupported(clazz), clazz = clazz.name, displayName = clazz.simpleName ) return EntityProperty( name = name, type = typeVO, value = value2string(value) ) } fun String.asEntityType(store: PersistentEntityStoreImpl): EntityType { val typeId = store.getEntityTypeId(store.currentTransaction!!, this, false) return EntityType(typeId, this) } fun EntityProperty.string2value(): Comparable<*>? { if (value == null) { return null } try { val clazz = type.clazz val type = UIPropertyTypes.uiTypeOf<Comparable<*>>(clazz) return type.toValue(this.value) } catch (e: RuntimeException) { throw InvalidFieldException(e, name, value!!) } } fun <T : Comparable<*>> value2string(value: T?): String? { if (value == null) { return null } try { val clazz = value.javaClass val type = UIPropertyTypes.uiTypeOf<T>(clazz) return type.toString(value) } catch (e: RuntimeException) { throw IllegalStateException(e) } } val Entity.label: String get() { return "$type[${toIdString()}]" }
16
Kotlin
25
60
6b4e7427c8a0b004a226c9e67ca5b8f492bc7afe
3,400
xodus-entity-browser
Apache License 2.0
app/src/main/java/com/demo/architecturecomponentstalk/api/json/MeetupEventJson.kt
milosevic81
149,103,329
false
null
package com.demo.architecturecomponentstalk.api.json import com.demo.architecturecomponentstalk.db.entity.Venue data class MeetupEventJson( val id: String, val name: String, val description: String, val venue: Venue )
3
Kotlin
0
0
e0af84c3e84324f45baa7fbaab317f269d9496d5
252
archcomponents
MIT License
src/main/kotlin/com/github/stefanosansone/intellijtargetprocessintegration/icons/TargetProcessIcons.kt
stefanosansone
692,485,851
false
{"Kotlin": 24551}
package com.github.stefanosansone.intellijtargetprocessintegration.icons import com.intellij.openapi.util.IconLoader object TargetProcessIcons { @JvmField val TargetProcessToolWindow = IconLoader.getIcon("/icons/toolWindowTargetProcess.svg", javaClass) }
0
Kotlin
0
0
d18ed51f18681a6d8688ce5b58006f68ced60a9a
264
intellij-targetprocess-integration
Apache License 2.0
domain/teamplay-business-domain/src/main/kotlin/com/teamplay/domain/business/club/function/FindNoticesByClubId.kt
YAPP-16th
235,351,938
false
{"Gradle Kotlin DSL": 10, "Gradle": 1, "Shell": 2, "Ignore List": 1, "Batchfile": 1, "Text": 1, "Markdown": 5, "XML": 8, "Kotlin": 185, "Java": 4, "Java Properties": 1, "YAML": 6}
package com.teamplay.domain.business.club.function import com.teamplay.core.function.Function import com.teamplay.domain.database.club.entity.Notice import com.teamplay.domain.database.jpa.club.repository.NoticeRepository class FindNoticesByClubId( private val noticeRepository: NoticeRepository ): Function<Long, List<Notice>> { override fun apply(clubId: Long): List<Notice> { return noticeRepository.findAllByClub_Id(clubId) } }
2
Kotlin
0
1
a3209b28ea6ca96cb9a81a0888793f9b0f4d02d2
453
Team_Android_2_Backend
MIT License
domain/teamplay-business-domain/src/main/kotlin/com/teamplay/domain/business/club/function/FindNoticesByClubId.kt
YAPP-16th
235,351,938
false
{"Gradle Kotlin DSL": 10, "Gradle": 1, "Shell": 2, "Ignore List": 1, "Batchfile": 1, "Text": 1, "Markdown": 5, "XML": 8, "Kotlin": 185, "Java": 4, "Java Properties": 1, "YAML": 6}
package com.teamplay.domain.business.club.function import com.teamplay.core.function.Function import com.teamplay.domain.database.club.entity.Notice import com.teamplay.domain.database.jpa.club.repository.NoticeRepository class FindNoticesByClubId( private val noticeRepository: NoticeRepository ): Function<Long, List<Notice>> { override fun apply(clubId: Long): List<Notice> { return noticeRepository.findAllByClub_Id(clubId) } }
2
Kotlin
0
1
a3209b28ea6ca96cb9a81a0888793f9b0f4d02d2
453
Team_Android_2_Backend
MIT License
src/main/kotlin/com/redissi/trakt/TraktAuthenticator.kt
IliasRedissi
235,675,675
true
{"Kotlin": 307912}
package com.redissi.trakt import kotlinx.coroutines.* import okhttp3.Authenticator import okhttp3.Request import okhttp3.Response import okhttp3.Route class TraktAuthenticator(val trakt: Trakt) : Authenticator { override fun authenticate(route: Route?, response: Response): Request? { return handleAuthenticate(response, trakt) } /** * If not doing a trakt [Trakt.getApiUrl] request tries to refresh the access token with the refresh token. * * @param response The response passed to [.authenticate]. * @param trakt The [Trakt] instance to get the API key from and to set the updated JSON web token on. * @return A request with updated authorization header or null if no auth is possible. */ private fun handleAuthenticate(response: Response, trakt: Trakt): Request? = runBlocking { if (Trakt.getApiHost(trakt.staging) != response.request.url.host) { return@runBlocking null // not a trakt API endpoint (possibly trakt OAuth or other API), give up. } if (responseCount(response) >= 2) { return@runBlocking null // failed 2 times, give up. } val refreshToken = trakt.refreshToken if (refreshToken == null || refreshToken.isEmpty()) { return@runBlocking null // have no refresh token, give up. } // try to refresh the access token with the refresh token val refreshResponse = trakt.refreshAccessToken(refreshToken) val body = refreshResponse.body() if (!refreshResponse.isSuccessful || body == null) { return@runBlocking null // failed to retrieve a token, give up. } // store the new tokens val accessToken = body.accessToken trakt.accessToken(accessToken) trakt.refreshToken(body.refreshToken) // retry request return@runBlocking response.request.newBuilder() .header(Trakt.HEADER_AUTHORIZATION, "Bearer $accessToken") .build() } private fun responseCount(response: Response): Int { var res = response var result = 1 var priorResponse = res.priorResponse while (priorResponse != null) { res = priorResponse priorResponse = res.priorResponse result++ } return result } }
4
Kotlin
0
0
c980c5c428edd8ba2d4b147be5e247e6e1356574
2,342
trakt-kotlin
The Unlicense
module-water/src/main/java/com/hardlove/cl/water/mvp/presenter/MinePresenter.kt
hardlove
154,798,245
true
{"Gradle": 20, "Markdown": 5, "Java Properties": 2, "Shell": 1, "Text": 1, "Ignore List": 13, "Batchfile": 1, "YAML": 1, "Proguard": 13, "Java": 198, "XML": 417, "JSON": 1, "Kotlin": 60}
package com.hardlove.cl.water.mvp.presenter import android.app.Application import com.hardlove.cl.water.mvp.contract.MineContract import com.jess.arms.di.scope.FragmentScope import com.jess.arms.http.imageloader.ImageLoader import com.jess.arms.integration.AppManager import com.jess.arms.mvp.BasePresenter import me.jessyan.rxerrorhandler.core.RxErrorHandler import javax.inject.Inject @FragmentScope class MinePresenter @Inject constructor(model: MineContract.Model, rootView: MineContract.View) : BasePresenter<MineContract.Model, MineContract.View>(model, rootView) { @Inject lateinit var mErrorHandler: RxErrorHandler @Inject lateinit var mApplication: Application @Inject lateinit var mImageLoader: ImageLoader @Inject lateinit var mAppManager: AppManager override fun onDestroy() { super.onDestroy(); } }
0
Java
0
0
732e8edf7e0046ae076cd5bd6a65630ddff8dc34
873
ArmsComponent
Apache License 2.0
agent-connection/src/main/kotlin/com/luxoft/blockchainlab/corda/hyperledger/indy/AgentConnection.kt
hyperledger-labs
159,397,274
false
null
package com.luxoft.blockchainlab.corda.hyperledger.indy import com.luxoft.blockchainlab.hyperledger.indy.models.* import rx.Single import rx.Subscription enum class AgentConnectionStatus { AGENT_CONNECTED, AGENT_DISCONNECTED } /** * Represents a connected Indy Party */ interface IndyPartyConnection { /** * Sends a credential offer message to the Indy Party represented by this connection * * @param offer credential offer message */ fun sendCredentialOffer(offer: CredentialOffer) /** * Receives a credential offer from the Indy Party represented by this connection * * @return observable ([Single]<>) object emitting a [CredentialOffer] upon subscription */ fun receiveCredentialOffer(): Single<CredentialOffer> /** * Sends a credential request message to the Indy Party represented by this connection * * @param request credential request message (JSON-serialized [CredentialRequestInfo]) */ fun sendCredentialRequest(request: CredentialRequestInfo) /** * Receives a credential request from the Indy Party represented by this connection * * @return observable ([Single]<>) object emitting a [CredentialRequestInfo] upon subscription */ fun receiveCredentialRequest(): Single<CredentialRequestInfo> /** * Sends a credential to Indy Party represented by this connection * * @param credential credential message */ fun sendCredential(credential: CredentialInfo) /** * Receives a credential from the Indy Party represented by this connection * * @return observable ([Single]<>) object emitting a [CredentialInfo] upon subscription */ fun receiveCredential(): Single<CredentialInfo> /** * Sends a proof request message to the Indy Party represented by this connection * * @param request proof request message */ fun sendProofRequest(request: ProofRequest) /** * Receives a proof request from the Indy Party represented by this connection * * @return observable ([Single]<>) object emitting a single [ProofRequest] upon subscription */ fun receiveProofRequest(): Single<ProofRequest> /** * Sends a proof to the Indy Party represented by this connection * * @param proof proof message */ fun sendProof(proof: ProofInfo) /** * Receives a proof from the Indy Party represented by this connection * * @return observable ([Single]<>) object emitting a single [ProofInfo] upon subscription */ fun receiveProof(): Single<ProofInfo> /** * Returns the connected Indy Party session DID */ fun partyDID(): String /** * Returns self session DID */ fun myDID(): String /** * Returns observable ([Single]<>) object, emitting string-encocoded Tails file by the given tails hash. * * @param tailsHash string-encocoded Tails file * * @return observable ([Single]<>) object emitting [TailsResponse] object */ fun requestTails(tailsHash: String) : Single<TailsResponse> /** * Sets handler for client's tails file requests * * @param handler a function producing [TailsResponse] from [TailsRequest] */ fun handleTailsRequestsWith(handler: (TailsRequest) -> TailsResponse) } class AgentConnectionException(obj: Any) : RuntimeException("AgentConnection exception: $obj") /** * Convenience extension to subscribe with a single lambda on both onSuccess() and onError() */ fun <T> Single<T>.handle(handle: (message: T?, ex: Throwable?) -> Unit): Subscription = this.subscribe({ handle(it, null) }, { handle(null, it) }) /** * Represents a connection to Indy Agent */ interface AgentConnection { /** * Connects to Indy Agent's connection endpoint * * @param url Indy Agent's endpoint URL * @param login endpoint's login * @param password endpoints's password * @return [Single]<Unit> emitting a Unit upon a successful handshake */ fun connect(url: String, login: String, password: String): Single<Unit> /** * Disconnects from the Agent's endpoint */ fun disconnect() /** * Requests the Agent to generate an Invite link. * * @return observable ([Single]<>) emitting the generated invite */ fun generateInvite(): Single<String> /** * Establishes a connection to remote Indy Party based on the given invite * * @return observable ([Single]<>) emitting an [IndyPartyConnection] */ fun acceptInvite(invite: String): Single<IndyPartyConnection> /** * Wait for incoming connection from remote Indy Party that accepted the specific invite * * @param invite invite string * @param timeout amount of milliseconds to wait for party * * @return observable ([Single]<>) emitting an [IndyPartyConnection] */ fun waitForInvitedParty(invite: String, timeout:Long = 60000): Single<IndyPartyConnection> /** * Recalls previously connected Indy Party by its DID and reconstructs corresponding {@code IndyPartyConnection} * * @param partyDID invite string * * @return observable ([Single]<>) emitting an [IndyPartyConnection] */ fun getIndyPartyConnection(partyDID: String): Single<IndyPartyConnection?> /** * Returns Agent connection status * * @return current Agent connection status represented by [AgentConnectionStatus] */ fun getConnectionStatus(): AgentConnectionStatus }
5
Kotlin
22
32
a27b8c613cd31356a353352ea5764b7aafa7c9b3
5,582
cordentity
Apache License 2.0
src/commonMain/kotlin/ch/tutteli/kbox/mapRemaining.kt
robstoll
79,735,987
false
{"Kotlin": 276135, "Java": 85}
package ch.tutteli.kbox /** * Maps remaining values of this [Iterator] with the help of the given [transform] functions, returns an empty list if * [Iterator.hasNext] returns `false` for the first call. * * @return A [List] of the mapped remaining values. */ fun <T, R> Iterator<T>.mapRemaining(transform: (T) -> R): List<R> { val mutableList = mutableListOf<R>() forEachRemaining { mutableList.add(transform(it)) } return mutableList } /** * Maps remaining values of this [Iterator] with the help of the given [transform] functions where a counter variable * is passed ot the [transform] function starting by 0; returns an empty list if [Iterator.hasNext] returns `false` * for the first call. * * @return A [List] of the mapped remaining values. */ fun <T, R> Iterator<T>.mapRemainingWithCounter(transform: (index: Int, T) -> R): List<R> { val mutableList = mutableListOf<R>() var counter = 0 forEachRemaining { mutableList.add(transform(counter, it)) ++counter } return mutableList }
1
Kotlin
4
8
757ebf5ba49cb57396c5409227511147cd06c5da
1,048
kbox
Apache License 2.0
dots/src/main/java/com/bcgdv/asia/lib/dots/DotsProgressIndicator.kt
alphamu
101,716,035
false
null
package com.bcgdv.asia.lib.dots import android.animation.Animator import android.animation.AnimatorSet import android.animation.ValueAnimator import android.annotation.TargetApi import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.os.Build import android.os.Handler import android.support.annotation.IntDef import android.support.v4.view.ViewCompat import android.util.AttributeSet import android.util.Log import android.util.TypedValue import android.view.View import android.view.animation.DecelerateInterpolator import com.bcgdv.asia.lib.R import java.math.BigDecimal class DotsProgressIndicator : View { private var paints: Array<Paint> = arrayOf(Paint(), Paint(), Paint()) private var colors: Array<Int> = arrayOf( Color.RED, Color.BLUE, Color.GREEN) private var dotCount = 3 private var viewTop: Int = 0 private var viewBottom: Int = 0 private var viewStart: Int = 0 private var viewEnd: Int = 0 private var dotPadding: Float = 4f private var dotDiameter = 0F private lateinit var bitmaps: Array<Bitmap> private lateinit var canvases: Array<Canvas> private lateinit var offsets: Array<Int> private var anims: List<Animator>? = null private var set: AnimatorSet = AnimatorSet() private val lock: Any = Any() private var showRunnable: Runnable? = null private var totalDotToSpacing = 4f private var isRunning = false private var visibilityChangeDelay = 1000L private var retryDelay = 200L private var defaultWidth = BigDecimal(50) private var defaultHeight = BigDecimal(30) private var mode = MODE_BEST_FIT constructor(context: Context) : super(context) { setup(context, null) } constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) { setup(context, attrs) } constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) { setup(context, attrs) } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Suppress("unused") constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) { setup(context, attrs) } fun setup(context: Context, attrs: AttributeSet?) { val ta = context.obtainStyledAttributes(attrs, R.styleable.DotsProgressIndicator, 0, 0) try { var outValue = TypedValue() ta.getValue(R.styleable.DotsProgressIndicator_dotsMode, outValue) mode = outValue.data dotCount = ta.getInt(R.styleable.DotsProgressIndicator_numberOfDots, dotCount) visibilityChangeDelay = ta.getInt(R.styleable.DotsProgressIndicator_visibilityChangeDelay, visibilityChangeDelay.toInt()).toLong() dotPadding = (context.resources.displayMetrics.density * dotPadding) outValue = TypedValue() ta.getValue(R.styleable.DotsProgressIndicator_dotColors, outValue) val colorsArrayResId = outValue.resourceId if (mode == MODE_SIZE_PROVIDED) { dotPadding = ta.getDimension(R.styleable.DotsProgressIndicator_dotsSpacing, dotPadding) dotDiameter = ta.getDimension(R.styleable.DotsProgressIndicator_dotsDiameter, dotDiameter) } try { if (isInEditMode || colorsArrayResId == 0) { colors = Array(dotCount) { i -> colors[i % colors.size] } } else { val colorType = context.resources.obtainTypedArray(colorsArrayResId) colors = Array(dotCount) { i -> colorType.getColor(i, colors[i % colors.size]) } colorType.recycle() } } catch (t: Throwable) { Log.e("DOTS", t.message, t) } } finally { ta.recycle() } paints = Array(dotCount) { i -> val p = Paint(Paint.ANTI_ALIAS_FLAG) p.color = colors[i%dotCount] p } offsets = Array(dotCount) { 0 } defaultWidth = defaultWidth.multiply(BigDecimal(context.resources.displayMetrics.density.toDouble())) defaultHeight = defaultHeight.multiply(BigDecimal(context.resources.displayMetrics.density.toDouble())) totalDotToSpacing = dotPadding * (dotCount - 1) if (mode == MODE_SIZE_PROVIDED) { dotPadding = (context.resources.displayMetrics.density * dotPadding) //should come from attr or this as default totalDotToSpacing = dotPadding * (dotCount - 1) //should come from attrs or default value already set defaultWidth = defaultWidth.multiply(BigDecimal(context.resources.displayMetrics.density.toDouble())) defaultHeight = defaultHeight.multiply(BigDecimal(context.resources.displayMetrics.density.toDouble())) } } private fun setupBitmaps() { bitmaps = Array(dotCount) { val bmpWidth = ((width - totalDotToSpacing.toInt() - getPaddingStartCompat() - getPaddingEndCompat()) / dotCount) Bitmap.createBitmap(bmpWidth, bmpWidth, Bitmap.Config.ARGB_4444) } canvases = Array(dotCount) { i -> val b = bitmaps[i] val c = Canvas(b) val cx = BigDecimal(b.width).divide(BigDecimal(2)).toFloat() c.drawCircle(cx, cx, cx, paints[i]) c } } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { val widthMode = MeasureSpec.getMode(widthMeasureSpec) val calculatedWidth = MeasureSpec.getSize(widthMeasureSpec) when (widthMode) { MeasureSpec.UNSPECIFIED -> Log.d("DOTS", "Measure UNSPECIFIED") MeasureSpec.AT_MOST -> Log.d("DOTS", "Measure AT_MOST") MeasureSpec.EXACTLY -> Log.d("DOTS", "Measure EXACTLY") } if (mode == MODE_SIZE_PROVIDED) { val totalWidth = (dotDiameter * dotCount) + totalDotToSpacing val msw = MeasureSpec.makeMeasureSpec(totalWidth.toInt(), MeasureSpec.EXACTLY) val bmpWidth = ((totalWidth.toInt() - totalDotToSpacing.toInt() - getPaddingStartCompat() - getPaddingEndCompat()) / dotCount) val msh = MeasureSpec.makeMeasureSpec(bmpWidth * 2, MeasureSpec.EXACTLY) super.onMeasure(msw, msh) } else if (widthMode == MeasureSpec.UNSPECIFIED || widthMode == MeasureSpec.AT_MOST) { val msw = MeasureSpec.makeMeasureSpec(defaultWidth.toInt(), MeasureSpec.EXACTLY) val bmpWidth = ((defaultWidth.toInt() - totalDotToSpacing.toInt() - getPaddingStartCompat() - getPaddingEndCompat()) / dotCount) val msh = MeasureSpec.makeMeasureSpec(bmpWidth * 2, MeasureSpec.EXACTLY) super.onMeasure(msw, msh) } else { val bmpWidth = ((calculatedWidth - totalDotToSpacing.toInt() - getPaddingStartCompat() - getPaddingEndCompat()) / dotCount) val msh = MeasureSpec.makeMeasureSpec(bmpWidth * 2, MeasureSpec.EXACTLY) super.onMeasure(widthMeasureSpec, msh) } } override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) { super.onSizeChanged(w, h, oldw, oldh) viewTop = paddingTop viewBottom = h - paddingBottom viewEnd = w - getPaddingEndCompat() viewStart = getPaddingStartCompat() setupBitmaps() if (visibility == View.VISIBLE && !isRunning) { start() } } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) bitmaps.forEachIndexed { i, it -> val space = dotPadding * i val xadd = (i * it.width) val x = viewStart.toFloat() + xadd + space var y = (viewBottom - bitmaps[i].height).toFloat() y -= offsets[i] canvas.drawBitmap(it, x, y, paints[i]) } } private fun start(): Boolean { synchronized(lock) { try { // hack as some times the bitamaps // are not ready when rendering bitmaps[0].height } catch (t: Throwable) { return false } anims = List<Animator>(dotCount) { i -> val h = bitmaps[0].height val va = ValueAnimator.ofInt(viewTop, h, viewTop) va.addUpdateListener { offsets[i] = it.animatedValue as Int // if (i == 0) // Log.d("DotsValueAnimInt", "Num = ${offsets[i]}") invalidate() } va.interpolator = DecelerateInterpolator() va.startDelay = if (i == 0) 0 else (600L / dotCount) * i va.duration = 200L va.repeatCount = 1 va } set = AnimatorSet() set.duration = 600L set.playTogether(anims) set.addListener(object : AbsAnimatorListener { override fun onAnimationEnd(animator: Animator?) { super.onAnimationEnd(animator) if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N) { return } if (visibility == View.VISIBLE) { post { start() } } } override fun onAnimationEnd(animation: Animator?, isReverse: Boolean) { super.onAnimationEnd(animation, isReverse) if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) { return } if (visibility == View.VISIBLE) { post { start() } } } }) set.start() isRunning = true return true } } private fun stop() { synchronized(lock) { isRunning = false } } override fun setVisibility(visibility: Int) { synchronized(lock) { if (showRunnable != null) { visibilityHandler.removeCallbacks(showRunnable) showRunnable = null } showRunnable = Runnable { super.setVisibility(visibility) var success = true if (visibility == View.VISIBLE) { success = start() } else { stop() } if (success) { showRunnable = null } else { visibilityHandler.postDelayed(showRunnable, retryDelay) } } visibilityHandler.postDelayed(showRunnable, visibilityChangeDelay) } } override fun onDetachedFromWindow() { synchronized(lock) { if (showRunnable != null) { visibilityHandler.removeCallbacks(showRunnable) showRunnable = null } } super.onDetachedFromWindow() } private fun getPaddingStartCompat(): Int { return ViewCompat.getPaddingStart(this) } private fun getPaddingEndCompat(): Int { return ViewCompat.getPaddingEnd(this) } companion object { val visibilityHandler: Handler = Handler() @IntDef(MODE_BEST_FIT, MODE_SIZE_PROVIDED) @Retention(AnnotationRetention.SOURCE) annotation class Mode private const val MODE_BEST_FIT = 0 private const val MODE_SIZE_PROVIDED = 1 } }
1
Kotlin
2
25
75955cf9e12a67aa10e9f06bda866ac4941c54a5
11,860
android-widget-dotsprogressindicator
Apache License 2.0
enro-core/src/main/java/dev/enro/core/compose/LocalNavigationHandle.kt
isaac-udy
256,179,010
false
null
package dev.enro.core.compose import androidx.compose.runtime.Composable import androidx.compose.runtime.compositionLocalOf import androidx.lifecycle.viewmodel.compose.LocalViewModelStoreOwner import dev.enro.core.NavigationHandle import dev.enro.core.NavigationKey import dev.enro.core.TypedNavigationHandle import dev.enro.core.asTyped import dev.enro.core.internal.handle.getNavigationHandleViewModel val LocalNavigationHandle = compositionLocalOf<NavigationHandle?> { null }
13
Kotlin
9
186
da2e56a58d210333eef2ea06833ffcd81cb79941
485
Enro
Apache License 2.0
src/main/java/net/bjoernpetersen/spotify/suggester/PlaylistChoice.kt
fossabot
202,222,482
true
{"Kotlin": 139538, "HTML": 266}
package net.bjoernpetersen.spotify.suggester import net.bjoernpetersen.musicbot.api.config.ConfigSerializer import net.bjoernpetersen.musicbot.api.config.DeserializationException internal data class PlaylistChoice(val id: String, val displayName: String) { companion object : ConfigSerializer<PlaylistChoice> { @Throws(DeserializationException::class) override fun deserialize(string: String): PlaylistChoice { string.split(';').let { if (it.size < 2) throw DeserializationException() else { val playlistId = it[0] val displayName = it.subList(1, it.size).joinToString(";") return PlaylistChoice(playlistId, displayName) } } } override fun serialize(obj: PlaylistChoice): String { return "${obj.id};${obj.displayName}" } } }
17
Kotlin
2
0
f9ff6853f0f68d5f138803febb6e62374cf64855
920
MusicBot-plugins
MIT License
domain/src/main/java/com/sergiom/domain/usecase/GetDiscountPromotionsUseCaseImpl.kt
SergioMardez
533,396,871
false
{"Kotlin": 56418}
package com.sergiom.domain.usecase import com.sergiom.data.model.ShopDiscount import com.sergiom.data.model.ShopDiscountModel import com.sergiom.data.utils.* interface GetDiscountPromotionsUseCase { suspend operator fun invoke(): Either<ShopDiscountModel, String> } class GetDiscountPromotionsUseCaseImpl: GetDiscountPromotionsUseCase { override suspend fun invoke(): Either<ShopDiscountModel, String> { return eitherSuccess(getDiscounts()) } } private fun getDiscounts(): ShopDiscountModel = ShopDiscountModel( discounts = listOf( ShopDiscount(itemCode = "VOUCHER", numOfItems = 2, price = 0.0, itemsToApply = 50, text = "2 x 1"), ShopDiscount(itemCode = "TSHIRT", numOfItems = 3, price = 19.00, itemsToApply = 100, text = "Buying 3 or more") ) )
0
Kotlin
0
0
c891db0dd294f24917db1586024752aa24d9a94f
797
cabifyChallenge
Apache License 2.0
src/main/kotlin/com/msg/gcms/domain/club/presentation/data/request/UpdateClubRequest.kt
GSM-MSG
592,816,374
false
null
package com.msg.gcms.domain.club.presentation.data.request import java.util.* import javax.validation.constraints.NotBlank import javax.validation.constraints.NotNull import javax.validation.constraints.Pattern import javax.validation.constraints.Size data class UpdateClubRequest ( @field:NotBlank @field:Size(min = 1, max = 25) val name: String, @field:NotBlank val content: String, @field:NotBlank val bannerImg: String, @field:NotBlank val contact: String, @field:NotBlank @field:Pattern(regexp = "^((http(s?))\\:\\/\\/)([0-9a-zA-Z\\-]+\\.)+[a-zA-Z]{2,6}(\\:[0-9]+)?(\\/\\S*)?\$") val notionLink: String, val teacher: String? = null, @field:NotNull val activityImgs: List<String>, @field:NotNull val member: List<UUID> )
10
Kotlin
0
8
d55e8ed3f343acca0c3937cf07b6fcfb8dd30598
794
GCMS-BackEnd
MIT License
characters/src/main/java/com/trivago/challenge/characters/networking/CharacterDetailsRepo.kt
zubyf09
218,471,403
false
null
package com.trivago.challenge.characters.networking import io.reactivex.Single class CharacterDetailsRepo(private val service: CharacterService) : CharacterDetailsContract.Repo { override fun getCharacterDetails(url: String): Single<com.trivago.challenge.characters.model.CharacterDetailsModel> = service.getCharacterDetails(url) override fun getSpecieDetails(url: String?): Single<com.trivago.challenge.characters.model.SpeciesResponseModel> = service.getCharacterSpecies(url) override fun getFilmDetails(url: String?): Single<com.trivago.challenge.characters.model.FilmResponseModel> = service.getCharacterFilms(url) override fun getHomeworldDetails(url: String?): Single<com.trivago.challenge.characters.model.HomeworldResponseModel?> = service.getCharacterHomeworld(url) }
0
Kotlin
0
0
c5827ffc695c8368086b5f4adcce7ffce3e70863
805
Star_Wars_Character_List
MIT License
app/src/main/java/com/example/appName/presentation/sum/calculation/CalculationViewState.kt
kubak89
141,586,462
false
null
package com.example.appName.presentation.sum.calculation import java.io.Serializable data class CalculationViewState( val firstNumber: Long = 0, val secondNumber: Long = 0, val sum: Long = 0 ) : Serializable { constructor( previous: CalculationViewState, firstNumber: Long = previous.firstNumber, secondNumber: Long = previous.secondNumber, sum: Long = firstNumber + secondNumber ) : this(firstNumber, secondNumber, sum) sealed class PartialState { data class SumCalculated(val sum: Long) : PartialState() } }
0
Kotlin
1
0
e61f418e10f9a3f4e3a01e6904af13834765e3bb
609
Mvi-Android-Example
MIT License
app/src/main/java/com/jesperqvarfordt/listn/explore/ExplorePresenter.kt
JesperQv
122,033,035
false
null
package com.jesperqvarfordt.listn.explore import com.jesperqvarfordt.listn.device.imagecache.ImageCache import com.jesperqvarfordt.listn.domain.model.Chart import com.jesperqvarfordt.listn.domain.model.Track import com.jesperqvarfordt.listn.domain.interactor.GetChartsInteractor import com.jesperqvarfordt.listn.domain.interactor.GetTracksOnChartInteractor import com.jesperqvarfordt.listn.domain.interactor.SearchTracksInteractor import com.jesperqvarfordt.listn.domain.interactor.SetPlaylistAndPlayInteractor import io.reactivex.disposables.CompositeDisposable import javax.inject.Inject class ExplorePresenter @Inject constructor(private val search: SearchTracksInteractor, private val startPlayingPlaylist: SetPlaylistAndPlayInteractor, private val getCharts: GetChartsInteractor, private val getTracksOnChart: GetTracksOnChartInteractor, private val imageCache: ImageCache) : ExploreContract.Presenter { private var view: ExploreContract.View? = null private val disposables = CompositeDisposable() override fun subscribe(view: ExploreContract.View) { this.view = view loadChartsAndShow() } private fun loadChartsAndShow() { disposables.add(getCharts.execute() .doOnSubscribe({ view?.toggleChartList() view?.showSearchBar() }) .subscribe({ charts -> view?.updateCharts(charts) }, { view?.showError() })) } override fun unsubscribe() { view = null disposables.clear() } override fun searchClicked(query: String) { view?.toggleTrackList() disposables.add(search.execute(query) .subscribe({ tracks -> if (tracks.isEmpty()) { view?.showEmpty() } else { view?.updateTracks(tracks) imageCache.preloadImages(tracks) } }, { view?.showError() })) } override fun trackClicked(tracks: List<Track>) { disposables.add(startPlayingPlaylist.execute(tracks) .subscribe()) view?.openMusicPlayer() } override fun chartClicked(chart: Chart) { view?.toggleTrackList() view?.showTitleBar(chart.name) disposables.add(getTracksOnChart.execute(chart) .subscribe({ tracks -> view?.updateTracks(tracks) imageCache.preloadImages(tracks) }, { view?.showError() })) } override fun backClicked() { loadChartsAndShow() } }
1
null
9
97
68b97f2d5437d1bab06df39b9eaf754d7941c520
2,807
Listn
MIT License
gradle/plugins/src/main/kotlin/net/twisterrob/gradle/plugins/settings/AcceptEnterpriseTOSPlugin.kt
TWiStErRob
116,494,236
false
null
package net.twisterrob.gradle.plugins.settings import org.gradle.api.Plugin import org.gradle.api.initialization.Settings import org.gradle.kotlin.dsl.gradleEnterprise class AcceptEnterpriseTOSPlugin : Plugin<Settings> { override fun apply(settings: Settings) { settings.plugins.withId("com.gradle.enterprise") { settings.gradleEnterprise { buildScan { termsOfServiceUrl = "https://gradle.com/terms-of-service" termsOfServiceAgree = "yes" } } } } }
76
Kotlin
4
12
9f04340ec78e58e590360dba9d7341a3f8eb05e9
481
net.twisterrob.gradle
The Unlicense
resume-ab-ktor-app/src/test/kotlin/ru/otus/otuskotln/resume/ktor/router/RouterTest.kt
otuskotlin
377,710,400
false
null
package ru.otus.otuskotln.resume.ktor.router import io.ktor.application.* import io.ktor.http.* import io.ktor.server.testing.* import ru.otus.otuskotlin.resume.ktor.configs.AppKtorConfig import ru.otus.otuskotlin.resume.ktor.configs.KtorAuthConfig import ru.otus.otuskotlin.resume.ktor.module import ru.otus.otuskotlin.resume.openapi.models.BaseMessage import ru.otus.otuskotln.resume.ktor.Utils import kotlin.test.assertEquals abstract class RouterTest { protected inline fun <reified T> testPostRequest( body: BaseMessage? = null, uri: String, config: AppKtorConfig = AppKtorConfig(), result: HttpStatusCode = HttpStatusCode.OK, crossinline block: T.() -> Unit = {} ) { withTestApplication({ module(config = config) }) { handleRequest(HttpMethod.Post, uri) { addHeader(HttpHeaders.ContentType, ContentType.Application.Json.withCharset(Charsets.UTF_8).toString()) addHeader(HttpHeaders.Authorization, "Bearer ${KtorAuthConfig.testUserToken()}") setBody(Utils.mapper.writeValueAsString(body)) }.apply { println(response.content) assertEquals(HttpStatusCode.OK, response.status()) if( result == HttpStatusCode.OK) { assertEquals(ContentType.Application.Json.withCharset(Charsets.UTF_8), response.contentType()) Utils.mapper.readValue(response.content, T::class.java).block() } } } } }
0
Kotlin
0
0
920d87731a128acc1c113acd393dcc09ed01411a
1,563
ok-202105-resume-ab
MIT License
core/common/src/main/kotlin/trebuchet/util/Time.kt
khadas
451,798,402
false
{"Kotlin": 259588, "Shell": 1647}
/* * Copyright 2019 Google 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 * * 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 trebuchet.util.time fun Double.secondValueToMillisecondString() = "%.3f ms".format(this * 1000.0)
0
Kotlin
0
0
b735f448e61c99f4c06101902ff76eee4e5496f1
703
android_tools_trebuchet
Apache License 2.0
base/lint/libs/lint-tests/src/test/java/com/android/tools/lint/checks/TranslucentViewDetectorTest.kt
qiangxu1996
301,210,525
false
null
/* * Copyright (C) 2018 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.lint.checks import com.android.tools.lint.detector.api.Detector class TranslucentViewDetectorTest : AbstractCheckTest() { fun testNoWarningPreO() { lint().files( manifestWithActivityThemeNoTargetSdk, themeFile ).run().expectClean() } // TODO: Test inherited themes // (activity uses theme where the translucency is from a parent style) fun testThemeInActivityManifest() { lint().files( manifestWithActivityTheme, themeFile ).run().expect( "res/values/styles.xml:7: Warning: Should not specify screen orientation with translucent or floating theme [TranslucentOrientation]\n" + " <item name=\"android:windowIsFloating\">true</item>\n" + " ~~~~~~~~~~~~~~~~~~~~~~~~\n" + " AndroidManifest.xml:9: <No location-specific message\n" + "0 errors, 1 warnings" ) } fun testThemeInApplicationManifest() { lint().files( manifestWithApplicationTheme, themeFile ).run().expect( "res/values/styles.xml:7: Warning: Should not specify screen orientation with translucent or floating theme [TranslucentOrientation]\n" + " <item name=\"android:windowIsFloating\">true</item>\n" + " ~~~~~~~~~~~~~~~~~~~~~~~~\n" + " AndroidManifest.xml:10: <No location-specific message\n" + "0 errors, 1 warnings" ) } fun testThemeFromActivity() { // Like previous test, but instead of specifying theme in manifest, specifies it // via code in the activity lint().files( manifestWithoutTheme, themeFile, java( "" + "package test.pkg;\n" + "\n" + "import android.os.Bundle;\n" + "import android.app.Activity;\n" + "\n" + "@SuppressWarnings(\"unused\")\n" + "public class MainActivity extends Activity {\n" + " @Override\n" + " protected void onCreate(Bundle savedInstanceState) {\n" + " super.onCreate(savedInstanceState);\n" + " setTheme(R.style.AppTheme);\n" + " setContentView(R.layout.activity_main);\n" + " }\n" + "}\n" ) ).run().expect( "res/values/styles.xml:7: Warning: Should not specify screen orientation with translucent or floating theme [TranslucentOrientation]\n" + " <item name=\"android:windowIsFloating\">true</item>\n" + " ~~~~~~~~~~~~~~~~~~~~~~~~\n" + " AndroidManifest.xml:9: <No location-specific message\n" + "0 errors, 1 warnings" ) } override fun getDetector(): Detector = TranslucentViewDetector() private val themeFile = xml( "res/values/styles.xml", "" + "<resources>\n" + "\n" + " <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.DarkActionBar\">\n" + " <item name=\"colorPrimary\">@color/colorPrimary</item>\n" + " <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item>\n" + " <item name=\"colorAccent\">@color/colorAccent</item>\n" + " <item name=\"android:windowIsFloating\">true</item>\n" + " <item name=\"android:windowIsTranslucent\">true</item>\n" + " </style>\n" + "\n" + " <style name=\"SubTheme\" parent=\"AppTheme\">\n" + " </style>\n" + "\n" + "</resources>\n" ) private val manifestWithActivityThemeNoTargetSdk = manifest( "" + "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" + " package=\"test.pkg\">\n" + "\n" + " <application\n" + " android:icon=\"@mipmap/ic_launcher\"\n" + " android:label=\"@string/app_name\">\n" + " <activity android:name=\".MainActivity\"\n" + " android:screenOrientation=\"landscape\"\n" + " android:theme=\"@style/AppTheme\" />\n" + " </application>\n" + "</manifest>" ) private val manifestWithActivityTheme = manifest( "" + "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" + " package=\"test.pkg\">\n" + " <uses-sdk android:minSdkVersion=\"16\" android:targetSdkVersion=\"26\" />\n" + " <application\n" + " android:icon=\"@mipmap/ic_launcher\"\n" + " android:label=\"@string/app_name\">\n" + " <activity android:name=\".MainActivity\"\n" + " android:screenOrientation=\"landscape\"\n" + " android:theme=\"@style/AppTheme\" />\n" + " </application>\n" + "</manifest>" ) private val manifestWithoutTheme = manifest( "" + "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" + " package=\"test.pkg\">\n" + " <uses-sdk android:minSdkVersion=\"16\" android:targetSdkVersion=\"26\" />\n" + " <application\n" + " android:icon=\"@mipmap/ic_launcher\"\n" + " android:label=\"@string/app_name\">\n" + " <activity android:name=\".MainActivity\"\n" + " android:screenOrientation=\"landscape\" />\n" + " </application>\n" + "</manifest>" ) private val manifestWithApplicationTheme = manifest( "" + "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n" + " package=\"test.pkg\">\n" + " <uses-sdk android:minSdkVersion=\"16\" android:targetSdkVersion=\"26\" />\n" + " <application\n" + " android:icon=\"@mipmap/ic_launcher\"\n" + " android:label=\"@string/app_name\"\n" + " android:theme=\"@style/AppTheme\">\n" + " <activity android:name=\".MainActivity\"\n" + " android:screenOrientation=\"landscape\" />\n" + " </application>\n" + "</manifest>" ) }
1
null
1
1
3411c5436d0d34e6e2b84cbf0e9395ac8c55c9d4
7,957
vmtrace
Apache License 2.0
game-api/src/main/kotlin/org/alter/api/ext/QueueTaskExt.kt
AlterRSPS
421,831,790
false
null
package gg.rsmod.plugins.api.ext import gg.rsmod.game.fs.def.ItemDef import gg.rsmod.game.fs.def.NpcDef import gg.rsmod.game.message.impl.ResumePauseButtonMessage import gg.rsmod.game.model.Appearance import gg.rsmod.game.model.attr.INTERACTING_NPC_ATTR import gg.rsmod.game.model.entity.Npc import gg.rsmod.game.model.entity.Pawn import gg.rsmod.game.model.entity.Player import gg.rsmod.game.model.queue.QueueTask import gg.rsmod.plugins.api.InterfaceDestination import gg.rsmod.plugins.api.Skills /** * The child id of the chat box in the gameframe interface. This can change * with revision. */ const val CHATBOX_CHILD = 561 /** * The id for the appearance interface. */ const val APPEARANCE_INTERFACE_ID = 269 /** * The default action that will occur when interrupting or finishing a dialog. */ private val closeDialog: QueueTask.() -> Unit = { player.closeComponent(parent = 162, child = CHATBOX_CHILD) } /** * Invoked when input dialog queues are interrupted. */ private val closeInput: QueueTask.() -> Unit = { player.closeInputDialog() } /** * Invoked when the appearance input is interrupted. */ private val closeAppearance: QueueTask.() -> Unit = { player.closeInterface(APPEARANCE_INTERFACE_ID) } /** * Gets the [QueueTask.ctx] as a [Pawn]. * * If [QueueTask.ctx] is not a [Pawn], a cast exception will be thrown. */ inline val QueueTask.pawn: Pawn get() = ctx as Pawn /** * Gets the [QueueTask.ctx] as a [Player]. * * If [QueueTask.ctx] is not a [Pawn], a cast exception will be thrown. */ inline val QueueTask.player: Player get() = ctx as Player /** * Gets the [QueueTask.ctx] as an [Npc]. * * If [QueueTask.ctx] is not a [Pawn], a cast exception will be thrown. */ inline val QueueTask.npc: Npc get() = ctx as Npc /** * Prompts the player with options. * * @return * The id of the option chosen. The id can range from [1] inclusive to [options.size] inclusive. */ suspend fun QueueTask.options(vararg options: String, title: String = "Select an Option"): Int { player.sendTempVarbit(5983, 1) player.runClientScript(2379) player.openInterface(parent = 162, child = CHATBOX_CHILD, interfaceId = 219) player.runClientScript(58, title, options.joinToString("|")) player.setInterfaceEvents(interfaceId = 219, component = 1, from = 1, to = options.size, setting = 1) terminateAction = closeDialog waitReturnValue() terminateAction!!(this) return (requestReturnValue as? ResumePauseButtonMessage)?.slot ?: -1 } /** * Prompts the player with an input dialog where they can only enter an integer. * * @return * The integer input. */ suspend fun QueueTask.inputInt(description: String = "Enter amount"): Int { player.runClientScript(108, description) terminateAction = closeInput waitReturnValue() terminateAction!!(this) return requestReturnValue as? Int ?: -1 } /** * Prompts the player with an input dialog where they can enter a string. * * @param description the title, or description, of the dialog box. * * @return the string input. */ suspend fun QueueTask.inputString(description: String = "Enter text"): String { player.runClientScript(110, description) terminateAction = closeInput waitReturnValue() terminateAction!!(this) return requestReturnValue as? String ?: "" } /** * Prompts the player with an input dialog where they can only enter a player * username. * * @param description the title, or description, of the dialog box. * * @return the player with the respective username, null if the player is not * online. */ suspend fun QueueTask.inputPlayer(description: String = "Enter name"): Player? { player.runClientScript(109, description) terminateAction = closeInput waitReturnValue() terminateAction!!(this) return requestReturnValue as? Player } /** * Prompts the player with a chatbox interface that allows them to search * for an item. * * @return * The selected item's id. */ suspend fun QueueTask.searchItemInput(message: String): Int { player.runClientScript(750, message, 1, -1) terminateAction = closeInput waitReturnValue() return requestReturnValue as? Int ?: -1 } /** * Sends a normal message dialog. * * @message * The message to render on the dialog box. * * @lineSpacing * The spacing, in pixels, in between each line that will be rendered on the * dialog box. */ suspend fun QueueTask.messageBox(message: String, lineSpacing: Int = 31) { player.openInterface(parent = 162, child = CHATBOX_CHILD, interfaceId = 229) player.setComponentText(interfaceId = 229, component = 1, text = message) player.runClientScript(600, 1, 1, lineSpacing, 15007745) player.setInterfaceEvents(interfaceId = 229, component = 2, range = -1..-1, setting = 1) player.setComponentText(interfaceId = 229, component = 2, text = "Click here to continue") terminateAction = closeDialog waitReturnValue() terminateAction!!(this) } /** * Send a dialog with an npc's head model. * * @param message * The message to render on the dialog box. * * @npc * The npc id which represents the npc that will be drawn on the dialog box. * If set to -1, the npc id will be set to the player's interacting npc. If the * player is not interacting with an npc, a [RuntimeException] will be thrown. * * @animation * The animation id of the npc's head model. * * @title * The title of the dialog, if left as null, the npc's name will be used. */ suspend fun QueueTask.chatNpc(message: String, npc: Int = -1, animation: Int = 588, title: String? = null) { val npcId = if (npc != -1) npc else player.attr[INTERACTING_NPC_ATTR]?.get()?.getTransform(player) ?: throw RuntimeException("Npc id must be manually set as the player is not interacting with an npc.") val dialogTitle = title ?: player.world.definitions.get(NpcDef::class.java, npcId).name player.runClientScript(2379) player.openInterface(parent = 162, child = CHATBOX_CHILD, interfaceId = 231) player.setComponentNpcHead(interfaceId = 231, component = 1, npc = npcId) player.setComponentAnim(interfaceId = 231, component = 1, anim = animation) player.setComponentText(interfaceId = 231, component = 2, text = dialogTitle) player.setComponentText(interfaceId = 231, component = 4, text = message) player.runClientScript(600, 1, 1, 16, 15138820) player.setInterfaceEvents(interfaceId = 231, component = 3, from = -1, to = -1, setting = 1) player.setComponentText(interfaceId = 231, component = 3, text = "Click here to continue") terminateAction = closeDialog waitReturnValue() terminateAction!!(this) } /** * Send a dialog with your player's head model. * * @param message * The message to render on the dialog box. */ suspend fun QueueTask.chatPlayer(message: String, animation: Int = 588, title: String? = null) { val dialogTitle = title ?: player.username player.runClientScript(2379) player.openInterface(parent = 162, child = CHATBOX_CHILD, interfaceId = 217) player.setComponentPlayerHead(interfaceId = 217, component = 1) player.setComponentAnim(interfaceId = 217, component = 1, anim = animation) player.setComponentText(interfaceId = 217, component = 2, text = dialogTitle) player.setComponentText(interfaceId = 217, component = 4, text = message) player.runClientScript(600, 1, 1, 16, 14221316) player.setInterfaceEvents(interfaceId = 217, component = 3, from = -1, to = -1, setting = 1) player.setComponentText(interfaceId = 217, component = 3, text = "Click here to continue") terminateAction = closeDialog waitReturnValue() terminateAction!!(this) } /** * Sends a single item dialog. * * @param message * The message to render on the dialog box. * * @param item * The id of the item to show on the dialog. * * @param amountOrZoom * The amount or zoom of the item to show on the dialog. * * @param options * Item dialog boxes can have multiple options be shown instead of the default * 'Click here to continue'. */ suspend fun QueueTask.itemMessageBox(message: String, item: Int, amountOrZoom: Int = 1, vararg options: String = arrayOf("Click here to continue")) { player.openInterface(parent = 162, child = CHATBOX_CHILD, interfaceId = 193) player.setInterfaceEvents(interfaceId = 193, component = 0, range = 0..1, setting = 1) player.setComponentItem(interfaceId = 193, component = 1, item = item, amountOrZoom = amountOrZoom) player.setComponentText(interfaceId = 193, component = 2, text = message) player.runClientScript(2868, *options) terminateAction = closeDialog waitReturnValue() terminateAction!!(this) } suspend fun QueueTask.doubleItemMessageBox(message: String, item1: Int, item2: Int, amount1: Int = 1, amount2: Int = 1) { player.setComponentItem(interfaceId = 11, component = 1, item = item1, amountOrZoom = amount1) player.setComponentText(interfaceId = 11, component = 2, text = message) player.setComponentItem(interfaceId = 11, component = 3, item = item2, amountOrZoom = amount2) player.setComponentText(interfaceId = 11, component = 4, text = "Click here to continue") player.setInterfaceEvents(interfaceId = 11, component = 4, range = -1..-1, setting = 1) player.openInterface(parent = 162, child = CHATBOX_CHILD, interfaceId = 11) terminateAction = closeDialog waitReturnValue() terminateAction!!(this) } suspend fun QueueTask.destroyItem(title: String = "Are you sure you want to destroy this item?", note: String, item: Int, amount: Int): Boolean { player.runClientScript(2379) player.openInterface(parent = 162, child = CHATBOX_CHILD, interfaceId = 584) player.runClientScript(814, item, amount, 0, title, note) player.setInterfaceEvents(interfaceId = 584, component = 0, range = 0..1, setting = 1) terminateAction = closeDialog waitReturnValue() terminateAction!!(this) val msg = requestReturnValue as? ResumePauseButtonMessage return msg?.slot == 1 } suspend fun QueueTask.selectAppearance(): Appearance? { player.openInterface(APPEARANCE_INTERFACE_ID, InterfaceDestination.MAIN_SCREEN) terminateAction = closeAppearance waitReturnValue() terminateAction?.invoke(this) return requestReturnValue as? Appearance } suspend fun QueueTask.levelUpMessageBox(skill: Int, levelIncrement: Int) { if (skill != Skills.HUNTER) { val children = mapOf( Skills.AGILITY to 4, Skills.ATTACK to 6, Skills.CONSTRUCTION to 9, Skills.COOKING to 12, Skills.CRAFTING to 14, Skills.DEFENCE to 17, Skills.FARMING to 19, Skills.FIREMAKING to 21, Skills.FISHING to 23, Skills.FLETCHING to 25, Skills.HERBLORE to 28, Skills.HITPOINTS to 30, Skills.MAGIC to 32, Skills.MINING to 34, Skills.PRAYER to 36, Skills.RANGED to 38, Skills.RUNECRAFTING to 41, Skills.SLAYER to 43, Skills.SMITHING to 45, Skills.STRENGTH to 47, Skills.THIEVING to 49, Skills.WOODCUTTING to 51) children.forEach { key, value -> player.setComponentHidden(interfaceId = 233, component = value, hidden = skill != key) } val skillName = Skills.getSkillName(player.world, skill) val initialChar = Character.toLowerCase(skillName.toCharArray().first()) val vowel = initialChar == 'a' || initialChar == 'e' || initialChar == 'i' || initialChar == 'o' || initialChar == 'u' val levelFormat = if (levelIncrement == 1) (if (vowel) "an" else "a") else "$levelIncrement" player.setComponentText(interfaceId = 233, component = 1, text = "<col=000080>Congratulations, you just advanced $levelFormat $skillName ${"level".pluralSuffix(levelIncrement)}.") player.setComponentText(interfaceId = 233, component = 2, text = "Your $skillName level is now ${player.getSkills().getMaxLevel(skill)}.") player.setComponentText(interfaceId = 233, component = 3, text = "Click here to continue") player.openInterface(parent = 162, child = CHATBOX_CHILD, interfaceId = 233) } else { val levelFormat = if (levelIncrement == 1) "a" else "$levelIncrement" player.setInterfaceEvents(interfaceId = 132, component = 3, from = -1, to = -1, setting = 1) player.setInterfaceEvents(interfaceId = 132, component = 4, from = -1, to = -1, setting = 0) player.setInterfaceEvents(interfaceId = 132, component = 5, from = -1, to = -1, setting = 0) player.setComponentItem(interfaceId = 193, component = 1, item = 9951, amountOrZoom = 400) player.setComponentText(interfaceId = 193, component = 2, text = "<col=000080>Congratulations, you've just advanced $levelFormat Hunter ${"level".pluralSuffix(levelIncrement)}." + "<col=000000><br><br>Your Hunter level is now ${player.getSkills().getMaxLevel(skill)}.") player.setComponentText(interfaceId = 193, component = 3, text = "Click here to continue") player.setComponentText(interfaceId = 193, component = 4, text = "") player.setComponentText(interfaceId = 193, component = 5, text = "") player.openInterface(parent = 162, child = CHATBOX_CHILD, interfaceId = 193) } terminateAction = closeDialog waitReturnValue() terminateAction!!(this) } suspend fun QueueTask.produceItemBox(vararg items: Int, type: Int = 0, title: String = "What would you like to make?", maxItems: Int = player.inventory.capacity, logic: Player.(Int, Int) -> Unit) { val defs = player.world.definitions val itemDefs = items.map { defs.get(ItemDef::class.java, it) } val baseChild = 14 val itemArray = Array(10) { -1 } val nameArray = Array(10) { "|" } itemDefs.withIndex().forEach { val def = it.value itemArray[it.index] = def.id nameArray[it.index] = "|${def.name}" } player.sendTempVarbit(5983, 1) player.openInterface(parent = 162, child = CHATBOX_CHILD, interfaceId = 270) player.runClientScript(2046, type, "$title${nameArray.joinToString("")}", maxItems, *itemArray) terminateAction = closeDialog waitReturnValue() terminateAction!!(this) val msg = requestReturnValue as? ResumePauseButtonMessage ?: return val child = msg.component if (child < baseChild || child >= baseChild + items.size) return val item = items[child - baseChild] val qty = msg.slot logic(player, item, qty) }
8
null
6
23
9dbd62d67de547cfedc43b902797306c5db8fb55
14,720
Alter
Apache License 2.0
main/src/main/java/com/google/android/apps/muzei/legacy/LegacySourceInfoFragment.kt
ianhanniballake
24,799,536
false
null
/* * Copyright 2019 Google 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.google.android.apps.muzei.legacy import android.app.Application import android.content.Intent import android.os.Bundle import android.provider.Settings import android.view.View import android.view.ViewGroup import androidx.core.net.toUri import androidx.core.view.isVisible import androidx.fragment.app.Fragment import androidx.fragment.app.viewModels import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import androidx.navigation.fragment.findNavController import androidx.recyclerview.widget.DiffUtil import androidx.recyclerview.widget.ListAdapter import androidx.recyclerview.widget.RecyclerView import com.google.android.apps.muzei.util.collectIn import com.google.android.apps.muzei.util.toast import com.google.firebase.analytics.FirebaseAnalytics import com.google.firebase.analytics.ktx.analytics import com.google.firebase.analytics.ktx.logEvent import com.google.firebase.ktx.Firebase import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.shareIn import net.nurik.roman.muzei.R import net.nurik.roman.muzei.databinding.LegacySourceInfoFragmentBinding import net.nurik.roman.muzei.databinding.LegacySourceInfoItemBinding class LegacySourceInfoViewModel(application: Application) : AndroidViewModel(application) { val unsupportedSources = LegacySourceManager.getInstance(application).unsupportedSources .shareIn(viewModelScope, SharingStarted.WhileSubscribed(5000L), 1) } class LegacySourceInfoFragment : Fragment(R.layout.legacy_source_info_fragment) { private val viewModel: LegacySourceInfoViewModel by viewModels() override fun onViewCreated(view: View, savedInstanceState: Bundle?) { val binding = LegacySourceInfoFragmentBinding.bind(view) binding.toolbar.setNavigationOnClickListener { findNavController().popBackStack() } if (binding.learnMore != null) { binding.learnMore.setOnClickListener { startActivity(Intent(Intent.ACTION_VIEW, LegacySourceManager.LEARN_MORE_LINK)) } } else { binding.toolbar.inflateMenu(R.menu.legacy_source_info_fragment) binding.toolbar.setOnMenuItemClickListener { startActivity(Intent(Intent.ACTION_VIEW, LegacySourceManager.LEARN_MORE_LINK)) true } } val adapter = LegacySourceListAdapter() binding.list.adapter = adapter viewModel.unsupportedSources.collectIn(viewLifecycleOwner) { if (it.isEmpty()) { requireContext().toast(R.string.legacy_source_all_uninstalled) findNavController().popBackStack() } else { adapter.submitList(it) } } } inner class LegacySourceViewHolder( private val binding: LegacySourceInfoItemBinding ) : RecyclerView.ViewHolder(binding.root) { fun bind(legacySourceInfo: LegacySourceInfo) = legacySourceInfo.run { binding.icon.setImageBitmap(icon) binding.title.text = title binding.appInfo.setOnClickListener { Firebase.analytics.logEvent("legacy_source_info_app_info_open") { param(FirebaseAnalytics.Param.ITEM_LIST_ID, packageName) param(FirebaseAnalytics.Param.ITEM_NAME, title) param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "sources") } val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS) intent.data = "package:$packageName".toUri() startActivity(intent) } val intent = Intent(Intent.ACTION_VIEW, "https://play.google.com/store/apps/details?id=$packageName".toUri()) binding.sendFeedback.isVisible = intent.resolveActivity(requireContext().packageManager) != null binding.sendFeedback.setOnClickListener { Firebase.analytics.logEvent("legacy_source_info_send_feedback_open") { param(FirebaseAnalytics.Param.ITEM_LIST_ID, packageName) param(FirebaseAnalytics.Param.ITEM_NAME, title) param(FirebaseAnalytics.Param.ITEM_LIST_NAME, "sources") } startActivity(intent) } } } inner class LegacySourceListAdapter : ListAdapter<LegacySourceInfo, LegacySourceViewHolder>( object : DiffUtil.ItemCallback<LegacySourceInfo>() { override fun areItemsTheSame( legacySourceInfo1: LegacySourceInfo, legacySourceInfo2: LegacySourceInfo ) = legacySourceInfo1.packageName == legacySourceInfo2.packageName override fun areContentsTheSame( legacySourceInfo1: LegacySourceInfo, legacySourceInfo2: LegacySourceInfo ) = legacySourceInfo1 == legacySourceInfo2 } ) { override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) = LegacySourceViewHolder(LegacySourceInfoItemBinding.inflate(layoutInflater, parent, false)) override fun onBindViewHolder(holder: LegacySourceViewHolder, position: Int) { holder.bind(getItem(position)) } } }
40
null
959
7
14a0c0c41e2628375bc5a5e5a135ff933d8b7c27
5,987
muzei
Apache License 2.0